Same agent Smaller bill. The tools and infrastructure to get more work from your AI. Fewer tokens. Less compute. Lower cost.
TypeScript agent-harnessagent-harness-engineeringai-engineeringai-observabilityamd-gpuclaude-codeclickhousecodexcoding-agentcoding-agentscursorgenaigpu-monitoringllm-observabilityllmopsnvidia-smiobservabilityopen-sourceopenaiopentelemetry
[Feat]: Add OpenTelemetry instrumentation for Monitoring LLM Applications using EmbedChain (#256)
patcher9e6eec0f8bb4a
diff --git a/sdk/python/pyproject.toml b/sdk/python/pyproject.tomlindex dc23bcf7..0bb471d5 100644--- a/sdk/python/pyproject.toml+++ b/sdk/python/pyproject.toml@@ -1,6 +1,6 @@[tool.poetry]name = "openlit"-version = "1.9.0"+version = "1.10.0"description = "OpenTelemetry-native Auto instrumentation library for monitoring LLM Applications, facilitating the integration of observability into your GenAI-driven projects"authors = ["OpenLIT"]repository = "https://github.com/openlit/openlit/tree/main/openlit/python"diff --git a/sdk/python/src/openlit/__init__.py b/sdk/python/src/openlit/__init__.pyindex 33bbd054..282082e1 100644--- a/sdk/python/src/openlit/__init__.py+++ b/sdk/python/src/openlit/__init__.py@@ -24,6 +24,7 @@ from openlit.instrumentation.ollama import OllamaInstrumentorfrom openlit.instrumentation.langchain import LangChainInstrumentorfrom openlit.instrumentation.llamaindex import LlamaIndexInstrumentorfrom openlit.instrumentation.haystack import HaystackInstrumentor+from openlit.instrumentation.embedchain import EmbedChainInstrumentorfrom openlit.instrumentation.chroma import ChromaInstrumentorfrom openlit.instrumentation.pinecone import PineconeInstrumentorfrom openlit.instrumentation.qdrant import QdrantInstrumentor@@ -163,6 +164,7 @@ def init(environment="default", application_name="default", tracer=None, otlp_en"langchain": "langchain","llama_index": "llama_index","haystack": "haystack",+ "embedchain": "embedchain","chroma": "chromadb","pinecone": "pinecone","qdrant": "qdrant_client",@@ -217,6 +219,7 @@ def init(environment="default", application_name="default", tracer=None, otlp_en"langchain": LangChainInstrumentor(),"llama_index": LlamaIndexInstrumentor(),"haystack": HaystackInstrumentor(),+ "embedchain": EmbedChainInstrumentor(),"chroma": ChromaInstrumentor(),"pinecone": PineconeInstrumentor(),"qdrant": QdrantInstrumentor(),diff --git a/sdk/python/src/openlit/instrumentation/chroma/chroma.py b/sdk/python/src/openlit/instrumentation/chroma/chroma.pyindex df64d965..34e5974d 100644--- a/sdk/python/src/openlit/instrumentation/chroma/chroma.py+++ b/sdk/python/src/openlit/instrumentation/chroma/chroma.py@@ -16,11 +16,13 @@ def object_count(obj):"""Counts Length of object if it exists, Else returns None"""+ try:+ cnt = len(obj)+ # pylint: disable=bare-except+ except:+ cnt = 0- if obj:- return len(obj)-- return None+ return cntdef general_wrap(gen_ai_endpoint, version, environment, application_name,tracer, pricing_info, trace_content, metrics, disable_metrics):@@ -87,24 +89,24 @@ def general_wrap(gen_ai_endpoint, version, environment, application_name,span.set_attribute(SemanticConvetion.DB_OPERATION,SemanticConvetion.DB_OPERATION_ADD)span.set_attribute(SemanticConvetion.DB_ID_COUNT,- object_count(kwargs.get("ids")))+ object_count(kwargs.get("ids", [])))span.set_attribute(SemanticConvetion.DB_VECTOR_COUNT,- object_count(kwargs.get("embeddings")))+ object_count(kwargs.get("embeddings", [])))span.set_attribute(SemanticConvetion.DB_VECTOR_COUNT,- object_count(kwargs.get("metadatas")))+ object_count(kwargs.get("metadatas", [])))span.set_attribute(SemanticConvetion.DB_DOCUMENTS_COUNT,- object_count(kwargs.get("documents")))+ object_count(kwargs.get("documents", [])))elif gen_ai_endpoint == "chroma.get":db_operation = SemanticConvetion.DB_OPERATION_GETspan.set_attribute(SemanticConvetion.DB_OPERATION,SemanticConvetion.DB_OPERATION_GET)span.set_attribute(SemanticConvetion.DB_ID_COUNT,- object_count(kwargs.get("ids")))+ object_count(kwargs.get("ids", [])))span.set_attribute(SemanticConvetion.DB_QUERY_LIMIT,- kwargs.get("limit"))+ kwargs.get("limit", ""))span.set_attribute(SemanticConvetion.DB_OFFSET,- kwargs.get("offset"))+ kwargs.get("offset", ""))span.set_attribute(SemanticConvetion.DB_WHERE_DOCUMENT,str(kwargs.get("where_document", "")))@@ -113,7 +115,7 @@ def general_wrap(gen_ai_endpoint, version, environment, application_name,span.set_attribute(SemanticConvetion.DB_OPERATION,SemanticConvetion.DB_OPERATION_QUERY)span.set_attribute(SemanticConvetion.DB_STATEMENT,- str(kwargs.get("query_texts")))+ str(kwargs.get("query_texts", "")))span.set_attribute(SemanticConvetion.DB_N_RESULTS,kwargs.get("n_results", ""))span.set_attribute(SemanticConvetion.DB_FILTER,@@ -126,33 +128,33 @@ def general_wrap(gen_ai_endpoint, version, environment, application_name,span.set_attribute(SemanticConvetion.DB_OPERATION,SemanticConvetion.DB_OPERATION_UPDATE)span.set_attribute(SemanticConvetion.DB_VECTOR_COUNT,- object_count(kwargs.get("embeddings")))+ object_count(kwargs.get("embeddings", [])))span.set_attribute(SemanticConvetion.DB_VECTOR_COUNT,- object_count(kwargs.get("metadatas")))+ object_count(kwargs.get("metadatas", [])))span.set_attribute(SemanticConvetion.DB_ID_COUNT,- object_count(kwargs.get("ids")))+ object_count(kwargs.get("ids", [])))span.set_attribute(SemanticConvetion.DB_DOCUMENTS_COUNT,- object_count(kwargs.get("documents")))+ object_count(kwargs.get("documents", [])))elif gen_ai_endpoint == "chroma.upsert":db_operation = SemanticConvetion.DB_OPERATION_UPSERTspan.set_attribute(SemanticConvetion.DB_OPERATION,SemanticConvetion.DB_OPERATION_UPSERT)span.set_attribute(SemanticConvetion.DB_VECTOR_COUNT,- object_count(kwargs.get("embeddings")))+ object_count(kwargs.get("embeddings", [])))span.set_attribute(SemanticConvetion.DB_VECTOR_COUNT,- object_count(kwargs.get("metadatas")))+ object_count(kwargs.get("metadatas", [])))span.set_attribute(SemanticConvetion.DB_ID_COUNT,- object_count(kwargs.get("ids")))+ object_count(kwargs.get("ids", [])))span.set_attribute(SemanticConvetion.DB_DOCUMENTS_COUNT,- object_count(kwargs.get("documents")))+ object_count(kwargs.get("documents", [])))elif gen_ai_endpoint == "chroma.delete":db_operation = SemanticConvetion.DB_OPERATION_DELETEspan.set_attribute(SemanticConvetion.DB_OPERATION,SemanticConvetion.DB_OPERATION_DELETE)span.set_attribute(SemanticConvetion.DB_ID_COUNT,- object_count(kwargs.get("ids")))+ object_count(kwargs.get("ids", [])))span.set_attribute(SemanticConvetion.DB_FILTER,str(kwargs.get("where", "")))span.set_attribute(SemanticConvetion.DB_DELETE_ALL,diff --git a/sdk/python/src/openlit/instrumentation/embedchain/__init__.py b/sdk/python/src/openlit/instrumentation/embedchain/__init__.pynew file mode 100644index 00000000..5177d286--- /dev/null+++ b/sdk/python/src/openlit/instrumentation/embedchain/__init__.py@@ -0,0 +1,55 @@+# pylint: disable=useless-return, bad-staticmethod-argument, disable=duplicate-code+"""Initializer of Auto Instrumentation of EmbedChain Functions"""+from typing import Collection+import importlib.metadata+from opentelemetry.instrumentation.instrumentor import BaseInstrumentor+from wrapt import wrap_function_wrapper++from openlit.instrumentation.embedchain.embedchain import evaluate, get_data_sources++_instruments = ("embedchain >= 0.1.104",)++WRAPPED_METHODS = [+ {+ "package": "embedchain",+ "object": "App.evaluate",+ "endpoint": "embedchain.evaluate",+ "wrapper": evaluate,+ },+ {+ "package": "embedchain",+ "object": "App.get_data_sources",+ "endpoint": "embedchain.get_data_sources",+ "wrapper": get_data_sources,+ },+]++class EmbedChainInstrumentor(BaseInstrumentor):+ """An instrumentor for EmbedChain's client library."""++ def instrumentation_dependencies(self) -> Collection[str]:+ return _instruments++ def _instrument(self, **kwargs):+ application_name = kwargs.get("application_name")+ environment = kwargs.get("environment")+ tracer = kwargs.get("tracer")+ pricing_info = kwargs.get("pricing_info")+ trace_content = kwargs.get("trace_content")+ version = importlib.metadata.version("embedchain")++ for wrapped_method in WRAPPED_METHODS:+ wrap_package = wrapped_method.get("package")+ wrap_object = wrapped_method.get("object")+ gen_ai_endpoint = wrapped_method.get("endpoint")+ wrapper = wrapped_method.get("wrapper")+ wrap_function_wrapper(+ wrap_package,+ wrap_object,+ wrapper(gen_ai_endpoint, version, environment, application_name,+ tracer, pricing_info, trace_content),+ )++ @staticmethod+ def _uninstrument(self, **kwargs):+ passdiff --git a/sdk/python/src/openlit/instrumentation/embedchain/embedchain.py b/sdk/python/src/openlit/instrumentation/embedchain/embedchain.pynew file mode 100644index 00000000..80d931f3--- /dev/null+++ b/sdk/python/src/openlit/instrumentation/embedchain/embedchain.py@@ -0,0 +1,165 @@+# pylint: disable=duplicate-code, broad-exception-caught, too-many-statements, unused-argument+"""+Module for monitoring EmbedChain applications.+"""++import logging+from opentelemetry.trace import SpanKind, Status, StatusCode+from opentelemetry.sdk.resources import TELEMETRY_SDK_NAME+from openlit.__helpers import handle_exception+from openlit.semcov import SemanticConvetion++# Initialize logger for logging potential issues and operations+logger = logging.getLogger(__name__)++def evaluate(gen_ai_endpoint, version, environment, application_name,+ tracer, pricing_info, trace_content):+ """+ Creates a wrapper around a function call to trace and log its execution metrics.++ This function wraps any given function to measure its execution time,+ log its operation, and trace its execution using OpenTelemetry.++ Parameters:+ - gen_ai_endpoint (str): A descriptor or name for the endpoint being traced.+ - version (str): The version of the EmbedChain application.+ - environment (str): The deployment environment (e.g., 'production', 'development').+ - application_name (str): Name of the EmbedChain application.+ - tracer (opentelemetry.trace.Tracer): The tracer object used for OpenTelemetry tracing.+ - pricing_info (dict): Information about the pricing for internal metrics (currently not used).+ - trace_content (bool): Flag indicating whether to trace the content of the response.++ Returns:+ - function: A higher-order function that takes a function 'wrapped' and returns+ a new function that wraps 'wrapped' with additional tracing and logging.+ """++ def wrapper(wrapped, instance, args, kwargs):+ """+ An inner wrapper function that executes the wrapped function, measures execution+ time, and records trace data using OpenTelemetry.++ Parameters:+ - wrapped (Callable): The original function that this wrapper will execute.+ - instance (object): The instance to which the wrapped function belongs. This+ is used for instance methods. For static and classmethods,+ this may be None.+ - args (tuple): Positional arguments passed to the wrapped function.+ - kwargs (dict): Keyword arguments passed to the wrapped function.++ Returns:+ - The result of the wrapped function call.++ The wrapper initiates a span with the provided tracer, sets various attributes+ on the span based on the function's execution and response, and ensures+ errors are handled and logged appropriately.+ """+ with tracer.start_as_current_span(gen_ai_endpoint, kind= SpanKind.CLIENT) as span:+ response = wrapped(*args, **kwargs)++ try:+ span.set_attribute(TELEMETRY_SDK_NAME, "openlit")+ span.set_attribute(SemanticConvetion.GEN_AI_SYSTEM,+ SemanticConvetion.GEN_AI_SYSTEM_EMBEDCHAIN)+ span.set_attribute(SemanticConvetion.GEN_AI_ENDPOINT,+ gen_ai_endpoint)+ span.set_attribute(SemanticConvetion.GEN_AI_ENVIRONMENT,+ environment)+ span.set_attribute(SemanticConvetion.GEN_AI_TYPE,+ SemanticConvetion.GEN_AI_TYPE_FRAMEWORK)+ span.set_attribute(SemanticConvetion.GEN_AI_APPLICATION_NAME,+ application_name)+ span.set_attribute(SemanticConvetion.GEN_AI_EVAL_CONTEXT_RELEVANCY,+ response["context_relevancy"])+ span.set_attribute(SemanticConvetion.GEN_AI_EVAL_ANSWER_RELEVANCY,+ response["answer_relevancy"])+ span.set_attribute(SemanticConvetion.GEN_AI_EVAL_GROUNDEDNESS,+ response["groundedness"])++ span.set_status(Status(StatusCode.OK))++ # Return original response+ return response++ except Exception as e:+ handle_exception(span, e)+ logger.error("Error in trace creation: %s", e)++ # Return original response+ return response++ return wrapper++def get_data_sources(gen_ai_endpoint, version, environment, application_name,+ tracer, pricing_info, trace_content):+ """+ Creates a wrapper around a function call to trace and log its execution metrics.++ This function wraps any given function to measure its execution time,+ log its operation, and trace its execution using OpenTelemetry.++ Parameters:+ - gen_ai_endpoint (str): A descriptor or name for the endpoint being traced.+ - version (str): The version of the EmbedChain application.+ - environment (str): The deployment environment (e.g., 'production', 'development').+ - application_name (str): Name of the EmbedChain application.+ - tracer (opentelemetry.trace.Tracer): The tracer object used for OpenTelemetry tracing.+ - pricing_info (dict): Information about the pricing for internal metrics (currently not used).+ - trace_content (bool): Flag indicating whether to trace the content of the response.++ Returns:+ - function: A higher-order function that takes a function 'wrapped' and returns+ a new function that wraps 'wrapped' with additional tracing and logging.+ """++ def wrapper(wrapped, instance, args, kwargs):+ """+ An inner wrapper function that executes the wrapped function, measures execution+ time, and records trace data using OpenTelemetry.++ Parameters:+ - wrapped (Callable): The original function that this wrapper will execute.+ - instance (object): The instance to which the wrapped function belongs. This+ is used for instance methods. For static and classmethods,+ this may be None.+ - args (tuple): Positional arguments passed to the wrapped function.+ - kwargs (dict): Keyword arguments passed to the wrapped function.++ Returns:+ - The result of the wrapped function call.++ The wrapper initiates a span with the provided tracer, sets various attributes+ on the span based on the function's execution and response, and ensures+ errors are handled and logged appropriately.+ """+ with tracer.start_as_current_span(gen_ai_endpoint, kind= SpanKind.CLIENT) as span:+ response = wrapped(*args, **kwargs)++ try:+ span.set_attribute(TELEMETRY_SDK_NAME, "openlit")+ span.set_attribute(SemanticConvetion.GEN_AI_SYSTEM,+ SemanticConvetion.GEN_AI_SYSTEM_EMBEDCHAIN)+ span.set_attribute(SemanticConvetion.GEN_AI_ENDPOINT,+ gen_ai_endpoint)+ span.set_attribute(SemanticConvetion.GEN_AI_ENVIRONMENT,+ environment)+ span.set_attribute(SemanticConvetion.GEN_AI_TYPE,+ SemanticConvetion.GEN_AI_TYPE_FRAMEWORK)+ span.set_attribute(SemanticConvetion.GEN_AI_APPLICATION_NAME,+ application_name)+ span.set_attribute(SemanticConvetion.GEN_AI_DATA_SOURCES,+ len(response))++ span.set_status(Status(StatusCode.OK))++ # Return original response+ return response++ except Exception as e:+ handle_exception(span, e)+ logger.error("Error in trace creation: %s", e)++ # Return original response+ return response++ return wrapperdiff --git a/sdk/python/src/openlit/instrumentation/llamaindex/__init__.py b/sdk/python/src/openlit/instrumentation/llamaindex/__init__.pyindex ab315ee1..43c66875 100644--- a/sdk/python/src/openlit/instrumentation/llamaindex/__init__.py+++ b/sdk/python/src/openlit/instrumentation/llamaindex/__init__.py@@ -25,7 +25,7 @@ WRAPPED_METHODS = []class LlamaIndexInstrumentor(BaseInstrumentor):- """An instrumentor for Cohere's client library."""+ """An instrumentor for LlamaIndex's client library."""def instrumentation_dependencies(self) -> Collection[str]:return _instrumentsdiff --git a/sdk/python/src/openlit/instrumentation/qdrant/qdrant.py b/sdk/python/src/openlit/instrumentation/qdrant/qdrant.pyindex 25fe56ba..e2cb9c93 100644--- a/sdk/python/src/openlit/instrumentation/qdrant/qdrant.py+++ b/sdk/python/src/openlit/instrumentation/qdrant/qdrant.py@@ -119,9 +119,9 @@ def general_wrap(gen_ai_endpoint, version, environment, application_name,span.set_attribute(SemanticConvetion.DB_OPERATION_STATUS,response.status)span.set_attribute(SemanticConvetion.DB_VECTOR_COUNT,- object_count(kwargs.get("points")))+ object_count(kwargs.get("points", [])))span.set_attribute(SemanticConvetion.DB_PAYLOAD_COUNT,- object_count(kwargs.get("payload")))+ object_count(kwargs.get("payload", [])))elif gen_ai_endpoint == "qdrant.retrieve":db_operation = SemanticConvetion.DB_OPERATION_QUERY@@ -130,7 +130,7 @@ def general_wrap(gen_ai_endpoint, version, environment, application_name,span.set_attribute(SemanticConvetion.DB_COLLECTION_NAME,kwargs.get("collection_name", ""))span.set_attribute(SemanticConvetion.DB_STATEMENT,- str(kwargs.get("ids")))+ str(kwargs.get("ids", "")))elif gen_ai_endpoint == "qdrant.scroll":db_operation = SemanticConvetion.DB_OPERATION_QUERY@@ -139,7 +139,7 @@ def general_wrap(gen_ai_endpoint, version, environment, application_name,span.set_attribute(SemanticConvetion.DB_COLLECTION_NAME,kwargs.get("collection_name", ""))span.set_attribute(SemanticConvetion.DB_STATEMENT,- str(kwargs.get("scroll_filter")))+ str(kwargs.get("scroll_filter", "")))elif gen_ai_endpoint in ["qdrant.search", "qdrant.search_groups"]:db_operation = SemanticConvetion.DB_OPERATION_QUERY@@ -148,7 +148,7 @@ def general_wrap(gen_ai_endpoint, version, environment, application_name,span.set_attribute(SemanticConvetion.DB_COLLECTION_NAME,kwargs.get("collection_name", ""))span.set_attribute(SemanticConvetion.DB_STATEMENT,- str(kwargs.get("query_vector")))+ str(kwargs.get("query_vector", "")))elif gen_ai_endpoint == "qdrant.recommend":db_operation = SemanticConvetion.DB_OPERATION_QUERYdiff --git a/sdk/python/src/openlit/semcov/__init__.py b/sdk/python/src/openlit/semcov/__init__.pyindex 131a6b2b..5db3ea10 100644--- a/sdk/python/src/openlit/semcov/__init__.py+++ b/sdk/python/src/openlit/semcov/__init__.py@@ -26,6 +26,7 @@ class SemanticConvetion:GEN_AI_HUB_REPO = "gen_ai.hub.repo"GEN_AI_RETRIEVAL_SOURCE = "gen_ai.retrieval.source"GEN_AI_REQUESTS = "gen_ai.total.requests"+ GEN_AI_DATA_SOURCES = "gen_ai.data_source_count"# GenAI RequestGEN_AI_REQUEST_MODEL = "gen_ai.request.model"@@ -71,6 +72,11 @@ class SemanticConvetion:GEN_AI_CONTENT_COMPLETION = "gen_ai.content.completion"GEN_AI_CONTENT_REVISED_PROMPT = "gen_ai.content.revised_prompt"+ # GenAI Evaluation Metrics+ GEN_AI_EVAL_CONTEXT_RELEVANCY = "gen_ai.eval.context_relevancy"+ GEN_AI_EVAL_ANSWER_RELEVANCY = "gen_ai.eval.answer_relevancy"+ GEN_AI_EVAL_GROUNDEDNESS = "gen_ai.eval.groundedness"+GEN_AI_TYPE_CHAT = "chat"GEN_AI_TYPE_EMBEDDING = "embedding"GEN_AI_TYPE_IMAGE = "image"@@ -92,6 +98,7 @@ class SemanticConvetion:GEN_AI_SYSTEM_LANGCHAIN = "langchain"GEN_AI_SYSTEM_LLAMAINDEX = "llama_index"GEN_AI_SYSTEM_HAYSTACK = "haystack"+ GEN_AI_SYSTEM_EMBEDCHAIN = "embedchain"# Vector DBDB_REQUESTS = "db.total.requests"diff --git a/sdk/python/tests/requirements.txt b/sdk/python/tests/requirements.txtindex f74bedd6..a3d6a345 100644--- a/sdk/python/tests/requirements.txt+++ b/sdk/python/tests/requirements.txt@@ -23,8 +23,8 @@ pymilvus>=2.4.3# Frameworkslangchain>=0.1.16-langchainhub>=0.1.15-langchain-community>=0.2.0+langchainhub>=0.1.16+embedchain>=0.1.104# Utilitiesbs4diff --git a/sdk/python/tests/test_embedchain.py b/sdk/python/tests/test_embedchain.pynew file mode 100644index 00000000..8c29a3a1--- /dev/null+++ b/sdk/python/tests/test_embedchain.py@@ -0,0 +1,77 @@+# pylint: disable=duplicate-code, no-member, no-name-in-module+"""+This module contains tests for Embedchain functionality using the embedchain Python library.++Tests cover various functions, including WebBaseLoader, TextSplitter,+and Prompt pull from Hub.+These tests validate integration with OpenLIT.++Note: Ensure the environment is properly configured for Embedchain and OpenLIT monitoring+prior to running these tests.+"""++import os+from embedchain import App+import openlit++# Initialize environment and application name for OpenLIT monitoring+openlit.init(environment="openlit-testing", application_name="openlit-python-test")+os.environ["OPENAI_API_KEY"] = os.getenv("OPENAI_API_TOKEN")++config = {+ 'app': {+ 'config': {+ 'name': 'openlit-testing'+ }+ },+ 'llm': {+ 'provider': 'openai',+ 'config': {+ 'model': 'gpt-3.5-turbo',+ 'temperature': 0.5,+ 'max_tokens': 1,+ 'top_p': 1,+ 'stream': False,+ 'api_key': os.getenv("OPENAI_API_TOKEN")+ }+ },+ 'vectordb': {+ 'provider': 'chroma',+ 'config': {+ 'collection_name': 'full-stack-app',+ 'dir': 'db',+ 'allow_reset': True+ }+ },+ 'embedder': {+ 'provider': 'openai',+ 'config': {+ 'model': 'text-embedding-ada-002',+ 'api_key': os.getenv("OPENAI_API_TOKEN")+ }+ }+}++def test_embedchain():+ """+ Verifies the functionality of Embedchain operations including document loading, text splitting,+ and prompt pulling from the Hub. Each operation is tested to ensure it functions as intended,+ confirming the efficient use of the Embedchain library for processing and interacting+ with text data.++ This test checks for the expected outcomes and metadata from each operation to+ confirm that the Embedchain library is working as expected within the intended use cases.++ Raises:+ AssertionError: If the outcomes from the Embedchain operations deviate from what is expected.+ """++ app = App()+ app.add("https://www.forbes.com/profile/elon-musk")++ data_sources = app.get_data_sources()+ assert isinstance(len(data_sources), int)++ evals = app.evaluate(["What is the net worth of Elon Musk?",+ "How many companies Elon Musk owns?"])+ assert isinstance(evals, dict)