Skip to content

Same agent Smaller bill. The tools and infrastructure to get more work from your AI. Fewer tokens. Less compute. Lower cost.

[Feat]: Add chat completion parse

Fahad Yousaf3b66966a4b6e
diff --git a/.gitignore b/.gitignore
index 98be4062..346c3a18 100644
--- a/.gitignore
+++ b/.gitignore
@@ -11,3 +11,4 @@ __pycache__/
logs/
.vscode/
+.idea/
\ No newline at end of file
diff --git a/sdk/python/pyproject.toml b/sdk/python/pyproject.toml
index 4f460328..2c666c06 100644
--- a/sdk/python/pyproject.toml
+++ b/sdk/python/pyproject.toml
@@ -1,6 +1,6 @@
[tool.poetry]
name = "openlit"
-version = "1.34.2"
+version = "1.34.3"
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/openai/__init__.py b/sdk/python/src/openlit/instrumentation/openai/__init__.py
index 8aa3855a..05cc840d 100644
--- a/sdk/python/src/openlit/instrumentation/openai/__init__.py
+++ b/sdk/python/src/openlit/instrumentation/openai/__init__.py
@@ -5,9 +5,10 @@ import importlib.metadata
from opentelemetry.instrumentation.instrumentor import BaseInstrumentor
from wrapt import wrap_function_wrapper
-from openlit.instrumentation.openai.openai import chat_completions, embedding, responses
+from openlit.instrumentation.openai.openai import chat_completions, embedding, responses, chat_completions_parse
from openlit.instrumentation.openai.openai import image_generate, image_variatons, audio_create
-from openlit.instrumentation.openai.async_openai import async_chat_completions, async_embedding
+from openlit.instrumentation.openai.async_openai import (async_chat_completions, async_embedding,
+ async_chat_completions_parse)
from openlit.instrumentation.openai.async_openai import async_image_generate, async_image_variatons
from openlit.instrumentation.openai.async_openai import async_audio_create, async_responses
@@ -127,6 +128,20 @@ class OpenAIInstrumentor(BaseInstrumentor):
metrics, disable_metrics),
)
+ wrap_function_wrapper(
+ "openai.resources.beta.chat.completions",
+ "Completions.parse",
+ chat_completions_parse(version, environment, application_name, tracer, pricing_info,
+ capture_message_content, metrics, disable_metrics),
+ )
+
+ wrap_function_wrapper(
+ "openai.resources.beta.chat.completions",
+ "AsyncCompletions.parse",
+ async_chat_completions_parse(version, environment, application_name, tracer, pricing_info,
+ capture_message_content, metrics, disable_metrics),
+ )
+
@staticmethod
def _uninstrument(self, **kwargs):
pass
diff --git a/sdk/python/src/openlit/instrumentation/openai/async_openai.py b/sdk/python/src/openlit/instrumentation/openai/async_openai.py
index 539d7f10..91cf7b54 100644
--- a/sdk/python/src/openlit/instrumentation/openai/async_openai.py
+++ b/sdk/python/src/openlit/instrumentation/openai/async_openai.py
@@ -882,6 +882,167 @@ def async_chat_completions(version, environment, application_name,
return wrapper
+def async_chat_completions_parse(version, environment, application_name, tracer, pricing_info, capture_message_content,
+ metrics, disable_metrics):
+ """
+ Generates a telemetry wrapper for chat completions parse 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 OpenAI API.
+ tracer: OpenTelemetry tracer for creating spans.
+ pricing_info: Information used for calculating the cost of OpenAI usage.
+ capture_message_content: Flag indicating whether to trace the actual content.
+
+ Returns:
+ A function that wraps the chat completions parse method to add telemetry.
+ """
+
+ async def wrapper(wrapped, instance, args, kwargs):
+ """
+ Wraps the 'chat.completions.parse' 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 'chat.completions' method to be wrapped.
+ instance: The instance of the class where the original method is defined.
+ args: Positional arguments for the 'chat.completions' method.
+ kwargs: Keyword arguments for the 'chat.completions' method.
+
+ Returns:
+ The response from the original 'chat.completions.parse' method.
+ """
+ server_address, server_port = set_server_address_and_port(instance, "api.openai.com", 443)
+ request_model = kwargs.get("model", "gpt-4o")
+ span_name = f"{SemanticConvention.GEN_AI_OPERATION_TYPE_CHAT} {request_model}"
+
+ with tracer.start_as_current_span(span_name, kind=SpanKind.CLIENT) as span:
+ start_time = time.time()
+ try:
+ # Execute the original 'parse' method
+ response = await wrapped(*args, **kwargs)
+ end_time = time.time()
+
+ response_dict = response_as_dict(response)
+
+ # Format 'messages' from kwargs to calculate input tokens
+ message_prompt = kwargs.get("messages", "")
+ formatted_messages = []
+ for message in message_prompt:
+ role = message.get("role")
+ content = message.get("content")
+ if content:
+ formatted_messages.append(f"{role}: {content}")
+ prompt = "\n".join(formatted_messages)
+
+ input_tokens = response_dict.get('usage').get('prompt_tokens')
+ output_tokens = response_dict.get('usage').get('completion_tokens')
+
+ # Calculate cost
+ cost = get_chat_model_cost(request_model,
+ pricing_info, input_tokens,
+ output_tokens)
+
+ # Set base span attribues (OTel Semconv)
+ span.set_attribute(TELEMETRY_SDK_NAME, "openlit")
+ span.set_attribute(SemanticConvention.GEN_AI_OPERATION, SemanticConvention.GEN_AI_OPERATION_TYPE_CHAT)
+ span.set_attribute(SemanticConvention.GEN_AI_SYSTEM, SemanticConvention.GEN_AI_SYSTEM_OPENAI)
+ span.set_attribute(SemanticConvention.GEN_AI_REQUEST_MODEL, request_model)
+ span.set_attribute(SemanticConvention.GEN_AI_REQUEST_SEED, str(kwargs.get("seed", "")))
+ span.set_attribute(SemanticConvention.SERVER_PORT, server_port)
+ span.set_attribute(SemanticConvention.GEN_AI_REQUEST_FREQUENCY_PENALTY,
+ str(kwargs.get("frequency_penalty", 0.0)))
+ span.set_attribute(SemanticConvention.GEN_AI_REQUEST_MAX_TOKENS, str(kwargs.get("max_tokens", -1)))
+ span.set_attribute(SemanticConvention.GEN_AI_REQUEST_PRESENCE_PENALTY,
+ str(kwargs.get("presence_penalty", 0.0)))
+ span.set_attribute(SemanticConvention.GEN_AI_REQUEST_STOP_SEQUENCES, str(kwargs.get("stop", [])))
+ span.set_attribute(SemanticConvention.GEN_AI_REQUEST_TEMPERATURE, str(kwargs.get("temperature", 1.0)))
+ span.set_attribute(SemanticConvention.GEN_AI_REQUEST_TOP_P, str(kwargs.get("top_p", 1.0)))
+ span.set_attribute(SemanticConvention.GEN_AI_RESPONSE_ID, response_dict.get("id"))
+ span.set_attribute(SemanticConvention.GEN_AI_RESPONSE_MODEL, response_dict.get('model'))
+ 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.SERVER_ADDRESS, server_address)
+ span.set_attribute(SemanticConvention.GEN_AI_REQUEST_SERVICE_TIER,
+ str(kwargs.get("service_tier", "auto")))
+ span.set_attribute(SemanticConvention.GEN_AI_RESPONSE_SERVICE_TIER,
+ response_dict.get('service_tier', 'auto'))
+ span.set_attribute(SemanticConvention.GEN_AI_RESPONSE_SYSTEM_FINGERPRINT,
+ str(response_dict.get('system_fingerprint', '')))
+
+ # 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_USER, kwargs.get("user", ""))
+ span.set_attribute(SemanticConvention.GEN_AI_SDK_VERSION, version)
+ span.set_attribute(SemanticConvention.GEN_AI_REQUEST_IS_STREAM, False)
+ span.set_attribute(SemanticConvention.GEN_AI_USAGE_TOTAL_TOKENS, input_tokens + output_tokens)
+ span.set_attribute(SemanticConvention.GEN_AI_USAGE_COST, cost)
+ span.set_attribute(SemanticConvention.GEN_AI_SERVER_TTFT, end_time - start_time)
+
+ if capture_message_content:
+ span.add_event(
+ name=SemanticConvention.GEN_AI_CONTENT_PROMPT_EVENT,
+ attributes={SemanticConvention.GEN_AI_CONTENT_PROMPT: prompt},
+ )
+
+ for i in range(kwargs.get('n', 1)):
+ span.set_attribute(SemanticConvention.GEN_AI_RESPONSE_FINISH_REASON,
+ [response_dict.get('choices')[i].get('finish_reason')])
+ if capture_message_content:
+ span.add_event(
+ name=SemanticConvention.GEN_AI_CONTENT_COMPLETION_EVENT,
+ attributes={
+ # pylint: disable=line-too-long
+ SemanticConvention.GEN_AI_CONTENT_COMPLETION: str(
+ response_dict.get('choices')[i].get('message').get('content')),
+ },
+ )
+ if kwargs.get('tools'):
+ span.set_attribute(SemanticConvention.GEN_AI_TOOL_CALLS,
+ str(response_dict.get('choices')[i].get('message').get('tool_calls')))
+
+ if isinstance(response_dict.get('choices')[i].get('message').get('content'), str):
+ span.set_attribute(SemanticConvention.GEN_AI_OUTPUT_TYPE,
+ "text")
+ elif response_dict.get('choices')[i].get('message').get('content') is not None:
+ span.set_attribute(SemanticConvention.GEN_AI_OUTPUT_TYPE,
+ "json")
+
+ span.set_status(Status(StatusCode.OK))
+
+ if not disable_metrics:
+ attributes = create_metrics_attributes(
+ service_name=application_name,
+ deployment_environment=environment,
+ operation=SemanticConvention.GEN_AI_OPERATION_TYPE_CHAT,
+ system=SemanticConvention.GEN_AI_SYSTEM_OPENAI,
+ request_model=request_model,
+ server_address=server_address,
+ server_port=server_port,
+ response_model=response_dict.get('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 response
+
+ except Exception as e:
+ handle_exception(span, e)
+ logger.error("Error in 'parse' trace creation: %s", e)
+ # Re-raise the exception to not interfere with the application flow
+ raise
+
+ return wrapper
+
def async_embedding(version, environment, application_name,
tracer, pricing_info, capture_message_content, metrics, disable_metrics):
"""
diff --git a/sdk/python/src/openlit/instrumentation/openai/openai.py b/sdk/python/src/openlit/instrumentation/openai/openai.py
index e51971d7..85ec01c2 100644
--- a/sdk/python/src/openlit/instrumentation/openai/openai.py
+++ b/sdk/python/src/openlit/instrumentation/openai/openai.py
@@ -882,6 +882,167 @@ def chat_completions(version, environment, application_name,
return wrapper
+def chat_completions_parse(version, environment, application_name, tracer, pricing_info, capture_message_content,
+ metrics, disable_metrics):
+ """
+ Generates a telemetry wrapper for chat completions parse 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 OpenAI API.
+ tracer: OpenTelemetry tracer for creating spans.
+ pricing_info: Information used for calculating the cost of OpenAI usage.
+ capture_message_content: Flag indicating whether to trace the actual content.
+
+ Returns:
+ A function that wraps the chat completions parse method to add telemetry.
+ """
+
+ def wrapper(wrapped, instance, args, kwargs):
+ """
+ Wraps the 'chat.completions.parse' 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 'chat.completions' method to be wrapped.
+ instance: The instance of the class where the original method is defined.
+ args: Positional arguments for the 'chat.completions' method.
+ kwargs: Keyword arguments for the 'chat.completions' method.
+
+ Returns:
+ The response from the original 'chat.completions.parse' method.
+ """
+ server_address, server_port = set_server_address_and_port(instance, "api.openai.com", 443)
+ request_model = kwargs.get("model", "gpt-4o")
+ span_name = f"{SemanticConvention.GEN_AI_OPERATION_TYPE_CHAT} {request_model}"
+
+ with tracer.start_as_current_span(span_name, kind=SpanKind.CLIENT) as span:
+ start_time = time.time()
+ try:
+ # Execute the original 'parse' method
+ response = wrapped(*args, **kwargs)
+ end_time = time.time()
+
+ response_dict = response_as_dict(response)
+
+ # Format 'messages' from kwargs to calculate input tokens
+ message_prompt = kwargs.get("messages", "")
+ formatted_messages = []
+ for message in message_prompt:
+ role = message.get("role")
+ content = message.get("content")
+ if content:
+ formatted_messages.append(f"{role}: {content}")
+ prompt = "\n".join(formatted_messages)
+
+ input_tokens = response_dict.get('usage').get('prompt_tokens')
+ output_tokens = response_dict.get('usage').get('completion_tokens')
+
+ # Calculate cost
+ cost = get_chat_model_cost(request_model,
+ pricing_info, input_tokens,
+ output_tokens)
+
+ # Set base span attribues (OTel Semconv)
+ span.set_attribute(TELEMETRY_SDK_NAME, "openlit")
+ span.set_attribute(SemanticConvention.GEN_AI_OPERATION, SemanticConvention.GEN_AI_OPERATION_TYPE_CHAT)
+ span.set_attribute(SemanticConvention.GEN_AI_SYSTEM, SemanticConvention.GEN_AI_SYSTEM_OPENAI)
+ span.set_attribute(SemanticConvention.GEN_AI_REQUEST_MODEL, request_model)
+ span.set_attribute(SemanticConvention.GEN_AI_REQUEST_SEED, str(kwargs.get("seed", "")))
+ span.set_attribute(SemanticConvention.SERVER_PORT, server_port)
+ span.set_attribute(SemanticConvention.GEN_AI_REQUEST_FREQUENCY_PENALTY,
+ str(kwargs.get("frequency_penalty", 0.0)))
+ span.set_attribute(SemanticConvention.GEN_AI_REQUEST_MAX_TOKENS, str(kwargs.get("max_tokens", -1)))
+ span.set_attribute(SemanticConvention.GEN_AI_REQUEST_PRESENCE_PENALTY,
+ str(kwargs.get("presence_penalty", 0.0)))
+ span.set_attribute(SemanticConvention.GEN_AI_REQUEST_STOP_SEQUENCES, str(kwargs.get("stop", [])))
+ span.set_attribute(SemanticConvention.GEN_AI_REQUEST_TEMPERATURE, str(kwargs.get("temperature", 1.0)))
+ span.set_attribute(SemanticConvention.GEN_AI_REQUEST_TOP_P, str(kwargs.get("top_p", 1.0)))
+ span.set_attribute(SemanticConvention.GEN_AI_RESPONSE_ID, response_dict.get("id"))
+ span.set_attribute(SemanticConvention.GEN_AI_RESPONSE_MODEL, response_dict.get('model'))
+ 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.SERVER_ADDRESS, server_address)
+ span.set_attribute(SemanticConvention.GEN_AI_REQUEST_SERVICE_TIER,
+ str(kwargs.get("service_tier", "auto")))
+ span.set_attribute(SemanticConvention.GEN_AI_RESPONSE_SERVICE_TIER,
+ response_dict.get('service_tier', 'auto'))
+ span.set_attribute(SemanticConvention.GEN_AI_RESPONSE_SYSTEM_FINGERPRINT,
+ str(response_dict.get('system_fingerprint', '')))
+
+ # 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_USER, kwargs.get("user", ""))
+ span.set_attribute(SemanticConvention.GEN_AI_SDK_VERSION, version)
+ span.set_attribute(SemanticConvention.GEN_AI_REQUEST_IS_STREAM, False)
+ span.set_attribute(SemanticConvention.GEN_AI_USAGE_TOTAL_TOKENS, input_tokens + output_tokens)
+ span.set_attribute(SemanticConvention.GEN_AI_USAGE_COST, cost)
+ span.set_attribute(SemanticConvention.GEN_AI_SERVER_TTFT, end_time - start_time)
+
+ if capture_message_content:
+ span.add_event(
+ name=SemanticConvention.GEN_AI_CONTENT_PROMPT_EVENT,
+ attributes={SemanticConvention.GEN_AI_CONTENT_PROMPT: prompt},
+ )
+
+ for i in range(kwargs.get('n', 1)):
+ span.set_attribute(SemanticConvention.GEN_AI_RESPONSE_FINISH_REASON,
+ [response_dict.get('choices')[i].get('finish_reason')])
+ if capture_message_content:
+ span.add_event(
+ name=SemanticConvention.GEN_AI_CONTENT_COMPLETION_EVENT,
+ attributes={
+ # pylint: disable=line-too-long
+ SemanticConvention.GEN_AI_CONTENT_COMPLETION: str(
+ response_dict.get('choices')[i].get('message').get('content')),
+ },
+ )
+ if kwargs.get('tools'):
+ span.set_attribute(SemanticConvention.GEN_AI_TOOL_CALLS,
+ str(response_dict.get('choices')[i].get('message').get('tool_calls')))
+
+ if isinstance(response_dict.get('choices')[i].get('message').get('content'), str):
+ span.set_attribute(SemanticConvention.GEN_AI_OUTPUT_TYPE,
+ "text")
+ elif response_dict.get('choices')[i].get('message').get('content') is not None:
+ span.set_attribute(SemanticConvention.GEN_AI_OUTPUT_TYPE,
+ "json")
+
+ span.set_status(Status(StatusCode.OK))
+
+ if not disable_metrics:
+ attributes = create_metrics_attributes(
+ service_name=application_name,
+ deployment_environment=environment,
+ operation=SemanticConvention.GEN_AI_OPERATION_TYPE_CHAT,
+ system=SemanticConvention.GEN_AI_SYSTEM_OPENAI,
+ request_model=request_model,
+ server_address=server_address,
+ server_port=server_port,
+ response_model=response_dict.get('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 response
+
+ except Exception as e:
+ handle_exception(span, e)
+ logger.error("Error in 'parse' trace creation: %s", e)
+ # Re-raise the exception to not interfere with the application flow
+ raise
+
+ return wrapper
+
def embedding(version, environment, application_name,
tracer, pricing_info, capture_message_content, metrics, disable_metrics):
"""
diff --git a/sdk/python/tests/test_openai.py b/sdk/python/tests/test_openai.py
index 3a47718b..bea1cfba 100644
--- a/sdk/python/tests/test_openai.py
+++ b/sdk/python/tests/test_openai.py
@@ -15,6 +15,7 @@ prior to running these tests.
import pytest
from openai import OpenAI, AsyncOpenAI
+from pydantic import BaseModel
import openlit
# Initialize synchronous OpenAI client
@@ -41,6 +42,30 @@ def test_sync_openai_chat_completions():
)
assert chat_completions_resp.object == 'chat.completion'
+def test_sync_openai_chat_completions_parse():
+ """
+ Tests synchronous chat completions with the 'gpt-3.5-turbo' model.
+
+ Raises:
+ AssertionError: If the chat completion response object is not as expected.
+ """
+
+ class User(BaseModel):
+ """A model to represent a user's details."""
+ name: str
+ age: int
+
+
+ chat_completions_resp = sync_client.beta.chat.completions.parse(
+ model="gpt-4o-mini",
+ messages=[
+ {"role": "system", "content": "Extract the user's name and age from the following text."},
+ {"role": "user", "content": "The user's name is John Doe and he is 30 years old."},
+ ],
+ response_format=User, # Pass the Pydantic model as the response format
+ )
+ assert chat_completions_resp.object == 'chat.completion'
+
def test_sync_openai_embeddings():
"""
Tests synchronous embedding creation with the 'text-embedding-ada-002' model.
@@ -139,6 +164,30 @@ async def test_async_openai_chat_completions():
)
assert chat_completions_resp.object == 'chat.completion'
+async def test_async_openai_chat_completions_parse():
+ """
+ Tests asynchronous chat completions parse with the 'gpt-3.5-turbo' model.
+
+ Raises:
+ AssertionError: If the chat completion parse response object is not as expected.
+ """
+
+ class User(BaseModel):
+ """A model to represent a user's details."""
+ name: str
+ age: int
+
+ chat_completions_resp = await async_client.beta.chat.completions.parse(
+ model="gpt-4o-mini",
+ messages=[
+ {"role": "system", "content": "Extract the user's name and age from the following text."},
+ {"role": "user", "content": "The user's name is John Doe and he is 30 years old."},
+ ],
+ response_format=User, # Pass the Pydantic model as the response format
+ )
+ assert chat_completions_resp.object == 'chat.completion'
+
# @pytest.mark.asyncio
# async def test_async_openai_embeddings():
# """