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 Reka AI OpenTelemetry Monitoring Instrumentation (#768)

Patcher1ceae5357c42
diff --git a/sdk/python/pyproject.toml b/sdk/python/pyproject.toml
index 2c75980c..ae426cb1 100644
--- a/sdk/python/pyproject.toml
+++ b/sdk/python/pyproject.toml
@@ -1,6 +1,6 @@
[tool.poetry]
name = "openlit"
-version = "1.34.5"
+version = "1.34.6"
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/reka/__init__.py b/sdk/python/src/openlit/instrumentation/reka/__init__.py
index ff1a6495..ef71ecf5 100644
--- a/sdk/python/src/openlit/instrumentation/reka/__init__.py
+++ b/sdk/python/src/openlit/instrumentation/reka/__init__.py
@@ -1,4 +1,3 @@
-# pylint: disable=useless-return, bad-staticmethod-argument, disable=duplicate-code
"""Initializer of Auto Instrumentation of Reka Functions"""
from typing import Collection
@@ -17,15 +16,15 @@ _instruments = ("reka-api >= 3.2.0",)
class RekaInstrumentor(BaseInstrumentor):
"""
- An instrumentor for Reka's client library.
+ An instrumentor for Reka 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", {})
@@ -33,7 +32,7 @@ class RekaInstrumentor(BaseInstrumentor):
disable_metrics = kwargs.get("disable_metrics")
version = importlib.metadata.version("reka-api")
- # sync chat
+ # Chat completions
wrap_function_wrapper(
"reka.chat.client",
"ChatClient.create",
@@ -41,7 +40,7 @@ class RekaInstrumentor(BaseInstrumentor):
tracer, pricing_info, capture_message_content, metrics, disable_metrics),
)
- # async chat
+ # Chat completions
wrap_function_wrapper(
"reka.chat.client",
"AsyncChatClient.create",
@@ -50,5 +49,4 @@ class RekaInstrumentor(BaseInstrumentor):
)
def _uninstrument(self, **kwargs):
- # Proper uninstrumentation logic to revert patched methods
pass
diff --git a/sdk/python/src/openlit/instrumentation/reka/async_reka.py b/sdk/python/src/openlit/instrumentation/reka/async_reka.py
index 267f73e7..dad31f9b 100644
--- a/sdk/python/src/openlit/instrumentation/reka/async_reka.py
+++ b/sdk/python/src/openlit/instrumentation/reka/async_reka.py
@@ -2,53 +2,26 @@
Module for monitoring Reka 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,
handle_exception,
- create_metrics_attributes,
set_server_address_and_port
)
+from openlit.instrumentation.reka.utils import (
+ process_chat_response
+)
from openlit.semcov import SemanticConvention
-# Initialize logger for logging potential issues and operations
-logger = logging.getLogger(__name__)
-
def async_chat(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 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 Reka API.
- tracer: OpenTelemetry tracer for creating spans.
- pricing_info: Information used for calculating the cost of Reka usage.
- capture_message_content: Flag indicating whether to trace the actual content.
-
- Returns:
- A function that wraps the chat method to add telemetry.
+ Generates a telemetry wrapper for GenAI function call
"""
async def wrapper(wrapped, instance, args, kwargs):
"""
- Wraps the 'chat' 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' method to be wrapped.
- instance: The instance of the class where the original method is defined.
- args: Positional arguments for the 'chat' method.
- kwargs: Keyword arguments for the 'chat' method.
-
- Returns:
- The response from the original 'chat' method.
+ Wraps the GenAI function call.
"""
server_address, server_port = set_server_address_and_port(instance, "api.reka.ai", 443)
@@ -56,142 +29,32 @@ def async_chat(version, environment, application_name,
span_name = f"{SemanticConvention.GEN_AI_OPERATION_TYPE_CHAT} {request_model}"
- 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 = await wrapped(*args, **kwargs)
- end_time = time.time()
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.usage.input_tokens
- output_tokens = response.usage.output_tokens
+ 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
+ )
- # Calculate cost of the operation
- cost = get_chat_model_cost(request_model,
- pricing_info, input_tokens, output_tokens)
-
- # Set Span attributes (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_REKAAI)
- span.set_attribute(SemanticConvention.GEN_AI_REQUEST_MODEL,
- request_model)
- span.set_attribute(SemanticConvention.SERVER_PORT,
- server_port)
- span.set_attribute(SemanticConvention.GEN_AI_REQUEST_SEED,
- kwargs.get("seed", ""))
- span.set_attribute(SemanticConvention.GEN_AI_REQUEST_MAX_TOKENS,
- kwargs.get("max_tokens", -1))
- span.set_attribute(SemanticConvention.GEN_AI_REQUEST_STOP_SEQUENCES,
- kwargs.get("stop", []))
- span.set_attribute(SemanticConvention.GEN_AI_REQUEST_PRESENCE_PENALTY,
- kwargs.get("presence_penalty", 0.0))
- span.set_attribute(SemanticConvention.GEN_AI_REQUEST_TEMPERATURE,
- kwargs.get("temperature", 0.4))
- span.set_attribute(SemanticConvention.GEN_AI_REQUEST_TOP_K,
- kwargs.get("top_k", 1.0))
- span.set_attribute(SemanticConvention.GEN_AI_REQUEST_TOP_P,
- kwargs.get("top_p", 1.0))
- span.set_attribute(SemanticConvention.GEN_AI_RESPONSE_FINISH_REASON,
- [response.responses[0].finish_reason])
- 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_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_OUTPUT_TYPE,
- 'text')
-
- # Set Span attributes (Extra)
- 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_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,
- },
- )
- span.add_event(
- name=SemanticConvention.GEN_AI_CONTENT_COMPLETION_EVENT,
- attributes={
- SemanticConvention.GEN_AI_CONTENT_COMPLETION: response.responses[0].message.content,
- },
- )
-
- 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_REKAAI,
- request_model=request_model,
- server_address=server_address,
- server_port=server_port,
- response_model=response.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
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/reka/reka.py b/sdk/python/src/openlit/instrumentation/reka/reka.py
index 695f5843..5c5a3eaa 100644
--- a/sdk/python/src/openlit/instrumentation/reka/reka.py
+++ b/sdk/python/src/openlit/instrumentation/reka/reka.py
@@ -2,53 +2,26 @@
Module for monitoring Reka 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,
handle_exception,
- create_metrics_attributes,
set_server_address_and_port
)
+from openlit.instrumentation.reka.utils import (
+ process_chat_response
+)
from openlit.semcov import SemanticConvention
-# Initialize logger for logging potential issues and operations
-logger = logging.getLogger(__name__)
-
def chat(version, environment, application_name,
tracer, pricing_info, capture_message_content, metrics, disable_metrics):
"""
- Generates a telemetry wrapper for chat 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 Reka API.
- tracer: OpenTelemetry tracer for creating spans.
- pricing_info: Information used for calculating the cost of Reka usage.
- capture_message_content: Flag indicating whether to trace the actual content.
-
- Returns:
- A function that wraps the chat method to add telemetry.
+ Generates a telemetry wrapper for GenAI function call
"""
def wrapper(wrapped, instance, args, kwargs):
"""
- Wraps the 'chat' 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' method to be wrapped.
- instance: The instance of the class where the original method is defined.
- args: Positional arguments for the 'chat' method.
- kwargs: Keyword arguments for the 'chat' method.
-
- Returns:
- The response from the original 'chat' method.
+ Wraps the GenAI function call.
"""
server_address, server_port = set_server_address_and_port(instance, "api.reka.ai", 443)
@@ -56,142 +29,32 @@ def chat(version, environment, application_name,
span_name = f"{SemanticConvention.GEN_AI_OPERATION_TYPE_CHAT} {request_model}"
- 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:
- # 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.usage.input_tokens
- output_tokens = response.usage.output_tokens
+ 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
+ )
- # Calculate cost of the operation
- cost = get_chat_model_cost(request_model,
- pricing_info, input_tokens, output_tokens)
-
- # Set Span attributes (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_REKAAI)
- span.set_attribute(SemanticConvention.GEN_AI_REQUEST_MODEL,
- request_model)
- span.set_attribute(SemanticConvention.SERVER_PORT,
- server_port)
- span.set_attribute(SemanticConvention.GEN_AI_REQUEST_SEED,
- kwargs.get("seed", ""))
- span.set_attribute(SemanticConvention.GEN_AI_REQUEST_MAX_TOKENS,
- kwargs.get("max_tokens", -1))
- span.set_attribute(SemanticConvention.GEN_AI_REQUEST_STOP_SEQUENCES,
- kwargs.get("stop", []))
- span.set_attribute(SemanticConvention.GEN_AI_REQUEST_PRESENCE_PENALTY,
- kwargs.get("presence_penalty", 0.0))
- span.set_attribute(SemanticConvention.GEN_AI_REQUEST_TEMPERATURE,
- kwargs.get("temperature", 0.4))
- span.set_attribute(SemanticConvention.GEN_AI_REQUEST_TOP_K,
- kwargs.get("top_k", 1.0))
- span.set_attribute(SemanticConvention.GEN_AI_REQUEST_TOP_P,
- kwargs.get("top_p", 1.0))
- span.set_attribute(SemanticConvention.GEN_AI_RESPONSE_FINISH_REASON,
- [response.responses[0].finish_reason])
- 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_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_OUTPUT_TYPE,
- 'text')
-
- # Set Span attributes (Extra)
- 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_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,
- },
- )
- span.add_event(
- name=SemanticConvention.GEN_AI_CONTENT_COMPLETION_EVENT,
- attributes={
- SemanticConvention.GEN_AI_CONTENT_COMPLETION: response.responses[0].message.content,
- },
- )
-
- 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_REKAAI,
- request_model=request_model,
- server_address=server_address,
- server_port=server_port,
- response_model=response.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
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/reka/utils.py b/sdk/python/src/openlit/instrumentation/reka/utils.py
new file mode 100644
index 00000000..9ce9279e
--- /dev/null
+++ b/sdk/python/src/openlit/instrumentation/reka/utils.py
@@ -0,0 +1,193 @@
+"""
+Reka 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 (
+ response_as_dict,
+ calculate_tbt,
+ get_chat_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 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 is not None:
+ metrics["genai_server_tbt"].record(tbt, attributes)
+ if ttft is not None:
+ 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", "reka-core-20240501")
+
+ 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_REKAAI,
+ 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_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", 0.4))
+ scope._span.set_attribute(SemanticConvention.GEN_AI_REQUEST_TOP_K, scope._kwargs.get("top_k", 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("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("parameters","")))
+
+ # 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_REKAAI,
+ 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_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("responses", [])
+ )
+ scope._response_id = response_dict.get("id")
+ scope._response_model = response_dict.get("model")
+ scope._input_tokens = response_dict.get("usage").get("input_tokens")
+ scope._output_tokens = response_dict.get("usage").get("output_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("responses")[0].get("finish_reason"))
+ if scope._kwargs.get("tools"):
+ scope._tools = response_dict.get("responses")[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
diff --git a/sdk/python/src/openlit/instrumentation/together/utils.py b/sdk/python/src/openlit/instrumentation/together/utils.py
index e98f0b71..8b213622 100644
--- a/sdk/python/src/openlit/instrumentation/together/utils.py
+++ b/sdk/python/src/openlit/instrumentation/together/utils.py
@@ -1,5 +1,5 @@
"""
-Google AI Studio OpenTelemetry instrumentation utility functions
+Together AI OpenTelemetry instrumentation utility functions
"""
import time
@@ -111,9 +111,9 @@ def record_common_metrics(metrics, gen_ai_operation, gen_ai_system, server_addre
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:
+ if tbt is not None:
metrics["genai_server_tbt"].record(tbt, attributes)
- if ttft:
+ if ttft is not None:
metrics["genai_server_ttft"].record(ttft, attributes)
def common_chat_logic(scope, pricing_info, environment, application_name, metrics,