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]: Refactor Together AI OpenTelemetry Instrumentation (#766)

Patcherc98c6371f69a
diff --git a/sdk/python/.pylintrc b/sdk/python/.pylintrc
index a5563435..c670ade6 100644
--- a/sdk/python/.pylintrc
+++ b/sdk/python/.pylintrc
@@ -10,7 +10,7 @@ max-args=25
max-positional-arguments=16
# Maximum allowed line length
-max-line-length=125
+max-line-length=135
# Maximum number of instance attributes
max-attributes=25
@@ -30,4 +30,5 @@ disable=
bare-except,
expression-not-assigned,
unnecessary-direct-lambda-call,
- no-member
\ No newline at end of file
+ no-member,
+ no-else-return
\ No newline at end of file
diff --git a/sdk/python/pyproject.toml b/sdk/python/pyproject.toml
index e180858c..2c75980c 100644
--- a/sdk/python/pyproject.toml
+++ b/sdk/python/pyproject.toml
@@ -1,6 +1,6 @@
[tool.poetry]
name = "openlit"
-version = "1.34.4"
+version = "1.34.5"
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/__init__.py b/sdk/python/src/openlit/instrumentation/google_ai_studio/__init__.py
index 09880208..5f13bbca 100644
--- a/sdk/python/src/openlit/instrumentation/google_ai_studio/__init__.py
+++ b/sdk/python/src/openlit/instrumentation/google_ai_studio/__init__.py
@@ -1,4 +1,3 @@
-# pylint: disable=useless-return, bad-staticmethod-argument, disable=duplicate-code
"""Initializer of Auto Instrumentation of Google AI Studio Functions"""
from typing import Collection
@@ -25,8 +24,8 @@ class GoogleAIStudioInstrumentor(BaseInstrumentor):
return _instruments
def _instrument(self, **kwargs):
- application_name = kwargs.get("application_name", "default_application")
- environment = kwargs.get("environment", "default_environment")
+ application_name = kwargs.get("application_name", "default")
+ environment = kwargs.get("environment", "default")
tracer = kwargs.get("tracer")
metrics = kwargs.get("metrics_dict")
pricing_info = kwargs.get("pricing_info", {})
@@ -67,5 +66,4 @@ class GoogleAIStudioInstrumentor(BaseInstrumentor):
)
def _uninstrument(self, **kwargs):
- # Proper uninstrumentation logic to revert patched methods
pass
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.py
index 9a574ba0..b9070c55 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
@@ -2,7 +2,6 @@
Module for monitoring Google AI Studio API calls.
"""
-import logging
import time
from opentelemetry.trace import SpanKind
from openlit.__helpers import (
@@ -16,9 +15,6 @@ from openlit.instrumentation.google_ai_studio.utils import (
)
from openlit.semcov import SemanticConvention
-# Initialize logger for logging potential issues and operations
-logger = logging.getLogger(__name__)
-
def async_generate(version, environment, application_name,
tracer, pricing_info, capture_message_content, metrics, disable_metrics):
"""
@@ -61,7 +57,6 @@ def async_generate(version, environment, application_name,
except Exception as e:
handle_exception(span, e)
- logger.error("Error in trace creation: %s", e)
# Return original response
return response
@@ -144,7 +139,6 @@ def async_generate_stream(version, environment, application_name,
except Exception as e:
handle_exception(self._span, e)
- logger.error("Error in trace creation: %s", e)
raise
async def wrapper(wrapped, instance, args, kwargs):
diff --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.py
index 2c6c8b15..13234572 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
@@ -2,7 +2,6 @@
Module for monitoring Google AI Studio API calls.
"""
-import logging
import time
from opentelemetry.trace import SpanKind
from openlit.__helpers import (
@@ -16,9 +15,6 @@ from openlit.instrumentation.google_ai_studio.utils import (
)
from openlit.semcov import SemanticConvention
-# Initialize logger for logging potential issues and operations
-logger = logging.getLogger(__name__)
-
def generate(version, environment, application_name,
tracer, pricing_info, capture_message_content, metrics, disable_metrics):
"""
@@ -61,7 +57,6 @@ def generate(version, environment, application_name,
except Exception as e:
handle_exception(span, e)
- logger.error("Error in trace creation: %s", e)
# Return original response
return response
@@ -144,7 +139,6 @@ def generate_stream(version, environment, application_name,
except Exception as e:
handle_exception(self._span, e)
- logger.error("Error in trace creation: %s", e)
raise
def wrapper(wrapped, instance, args, kwargs):
diff --git a/sdk/python/src/openlit/instrumentation/google_ai_studio/utils.py b/sdk/python/src/openlit/instrumentation/google_ai_studio/utils.py
index cad85156..efd2fb0a 100644
--- a/sdk/python/src/openlit/instrumentation/google_ai_studio/utils.py
+++ b/sdk/python/src/openlit/instrumentation/google_ai_studio/utils.py
@@ -15,8 +15,7 @@ from openlit.semcov import SemanticConvention
def format_content(messages):
"""
- Process a list of messages to extract content, categorize them by role,
- and concatenate all 'content' fields into a single string with role: content format.
+ Process a list of messages to extract content.
"""
formatted_messages = []
diff --git a/sdk/python/src/openlit/instrumentation/together/__init__.py b/sdk/python/src/openlit/instrumentation/together/__init__.py
index a60c5af9..7035e799 100644
--- a/sdk/python/src/openlit/instrumentation/together/__init__.py
+++ b/sdk/python/src/openlit/instrumentation/together/__init__.py
@@ -1,4 +1,3 @@
-# pylint: disable=useless-return, bad-staticmethod-argument, disable=duplicate-code
"""Initializer of Auto Instrumentation of Together AI Functions"""
from typing import Collection
@@ -17,15 +16,15 @@ _instruments = ("together >= 1.3.5",)
class TogetherInstrumentor(BaseInstrumentor):
"""
- An instrumentor for Together's client library.
+ An instrumentor for Together client library.
"""
def instrumentation_dependencies(self) -> Collection[str]:
return _instruments
def _instrument(self, **kwargs):
- application_name = kwargs.get("application_name", "default_application")
- environment = kwargs.get("environment", "default_environment")
+ application_name = kwargs.get("application_name", "default")
+ environment = kwargs.get("environment", "default")
tracer = kwargs.get("tracer")
metrics = kwargs.get("metrics_dict")
pricing_info = kwargs.get("pricing_info", {})
@@ -66,5 +65,4 @@ class TogetherInstrumentor(BaseInstrumentor):
)
def _uninstrument(self, **kwargs):
- # Proper uninstrumentation logic to revert patched methods
pass
diff --git a/sdk/python/src/openlit/instrumentation/together/async_together.py b/sdk/python/src/openlit/instrumentation/together/async_together.py
index 6d7645b4..e35f1d55 100644
--- a/sdk/python/src/openlit/instrumentation/together/async_together.py
+++ b/sdk/python/src/openlit/instrumentation/together/async_together.py
@@ -1,58 +1,37 @@
"""
-Module for monitoring Together calls.
+Module for monitoring Together API calls.
"""
-import logging
import time
-from opentelemetry.trace import SpanKind, Status, StatusCode
-from opentelemetry.sdk.resources import SERVICE_NAME, TELEMETRY_SDK_NAME, DEPLOYMENT_ENVIRONMENT
+from opentelemetry.trace import SpanKind
from openlit.__helpers import (
- get_chat_model_cost,
- get_image_model_cost,
handle_exception,
- response_as_dict,
- calculate_ttft,
- calculate_tbt,
- create_metrics_attributes,
set_server_address_and_port
)
+from openlit.instrumentation.together.utils import (
+ process_chat_response,
+ process_chunk,
+ process_streaming_chat_response,
+ process_image_response
+)
from openlit.semcov import SemanticConvention
-# Initialize logger for logging potential issues and operations
-logger = logging.getLogger(__name__)
-
def async_completion(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 chat completions 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 Together AI API.
- tracer: OpenTelemetry tracer for creating spans.
- pricing_info: Information used for calculating the cost of Together AI usage.
- capture_message_content: Flag indicating whether to trace the actual content.
-
- Returns:
- A function that wraps the chat completions method to add telemetry.
+ Generates a telemetry wrapper for GenAI function call
"""
class TracedAsyncStream:
"""
- Wrapper for streaming responses to collect metrics and trace data.
- Wraps the response to collect message IDs and aggregated response.
-
- This class implements the '__aiter__' and '__anext__' methods that
- handle asynchronous streaming responses.
-
- This class also implements '__aenter__' and '__aexit__' methods that
- handle asynchronous context management protocol.
+ Wrapper for streaming responses to collect telemetry.
"""
+
def __init__(
self,
wrapped,
span,
+ span_name,
kwargs,
server_address,
server_port,
@@ -60,14 +39,14 @@ def async_completion(version, environment, application_name,
):
self.__wrapped__ = wrapped
self._span = span
- # Placeholder for aggregating streaming response
+ self._span_name = span_name
self._llmresponse = ""
self._response_id = ""
self._response_model = ""
- self._finish_reason = ""
self._input_tokens = 0
self._output_tokens = 0
-
+ self._finish_reason = ""
+ self._tools = None
self._args = args
self._kwargs = kwargs
self._start_time = time.time()
@@ -95,401 +74,86 @@ def async_completion(version, environment, application_name,
async def __anext__(self):
try:
chunk = await self.__wrapped__.__anext__()
- end_time = time.time()
- # Record the timestamp for the current chunk
- self._timestamps.append(end_time)
-
- if len(self._timestamps) == 1:
- # Calculate time to first chunk
- self._ttft = calculate_ttft(self._timestamps, self._start_time)
-
- chunked = response_as_dict(chunk)
- # Collect message IDs and aggregated response from events
- if (len(chunked.get('choices')) > 0 and ('delta' in chunked.get('choices')[0] and
- 'content' in chunked.get('choices')[0].get('delta'))):
-
- content = chunked.get('choices')[0].get('delta').get('content')
- if content:
- self._llmresponse += content
-
- if chunked.get('usage'):
- self._response_id = chunked.get('id')
- self._response_model = chunked.get('model')
- self._finish_reason = str(chunked.get('choices')[0].get('finish_reason'))
- self._input_tokens = chunked.get('usage').get('prompt_tokens')
- self._output_tokens = chunked.get('usage').get('completion_tokens')
-
+ process_chunk(self, chunk)
return chunk
- except StopAsyncIteration:
- # Handling exception ensure observability without disrupting operation
+ except StopIteration:
try:
- self._end_time = time.time()
- if len(self._timestamps) > 1:
- self._tbt = calculate_tbt(self._timestamps)
-
- # Format 'messages' into a single string
- message_prompt = self._kwargs.get("messages", "")
- formatted_messages = []
- for message in message_prompt:
- role = message["role"]
- content = message["content"]
-
- if isinstance(content, list):
- content_str_list = []
- for item in content:
- if item["type"] == "text":
- content_str_list.append(f'text: {item["text"]}')
- elif (item["type"] == "image_url" and
- not item["image_url"]["url"].startswith("data:")):
- content_str_list.append(f'image_url: {item["image_url"]["url"]}')
- content_str = ", ".join(content_str_list)
- formatted_messages.append(f"{role}: {content_str}")
- else:
- formatted_messages.append(f"{role}: {content}")
- prompt = "\n".join(formatted_messages)
-
- request_model = self._kwargs.get("model", "gpt-4o")
-
- # Calculate cost of the operation
- cost = get_chat_model_cost(request_model,
- pricing_info, self._input_tokens,
- self._output_tokens)
-
- # Set Span attributes (OTel Semconv)
- self._span.set_attribute(TELEMETRY_SDK_NAME, "openlit")
- self._span.set_attribute(SemanticConvention.GEN_AI_OPERATION,
- SemanticConvention.GEN_AI_OPERATION_TYPE_CHAT)
- self._span.set_attribute(SemanticConvention.GEN_AI_SYSTEM,
- SemanticConvention.GEN_AI_SYSTEM_TOGETHER)
- self._span.set_attribute(SemanticConvention.GEN_AI_REQUEST_MODEL,
- request_model)
- self._span.set_attribute(SemanticConvention.GEN_AI_REQUEST_SEED,
- self._kwargs.get("seed", ""))
- self._span.set_attribute(SemanticConvention.SERVER_PORT,
- self._server_port)
- self._span.set_attribute(SemanticConvention.GEN_AI_REQUEST_FREQUENCY_PENALTY,
- self._kwargs.get("frequency_penalty", 0.0))
- self._span.set_attribute(SemanticConvention.GEN_AI_REQUEST_MAX_TOKENS,
- self._kwargs.get("max_tokens", -1))
- self._span.set_attribute(SemanticConvention.GEN_AI_REQUEST_PRESENCE_PENALTY,
- self._kwargs.get("presence_penalty", 0.0))
- self._span.set_attribute(SemanticConvention.GEN_AI_REQUEST_STOP_SEQUENCES,
- self._kwargs.get("stop", []))
- self._span.set_attribute(SemanticConvention.GEN_AI_REQUEST_TEMPERATURE,
- self._kwargs.get("temperature", 1.0))
- self._span.set_attribute(SemanticConvention.GEN_AI_REQUEST_TOP_P,
- self._kwargs.get("top_p", 1.0))
- self._span.set_attribute(SemanticConvention.GEN_AI_RESPONSE_FINISH_REASON,
- [self._finish_reason])
- self._span.set_attribute(SemanticConvention.GEN_AI_RESPONSE_ID,
- self._response_id)
- self._span.set_attribute(SemanticConvention.GEN_AI_RESPONSE_MODEL,
- self._response_model)
- self._span.set_attribute(SemanticConvention.GEN_AI_USAGE_INPUT_TOKENS,
- self._input_tokens)
- self._span.set_attribute(SemanticConvention.GEN_AI_USAGE_OUTPUT_TOKENS,
- self._output_tokens)
- self._span.set_attribute(SemanticConvention.SERVER_ADDRESS,
- self._server_address)
-
- if isinstance(self._llmresponse, str):
- self._span.set_attribute(SemanticConvention.GEN_AI_OUTPUT_TYPE,
- "text")
- else:
- self._span.set_attribute(SemanticConvention.GEN_AI_OUTPUT_TYPE,
- "json")
-
- # Set Span attributes (Extra)
- self._span.set_attribute(DEPLOYMENT_ENVIRONMENT,
- environment)
- self._span.set_attribute(SERVICE_NAME,
- application_name)
- self._span.set_attribute(SemanticConvention.GEN_AI_REQUEST_USER,
- self._kwargs.get("user", ""))
- self._span.set_attribute(SemanticConvention.GEN_AI_REQUEST_IS_STREAM,
- True)
- self._span.set_attribute(SemanticConvention.GEN_AI_USAGE_TOTAL_TOKENS,
- self._input_tokens + self._output_tokens)
- self._span.set_attribute(SemanticConvention.GEN_AI_USAGE_COST,
- cost)
- self._span.set_attribute(SemanticConvention.GEN_AI_SERVER_TBT,
- self._tbt)
- self._span.set_attribute(SemanticConvention.GEN_AI_SERVER_TTFT,
- self._ttft)
- self._span.set_attribute(SemanticConvention.GEN_AI_SDK_VERSION,
- version)
- if capture_message_content:
- self._span.add_event(
- name=SemanticConvention.GEN_AI_CONTENT_PROMPT_EVENT,
- attributes={
- SemanticConvention.GEN_AI_CONTENT_PROMPT: prompt,
- },
- )
- self._span.add_event(
- name=SemanticConvention.GEN_AI_CONTENT_COMPLETION_EVENT,
- attributes={
- SemanticConvention.GEN_AI_CONTENT_COMPLETION: self._llmresponse,
- },
- )
- self._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_TOGETHER,
- request_model=request_model,
- server_address=self._server_address,
- server_port=self._server_port,
- response_model=self._response_model,
- )
-
- metrics["genai_client_usage_tokens"].record(
- self._input_tokens + self._output_tokens, attributes
- )
- metrics["genai_client_operation_duration"].record(
- self._end_time - self._start_time, attributes
- )
- metrics["genai_server_tbt"].record(
- self._tbt, attributes
- )
- metrics["genai_server_ttft"].record(
- self._ttft, attributes
+ with tracer.start_as_current_span(self._span_name, kind= SpanKind.CLIENT) as self._span:
+ process_streaming_chat_response(
+ self,
+ pricing_info=pricing_info,
+ environment=environment,
+ application_name=application_name,
+ metrics=metrics,
+ capture_message_content=capture_message_content,
+ disable_metrics=disable_metrics,
+ version=version
)
- metrics["genai_requests"].add(1, attributes)
- metrics["genai_completion_tokens"].add(self._output_tokens, attributes)
- metrics["genai_prompt_tokens"].add(self._input_tokens, attributes)
- metrics["genai_cost"].record(cost, attributes)
except Exception as e:
handle_exception(self._span, e)
- logger.error("Error in trace creation: %s", e)
- finally:
- self._span.end()
+
raise
+
async def wrapper(wrapped, instance, args, kwargs):
"""
- Wraps the 'chat.completions' 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' method.
+ Wraps the GenAI function call.
"""
# Check if streaming is enabled for the API call
streaming = kwargs.get("stream", False)
+
server_address, server_port = set_server_address_and_port(instance, "api.together.xyz", 443)
request_model = kwargs.get("model", "gpt-4o")
span_name = f"{SemanticConvention.GEN_AI_OPERATION_TYPE_CHAT} {request_model}"
- # pylint: disable=no-else-return
if streaming:
# Special handling for streaming response to accommodate the nature of data flow
awaited_wrapped = await wrapped(*args, **kwargs)
span = tracer.start_span(span_name, kind=SpanKind.CLIENT)
-
- return TracedAsyncStream(awaited_wrapped, span, kwargs, server_address, server_port)
+ return TracedAsyncStream(awaited_wrapped, span, span_name, kwargs, server_address, server_port)
# Handling for non-streaming responses
else:
with tracer.start_as_current_span(span_name, kind= SpanKind.CLIENT) as span:
start_time = time.time()
response = await wrapped(*args, **kwargs)
- end_time = time.time()
-
- response_dict = response_as_dict(response)
try:
- # Format 'messages' into a single string
- message_prompt = kwargs.get("messages", "")
- formatted_messages = []
- for message in message_prompt:
- role = message["role"]
- content = message["content"]
-
- if isinstance(content, list):
- content_str = ", ".join(
- f'{item["type"]}: {item["text"] if "text" in item else item["image_url"]}'
- if "type" in item else f'text: {item["text"]}'
- for item in content
- )
- formatted_messages.append(f"{role}: {content_str}")
- else:
- 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 of the operation
- 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_TOGETHER)
- span.set_attribute(SemanticConvention.GEN_AI_REQUEST_MODEL,
- request_model)
- span.set_attribute(SemanticConvention.GEN_AI_REQUEST_SEED,
- kwargs.get("seed", ""))
- span.set_attribute(SemanticConvention.SERVER_PORT,
- server_port)
- span.set_attribute(SemanticConvention.GEN_AI_REQUEST_FREQUENCY_PENALTY,
- kwargs.get("frequency_penalty", 0.0))
- span.set_attribute(SemanticConvention.GEN_AI_REQUEST_MAX_TOKENS,
- kwargs.get("max_tokens", -1))
- span.set_attribute(SemanticConvention.GEN_AI_REQUEST_PRESENCE_PENALTY,
- kwargs.get("presence_penalty", 0.0))
- span.set_attribute(SemanticConvention.GEN_AI_REQUEST_STOP_SEQUENCES,
- kwargs.get("stop", []))
- span.set_attribute(SemanticConvention.GEN_AI_REQUEST_TEMPERATURE,
- kwargs.get("temperature", 1.0))
- span.set_attribute(SemanticConvention.GEN_AI_REQUEST_TOP_P,
- 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)
-
- # 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_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)
- span.set_attribute(SemanticConvention.GEN_AI_SDK_VERSION,
- version)
- 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,
- [str(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 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_TOGETHER,
- 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 original response
- return response
+ response = process_chat_response(
+ 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,
+ capture_message_content=capture_message_content,
+ disable_metrics=disable_metrics,
+ version=version,
+ **kwargs
+ )
except Exception as e:
handle_exception(span, e)
- logger.error("Error in trace creation: %s", e)
- # Return original response
- return response
+ return response
return wrapper
def async_image_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 image generation 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 Together AI API.
- tracer: OpenTelemetry tracer for creating spans.
- pricing_info: Information used for calculating the cost of Together AI image generation.
- capture_message_content: Flag indicating whether to trace the input prompt and generated images.
-
- Returns:
- A function that wraps the image generation method to add telemetry.
+ Generates a telemetry wrapper for GenAI function call
"""
async def wrapper(wrapped, instance, args, kwargs):
"""
- Wraps the 'images.generate' API call to add telemetry.
-
- This collects metrics such as execution time, cost, and handles errors
- gracefully, adding details to the trace for observability.
-
- Args:
- wrapped: The original 'images.generate' method to be wrapped.
- instance: The instance of the class where the original method is defined.
- args: Positional arguments for the 'images.generate' method.
- kwargs: Keyword arguments for the 'images.generate' method.
-
- Returns:
- The response from the original 'images.generate' method.
+ Wraps the GenAI function call.
"""
server_address, server_port = set_server_address_and_port(instance, "api.together.xyz", 443)
@@ -502,99 +166,29 @@ def async_image_generate(version, environment, application_name,
response = await wrapped(*args, **kwargs)
end_time = time.time()
- images_count = 0
-
try:
- # Find Image format
- if "response_format" in kwargs and kwargs["response_format"] == "b64_json":
- image = "b64_json"
- else:
- image = "url"
-
- image_size = str(kwargs.get('width')) + 'x' + str(kwargs.get('height'))
-
- # Calculate cost of the operation
- cost = get_image_model_cost(request_model,
- pricing_info, image_size,
- kwargs.get("quality", "standard"))
-
- for items in response.data:
- # Set Span attributes (OTel Semconv)
- span.set_attribute(TELEMETRY_SDK_NAME, "openlit")
- span.set_attribute(SemanticConvention.GEN_AI_OPERATION,
- SemanticConvention.GEN_AI_OPERATION_TYPE_IMAGE)
- span.set_attribute(SemanticConvention.GEN_AI_SYSTEM,
- SemanticConvention.GEN_AI_SYSTEM_TOGETHER)
- span.set_attribute(SemanticConvention.GEN_AI_REQUEST_MODEL,
- request_model)
- span.set_attribute(SemanticConvention.SERVER_ADDRESS,
- server_address)
- span.set_attribute(SemanticConvention.SERVER_PORT,
- server_port)
- span.set_attribute(SemanticConvention.GEN_AI_RESPONSE_ID,
- response.id)
- span.set_attribute(SemanticConvention.GEN_AI_RESPONSE_MODEL,
- response.model)
- span.set_attribute(SemanticConvention.GEN_AI_OUTPUT_TYPE,
- "image")
-
- # Set Span attributes (Extras)
- span.set_attribute(DEPLOYMENT_ENVIRONMENT,
- environment)
- span.set_attribute(SERVICE_NAME,
- application_name)
- span.set_attribute(SemanticConvention.GEN_AI_REQUEST_IMAGE_SIZE,
- image_size)
- span.set_attribute(SemanticConvention.GEN_AI_SDK_VERSION,
- version)
-
- if capture_message_content:
- span.add_event(
- name=SemanticConvention.GEN_AI_CONTENT_PROMPT_EVENT,
- attributes={
- SemanticConvention.GEN_AI_CONTENT_PROMPT: kwargs.get("prompt", ""),
- },
- )
- attribute_name = f"{SemanticConvention.GEN_AI_RESPONSE_IMAGE}.{images_count}"
- span.add_event(
- name=attribute_name,
- attributes={
- SemanticConvention.GEN_AI_CONTENT_COMPLETION: getattr(items, image),
- },
- )
+ response = process_image_response(
+ response=response,
+ request_model=request_model,
+ pricing_info=pricing_info,
+ server_address=server_address,
+ server_port=server_port,
+ environment=environment,
+ application_name=application_name,
+ metrics=metrics,
+ start_time=start_time,
+ end_time=end_time,
+ span=span,
+ capture_message_content=capture_message_content,
+ disable_metrics=disable_metrics,
+ version=version,
+ **kwargs
+ )
- images_count+=1
-
- span.set_attribute(SemanticConvention.GEN_AI_USAGE_COST,
- len(response.data) * 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_IMAGE,
- system=SemanticConvention.GEN_AI_SYSTEM_TOGETHER,
- request_model=request_model,
- server_address=server_address,
- server_port=server_port,
- response_model=response.model,
- )
-
- metrics["genai_client_operation_duration"].record(
- end_time - start_time, attributes
- )
- metrics["genai_requests"].add(1, attributes)
- metrics["genai_cost"].record(cost, attributes)
-
- # 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
diff --git a/sdk/python/src/openlit/instrumentation/together/together.py b/sdk/python/src/openlit/instrumentation/together/together.py
index 0fced46c..390f578e 100644
--- a/sdk/python/src/openlit/instrumentation/together/together.py
+++ b/sdk/python/src/openlit/instrumentation/together/together.py
@@ -1,58 +1,37 @@
"""
-Module for monitoring Together calls.
+Module for monitoring Together API calls.
"""
-import logging
import time
-from opentelemetry.trace import SpanKind, Status, StatusCode
-from opentelemetry.sdk.resources import SERVICE_NAME, TELEMETRY_SDK_NAME, DEPLOYMENT_ENVIRONMENT
+from opentelemetry.trace import SpanKind
from openlit.__helpers import (
- get_chat_model_cost,
- get_image_model_cost,
handle_exception,
- response_as_dict,
- calculate_ttft,
- calculate_tbt,
- create_metrics_attributes,
set_server_address_and_port
)
+from openlit.instrumentation.together.utils import (
+ process_chat_response,
+ process_chunk,
+ process_streaming_chat_response,
+ process_image_response
+)
from openlit.semcov import SemanticConvention
-# Initialize logger for logging potential issues and operations
-logger = logging.getLogger(__name__)
-
def completion(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 chat completions 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 Together AI API.
- tracer: OpenTelemetry tracer for creating spans.
- pricing_info: Information used for calculating the cost of Together AI usage.
- capture_message_content: Flag indicating whether to trace the actual content.
-
- Returns:
- A function that wraps the chat completions method to add telemetry.
+ Generates a telemetry wrapper for GenAI function call
"""
class TracedSyncStream:
"""
- Wrapper for streaming responses to collect metrics and trace data.
- Wraps the response to collect message IDs and aggregated response.
-
- This class implements the '__aiter__' and '__anext__' methods that
- handle asynchronous streaming responses.
-
- This class also implements '__aenter__' and '__aexit__' methods that
- handle asynchronous context management protocol.
+ Wrapper for streaming responses to collect telemetry.
"""
+
def __init__(
self,
wrapped,
span,
+ span_name,
kwargs,
server_address,
server_port,
@@ -60,14 +39,14 @@ def completion(version, environment, application_name,
):
self.__wrapped__ = wrapped
self._span = span
- # Placeholder for aggregating streaming response
+ self._span_name = span_name
self._llmresponse = ""
self._response_id = ""
self._response_model = ""
- self._finish_reason = ""
self._input_tokens = 0
self._output_tokens = 0
-
+ self._finish_reason = ""
+ self._tools = None
self._args = args
self._kwargs = kwargs
self._start_time = time.time()
@@ -95,401 +74,86 @@ def completion(version, environment, application_name,
def __next__(self):
try:
chunk = self.__wrapped__.__next__()
- end_time = time.time()
- # Record the timestamp for the current chunk
- self._timestamps.append(end_time)
-
- if len(self._timestamps) == 1:
- # Calculate time to first chunk
- self._ttft = calculate_ttft(self._timestamps, self._start_time)
-
- chunked = response_as_dict(chunk)
- # Collect message IDs and aggregated response from events
- if (len(chunked.get('choices')) > 0 and ('delta' in chunked.get('choices')[0] and
- 'content' in chunked.get('choices')[0].get('delta'))):
-
- content = chunked.get('choices')[0].get('delta').get('content')
- if content:
- self._llmresponse += content
-
- if chunked.get('usage'):
- self._response_id = chunked.get('id')
- self._response_model = chunked.get('model')
- self._finish_reason = str(chunked.get('choices')[0].get('finish_reason'))
- self._input_tokens = chunked.get('usage').get('prompt_tokens')
- self._output_tokens = chunked.get('usage').get('completion_tokens')
-
+ process_chunk(self, chunk)
return chunk
except StopIteration:
- # Handling exception ensure observability without disrupting operation
try:
- self._end_time = time.time()
- if len(self._timestamps) > 1:
- self._tbt = calculate_tbt(self._timestamps)
-
- # Format 'messages' into a single string
- message_prompt = self._kwargs.get("messages", "")
- formatted_messages = []
- for message in message_prompt:
- role = message["role"]
- content = message["content"]
-
- if isinstance(content, list):
- content_str_list = []
- for item in content:
- if item["type"] == "text":
- content_str_list.append(f'text: {item["text"]}')
- elif (item["type"] == "image_url" and
- not item["image_url"]["url"].startswith("data:")):
- content_str_list.append(f'image_url: {item["image_url"]["url"]}')
- content_str = ", ".join(content_str_list)
- formatted_messages.append(f"{role}: {content_str}")
- else:
- formatted_messages.append(f"{role}: {content}")
- prompt = "\n".join(formatted_messages)
-
- request_model = self._kwargs.get("model", "gpt-4o")
-
- # Calculate cost of the operation
- cost = get_chat_model_cost(request_model,
- pricing_info, self._input_tokens,
- self._output_tokens)
-
- # Set Span attributes (OTel Semconv)
- self._span.set_attribute(TELEMETRY_SDK_NAME, "openlit")
- self._span.set_attribute(SemanticConvention.GEN_AI_OPERATION,
- SemanticConvention.GEN_AI_OPERATION_TYPE_CHAT)
- self._span.set_attribute(SemanticConvention.GEN_AI_SYSTEM,
- SemanticConvention.GEN_AI_SYSTEM_TOGETHER)
- self._span.set_attribute(SemanticConvention.GEN_AI_REQUEST_MODEL,
- request_model)
- self._span.set_attribute(SemanticConvention.GEN_AI_REQUEST_SEED,
- self._kwargs.get("seed", ""))
- self._span.set_attribute(SemanticConvention.SERVER_PORT,
- self._server_port)
- self._span.set_attribute(SemanticConvention.GEN_AI_REQUEST_FREQUENCY_PENALTY,
- self._kwargs.get("frequency_penalty", 0.0))
- self._span.set_attribute(SemanticConvention.GEN_AI_REQUEST_MAX_TOKENS,
- self._kwargs.get("max_tokens", -1))
- self._span.set_attribute(SemanticConvention.GEN_AI_REQUEST_PRESENCE_PENALTY,
- self._kwargs.get("presence_penalty", 0.0))
- self._span.set_attribute(SemanticConvention.GEN_AI_REQUEST_STOP_SEQUENCES,
- self._kwargs.get("stop", []))
- self._span.set_attribute(SemanticConvention.GEN_AI_REQUEST_TEMPERATURE,
- self._kwargs.get("temperature", 1.0))
- self._span.set_attribute(SemanticConvention.GEN_AI_REQUEST_TOP_P,
- self._kwargs.get("top_p", 1.0))
- self._span.set_attribute(SemanticConvention.GEN_AI_RESPONSE_FINISH_REASON,
- [self._finish_reason])
- self._span.set_attribute(SemanticConvention.GEN_AI_RESPONSE_ID,
- self._response_id)
- self._span.set_attribute(SemanticConvention.GEN_AI_RESPONSE_MODEL,
- self._response_model)
- self._span.set_attribute(SemanticConvention.GEN_AI_USAGE_INPUT_TOKENS,
- self._input_tokens)
- self._span.set_attribute(SemanticConvention.GEN_AI_USAGE_OUTPUT_TOKENS,
- self._output_tokens)
- self._span.set_attribute(SemanticConvention.SERVER_ADDRESS,
- self._server_address)
-
- if isinstance(self._llmresponse, str):
- self._span.set_attribute(SemanticConvention.GEN_AI_OUTPUT_TYPE,
- "text")
- else:
- self._span.set_attribute(SemanticConvention.GEN_AI_OUTPUT_TYPE,
- "json")
-
- # Set Span attributes (Extra)
- self._span.set_attribute(DEPLOYMENT_ENVIRONMENT,
- environment)
- self._span.set_attribute(SERVICE_NAME,
- application_name)
- self._span.set_attribute(SemanticConvention.GEN_AI_REQUEST_USER,
- self._kwargs.get("user", ""))
- self._span.set_attribute(SemanticConvention.GEN_AI_REQUEST_IS_STREAM,
- True)
- self._span.set_attribute(SemanticConvention.GEN_AI_USAGE_TOTAL_TOKENS,
- self._input_tokens + self._output_tokens)
- self._span.set_attribute(SemanticConvention.GEN_AI_USAGE_COST,
- cost)
- self._span.set_attribute(SemanticConvention.GEN_AI_SERVER_TBT,
- self._tbt)
- self._span.set_attribute(SemanticConvention.GEN_AI_SERVER_TTFT,
- self._ttft)
- self._span.set_attribute(SemanticConvention.GEN_AI_SDK_VERSION,
- version)
- if capture_message_content:
- self._span.add_event(
- name=SemanticConvention.GEN_AI_CONTENT_PROMPT_EVENT,
- attributes={
- SemanticConvention.GEN_AI_CONTENT_PROMPT: prompt,
- },
- )
- self._span.add_event(
- name=SemanticConvention.GEN_AI_CONTENT_COMPLETION_EVENT,
- attributes={
- SemanticConvention.GEN_AI_CONTENT_COMPLETION: self._llmresponse,
- },
- )
- self._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_TOGETHER,
- request_model=request_model,
- server_address=self._server_address,
- server_port=self._server_port,
- response_model=self._response_model,
- )
-
- metrics["genai_client_usage_tokens"].record(
- self._input_tokens + self._output_tokens, attributes
- )
- metrics["genai_client_operation_duration"].record(
- self._end_time - self._start_time, attributes
- )
- metrics["genai_server_tbt"].record(
- self._tbt, attributes
- )
- metrics["genai_server_ttft"].record(
- self._ttft, attributes
+ with tracer.start_as_current_span(self._span_name, kind= SpanKind.CLIENT) as self._span:
+ process_streaming_chat_response(
+ self,
+ pricing_info=pricing_info,
+ environment=environment,
+ application_name=application_name,
+ metrics=metrics,
+ capture_message_content=capture_message_content,
+ disable_metrics=disable_metrics,
+ version=version
)
- metrics["genai_requests"].add(1, attributes)
- metrics["genai_completion_tokens"].add(self._output_tokens, attributes)
- metrics["genai_prompt_tokens"].add(self._input_tokens, attributes)
- metrics["genai_cost"].record(cost, attributes)
except Exception as e:
handle_exception(self._span, e)
- logger.error("Error in trace creation: %s", e)
- finally:
- self._span.end()
+
raise
+
def wrapper(wrapped, instance, args, kwargs):
"""
- Wraps the 'chat.completions' 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' method.
+ Wraps the GenAI function call.
"""
# Check if streaming is enabled for the API call
streaming = kwargs.get("stream", False)
+
server_address, server_port = set_server_address_and_port(instance, "api.together.xyz", 443)
request_model = kwargs.get("model", "gpt-4o")
span_name = f"{SemanticConvention.GEN_AI_OPERATION_TYPE_CHAT} {request_model}"
- # pylint: disable=no-else-return
if streaming:
# Special handling for streaming response to accommodate the nature of data flow
awaited_wrapped = wrapped(*args, **kwargs)
span = tracer.start_span(span_name, kind=SpanKind.CLIENT)
-
- return TracedSyncStream(awaited_wrapped, span, kwargs, server_address, server_port)
+ return TracedSyncStream(awaited_wrapped, span, span_name, kwargs, server_address, server_port)
# Handling for non-streaming responses
else:
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()
-
- response_dict = response_as_dict(response)
try:
- # Format 'messages' into a single string
- message_prompt = kwargs.get("messages", "")
- formatted_messages = []
- for message in message_prompt:
- role = message["role"]
- content = message["content"]
-
- if isinstance(content, list):
- content_str = ", ".join(
- f'{item["type"]}: {item["text"] if "text" in item else item["image_url"]}'
- if "type" in item else f'text: {item["text"]}'
- for item in content
- )
- formatted_messages.append(f"{role}: {content_str}")
- else:
- 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 of the operation
- 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_TOGETHER)
- span.set_attribute(SemanticConvention.GEN_AI_REQUEST_MODEL,
- request_model)
- span.set_attribute(SemanticConvention.GEN_AI_REQUEST_SEED,
- kwargs.get("seed", ""))
- span.set_attribute(SemanticConvention.SERVER_PORT,
- server_port)
- span.set_attribute(SemanticConvention.GEN_AI_REQUEST_FREQUENCY_PENALTY,
- kwargs.get("frequency_penalty", 0.0))
- span.set_attribute(SemanticConvention.GEN_AI_REQUEST_MAX_TOKENS,
- kwargs.get("max_tokens", -1))
- span.set_attribute(SemanticConvention.GEN_AI_REQUEST_PRESENCE_PENALTY,
- kwargs.get("presence_penalty", 0.0))
- span.set_attribute(SemanticConvention.GEN_AI_REQUEST_STOP_SEQUENCES,
- kwargs.get("stop", []))
- span.set_attribute(SemanticConvention.GEN_AI_REQUEST_TEMPERATURE,
- kwargs.get("temperature", 1.0))
- span.set_attribute(SemanticConvention.GEN_AI_REQUEST_TOP_P,
- 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)
-
- # 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_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)
- span.set_attribute(SemanticConvention.GEN_AI_SDK_VERSION,
- version)
- 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,
- [str(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 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_TOGETHER,
- 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 original response
- return response
+ response = process_chat_response(
+ 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,
+ capture_message_content=capture_message_content,
+ disable_metrics=disable_metrics,
+ version=version,
+ **kwargs
+ )
except Exception as e:
handle_exception(span, e)
- logger.error("Error in trace creation: %s", e)
- # Return original response
- return response
+ return response
return wrapper
def image_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 image generation 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 Together AI API.
- tracer: OpenTelemetry tracer for creating spans.
- pricing_info: Information used for calculating the cost of Together AI image generation.
- capture_message_content: Flag indicating whether to trace the input prompt and generated images.
-
- Returns:
- A function that wraps the image generation method to add telemetry.
+ Generates a telemetry wrapper for GenAI function call
"""
def wrapper(wrapped, instance, args, kwargs):
"""
- Wraps the 'images.generate' API call to add telemetry.
-
- This collects metrics such as execution time, cost, and handles errors
- gracefully, adding details to the trace for observability.
-
- Args:
- wrapped: The original 'images.generate' method to be wrapped.
- instance: The instance of the class where the original method is defined.
- args: Positional arguments for the 'images.generate' method.
- kwargs: Keyword arguments for the 'images.generate' method.
-
- Returns:
- The response from the original 'images.generate' method.
+ Wraps the GenAI function call.
"""
server_address, server_port = set_server_address_and_port(instance, "api.together.xyz", 443)
@@ -502,99 +166,29 @@ def image_generate(version, environment, application_name,
response = wrapped(*args, **kwargs)
end_time = time.time()
- images_count = 0
-
try:
- # Find Image format
- if "response_format" in kwargs and kwargs["response_format"] == "b64_json":
- image = "b64_json"
- else:
- image = "url"
-
- image_size = str(kwargs.get('width')) + 'x' + str(kwargs.get('height'))
-
- # Calculate cost of the operation
- cost = get_image_model_cost(request_model,
- pricing_info, image_size,
- kwargs.get("quality", "standard"))
-
- for items in response.data:
- # Set Span attributes (OTel Semconv)
- span.set_attribute(TELEMETRY_SDK_NAME, "openlit")
- span.set_attribute(SemanticConvention.GEN_AI_OPERATION,
- SemanticConvention.GEN_AI_OPERATION_TYPE_IMAGE)
- span.set_attribute(SemanticConvention.GEN_AI_SYSTEM,
- SemanticConvention.GEN_AI_SYSTEM_TOGETHER)
- span.set_attribute(SemanticConvention.GEN_AI_REQUEST_MODEL,
- request_model)
- span.set_attribute(SemanticConvention.SERVER_ADDRESS,
- server_address)
- span.set_attribute(SemanticConvention.SERVER_PORT,
- server_port)
- span.set_attribute(SemanticConvention.GEN_AI_RESPONSE_ID,
- response.id)
- span.set_attribute(SemanticConvention.GEN_AI_RESPONSE_MODEL,
- response.model)
- span.set_attribute(SemanticConvention.GEN_AI_OUTPUT_TYPE,
- "image")
-
- # Set Span attributes (Extras)
- span.set_attribute(DEPLOYMENT_ENVIRONMENT,
- environment)
- span.set_attribute(SERVICE_NAME,
- application_name)
- span.set_attribute(SemanticConvention.GEN_AI_REQUEST_IMAGE_SIZE,
- image_size)
- span.set_attribute(SemanticConvention.GEN_AI_SDK_VERSION,
- version)
-
- if capture_message_content:
- span.add_event(
- name=SemanticConvention.GEN_AI_CONTENT_PROMPT_EVENT,
- attributes={
- SemanticConvention.GEN_AI_CONTENT_PROMPT: kwargs.get("prompt", ""),
- },
- )
- attribute_name = f"{SemanticConvention.GEN_AI_RESPONSE_IMAGE}.{images_count}"
- span.add_event(
- name=attribute_name,
- attributes={
- SemanticConvention.GEN_AI_CONTENT_COMPLETION: getattr(items, image),
- },
- )
+ response = process_image_response(
+ response=response,
+ request_model=request_model,
+ pricing_info=pricing_info,
+ server_address=server_address,
+ server_port=server_port,
+ environment=environment,
+ application_name=application_name,
+ metrics=metrics,
+ start_time=start_time,
+ end_time=end_time,
+ span=span,
+ capture_message_content=capture_message_content,
+ disable_metrics=disable_metrics,
+ version=version,
+ **kwargs
+ )
- images_count+=1
-
- span.set_attribute(SemanticConvention.GEN_AI_USAGE_COST,
- len(response.data) * 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_IMAGE,
- system=SemanticConvention.GEN_AI_SYSTEM_TOGETHER,
- request_model=request_model,
- server_address=server_address,
- server_port=server_port,
- response_model=response.model,
- )
-
- metrics["genai_client_operation_duration"].record(
- end_time - start_time, attributes
- )
- metrics["genai_requests"].add(1, attributes)
- metrics["genai_cost"].record(cost, attributes)
-
- # 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
diff --git a/sdk/python/src/openlit/instrumentation/together/utils.py b/sdk/python/src/openlit/instrumentation/together/utils.py
new file mode 100644
index 00000000..e98f0b71
--- /dev/null
+++ b/sdk/python/src/openlit/instrumentation/together/utils.py
@@ -0,0 +1,320 @@
+"""
+Google AI Studio OpenTelemetry instrumentation utility functions
+"""
+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_ttft,
+ response_as_dict,
+ calculate_tbt,
+ get_chat_model_cost,
+ get_image_model_cost,
+ create_metrics_attributes,
+)
+from openlit.semcov import SemanticConvention
+
+def format_content(messages):
+ """
+ Process a list of messages to extract content.
+ """
+
+ formatted_messages = []
+ for message in messages:
+ role = message["role"]
+ content = message["content"]
+
+ if isinstance(content, list):
+ content_str = ", ".join(
+ f'{item["type"]}: {item["text"] if "text" in item else item["image_url"]}'
+ if "type" in item else f'text: {item["text"]}'
+ for item in content
+ )
+ formatted_messages.append(f"{role}: {content_str}")
+ else:
+ formatted_messages.append(f"{role}: {content}")
+
+ return "\n".join(formatted_messages)
+
+def process_chunk(scope, chunk):
+ """
+ Process a chunk of response data and update state.
+ """
+
+ end_time = time.time()
+ # Record the timestamp for the current chunk
+ scope._timestamps.append(end_time)
+
+ if len(scope._timestamps) == 1:
+ # Calculate time to first chunk
+ scope._ttft = calculate_ttft(scope._timestamps, scope._start_time)
+
+ chunked = response_as_dict(chunk)
+ # Collect message IDs and aggregated response from events
+ if (len(chunked.get("choices")) > 0 and ("delta" in chunked.get("choices")[0] and
+ "content" in chunked.get("choices")[0].get("delta"))):
+
+ content = chunked.get("choices")[0].get("delta").get("content")
+ if content:
+ scope._llmresponse += content
+
+ if chunked.get("usage"):
+ scope._response_id = chunked.get("id")
+ scope._response_model = chunked.get("model")
+ scope._input_tokens = chunked.get("usage").get("prompt_tokens")
+ scope._output_tokens = chunked.get("usage").get("completion_tokens")
+ scope._finish_reason = str(chunked.get("finish_reason"))
+ scope._end_time = time.time()
+
+def common_span_attributes(scope, gen_ai_operation, gen_ai_system, server_address, server_port,
+ request_model, response_model, environment, application_name, is_stream, tbt, ttft, version):
+ """
+ Set common span attributes for both chat and RAG operations.
+ """
+
+ scope._span.set_attribute(TELEMETRY_SDK_NAME, "openlit")
+ scope._span.set_attribute(SemanticConvention.GEN_AI_OPERATION, gen_ai_operation)
+ scope._span.set_attribute(SemanticConvention.GEN_AI_SYSTEM, gen_ai_system)
+ scope._span.set_attribute(SemanticConvention.SERVER_ADDRESS, server_address)
+ scope._span.set_attribute(SemanticConvention.SERVER_PORT, server_port)
+ scope._span.set_attribute(SemanticConvention.GEN_AI_REQUEST_MODEL, request_model)
+ scope._span.set_attribute(SemanticConvention.GEN_AI_RESPONSE_MODEL, scope._response_model)
+ 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)
+
+def record_common_metrics(metrics, gen_ai_operation, gen_ai_system, server_address, server_port,
+ request_model, response_model, environment, application_name, start_time, end_time,
+ input_tokens, output_tokens, cost, tbt=None, ttft=None):
+ """
+ Record common metrics for the operation.
+ """
+
+ attributes = create_metrics_attributes(
+ operation=gen_ai_operation,
+ system=gen_ai_system,
+ server_address=server_address,
+ server_port=server_port,
+ request_model=request_model,
+ response_model=response_model,
+ service_name=application_name,
+ deployment_environment=environment,
+ )
+ metrics["genai_client_operation_duration"].record(end_time - start_time, attributes)
+ metrics["genai_requests"].add(1, attributes)
+ metrics["genai_prompt_tokens"].add(input_tokens, attributes)
+ metrics["genai_completion_tokens"].add(output_tokens, attributes)
+ metrics["genai_client_usage_tokens"].record(input_tokens + output_tokens, attributes)
+ metrics["genai_cost"].record(cost, attributes)
+ if tbt:
+ metrics["genai_server_tbt"].record(tbt, attributes)
+ if ttft:
+ metrics["genai_server_ttft"].record(ttft, attributes)
+
+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
+ """
+
+ if len(scope._timestamps) > 1:
+ scope._tbt = calculate_tbt(scope._timestamps)
+
+ prompt = format_content(scope._kwargs.get("messages", ""))
+ request_model = scope._kwargs.get("model", "jamba-1.5-mini")
+
+ cost = get_chat_model_cost(request_model, pricing_info, scope._input_tokens, scope._output_tokens)
+
+ # Common Span Attributes
+ common_span_attributes(scope,
+ SemanticConvention.GEN_AI_OPERATION_TYPE_CHAT,SemanticConvention.GEN_AI_SYSTEM_TOGETHER,
+ scope._server_address, scope._server_port, request_model, scope._response_model,
+ environment, application_name, is_stream, scope._tbt, scope._ttft, version)
+
+ # Span Attributes for Response parameters
+ scope._span.set_attribute(SemanticConvention.GEN_AI_RESPONSE_FINISH_REASON, [scope._finish_reason])
+ scope._span.set_attribute(SemanticConvention.GEN_AI_REQUEST_SEED, scope._kwargs.get("seed", ""))
+ scope._span.set_attribute(SemanticConvention.GEN_AI_REQUEST_FREQUENCY_PENALTY, scope._kwargs.get("frequency_penalty", 0.0))
+ scope._span.set_attribute(SemanticConvention.GEN_AI_REQUEST_MAX_TOKENS, scope._kwargs.get("max_tokens", -1))
+ scope._span.set_attribute(SemanticConvention.GEN_AI_REQUEST_PRESENCE_PENALTY, scope._kwargs.get("presence_penalty", 0.0))
+ scope._span.set_attribute(SemanticConvention.GEN_AI_REQUEST_STOP_SEQUENCES, scope._kwargs.get("stop", []))
+ scope._span.set_attribute(SemanticConvention.GEN_AI_REQUEST_TEMPERATURE, scope._kwargs.get("temperature", 1.0))
+ scope._span.set_attribute(SemanticConvention.GEN_AI_REQUEST_TOP_P, scope._kwargs.get("top_p", 1.0))
+ scope._span.set_attribute(SemanticConvention.GEN_AI_RESPONSE_ID, scope._response_id)
+ scope._span.set_attribute(SemanticConvention.GEN_AI_OUTPUT_TYPE, "text" if isinstance(scope._llmresponse, str) else "json")
+
+ # Span Attributes for Cost and Tokens
+ scope._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_CLIENT_TOKEN_USAGE, scope._input_tokens + scope._output_tokens)
+ scope._span.set_attribute(SemanticConvention.GEN_AI_USAGE_COST, cost)
+
+ # Span Attributes for Tools
+ if scope._tools:
+ scope._span.set_attribute(SemanticConvention.GEN_AI_TOOL_NAME, scope._tools.get("function","")).get("name","")
+ scope._span.set_attribute(SemanticConvention.GEN_AI_TOOL_CALL_ID, str(scope._tools.get("id","")))
+ scope._span.set_attribute(SemanticConvention.GEN_AI_TOOL_ARGS, str(scope._tools.get("function","").get("arguments","")))
+
+ # Span Attributes for Content
+ if capture_message_content:
+ scope._span.set_attribute(SemanticConvention.GEN_AI_CONTENT_PROMPT, prompt)
+ scope._span.set_attribute(SemanticConvention.GEN_AI_CONTENT_COMPLETION, scope._llmresponse)
+
+ # To be removed one the change to span_attributes (from span events) is complete
+ scope._span.add_event(
+ name=SemanticConvention.GEN_AI_CONTENT_PROMPT_EVENT,
+ attributes={
+ SemanticConvention.GEN_AI_CONTENT_PROMPT: prompt,
+ },
+ )
+ scope._span.add_event(
+ name=SemanticConvention.GEN_AI_CONTENT_COMPLETION_EVENT,
+ attributes={
+ SemanticConvention.GEN_AI_CONTENT_COMPLETION: scope._llmresponse,
+ },
+ )
+
+ scope._span.set_status(Status(StatusCode.OK))
+
+ # Metrics
+ if not disable_metrics:
+ record_common_metrics(metrics, SemanticConvention.GEN_AI_OPERATION_TYPE_CHAT, SemanticConvention.GEN_AI_SYSTEM_TOGETHER,
+ scope._server_address, scope._server_port, request_model, scope._response_model, environment,
+ application_name, scope._start_time, scope._end_time, scope._input_tokens, scope._output_tokens,
+ cost, scope._tbt, scope._ttft)
+
+def process_streaming_chat_response(scope, pricing_info, environment, application_name, metrics,
+ capture_message_content=False, disable_metrics=False, version=""):
+ """
+ Process chat request and generate Telemetry
+ """
+ common_chat_logic(scope, pricing_info, environment, application_name, metrics,
+ capture_message_content, disable_metrics, version, is_stream=True)
+
+def process_chat_response(response, request_model, pricing_info, server_port, server_address,
+ environment, application_name, metrics, start_time, span, capture_message_content=False,
+ disable_metrics=False, version="1.0.0", **kwargs):
+ """
+ Process chat request and generate Telemetry
+ """
+
+ scope = type("GenericScope", (), {})()
+ response_dict = response_as_dict(response)
+
+ scope._start_time = start_time
+ scope._end_time = time.time()
+ scope._span = span
+ scope._llmresponse = " ".join(
+ (choice.get("message", {}).get("content") or "")
+ for choice in response_dict.get("choices", [])
+ )
+ scope._response_id = response_dict.get("id")
+ scope._response_model = response_dict.get("model")
+ scope._input_tokens = response_dict.get("usage").get("prompt_tokens")
+ scope._output_tokens = response_dict.get("usage").get("completion_tokens")
+ scope._timestamps = []
+ scope._ttft, scope._tbt = scope._end_time - scope._start_time, 0
+ scope._server_address, scope._server_port = server_address, server_port
+ scope._kwargs = kwargs
+ scope._finish_reason = str(response_dict.get("choices")[0].get("finish_reason"))
+
+ if scope._kwargs.get("tools"):
+ scope._tools = response_dict.get("choices")[0].get("message").get("tool_calls")
+ else:
+ scope._tools = None
+
+ common_chat_logic(scope, pricing_info, environment, application_name, metrics,
+ capture_message_content, disable_metrics, version, is_stream=False)
+
+ return response
+
+def common_image_logic(scope, pricing_info, environment, application_name, metrics,
+ capture_message_content, disable_metrics, version):
+ """
+ Process image generation request and generate Telemetry
+ """
+
+ # Find Image format
+ if "response_format" in scope._kwargs and scope._kwargs["response_format"] == "b64_json":
+ image_format = "b64_json"
+ else:
+ image_format = "url"
+
+ image_size = str(scope._kwargs.get("width", "1024")) + "x" + str(scope._kwargs.get("height", "1024"))
+ request_model = scope._kwargs.get("model", "dall-e-2")
+
+ # Calculate cost of the operation
+ cost = get_image_model_cost(request_model, pricing_info, image_size,
+ scope._kwargs.get("quality", "standard"))
+
+ # Common Span Attributes
+ common_span_attributes(scope,
+ SemanticConvention.GEN_AI_OPERATION_TYPE_IMAGE, SemanticConvention.GEN_AI_SYSTEM_TOGETHER,
+ scope._server_address, scope._server_port, request_model, scope._response_model,
+ environment, application_name, False, scope._tbt, scope._ttft, version)
+
+ # Image-specific span attributes
+ scope._span.set_attribute(SemanticConvention.GEN_AI_RESPONSE_ID, scope._response_id)
+ scope._span.set_attribute(SemanticConvention.GEN_AI_OUTPUT_TYPE, "image")
+ scope._span.set_attribute(SemanticConvention.GEN_AI_REQUEST_IMAGE_SIZE, image_size)
+ scope._span.set_attribute(SemanticConvention.GEN_AI_USAGE_COST, len(scope._response_data) * cost)
+
+ # Content attributes
+ if capture_message_content:
+ scope._span.add_event(
+ name=SemanticConvention.GEN_AI_CONTENT_PROMPT_EVENT,
+ attributes={
+ SemanticConvention.GEN_AI_CONTENT_PROMPT: scope._kwargs.get("prompt", ""),
+ },
+ )
+
+ for images_count, item in enumerate(scope._response_data):
+ attribute_name = f"{SemanticConvention.GEN_AI_RESPONSE_IMAGE}.{images_count}"
+ scope._span.add_event(
+ name=attribute_name,
+ attributes={
+ SemanticConvention.GEN_AI_CONTENT_COMPLETION: getattr(item, image_format),
+ },
+ )
+
+ scope._span.set_status(Status(StatusCode.OK))
+
+ # Metrics
+ if not disable_metrics:
+ record_common_metrics(
+ metrics, SemanticConvention.GEN_AI_OPERATION_TYPE_IMAGE,
+ SemanticConvention.GEN_AI_SYSTEM_TOGETHER, scope._server_address, scope._server_port,
+ request_model, scope._response_model, environment, application_name,
+ scope._start_time, scope._end_time, 0, 0, len(scope._response_data) * cost
+ )
+
+def process_image_response(response, request_model, pricing_info, server_address, server_port,
+ environment, application_name, metrics, start_time, end_time, span, capture_message_content,
+ disable_metrics, version, **kwargs):
+ """
+ Process image generation request and generate Telemetry
+ """
+
+ scope = type("GenericScope", (), {})()
+
+ scope._start_time = start_time
+ scope._end_time = end_time
+ scope._span = span
+ scope._response_id = response.id
+ scope._response_model = response.model
+ scope._response_data = response.data
+ scope._server_address = server_address
+ scope._server_port = server_port
+ scope._kwargs = kwargs
+ scope._tbt = 0
+ scope._ttft = end_time - start_time
+
+ common_image_logic(scope, pricing_info, environment, application_name, metrics,
+ capture_message_content, disable_metrics, version)
+
+ return response
diff --git a/sdk/python/tests/test_together.py b/sdk/python/tests/test_together.py
index eda58878..5330b210 100644
--- a/sdk/python/tests/test_together.py
+++ b/sdk/python/tests/test_together.py
@@ -1,4 +1,3 @@
-# pylint: disable=duplicate-code, no-name-in-module, broad-exception-caught
"""
This module contains tests for Together functionality using the Together Python library.