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]: Refactor vLLM OpenTelemetry Instrumentation (#759)
Patcherabc1e68db921
diff --git a/sdk/python/pyproject.toml b/sdk/python/pyproject.tomlindex c5cea232..4f460328 100644--- a/sdk/python/pyproject.toml+++ b/sdk/python/pyproject.toml@@ -1,6 +1,6 @@[tool.poetry]name = "openlit"-version = "1.34.1"+version = "1.34.2"description = "OpenTelemetry-native Auto instrumentation library for monitoring LLM Applications and GPUs, facilitating the integration of observability into your GenAI-driven projects"authors = ["OpenLIT"]license = "Apache-2.0"diff --git a/sdk/python/src/openlit/instrumentation/google_ai_studio/async_google_ai_studio.py b/sdk/python/src/openlit/instrumentation/google_ai_studio/async_google_ai_studio.pyindex 9ae62fb3..9a574ba0 100644--- a/sdk/python/src/openlit/instrumentation/google_ai_studio/async_google_ai_studio.py+++ b/sdk/python/src/openlit/instrumentation/google_ai_studio/async_google_ai_studio.py@@ -59,14 +59,12 @@ def async_generate(version, environment, application_name,version=version,)- return response-except Exception as e:handle_exception(span, e)logger.error("Error in trace creation: %s", e)- # Return original response- return response+ # Return original response+ return responsereturn wrapperdiff --git a/sdk/python/src/openlit/instrumentation/google_ai_studio/google_ai_studio.py b/sdk/python/src/openlit/instrumentation/google_ai_studio/google_ai_studio.pyindex a82413ec..2c6c8b15 100644--- a/sdk/python/src/openlit/instrumentation/google_ai_studio/google_ai_studio.py+++ b/sdk/python/src/openlit/instrumentation/google_ai_studio/google_ai_studio.py@@ -59,14 +59,12 @@ def generate(version, environment, application_name,version=version,)- return response-except Exception as e:handle_exception(span, e)logger.error("Error in trace creation: %s", e)- # Return original response- return response+ # Return original response+ return responsereturn wrapperdiff --git a/sdk/python/src/openlit/instrumentation/google_ai_studio/utils.py b/sdk/python/src/openlit/instrumentation/google_ai_studio/utils.pyindex 4e31a2fe..cad85156 100644--- a/sdk/python/src/openlit/instrumentation/google_ai_studio/utils.py+++ b/sdk/python/src/openlit/instrumentation/google_ai_studio/utils.py@@ -2,10 +2,8 @@Google AI Studio OpenTelemetry instrumentation utility functions"""import time-from opentelemetry.sdk.resources import SERVICE_NAME, TELEMETRY_SDK_NAME, DEPLOYMENT_ENVIRONMENTfrom opentelemetry.trace import Status, StatusCode-from openlit.__helpers import (calculate_ttft,response_as_dict,@@ -117,6 +115,7 @@ def common_chat_logic(scope, pricing_info, environment, application_name, metricscope._span.set_attribute(SemanticConvention.GEN_AI_SYSTEM, SemanticConvention.GEN_AI_SYSTEM_GEMINI)scope._span.set_attribute(SemanticConvention.GEN_AI_REQUEST_MODEL, request_model)scope._span.set_attribute(SemanticConvention.SERVER_PORT, scope._server_port)+ scope._span.set_attribute(SemanticConvention.SERVER_ADDRESS, scope._server_address)inference_config = scope._kwargs.get('config', {})@@ -142,7 +141,6 @@ def common_chat_logic(scope, pricing_info, environment, application_name, metricscope._span.set_attribute(SemanticConvention.GEN_AI_USAGE_INPUT_TOKENS, scope._input_tokens)scope._span.set_attribute(SemanticConvention.GEN_AI_USAGE_OUTPUT_TOKENS, scope._output_tokens)scope._span.set_attribute(SemanticConvention.GEN_AI_USAGE_REASONING_TOKENS, scope._reasoning_tokens)- scope._span.set_attribute(SemanticConvention.SERVER_ADDRESS, scope._server_address)scope._span.set_attribute(SemanticConvention.GEN_AI_OUTPUT_TYPE,'text' if isinstance(scope._llmresponse, str) else 'json')diff --git a/sdk/python/src/openlit/instrumentation/vllm/__init__.py b/sdk/python/src/openlit/instrumentation/vllm/__init__.pyindex acd3b083..9cbb8569 100644--- a/sdk/python/src/openlit/instrumentation/vllm/__init__.py+++ b/sdk/python/src/openlit/instrumentation/vllm/__init__.py@@ -32,7 +32,7 @@ class VLLMInstrumentor(BaseInstrumentor):# sync chatwrap_function_wrapper(- "vllm",+ "vllm.entrypoints.llm","LLM.generate",generate(version, environment, application_name,tracer, pricing_info, capture_message_content, metrics, disable_metrics),diff --git a/sdk/python/src/openlit/instrumentation/vllm/utils.py b/sdk/python/src/openlit/instrumentation/vllm/utils.pynew file mode 100644index 00000000..6b5e99a9--- /dev/null+++ b/sdk/python/src/openlit/instrumentation/vllm/utils.py@@ -0,0 +1,161 @@+"""+Utility functions for vLLM instrumentation.+"""++import time+from opentelemetry.sdk.resources import SERVICE_NAME, TELEMETRY_SDK_NAME, DEPLOYMENT_ENVIRONMENT+from opentelemetry.trace import Status, StatusCode+from openlit.__helpers import (+ calculate_tbt,+ get_chat_model_cost,+ general_tokens,+ create_metrics_attributes,+)+from openlit.semcov import SemanticConvention++def get_inference_config(args, kwargs):+ """+ Safely extract inference configuration from args or kwargs.+ """++ if 'sampling_params' in kwargs:+ return kwargs['sampling_params']+ if len(args) > 1:+ return args[1]+ return None++def common_chat_logic(scope, pricing_info, environment, application_name, metrics,+ capture_message_content, disable_metrics, version, is_stream):+ """+ Process chat request and generate Telemetry+ """++ scope._end_time = time.time()+ if len(scope._timestamps) > 1:+ scope._tbt = calculate_tbt(scope._timestamps)++ # Set base span attributes+ scope._span.set_attribute(TELEMETRY_SDK_NAME, "openlit")+ scope._span.set_attribute(SemanticConvention.GEN_AI_OPERATION, SemanticConvention.GEN_AI_OPERATION_TYPE_CHAT)+ scope._span.set_attribute(SemanticConvention.GEN_AI_SYSTEM, SemanticConvention.GEN_AI_SYSTEM_VLLM)+ scope._span.set_attribute(SemanticConvention.GEN_AI_REQUEST_MODEL, scope._request_model)+ scope._span.set_attribute(SemanticConvention.SERVER_PORT, scope._server_port)+ scope._span.set_attribute(SemanticConvention.SERVER_ADDRESS, scope._server_address)++ # Handle inference configuration+ inference_config = get_inference_config(scope._args, scope._kwargs)+ if inference_config:+ attributes = [+ (SemanticConvention.GEN_AI_REQUEST_FREQUENCY_PENALTY, 'frequency_penalty'),+ (SemanticConvention.GEN_AI_REQUEST_MAX_TOKENS, 'max_tokens'),+ (SemanticConvention.GEN_AI_REQUEST_PRESENCE_PENALTY, 'presence_penalty'),+ (SemanticConvention.GEN_AI_REQUEST_STOP_SEQUENCES, 'stop_sequences'),+ (SemanticConvention.GEN_AI_REQUEST_TEMPERATURE, 'temperature'),+ (SemanticConvention.GEN_AI_REQUEST_TOP_P, 'top_p'),+ (SemanticConvention.GEN_AI_REQUEST_TOP_K, 'top_k'),+ ]++ for attribute, key in attributes:+ value = getattr(inference_config, key, None)+ if value is not None:+ scope._span.set_attribute(attribute, value)++ scope._span.set_attribute(SemanticConvention.GEN_AI_RESPONSE_MODEL, scope._request_model)+ scope._span.set_attribute(SemanticConvention.GEN_AI_OUTPUT_TYPE, "text")++ # Set base span attributes (Extras)+ scope._span.set_attribute(DEPLOYMENT_ENVIRONMENT, environment)+ scope._span.set_attribute(SERVICE_NAME, application_name)+ scope._span.set_attribute(SemanticConvention.GEN_AI_REQUEST_IS_STREAM, is_stream)+ scope._span.set_attribute(SemanticConvention.GEN_AI_SERVER_TBT, scope._tbt)+ scope._span.set_attribute(SemanticConvention.GEN_AI_SERVER_TTFT, scope._ttft)+ scope._span.set_attribute(SemanticConvention.GEN_AI_SDK_VERSION, version)++ input_tokens = 0+ output_tokens = 0+ cost = 0++ if capture_message_content:+ prompt = ""+ completion = ""++ for output in scope._response:+ prompt += output.prompt + "\n"+ if output.outputs and len(output.outputs) > 0:+ completion += output.outputs[0].text + "\n"+ input_tokens += general_tokens(output.prompt)+ output_tokens += general_tokens(output.outputs[0].text)++ # Add a single event for prompt+ scope._span.add_event(+ name=SemanticConvention.GEN_AI_CONTENT_PROMPT_EVENT,+ attributes={+ SemanticConvention.GEN_AI_CONTENT_PROMPT: prompt,+ },+ )++ # Add a single event for completion+ scope._span.add_event(+ name=SemanticConvention.GEN_AI_CONTENT_COMPLETION_EVENT,+ attributes={+ SemanticConvention.GEN_AI_CONTENT_COMPLETION: completion,+ },+ )++ scope._span.set_attribute(SemanticConvention.GEN_AI_USAGE_INPUT_TOKENS,+ input_tokens)+ scope._span.set_attribute(SemanticConvention.GEN_AI_USAGE_OUTPUT_TOKENS,+ output_tokens)+ scope._span.set_attribute(SemanticConvention.GEN_AI_CLIENT_TOKEN_USAGE,+ input_tokens + output_tokens)++ # Calculate cost of the operation+ cost = get_chat_model_cost(scope._request_model, pricing_info, input_tokens, output_tokens)+ scope._span.set_attribute(SemanticConvention.GEN_AI_USAGE_COST, cost)++ scope._span.set_status(Status(StatusCode.OK))++ if disable_metrics is False:+ metrics_attributes = create_metrics_attributes(+ service_name=application_name,+ deployment_environment=environment,+ operation=SemanticConvention.GEN_AI_OPERATION_TYPE_CHAT,+ system=SemanticConvention.GEN_AI_SYSTEM_VLLM,+ request_model=scope._request_model,+ server_address=scope._server_address,+ server_port=scope._server_port,+ response_model=scope._request_model,+ )+ metrics['genai_client_operation_duration'].record(scope._end_time - scope._start_time, metrics_attributes)+ metrics['genai_server_tbt'].record(scope._tbt, metrics_attributes)+ metrics['genai_server_ttft'].record(scope._ttft, metrics_attributes)+ metrics['genai_requests'].add(1, metrics_attributes)+ metrics['genai_completion_tokens'].add(output_tokens, metrics_attributes)+ metrics['genai_prompt_tokens'].add(input_tokens, metrics_attributes)+ metrics['genai_cost'].record(cost, metrics_attributes)+ metrics['genai_client_usage_tokens'].record(+ input_tokens + output_tokens, metrics_attributes)++def process_chat_response(instance, response, request_model, pricing_info, server_port, server_address,+ environment, application_name, metrics, start_time, span, args, kwargs,+ capture_message_content=False, disable_metrics=False, version="1.0.0"):+ """+ Process chat request and generate Telemetry+ """+ self = type('GenericScope', (), {})()+ self._response = response+ self._start_time = start_time+ self._end_time = time.time()+ self._span = span+ self._ttft, self._tbt = self._end_time - self._start_time, 0+ self._server_address = server_address+ self._server_port = server_port+ self._request_model = request_model+ self._timestamps = []+ self._args = args+ self._kwargs = kwargs++ common_chat_logic(self, pricing_info, environment, application_name, metrics,+ capture_message_content, disable_metrics, version, is_stream=False)++ return responsediff --git a/sdk/python/src/openlit/instrumentation/vllm/vllm.py b/sdk/python/src/openlit/instrumentation/vllm/vllm.pyindex 71f9701b..0de2cef0 100644--- a/sdk/python/src/openlit/instrumentation/vllm/vllm.py+++ b/sdk/python/src/openlit/instrumentation/vllm/vllm.py@@ -4,170 +4,62 @@ Module for monitoring vLLM API calls.import loggingimport time-from opentelemetry.trace import SpanKind, Status, StatusCode-from opentelemetry.sdk.resources import SERVICE_NAME, TELEMETRY_SDK_NAME, DEPLOYMENT_ENVIRONMENT+from opentelemetry.trace import SpanKindfrom openlit.__helpers import (- get_chat_model_cost,handle_exception,- general_tokens,- create_metrics_attributes,set_server_address_and_port)+from openlit.instrumentation.vllm.utils import (+ process_chat_response+)from openlit.semcov import SemanticConvention# Initialize logger for logging potential issues and operationslogger = logging.getLogger(__name__)def generate(version, environment, application_name,- tracer, pricing_info, capture_message_content, metrics, disable_metrics):+ tracer, pricing_info, capture_message_content, metrics, disable_metrics):"""- Generates a telemetry wrapper for generate to collect metrics.-- Args:- version: Version of the monitoring package.- environment: Deployment environment (e.g., production, staging).- application_name: Name of the application using the vLLM API.- tracer: OpenTelemetry tracer for creating spans.- pricing_info: Information used for calculating the cost of vLLM usage.- capture_message_content: Flag indicating whether to trace the actual content.-- Returns:- A function that wraps the generate method to add telemetry.+ Generates a telemetry wrapper for GenAI function call"""def wrapper(wrapped, instance, args, kwargs):"""- Wraps the 'generate' API call to add telemetry.-- This collects metrics such as execution time, cost, and token usage, and handles errors- gracefully, adding details to the trace for observability.-- Args:- wrapped: The original 'generate' method to be wrapped.- instance: The instance of the class where the original method is defined.- args: Positional arguments for the 'generate' method.- kwargs: Keyword arguments for the 'generate' method.-- Returns:- The response from the original 'generate' method.+ Wraps the GenAI function call."""- server_address, server_port = set_server_address_and_port(instance, "api.cohere.com", 443)+ server_address, server_port = set_server_address_and_port(instance, "http://127.0.0.1", 443)request_model = instance.llm_engine.model_config.model or "facebook/opt-125m"span_name = f"{SemanticConvention.GEN_AI_OPERATION_TYPE_CHAT} {request_model}"- # pylint: disable=line-too-long- with tracer.start_as_current_span(span_name, kind= SpanKind.CLIENT) as span:+ with tracer.start_as_current_span(span_name, kind=SpanKind.CLIENT) as span:start_time = time.time()response = wrapped(*args, **kwargs)- end_time = time.time()try:- # Set base span attribues- span.set_attribute(TELEMETRY_SDK_NAME, "openlit")- span.set_attribute(SemanticConvention.GEN_AI_SYSTEM,- SemanticConvention.GEN_AI_SYSTEM_VLLM)- span.set_attribute(SemanticConvention.GEN_AI_OPERATION,- SemanticConvention.GEN_AI_OPERATION_TYPE_CHAT)- span.set_attribute(SemanticConvention.SERVER_PORT,- server_port)- span.set_attribute(SemanticConvention.GEN_AI_REQUEST_MODEL,- request_model)- span.set_attribute(SemanticConvention.GEN_AI_RESPONSE_MODEL,- request_model)- span.set_attribute(SemanticConvention.SERVER_ADDRESS,- server_address)- span.set_attribute(SemanticConvention.GEN_AI_OUTPUT_TYPE,- "text")-- # Set base span attribues (Extras)- span.set_attribute(DEPLOYMENT_ENVIRONMENT,- environment)- span.set_attribute(SERVICE_NAME,- application_name)- span.set_attribute(SemanticConvention.GEN_AI_REQUEST_IS_STREAM,- False)- span.set_attribute(SemanticConvention.GEN_AI_SERVER_TTFT,- end_time - start_time)- span.set_attribute(SemanticConvention.GEN_AI_SDK_VERSION,- version)-- input_tokens = 0- output_tokens = 0- cost = 0-- if capture_message_content:- prompt_attributes = {}- completion_attributes = {}-- for i, output in enumerate(response):- prompt_attributes[f"{SemanticConvention.GEN_AI_CONTENT_PROMPT}.{i}"] = output.prompt- completion_attributes[f"{SemanticConvention.GEN_AI_CONTENT_COMPLETION}.{i}"] = output.outputs[0].text- input_tokens += general_tokens(output.prompt)- output_tokens += general_tokens(output.outputs[0].text)-- # Add a single event for all prompts- span.add_event(- name=SemanticConvention.GEN_AI_CONTENT_PROMPT_EVENT,- attributes=prompt_attributes,- )-- # Add a single event for all completions- span.add_event(- name=SemanticConvention.GEN_AI_CONTENT_COMPLETION_EVENT,- attributes=completion_attributes,- )-- span.set_attribute(SemanticConvention.GEN_AI_USAGE_INPUT_TOKENS,- input_tokens)- span.set_attribute(SemanticConvention.GEN_AI_USAGE_OUTPUT_TOKENS,- output_tokens)- span.set_attribute(SemanticConvention.GEN_AI_USAGE_TOTAL_TOKENS,- input_tokens + output_tokens)-- # Calculate cost of the operation- cost = get_chat_model_cost(request_model, pricing_info,- input_tokens, output_tokens)- span.set_attribute(SemanticConvention.GEN_AI_USAGE_COST,- cost)-- span.set_status(Status(StatusCode.OK))-- if disable_metrics is False:- attributes = create_metrics_attributes(- service_name=application_name,- deployment_environment=environment,- operation=SemanticConvention.GEN_AI_OPERATION_TYPE_CHAT,- system=SemanticConvention.GEN_AI_SYSTEM_VLLM,- request_model=request_model,- server_address=server_address,- server_port=server_port,- response_model=request_model,- )-- metrics["genai_client_usage_tokens"].record(- input_tokens + output_tokens, attributes- )- metrics["genai_client_operation_duration"].record(- end_time - start_time, attributes- )- metrics["genai_server_ttft"].record(- end_time - start_time, attributes- )- metrics["genai_requests"].add(1, attributes)- metrics["genai_completion_tokens"].add(output_tokens, attributes)- metrics["genai_prompt_tokens"].add(input_tokens, attributes)- metrics["genai_cost"].record(cost, attributes)-- # Return original response- return response-+ response = process_chat_response(+ instance=instance,+ response=response,+ request_model=request_model,+ pricing_info=pricing_info,+ server_port=server_port,+ server_address=server_address,+ environment=environment,+ application_name=application_name,+ metrics=metrics,+ start_time=start_time,+ span=span,+ args=args,+ kwargs=kwargs,+ capture_message_content=capture_message_content,+ disable_metrics=disable_metrics,+ version=version,+ )except Exception as e:handle_exception(span, e)logger.error("Error in trace creation: %s", e)- # Return original response- return response+ return responsereturn wrapper