Same agent Smaller bill. The tools and infrastructure to get more work from your AI. Fewer tokens. Less compute. Lower cost.
TypeScript agent-harnessagent-harness-engineeringai-engineeringai-observabilityamd-gpuclaude-codeclickhousecodexcoding-agentcoding-agentscursorgenaigpu-monitoringllm-observabilityllmopsnvidia-smiobservabilityopen-sourceopenaiopentelemetry
[Feat]: Refactor Gemini Instrumentation and fix bugs (#732)
Patcher8832e0212264
diff --git a/sdk/python/.pylintrc b/sdk/python/.pylintrcindex 8c45d179..a5563435 100644--- a/sdk/python/.pylintrc+++ b/sdk/python/.pylintrc@@ -10,7 +10,7 @@ max-args=25max-positional-arguments=16# Maximum allowed line length-max-line-length=120+max-line-length=125# Maximum number of instance attributesmax-attributes=25@@ -29,4 +29,5 @@ disable=protected-access,bare-except,expression-not-assigned,- unnecessary-direct-lambda-call\ No newline at end of file+ unnecessary-direct-lambda-call,+ no-member\ No newline at end of filediff --git a/sdk/python/pyproject.toml b/sdk/python/pyproject.tomlindex 042557ce..5a78d796 100644--- a/sdk/python/pyproject.toml+++ b/sdk/python/pyproject.toml@@ -1,6 +1,6 @@[tool.poetry]name = "openlit"-version = "1.33.21"+version = "1.33.22"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__.pyindex 3e9f8450..09880208 100644--- a/sdk/python/src/openlit/instrumentation/google_ai_studio/__init__.py+++ b/sdk/python/src/openlit/instrumentation/google_ai_studio/__init__.py@@ -7,11 +7,11 @@ from opentelemetry.instrumentation.instrumentor import BaseInstrumentorfrom wrapt import wrap_function_wrapperfrom openlit.instrumentation.google_ai_studio.google_ai_studio import (- generate+ generate, generate_stream)from openlit.instrumentation.google_ai_studio.async_google_ai_studio import (- async_generate+ async_generate, async_generate_stream)_instruments = ("google-genai >= 1.3.0",)@@ -39,16 +39,31 @@ class GoogleAIStudioInstrumentor(BaseInstrumentor):"google.genai.models","Models.generate_content",generate(version, environment, application_name,- tracer, pricing_info, capture_message_content, metrics, disable_metrics),+ tracer, pricing_info, capture_message_content, metrics, disable_metrics),+ )++ # sync stream generate+ wrap_function_wrapper(+ "google.genai.models",+ "Models.generate_content_stream",+ generate_stream(version, environment, application_name,+ tracer, pricing_info, capture_message_content, metrics, disable_metrics),)# async generatewrap_function_wrapper("google.genai.models","AsyncModels.generate_content",- async_generate(version, environment,- application_name, tracer, pricing_info, capture_message_content, metrics,- disable_metrics),+ async_generate(version, environment, application_name,+ tracer, pricing_info, capture_message_content, metrics, disable_metrics),+ )++ # async stream generate+ wrap_function_wrapper(+ "google.genai.models",+ "AsyncModels.generate_content_stream",+ async_generate_stream(version, environment, application_name,+ tracer, pricing_info, capture_message_content, metrics, disable_metrics),)def _uninstrument(self, **kwargs):diff --git a/sdk/python/src/openlit/instrumentation/google_ai_studio/async_google_ai_studio.py b/sdk/python/src/openlit/instrumentation/google_ai_studio/async_google_ai_studio.pyindex 5e543d54..ecaa6382 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@@ -4,53 +4,30 @@ Module for monitoring Google AI Studio API calls.import loggingimport time-from opentelemetry.trace import SpanKind, Status, StatusCode-from opentelemetry.sdk.resources import SERVICE_NAME, TELEMETRY_SDK_NAME, DEPLOYMENT_ENVIRONMENT+from opentelemetry.trace import SpanKindfrom openlit.__helpers import (- get_chat_model_cost,handle_exception,- response_as_dict,- create_metrics_attributes,set_server_address_and_port)+from openlit.instrumentation.google_ai_studio.utils import (+ process_chat_response,+ process_chunk,+ process_streaming_chat_response+)from openlit.semcov import SemanticConvention# Initialize logger for logging potential issues and operationslogger = logging.getLogger(__name__)def async_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 chat to collect metrics.-- Args:- gen_ai_endpoint: Endpoint identifier for logging and tracing.- version: Version of the monitoring package.- environment: Deployment environment (e.g., production, staging).- application_name: Name of the application using the Google AI Studio API.- tracer: OpenTelemetry tracer for creating spans.- pricing_info: Information used for calculating the cost of Google AI Studio 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.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."""server_address, server_port = set_server_address_and_port(instance, "generativelanguage.googleapis.com", 443)@@ -61,167 +38,122 @@ def async_generate(version, environment, application_name,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)+ response = process_chat_response(+ instance = instance,+ response=response,+ request_model=request_model,+ pricing_info=pricing_info,+ server_port=server_port,+ server_address=server_address,+ environment=environment,+ application_name=application_name,+ metrics=metrics,+ start_time=start_time,+ span=span,+ args=args,+ kwargs=kwargs,+ capture_message_content=capture_message_content,+ disable_metrics=disable_metrics,+ version=version,+ )++ return response++ return wrapper++def async_generate_stream(version, environment, application_name,+ tracer, pricing_info, capture_message_content, metrics, disable_metrics):+ """+ Generates a telemetry wrapper for GenAI function call+ """++ class TracedAsyncStream:+ """+ Wrapper for streaming responses to collect telemetry.+ """+ def __init__(+ self,+ wrapped,+ span,+ span_name,+ kwargs,+ server_address,+ server_port,+ **args,+ ):+ self.__wrapped__ = wrapped+ self._span = span+ self._span_name = span_name+ self._llmresponse = ''+ self._finish_reason = ''+ self._output_tokens = ''+ self._input_tokens = ''+ self._response_model = ''+ self._tools = None++ self._args = args+ self._kwargs = kwargs+ self._start_time = time.time()+ self._end_time = None+ self._timestamps = []+ self._ttft = 0+ self._tbt = 0+ self._server_address = server_address+ self._server_port = server_port++ async def __aenter__(self):+ await self.__wrapped__.__aenter__()+ return self++ async def __aexit__(self, exc_type, exc_value, traceback):+ await self.__wrapped__.__aexit__(exc_type, exc_value, traceback)++ def __aiter__(self):+ return self++ async def __getattr__(self, name):+ """Delegate attribute access to the wrapped object."""+ return getattr(await self.__wrapped__, name)++ async def __anext__(self):try:- # Format 'messages' into a single string- message_prompt = kwargs.get("contents", [])- formatted_messages = []-- for content in message_prompt:- role = content.role- parts = content.parts- content_str = []-- for part in parts:- # Collect relevant fields and handle each type of data that Part could contain- if part.text:- content_str.append(f"text: {part.text}")- if part.video_metadata:- content_str.append(f"video_metadata: {part.video_metadata}")- if part.thought:- content_str.append(f"thought: {part.thought}")- if part.code_execution_result:- content_str.append(f"code_execution_result: {part.code_execution_result}")- if part.executable_code:- content_str.append(f"executable_code: {part.executable_code}")- if part.file_data:- content_str.append(f"file_data: {part.file_data}")- if part.function_call:- content_str.append(f"function_call: {part.function_call}")- if part.function_response:- content_str.append(f"function_response: {part.function_response}")- if part.inline_data:- content_str.append(f"inline_data: {part.inline_data}")-- formatted_messages.append(f"{role}: {', '.join(content_str)}")-- prompt = "\n".join(formatted_messages)-- input_tokens = response_dict.get('usage_metadata').get('prompt_token_count')- output_tokens = response_dict.get('usage_metadata').get('candidates_token_count')-- # 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_GEMINI)- span.set_attribute(SemanticConvention.GEN_AI_REQUEST_MODEL,- request_model)- span.set_attribute(SemanticConvention.SERVER_PORT,- server_port)-- inference_config = kwargs.get('config', {})-- # List of attributes and their config keys- attributes = [- (SemanticConvention.GEN_AI_REQUEST_FREQUENCY_PENALTY, 'frequency_penalty'),- (SemanticConvention.GEN_AI_REQUEST_MAX_TOKENS, 'max_tokens'),- (SemanticConvention.GEN_AI_REQUEST_PRESENCE_PENALTY, 'presence_penalty'),- (SemanticConvention.GEN_AI_REQUEST_STOP_SEQUENCES, 'stop_sequences'),- (SemanticConvention.GEN_AI_REQUEST_TEMPERATURE, 'temperature'),- (SemanticConvention.GEN_AI_REQUEST_TOP_P, 'top_p'),- (SemanticConvention.GEN_AI_REQUEST_TOP_K, 'top_k'),- ]-- # Set each attribute if the corresponding value exists and is not None- for attribute, key in attributes:- # Use getattr to get the attribute value from the object- value = getattr(inference_config, key, None)- if value is not None:- span.set_attribute(attribute, value)-- span.set_attribute(SemanticConvention.GEN_AI_RESPONSE_MODEL,- response_dict.get('model_version'))- 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_RESPONSE_FINISH_REASON,- [str(response_dict.get('candidates')[0].get('finish_reason'))])-- # Set base span attribues (Extras)- span.set_attribute(DEPLOYMENT_ENVIRONMENT,- environment)- span.set_attribute(SERVICE_NAME,- application_name)- span.set_attribute(SemanticConvention.GEN_AI_REQUEST_IS_STREAM,- False)- span.set_attribute(SemanticConvention.GEN_AI_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.text,- },- )-- if isinstance(response_dict.get('text'), str):- span.set_attribute(SemanticConvention.GEN_AI_OUTPUT_TYPE,- "text")- elif response_dict.get('text') 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_GEMINI,- request_model=request_model,- server_address=server_address,- server_port=server_port,- response_model=response_dict.get('model_version'),- )-- 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+ chunk = await self.__wrapped__.__anext__()+ process_chunk(self, chunk)+ return chunk+ except StopAsyncIteration:+ try:+ 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+ )++ 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):+ """+ Wraps the GenAI function call.+ """++ server_address, server_port = set_server_address_and_port(instance, "generativelanguage.googleapis.com", 443)+ request_model = kwargs.get("model", "gemini-2.0-flash")++ span_name = f"{SemanticConvention.GEN_AI_OPERATION_TYPE_CHAT} {request_model}"++ awaited_wrapped = await wrapped(*args, **kwargs)+ span = tracer.start_as_current_span(span_name, kind=SpanKind.CLIENT)++ return TracedAsyncStream(awaited_wrapped, span, span_name, kwargs, server_address, server_port)return wrapperdiff --git a/sdk/python/src/openlit/instrumentation/google_ai_studio/google_ai_studio.py b/sdk/python/src/openlit/instrumentation/google_ai_studio/google_ai_studio.pyindex 0afbde41..ed7f6f85 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@@ -4,53 +4,30 @@ Module for monitoring Google AI Studio API calls.import loggingimport time-from opentelemetry.trace import SpanKind, Status, StatusCode-from opentelemetry.sdk.resources import SERVICE_NAME, TELEMETRY_SDK_NAME, DEPLOYMENT_ENVIRONMENT+from opentelemetry.trace import SpanKindfrom openlit.__helpers import (- get_chat_model_cost,handle_exception,- response_as_dict,- create_metrics_attributes,set_server_address_and_port)+from openlit.instrumentation.google_ai_studio.utils import (+ process_chat_response,+ process_chunk,+ process_streaming_chat_response+)from openlit.semcov import SemanticConvention# Initialize logger for logging potential issues and operationslogger = logging.getLogger(__name__)def generate(version, environment, application_name,- tracer, pricing_info, capture_message_content, metrics, disable_metrics):+ tracer, pricing_info, capture_message_content, metrics, disable_metrics):"""- Generates a telemetry wrapper for chat to collect metrics.-- Args:- gen_ai_endpoint: Endpoint identifier for logging and tracing.- version: Version of the monitoring package.- environment: Deployment environment (e.g., production, staging).- application_name: Name of the application using the Google AI Studio API.- tracer: OpenTelemetry tracer for creating spans.- pricing_info: Information used for calculating the cost of Google AI Studio 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.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."""server_address, server_port = set_server_address_and_port(instance, "generativelanguage.googleapis.com", 443)@@ -61,167 +38,122 @@ def generate(version, environment, application_name,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)+ response = process_chat_response(+ instance = instance,+ response=response,+ request_model=request_model,+ pricing_info=pricing_info,+ server_port=server_port,+ server_address=server_address,+ environment=environment,+ application_name=application_name,+ metrics=metrics,+ start_time=start_time,+ span=span,+ args=args,+ kwargs=kwargs,+ capture_message_content=capture_message_content,+ disable_metrics=disable_metrics,+ version=version,+ )++ return response++ return wrapper++def generate_stream(version, environment, application_name,+ tracer, pricing_info, capture_message_content, metrics, disable_metrics):+ """+ Generates a telemetry wrapper for GenAI function call+ """++ class TracedSyncStream:+ """+ Wrapper for streaming responses to collect telemetry.+ """+ def __init__(+ self,+ wrapped,+ span,+ span_name,+ kwargs,+ server_address,+ server_port,+ **args,+ ):+ self.__wrapped__ = wrapped+ self._span = span+ self._span_name = span_name+ self._llmresponse = ''+ self._finish_reason = ''+ self._output_tokens = ''+ self._input_tokens = ''+ self._response_model = ''+ self._tools = None++ self._args = args+ self._kwargs = kwargs+ self._start_time = time.time()+ self._end_time = None+ self._timestamps = []+ self._ttft = 0+ self._tbt = 0+ self._server_address = server_address+ self._server_port = server_port++ def __enter__(self):+ self.__wrapped__.__enter__()+ return self++ def __exit__(self, exc_type, exc_value, traceback):+ self.__wrapped__.__exit__(exc_type, exc_value, traceback)++ def __iter__(self):+ return self++ def __getattr__(self, name):+ """Delegate attribute access to the wrapped object."""+ return getattr(self.__wrapped__, name)++ def __next__(self):try:- # Format 'messages' into a single string- message_prompt = kwargs.get("contents", [])- formatted_messages = []-- for content in message_prompt:- role = content.role- parts = content.parts- content_str = []-- for part in parts:- # Collect relevant fields and handle each type of data that Part could contain- if part.text:- content_str.append(f"text: {part.text}")- if part.video_metadata:- content_str.append(f"video_metadata: {part.video_metadata}")- if part.thought:- content_str.append(f"thought: {part.thought}")- if part.code_execution_result:- content_str.append(f"code_execution_result: {part.code_execution_result}")- if part.executable_code:- content_str.append(f"executable_code: {part.executable_code}")- if part.file_data:- content_str.append(f"file_data: {part.file_data}")- if part.function_call:- content_str.append(f"function_call: {part.function_call}")- if part.function_response:- content_str.append(f"function_response: {part.function_response}")- if part.inline_data:- content_str.append(f"inline_data: {part.inline_data}")-- formatted_messages.append(f"{role}: {', '.join(content_str)}")-- prompt = "\n".join(formatted_messages)-- input_tokens = response_dict.get('usage_metadata').get('prompt_token_count')- output_tokens = response_dict.get('usage_metadata').get('candidates_token_count')-- # 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_GEMINI)- span.set_attribute(SemanticConvention.GEN_AI_REQUEST_MODEL,- request_model)- span.set_attribute(SemanticConvention.SERVER_PORT,- server_port)-- inference_config = kwargs.get('config', {})-- # List of attributes and their config keys- attributes = [- (SemanticConvention.GEN_AI_REQUEST_FREQUENCY_PENALTY, 'frequency_penalty'),- (SemanticConvention.GEN_AI_REQUEST_MAX_TOKENS, 'max_tokens'),- (SemanticConvention.GEN_AI_REQUEST_PRESENCE_PENALTY, 'presence_penalty'),- (SemanticConvention.GEN_AI_REQUEST_STOP_SEQUENCES, 'stop_sequences'),- (SemanticConvention.GEN_AI_REQUEST_TEMPERATURE, 'temperature'),- (SemanticConvention.GEN_AI_REQUEST_TOP_P, 'top_p'),- (SemanticConvention.GEN_AI_REQUEST_TOP_K, 'top_k'),- ]-- # Set each attribute if the corresponding value exists and is not None- for attribute, key in attributes:- # Use getattr to get the attribute value from the object- value = getattr(inference_config, key, None)- if value is not None:- span.set_attribute(attribute, value)-- span.set_attribute(SemanticConvention.GEN_AI_RESPONSE_MODEL,- response_dict.get('model_version'))- 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_RESPONSE_FINISH_REASON,- [str(response_dict.get('candidates')[0].get('finish_reason'))])-- # Set base span attribues (Extras)- span.set_attribute(DEPLOYMENT_ENVIRONMENT,- environment)- span.set_attribute(SERVICE_NAME,- application_name)- span.set_attribute(SemanticConvention.GEN_AI_REQUEST_IS_STREAM,- False)- span.set_attribute(SemanticConvention.GEN_AI_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.text,- },- )-- if isinstance(response_dict.get('text'), str):- span.set_attribute(SemanticConvention.GEN_AI_OUTPUT_TYPE,- "text")- elif response_dict.get('text') 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_GEMINI,- request_model=request_model,- server_address=server_address,- server_port=server_port,- response_model=response_dict.get('model_version'),- )-- 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+ chunk = self.__wrapped__.__next__()+ process_chunk(self, chunk)+ return chunk+ except StopIteration:+ try:+ 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+ )++ except Exception as e:+ handle_exception(self._span, e)+ logger.error("Error in trace creation: %s", e)+ raise++ def wrapper(wrapped, instance, args, kwargs):+ """+ Wraps the GenAI function call.+ """++ server_address, server_port = set_server_address_and_port(instance, "generativelanguage.googleapis.com", 443)+ request_model = kwargs.get("model", "gemini-2.0-flash")++ span_name = f"{SemanticConvention.GEN_AI_OPERATION_TYPE_CHAT} {request_model}"++ awaited_wrapped = wrapped(*args, **kwargs)+ span = tracer.start_as_current_span(span_name, kind=SpanKind.CLIENT)++ return TracedSyncStream(awaited_wrapped, span, span_name, kwargs, server_address, server_port)return wrapperdiff --git a/sdk/python/src/openlit/instrumentation/google_ai_studio/utils.py b/sdk/python/src/openlit/instrumentation/google_ai_studio/utils.pynew file mode 100644index 00000000..09aac1a3--- /dev/null+++ b/sdk/python/src/openlit/instrumentation/google_ai_studio/utils.py@@ -0,0 +1,245 @@+"""+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,+ create_metrics_attributes,+)+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.+ """++ formatted_messages = []+ prompt = ""++ if isinstance(messages, list):+ for content in messages:+ role = content.role+ parts = content.parts+ content_str = []++ for part in parts:+ # Collect relevant fields and handle each type of data that Part could contain+ if part.text:+ content_str.append(f"text: {part.text}")+ if part.video_metadata:+ content_str.append(f"video_metadata: {part.video_metadata}")+ if part.thought:+ content_str.append(f"thought: {part.thought}")+ if part.code_execution_result:+ content_str.append(f"code_execution_result: {part.code_execution_result}")+ if part.executable_code:+ content_str.append(f"executable_code: {part.executable_code}")+ if part.file_data:+ content_str.append(f"file_data: {part.file_data}")+ if part.function_call:+ content_str.append(f"function_call: {part.function_call}")+ if part.function_response:+ content_str.append(f"function_response: {part.function_response}")+ if part.inline_data:+ content_str.append(f"inline_data: {part.inline_data}")++ formatted_messages.append(f"{role}: {', '.join(content_str)}")++ prompt = "\n".join(formatted_messages)++ else:+ prompt = messages++ return prompt++def process_chunk(self, chunk):+ """+ Process a chunk of response data and update state.+ """++ 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)+++ self._response_id = str(chunked.get('response_id'))+ self._input_tokens = chunked.get('usage_metadata').get('prompt_token_count')+ self._response_model = chunked.get('model_version')++ if chunk.text:+ self._llmresponse += str(chunk.text)++ self._output_tokens = chunked.get('usage_metadata').get('candidates_token_count')+ self._reasoning_tokens = chunked.get('usage_metadata').get('thoughts_token_count') or 0+ self._finish_reason = str(chunked.get('candidates')[0].get('finish_reason'))++ try:+ self._tools = chunked.get('candidates', [])[0].get('content', {}).get('parts', [])[0].get('function_call', '')+ except:+ self._tools = None++def common_chat_logic(scope, pricing_info, environment, application_name, metrics,+ capture_message_content, disable_metrics, version, is_stream):+ """+ Process chat request and generate Telemetry+ """++ scope._end_time = time.time()+ if len(scope._timestamps) > 1:+ scope._tbt = calculate_tbt(scope._timestamps)++ prompt = format_content(scope._kwargs.get('contents', ''))+ request_model = scope._kwargs.get("model", "gemini-2.0-flash")++ cost = get_chat_model_cost(request_model, pricing_info, scope._input_tokens, scope._output_tokens)++ # Set Span attributes (OTel Semconv)+ scope._span.set_attribute(TELEMETRY_SDK_NAME, 'openlit')+ scope._span.set_attribute(SemanticConvention.GEN_AI_OPERATION, SemanticConvention.GEN_AI_OPERATION_TYPE_CHAT)+ scope._span.set_attribute(SemanticConvention.GEN_AI_SYSTEM, SemanticConvention.GEN_AI_SYSTEM_GEMINI)+ scope._span.set_attribute(SemanticConvention.GEN_AI_REQUEST_MODEL, request_model)+ scope._span.set_attribute(SemanticConvention.SERVER_PORT, scope._server_port)++ inference_config = scope._kwargs.get('config', {})++ attributes = [+ (SemanticConvention.GEN_AI_REQUEST_FREQUENCY_PENALTY, 'frequency_penalty'),+ (SemanticConvention.GEN_AI_REQUEST_MAX_TOKENS, 'max_tokens'),+ (SemanticConvention.GEN_AI_REQUEST_PRESENCE_PENALTY, 'presence_penalty'),+ (SemanticConvention.GEN_AI_REQUEST_STOP_SEQUENCES, 'stop_sequences'),+ (SemanticConvention.GEN_AI_REQUEST_TEMPERATURE, 'temperature'),+ (SemanticConvention.GEN_AI_REQUEST_TOP_P, 'top_p'),+ (SemanticConvention.GEN_AI_REQUEST_TOP_K, 'top_k'),+ ]++ # Set each attribute if the corresponding value exists and is not None+ for attribute, key in attributes:+ # Use getattr to get the attribute value from the object+ value = getattr(inference_config, key, None)+ if value is not None:+ scope._span.set_attribute(attribute, value)++ scope._span.set_attribute(SemanticConvention.GEN_AI_RESPONSE_FINISH_REASON, [scope._finish_reason])+ scope._span.set_attribute(SemanticConvention.GEN_AI_RESPONSE_MODEL, scope._response_model)+ 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_USAGE_REASONING_TOKENS, scope._reasoning_tokens)+ scope._span.set_attribute(SemanticConvention.SERVER_ADDRESS, scope._server_address)++ scope._span.set_attribute(SemanticConvention.GEN_AI_OUTPUT_TYPE,+ 'text' if isinstance(scope._llmresponse, str) else 'json')++ 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_USAGE_COST, cost)+ 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)+ scope._span.set_attribute(SemanticConvention.GEN_AI_CLIENT_TOKEN_USAGE,+ scope._input_tokens + scope._output_tokens + scope._reasoning_tokens)++ 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('args','')))++ # To be removed one the change to span_attributes (from span events) is complete+ 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)+ 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))++ if not disable_metrics:+ metrics_attributes = create_metrics_attributes(+ service_name=application_name,+ deployment_environment=environment,+ operation=SemanticConvention.GEN_AI_OPERATION_TYPE_CHAT,+ system=SemanticConvention.GEN_AI_SYSTEM_GEMINI,+ request_model=request_model,+ server_address=scope._server_address,+ server_port=scope._server_port,+ response_model=scope._response_model,+ )++ metrics['genai_client_operation_duration'].record(scope._end_time - scope._start_time, metrics_attributes)+ metrics['genai_server_tbt'].record(scope._tbt, metrics_attributes)+ metrics['genai_server_ttft'].record(scope._ttft, metrics_attributes)+ metrics['genai_requests'].add(1, metrics_attributes)+ metrics['genai_completion_tokens'].add(scope._output_tokens, metrics_attributes)+ metrics['genai_prompt_tokens'].add(scope._input_tokens, metrics_attributes)+ metrics['genai_reasoning_tokens'].add(scope._reasoning_tokens, metrics_attributes)+ metrics['genai_cost'].record(cost, metrics_attributes)+ metrics['genai_client_usage_tokens'].record(+ scope._input_tokens + scope._output_tokens + scope._reasoning_tokens, metrics_attributes)+++def process_streaming_chat_response(self, pricing_info, environment, application_name, metrics,+ capture_message_content=False, disable_metrics=False, version=''):+ """+ Process chat request and generate Telemetry+ """++ common_chat_logic(self, pricing_info, environment, application_name, metrics,+ capture_message_content, disable_metrics, version, is_stream=True)++def process_chat_response(instance, response, request_model, pricing_info, server_port, server_address,+ environment, application_name, metrics, start_time,+ span, args, kwargs, capture_message_content=False, disable_metrics=False, version="1.0.0"):+ """+ Process chat request and generate Telemetry+ """++ self = type('GenericScope', (), {})()+ response_dict = response_as_dict(response)++ self._start_time = start_time+ self._end_time = time.time()+ self._span = span+ self._llmresponse = str(response.text)+ self._input_tokens = response_dict.get('usage_metadata').get('prompt_token_count')+ self._output_tokens = response_dict.get('usage_metadata').get('candidates_token_count')+ self._reasoning_tokens = response_dict.get('usage_metadata').get('thoughts_token_count') or 0+ self._response_model = response_dict.get('model_version')+ self._timestamps = []+ self._ttft, self._tbt = self._end_time - self._start_time, 0+ self._server_address, self._server_port = server_address, server_port+ self._kwargs = kwargs+ self._finish_reason = str(response_dict.get('candidates')[0].get('finish_reason'))++ try:+ self._tools = response_dict.get('candidates', [])[0].get('content', {}).get('parts', [])[0].get('function_call', '')+ except:+ self._tools = None++ common_chat_logic(self, pricing_info, environment, application_name, metrics,+ capture_message_content, disable_metrics, version, is_stream=False)++ return responsediff --git a/sdk/python/src/openlit/instrumentation/transformers/transformers.py b/sdk/python/src/openlit/instrumentation/transformers/transformers.pyindex bba9a9a2..60b5dbfa 100644--- a/sdk/python/src/openlit/instrumentation/transformers/transformers.py+++ b/sdk/python/src/openlit/instrumentation/transformers/transformers.py@@ -8,7 +8,6 @@ from opentelemetry.trace import SpanKindfrom openlit.__helpers import (set_server_address_and_port)-from openlit.instrumentation.transformers.utils import (process_chat_response,)@@ -18,7 +17,7 @@ from openlit.semcov import SemanticConventionlogger = logging.getLogger(__name__)def pipeline_wrapper(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 GenAI function call"""diff --git a/sdk/python/src/openlit/instrumentation/transformers/utils.py b/sdk/python/src/openlit/instrumentation/transformers/utils.pyindex b437095e..d4fa2888 100644--- a/sdk/python/src/openlit/instrumentation/transformers/utils.py+++ b/sdk/python/src/openlit/instrumentation/transformers/utils.py@@ -72,7 +72,7 @@ def common_chat_logic(scope, pricing_info, environment, application_name, metric# To be removed one the change to span_attributes (from span events) is completeif capture_message_content:scope._span.set_attribute(SemanticConvention.GEN_AI_CONTENT_PROMPT, scope._prompt)- scope._span.set_attribute(SemanticConvention.GEN_AI_CONTENT_COMPLETION, scope._llmresponse,)+ scope._span.set_attribute(SemanticConvention.GEN_AI_CONTENT_COMPLETION, scope._llmresponse)scope._span.add_event(name=SemanticConvention.GEN_AI_CONTENT_PROMPT_EVENT,@@ -111,8 +111,8 @@ def common_chat_logic(scope, pricing_info, environment, application_name, metricmetrics["genai_cost"].record(cost, metrics_attributes)def process_chat_response(instance, response, request_model, pricing_info, server_port, server_address,- environment, application_name, metrics, start_time,- span, args, kwargs, capture_message_content=False, disable_metrics=False, version="1.0.0"):+ environment, application_name, metrics, start_time,+ span, args, kwargs, capture_message_content=False, disable_metrics=False, version="1.0.0"):"""Process chat request and generate Telemetry"""diff --git a/sdk/python/src/openlit/otel/metrics.py b/sdk/python/src/openlit/otel/metrics.pyindex da9192f2..9f24e00a 100644--- a/sdk/python/src/openlit/otel/metrics.py+++ b/sdk/python/src/openlit/otel/metrics.py@@ -202,6 +202,11 @@ def setup_meter(application_name, environment, meter, otlp_endpoint, otlp_headerdescription="Number of completion tokens processed.",unit="1",),+ "genai_reasoning_tokens": meter.create_counter(+ name=SemanticConvention.GEN_AI_USAGE_REASONING_TOKENS,+ description="Number of reasoning thought tokens processed.",+ unit="1",+ ),"genai_cost": meter.create_histogram(name=SemanticConvention.GEN_AI_USAGE_COST,description="The distribution of GenAI request costs.",diff --git a/sdk/python/src/openlit/semcov/__init__.py b/sdk/python/src/openlit/semcov/__init__.pyindex aebda306..cba0e71c 100644--- a/sdk/python/src/openlit/semcov/__init__.py+++ b/sdk/python/src/openlit/semcov/__init__.py@@ -58,8 +58,10 @@ class SemanticConvention:GEN_AI_RESPONSE_MODEL = "gen_ai.response.model"GEN_AI_USAGE_INPUT_TOKENS = "gen_ai.usage.input_tokens"GEN_AI_USAGE_OUTPUT_TOKENS = "gen_ai.usage.output_tokens"+ GEN_AI_USAGE_REASONING_TOKENS = "gen_ai.usage.reasoning_tokens"GEN_AI_TOOL_CALL_ID = "gen_ai.tool.call.id"GEN_AI_TOOL_NAME = "gen_ai.tool.name"+ GEN_AI_TOOL_ARGS = "gen_ai.tool.args"# GenAI Operation Types (OTel Semconv)GEN_AI_OPERATION_TYPE_CHAT = "chat"diff --git a/sdk/python/tests/requirements.txt b/sdk/python/tests/requirements.txtindex e64108f7..cd2ee094 100644--- a/sdk/python/tests/requirements.txt+++ b/sdk/python/tests/requirements.txt@@ -12,7 +12,7 @@ anthropicmistralaiboto3botocore-google-generativeai+google-genaiazure-ai-inferencereka-apimultiondiff --git a/sdk/python/tests/test_elevenlabs.py b/sdk/python/tests/test_elevenlabs.py.holdsimilarity index 100%rename from sdk/python/tests/test_elevenlabs.pyrename to sdk/python/tests/test_elevenlabs.py.holddiff --git a/sdk/python/tests/test_google_ai_studio.py.hold b/sdk/python/tests/test_google_ai_studio.pysimilarity index 63%rename from sdk/python/tests/test_google_ai_studio.py.holdrename to sdk/python/tests/test_google_ai_studio.pyindex 31c601bc..5b5360f7 100644--- a/sdk/python/tests/test_google_ai_studio.py.hold+++ b/sdk/python/tests/test_google_ai_studio.py@@ -15,32 +15,45 @@ OpenLIT monitoring prior to running these tests.import osimport pytest-import google.generativeai as genai+from google import genai+from google.genai import typesimport openlit# Initialize Google AI Studio client-genai.configure(api_key=os.getenv("GOOGLE_AI_STUDIO_API_TOKEN"))-model = genai.GenerativeModel("gemini-1.5-flash")+client = genai.Client(+ api_key=os.getenv("GOOGLE_AI_STUDIO_API_TOKEN")+)+contents = [+ types.Content(+ role="user",+ parts=[+ types.Part.from_text(text="""Hi"""),+ ],+ ),+]+generate_content_config = types.GenerateContentConfig(+ response_mime_type="text/plain",+)# Initialize environment and application name for OpenLIT monitoring-openlit.init(environment="openlit-testing", application_name="openlit-python-test")+openlit.init(environment="openlit-testing", application_name="openlit-python-gemini-test")def test_sync_generate_content():"""- Tests synchronous Generate content with the "gemini-1.5-flash" model.+ Tests synchronous Generate content with the "gemini-2.0-flash" model.Raises:AssertionError: If the generate content response object is not as expected."""try:- response = model.generate_content("Observability for LLMs", stream=False)+ response = client.models.generate_content(+ model="gemini-2.0-flash",+ contents=contents,+ config=generate_content_config,+ )assert isinstance(response.text, str)- response = model.generate_content("Monitor AI", stream=True)- for text in response:- assert isinstance(text.text, str)-# pylint: disable=broad-exception-caughtexcept Exception as e:if "rate limit" in str(e).lower():@@ -51,20 +64,20 @@ def test_sync_generate_content():@pytest.mark.asyncioasync def test_async_generate_content():"""- Tests synchronous Generate content with the "gemini-1.5-flash" model.+ Tests synchronous Generate content with the "gemini-2.0-flash" model.Raises:AssertionError: If the generate content response object is not as expected."""try:- response = await model.generate_content_async("Observability for LLMs", stream=False)+ response = await client.aio.models.generate_content(+ model="gemini-2.0-flash",+ contents=contents,+ config=generate_content_config,+ )assert isinstance(response.text, str)- response = await model.generate_content_async("Monitor AI", stream=True)- async for text in response:- assert isinstance(text.text, str)-# pylint: disable=broad-exception-caughtexcept Exception as e:if "rate limit" in str(e).lower():