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 ElevenLabs and AssemblyAI OpenTelemetry Monitoring Instrumentation (#772)

Patcher35425467217b
diff --git a/sdk/python/pyproject.toml b/sdk/python/pyproject.toml
index 4a131781..749b3509 100644
--- a/sdk/python/pyproject.toml
+++ b/sdk/python/pyproject.toml
@@ -1,6 +1,6 @@
[tool.poetry]
name = "openlit"
-version = "1.34.8"
+version = "1.34.9"
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/assemblyai/__init__.py b/sdk/python/src/openlit/instrumentation/assemblyai/__init__.py
index d17a01b2..178c45df 100644
--- a/sdk/python/src/openlit/instrumentation/assemblyai/__init__.py
+++ b/sdk/python/src/openlit/instrumentation/assemblyai/__init__.py
@@ -5,39 +5,35 @@ import importlib.metadata
from opentelemetry.instrumentation.instrumentor import BaseInstrumentor
from wrapt import wrap_function_wrapper
-from openlit.instrumentation.assemblyai.assemblyai import (
- transcribe
-)
+from openlit.instrumentation.assemblyai.assemblyai import transcribe
-_instruments = ('assemblyai >= 0.35.1',)
+_instruments = ("assemblyai >= 0.35.1",)
class AssemblyAIInstrumentor(BaseInstrumentor):
"""
- An instrumentor for AssemblyAI's client library.
+ An instrumentor for AssemblyAI client library.
"""
def instrumentation_dependencies(self) -> Collection[str]:
return _instruments
def _instrument(self, **kwargs):
- application_name = kwargs.get('application_name', 'default')
- environment = kwargs.get('environment', 'default')
- tracer = kwargs.get('tracer')
- event_provider = kwargs.get('event_provider')
- metrics = kwargs.get('metrics_dict')
- pricing_info = kwargs.get('pricing_info', {})
- capture_message_content = kwargs.get('capture_message_content', False)
- disable_metrics = kwargs.get('disable_metrics')
- version = importlib.metadata.version('assemblyai')
+ 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", {})
+ capture_message_content = kwargs.get("capture_message_content", False)
+ disable_metrics = kwargs.get("disable_metrics")
+ version = importlib.metadata.version("assemblyai")
# sync transcribe
wrap_function_wrapper(
- 'assemblyai.transcriber',
- 'Transcriber.transcribe',
+ "assemblyai.transcriber",
+ "Transcriber.transcribe",
transcribe(version, environment, application_name,
- tracer, event_provider, pricing_info, capture_message_content, metrics, disable_metrics),
+ tracer, pricing_info, capture_message_content, metrics, disable_metrics),
)
def _uninstrument(self, **kwargs):
- # Proper uninstrumentation logic to revert patched methods
pass
diff --git a/sdk/python/src/openlit/instrumentation/assemblyai/assemblyai.py b/sdk/python/src/openlit/instrumentation/assemblyai/assemblyai.py
index 5c3e6cbb..902d8191 100644
--- a/sdk/python/src/openlit/instrumentation/assemblyai/assemblyai.py
+++ b/sdk/python/src/openlit/instrumentation/assemblyai/assemblyai.py
@@ -1,150 +1,59 @@
"""
-Module for monitoring Assembly AI API calls.
+Module for monitoring AssemblyAI 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 openlit.__helpers import (
- get_audio_model_cost,
- handle_exception,
- create_metrics_attributes,
- set_server_address_and_port,
- otel_event
-)
+from opentelemetry.trace import SpanKind
+from openlit.__helpers import handle_exception, set_server_address_and_port
+from openlit.instrumentation.assemblyai.utils import process_audio_response
from openlit.semcov import SemanticConvention
# Initialize logger for logging potential issues and operations
logger = logging.getLogger(__name__)
def transcribe(version, environment, application_name,
- tracer, event_provider, 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
+ Generates a telemetry wrapper for AssemblyAI transcribe function call
"""
-
def wrapper(wrapped, instance, args, kwargs):
"""
- Wraps the GenAI function call.
+ Wraps the AssemblyAI transcribe function call.
"""
- server_address, server_port = set_server_address_and_port(instance, 'api.assemblyai.com', 443)
- request_model = kwargs.get('speech_model', 'best')
+ server_address, server_port = set_server_address_and_port(instance, "api.assemblyai.com", 443)
+ request_model = kwargs.get("speech_model", "best")
- span_name = f'{SemanticConvention.GEN_AI_OPERATION_TYPE_AUDIO} {request_model}'
+ span_name = f"{SemanticConvention.GEN_AI_OPERATION_TYPE_AUDIO} {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:
- # Calculate cost of the operation
- cost = get_audio_model_cost(request_model,
- pricing_info, None, response.audio_duration)
-
- # Set Span attributes (OTel Semconv)
- span.set_attribute(TELEMETRY_SDK_NAME, 'openlit')
- span.set_attribute(SemanticConvention.GEN_AI_OPERATION,
- SemanticConvention.GEN_AI_OPERATION_TYPE_AUDIO)
- span.set_attribute(SemanticConvention.GEN_AI_SYSTEM,
- SemanticConvention.GEN_AI_SYSTEM_ASSEMBLYAI)
- 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_MODEL,
- request_model)
- span.set_attribute(SemanticConvention.GEN_AI_OUTPUT_TYPE,
- 'text')
-
- # Set Span attributes (Extras)
- span.set_attribute(DEPLOYMENT_ENVIRONMENT,
- environment)
- span.set_attribute(SERVICE_NAME,
- application_name)
- span.set_attribute(SemanticConvention.GEN_AI_REQUEST_AUDIO_DURATION,
- response.audio_duration)
- span.set_attribute(SemanticConvention.GEN_AI_USAGE_COST,
- cost)
- span.set_attribute(SemanticConvention.GEN_AI_SDK_VERSION,
- version)
-
- # To be removed one the change to log events (from span events) is complete
- if capture_message_content:
- span.add_event(
- name=SemanticConvention.GEN_AI_CONTENT_PROMPT_EVENT,
- attributes={
- SemanticConvention.GEN_AI_CONTENT_PROMPT: response.audio_url,
- },
- )
- span.add_event(
- name=SemanticConvention.GEN_AI_CONTENT_COMPLETION_EVENT,
- attributes={
- SemanticConvention.GEN_AI_CONTENT_COMPLETION: response.text,
- },
- )
-
- input_event = otel_event(
- name=SemanticConvention.GEN_AI_USER_MESSAGE,
- attributes={
- SemanticConvention.GEN_AI_SYSTEM: SemanticConvention.GEN_AI_SYSTEM_ASSEMBLYAI
- },
- body={
- **({'content': response.audio_url} if capture_message_content else {}),
- 'role': 'user'
- }
+ response = wrapped(*args, **kwargs)
+
+ response = process_audio_response(
+ response=response,
+ gen_ai_endpoint="assemblyai.transcribe",
+ 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
)
- event_provider.emit(input_event)
-
- output_event = otel_event(
- name=SemanticConvention.GEN_AI_CHOICE,
- attributes={
- SemanticConvention.GEN_AI_SYSTEM: SemanticConvention.GEN_AI_SYSTEM_ASSEMBLYAI
- },
- body={
- 'finish_reason': 'stop',
- 'index': 0,
- 'message': {
- **({'content': response.text} if capture_message_content else {}),
- 'role': 'assistant'
- }
- }
- )
- event_provider.emit(output_event)
-
- 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_AUDIO,
- system=SemanticConvention.GEN_AI_SYSTEM_ASSEMBLYAI,
- request_model=request_model,
- server_address=server_address,
- server_port=server_port,
- response_model=request_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 response
return wrapper
diff --git a/sdk/python/src/openlit/instrumentation/assemblyai/utils.py b/sdk/python/src/openlit/instrumentation/assemblyai/utils.py
new file mode 100644
index 00000000..1a412a93
--- /dev/null
+++ b/sdk/python/src/openlit/instrumentation/assemblyai/utils.py
@@ -0,0 +1,142 @@
+"""
+AssemblyAI 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 (
+ get_audio_model_cost,
+ create_metrics_attributes,
+)
+from openlit.semcov import SemanticConvention
+
+def format_audio_url(audio_url):
+ """
+ Process audio URL input to extract content.
+ """
+ return str(audio_url) if audio_url else ""
+
+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_audio_metrics(metrics, gen_ai_operation, gen_ai_system, server_address, server_port,
+ request_model, response_model, environment, application_name, start_time, end_time, cost):
+ """
+ Record audio 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_cost"].record(cost, attributes)
+
+def common_audio_logic(scope, gen_ai_endpoint, pricing_info, environment, application_name,
+ metrics, capture_message_content, disable_metrics, version):
+ """
+ Process audio transcription request and generate Telemetry
+ """
+
+ prompt = scope._response.audio_url
+ request_model = scope._kwargs.get("speech_model", "best")
+ is_stream = False
+
+ # Calculate cost based on audio duration
+ cost = get_audio_model_cost(request_model, pricing_info, prompt, scope._response.audio_duration)
+
+ # Common Span Attributes
+ common_span_attributes(scope,
+ SemanticConvention.GEN_AI_OPERATION_TYPE_AUDIO, SemanticConvention.GEN_AI_SYSTEM_ASSEMBLYAI,
+ scope._server_address, scope._server_port, request_model, request_model,
+ environment, application_name, is_stream, scope._tbt, scope._ttft, version)
+
+ # Span Attributes for Response parameters
+ scope._span.set_attribute(SemanticConvention.GEN_AI_OUTPUT_TYPE, "text")
+ scope._span.set_attribute(SemanticConvention.GEN_AI_RESPONSE_ID, scope._response.id)
+
+ # Span Attributes for Cost
+ scope._span.set_attribute(SemanticConvention.GEN_AI_USAGE_COST, cost)
+
+ # Audio-specific span attributes
+ scope._span.set_attribute(SemanticConvention.GEN_AI_REQUEST_AUDIO_DURATION, scope._response.audio_duration)
+
+ # 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._response.text)
+
+ # To be removed once 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._response.text,
+ },
+ )
+
+ scope._span.set_status(Status(StatusCode.OK))
+
+ # Metrics
+ if not disable_metrics:
+ record_audio_metrics(metrics, SemanticConvention.GEN_AI_OPERATION_TYPE_AUDIO,
+ SemanticConvention.GEN_AI_SYSTEM_ASSEMBLYAI, scope._server_address, scope._server_port,
+ request_model, request_model, environment, application_name, scope._start_time,
+ scope._end_time, cost)
+
+def process_audio_response(response, gen_ai_endpoint, 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 audio transcription request and generate Telemetry
+ """
+
+ scope = type("GenericScope", (), {})()
+
+ scope._start_time = start_time
+ scope._end_time = time.time()
+ scope._span = span
+ scope._server_address, scope._server_port = server_address, server_port
+ scope._kwargs = kwargs
+ scope._response = response
+
+ # Initialize streaming and timing values for AssemblyAI transcription
+ scope._response_model = kwargs.get("speech_model", "best")
+ scope._tbt = 0.0
+ scope._ttft = scope._end_time - scope._start_time
+
+ common_audio_logic(scope, gen_ai_endpoint, pricing_info, environment, application_name,
+ metrics, capture_message_content, disable_metrics, version)
+
+ return response
diff --git a/sdk/python/src/openlit/instrumentation/elevenlabs/__init__.py b/sdk/python/src/openlit/instrumentation/elevenlabs/__init__.py
index ba08ed6a..ebb898a2 100644
--- a/sdk/python/src/openlit/instrumentation/elevenlabs/__init__.py
+++ b/sdk/python/src/openlit/instrumentation/elevenlabs/__init__.py
@@ -1,4 +1,3 @@
-# pylint: disable=useless-return, bad-staticmethod-argument, disable=duplicate-code
"""Initializer of Auto Instrumentation of ElevenLabs Functions"""
from typing import Collection
@@ -6,18 +5,14 @@ import importlib.metadata
from opentelemetry.instrumentation.instrumentor import BaseInstrumentor
from wrapt import wrap_function_wrapper
-from openlit.instrumentation.elevenlabs.elevenlabs import (
- generate
-)
-from openlit.instrumentation.elevenlabs.async_elevenlabs import (
- async_generate
-)
+from openlit.instrumentation.elevenlabs.elevenlabs import generate
+from openlit.instrumentation.elevenlabs.async_elevenlabs import async_generate
_instruments = ("elevenlabs >= 1.4.0",)
class ElevenLabsInstrumentor(BaseInstrumentor):
"""
- An instrumentor for ElevenLabs's client library.
+ An instrumentor for ElevenLabs client library.
"""
def instrumentation_dependencies(self) -> Collection[str]:
@@ -33,14 +28,6 @@ class ElevenLabsInstrumentor(BaseInstrumentor):
disable_metrics = kwargs.get("disable_metrics")
version = importlib.metadata.version("elevenlabs")
- # sync generate
- wrap_function_wrapper(
- "elevenlabs.client",
- "ElevenLabs.generate",
- generate("elevenlabs.generate", version, environment, application_name,
- tracer, pricing_info, capture_message_content, metrics, disable_metrics),
- )
-
# sync text_to_speech.convert
wrap_function_wrapper(
"elevenlabs.text_to_speech.client",
@@ -49,22 +36,13 @@ class ElevenLabsInstrumentor(BaseInstrumentor):
tracer, pricing_info, capture_message_content, metrics, disable_metrics),
)
- # async generate
- wrap_function_wrapper(
- "elevenlabs.client",
- "AsyncElevenLabs.generate",
- async_generate("elevenlabs.generate", version, environment, application_name,
- tracer, pricing_info, capture_message_content, metrics, disable_metrics),
- )
-
- # sync text_to_speech.convert
+ # async text_to_speech.convert
wrap_function_wrapper(
"elevenlabs.text_to_speech.client",
"AsyncTextToSpeechClient.convert",
- generate("elevenlabs.text_to_speech", version, environment, application_name,
+ async_generate("elevenlabs.text_to_speech", version, environment, application_name,
tracer, pricing_info, capture_message_content, metrics, disable_metrics),
)
def _uninstrument(self, **kwargs):
- # Proper uninstrumentation logic to revert patched methods
pass
diff --git a/sdk/python/src/openlit/instrumentation/elevenlabs/async_elevenlabs.py b/sdk/python/src/openlit/instrumentation/elevenlabs/async_elevenlabs.py
index 6297cccb..a8229bd4 100644
--- a/sdk/python/src/openlit/instrumentation/elevenlabs/async_elevenlabs.py
+++ b/sdk/python/src/openlit/instrumentation/elevenlabs/async_elevenlabs.py
@@ -1,145 +1,55 @@
"""
-Module for monitoring Ollama API calls.
+Module for monitoring ElevenLabs 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 openlit.__helpers import (
- get_audio_model_cost,
- handle_exception,
- create_metrics_attributes,
-)
+from opentelemetry.trace import SpanKind
+from openlit.__helpers import handle_exception
+from openlit.instrumentation.elevenlabs.utils import process_audio_response
from openlit.semcov import SemanticConvention
-# Initialize logger for logging potential issues and operations
-logger = logging.getLogger(__name__)
-
def async_generate(gen_ai_endpoint, 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 creating speech audio 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 ElevenLabs API.
- tracer: OpenTelemetry tracer for creating spans.
- pricing_info: Information used for calculating the cost of generating speech audio.
- capture_message_content: Flag indicating whether to trace the input text and generated audio.
-
- Returns:
- A function that wraps the speech audio creation method to add telemetry.
+ Generates a telemetry wrapper for GenAI function call
"""
async def wrapper(wrapped, instance, args, kwargs):
"""
- Wraps the '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 'generate' method to be wrapped.
- instance: The instance of the class where the original method is defined.
- args: Positional arguments for the 'generate' method.
- kwargs: Keyword arguments for the 'generate' method.
-
- Returns:
- The response from the original 'generate' method.
+ Wraps the GenAI function call.
"""
server_address, server_port = "api.elevenlabs.io", 443
- request_model = kwargs.get('model', kwargs.get('model_id', 'eleven_multilingual_v2'))
+ request_model = kwargs.get("model", kwargs.get("model_id", "eleven_multilingual_v2"))
- span_name = f'{SemanticConvention.GEN_AI_OPERATION_TYPE_AUDIO} {request_model}'
+ span_name = f"{SemanticConvention.GEN_AI_OPERATION_TYPE_AUDIO} {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()
+ response = wrapped(*args, **kwargs)
try:
- # Calculate cost of the operation
- cost = get_audio_model_cost(request_model,
- pricing_info, kwargs.get('text', ''))
-
- # Set Span attributes
- span.set_attribute(TELEMETRY_SDK_NAME, 'openlit')
- span.set_attribute(SemanticConvention.GEN_AI_OPERATION,
- SemanticConvention.GEN_AI_OPERATION_TYPE_AUDIO)
- span.set_attribute(SemanticConvention.GEN_AI_SYSTEM,
- SemanticConvention.GEN_AI_SYSTEM_ASSEMBLYAI)
- 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_MODEL,
- request_model)
- span.set_attribute(SemanticConvention.GEN_AI_REQUEST_MODEL,
- request_model)
- span.set_attribute(SemanticConvention.GEN_AI_OUTPUT_TYPE,
- 'audio')
-
- # Set Span attributes (Extras)
- if gen_ai_endpoint == 'elevenlabs.generate':
- if isinstance(kwargs.get('voice', 'Rachel'), str):
- span.set_attribute(SemanticConvention.GEN_AI_REQUEST_AUDIO_VOICE,
- kwargs.get('voice', 'Rachel'))
- else:
- span.set_attribute(SemanticConvention.GEN_AI_REQUEST_AUDIO_VOICE,
- kwargs.get('voice_id', ''))
- span.set_attribute(SemanticConvention.GEN_AI_REQUEST_AUDIO_RESPONSE_FORMAT,
- kwargs.get('output_format', 'mp3'))
- span.set_attribute(SemanticConvention.GEN_AI_REQUEST_AUDIO_SETTINGS,
- str(kwargs.get('voice_settings', '')))
- span.set_attribute(DEPLOYMENT_ENVIRONMENT,
- environment)
- span.set_attribute(SERVICE_NAME,
- application_name)
- span.set_attribute(SemanticConvention.GEN_AI_USAGE_COST,
- cost)
- 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: str(kwargs.get('text', '')),
- },
- )
-
- 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_AUDIO,
- system=SemanticConvention.GEN_AI_SYSTEM_ELEVENLABS,
- request_model=request_model,
- server_address=server_address,
- server_port=server_port,
- response_model=request_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
+ response = process_audio_response(
+ response=response,
+ gen_ai_endpoint=gen_ai_endpoint,
+ pricing_info=pricing_info,
+ server_port=server_port,
+ server_address=server_address,
+ environment=environment,
+ application_name=application_name,
+ metrics=metrics,
+ start_time=start_time,
+ span=span,
+ args=args,
+ kwargs=kwargs,
+ capture_message_content=capture_message_content,
+ disable_metrics=disable_metrics,
+ version=version
+ )
except Exception as e:
handle_exception(span, e)
- logger.error('Error in trace creation: %s', e)
- # Return original response
- return response
+ return response
return wrapper
diff --git a/sdk/python/src/openlit/instrumentation/elevenlabs/elevenlabs.py b/sdk/python/src/openlit/instrumentation/elevenlabs/elevenlabs.py
index 84f9c99b..4963c89c 100644
--- a/sdk/python/src/openlit/instrumentation/elevenlabs/elevenlabs.py
+++ b/sdk/python/src/openlit/instrumentation/elevenlabs/elevenlabs.py
@@ -1,145 +1,55 @@
"""
-Module for monitoring Ollama API calls.
+Module for monitoring ElevenLabs 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 openlit.__helpers import (
- get_audio_model_cost,
- handle_exception,
- create_metrics_attributes,
-)
+from opentelemetry.trace import SpanKind
+from openlit.__helpers import handle_exception
+from openlit.instrumentation.elevenlabs.utils import process_audio_response
from openlit.semcov import SemanticConvention
-# Initialize logger for logging potential issues and operations
-logger = logging.getLogger(__name__)
-
def generate(gen_ai_endpoint, 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 creating speech audio 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 ElevenLabs API.
- tracer: OpenTelemetry tracer for creating spans.
- pricing_info: Information used for calculating the cost of generating speech audio.
- capture_message_content: Flag indicating whether to trace the input text and generated audio.
-
- Returns:
- A function that wraps the speech audio creation method to add telemetry.
+ Generates a telemetry wrapper for GenAI function call
"""
def wrapper(wrapped, instance, args, kwargs):
"""
- Wraps the 'generate' API call to add telemetry.
-
- This collects metrics such as execution time, cost, and handles errors
- gracefully, adding details to the trace for observability.
-
- Args:
- wrapped: The original 'generate' method to be wrapped.
- instance: The instance of the class where the original method is defined.
- args: Positional arguments for the 'generate' method.
- kwargs: Keyword arguments for the 'generate' method.
-
- Returns:
- The response from the original 'generate' method.
+ Wraps the GenAI function call.
"""
server_address, server_port = "api.elevenlabs.io", 443
- request_model = kwargs.get('model', kwargs.get('model_id', 'eleven_multilingual_v2'))
+ request_model = kwargs.get("model", kwargs.get("model_id", "eleven_multilingual_v2"))
- span_name = f'{SemanticConvention.GEN_AI_OPERATION_TYPE_AUDIO} {request_model}'
+ span_name = f"{SemanticConvention.GEN_AI_OPERATION_TYPE_AUDIO} {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:
- # Calculate cost of the operation
- cost = get_audio_model_cost(request_model,
- pricing_info, kwargs.get('text', ''))
-
- # Set Span attributes
- span.set_attribute(TELEMETRY_SDK_NAME, 'openlit')
- span.set_attribute(SemanticConvention.GEN_AI_OPERATION,
- SemanticConvention.GEN_AI_OPERATION_TYPE_AUDIO)
- span.set_attribute(SemanticConvention.GEN_AI_SYSTEM,
- SemanticConvention.GEN_AI_SYSTEM_ASSEMBLYAI)
- 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_MODEL,
- request_model)
- span.set_attribute(SemanticConvention.GEN_AI_REQUEST_MODEL,
- request_model)
- span.set_attribute(SemanticConvention.GEN_AI_OUTPUT_TYPE,
- 'audio')
-
- # Set Span attributes (Extras)
- if gen_ai_endpoint == 'elevenlabs.generate':
- if isinstance(kwargs.get('voice', 'Rachel'), str):
- span.set_attribute(SemanticConvention.GEN_AI_REQUEST_AUDIO_VOICE,
- kwargs.get('voice', 'Rachel'))
- else:
- span.set_attribute(SemanticConvention.GEN_AI_REQUEST_AUDIO_VOICE,
- kwargs.get('voice_id', ''))
- span.set_attribute(SemanticConvention.GEN_AI_REQUEST_AUDIO_RESPONSE_FORMAT,
- kwargs.get('output_format', 'mp3'))
- span.set_attribute(SemanticConvention.GEN_AI_REQUEST_AUDIO_SETTINGS,
- str(kwargs.get('voice_settings', '')))
- span.set_attribute(DEPLOYMENT_ENVIRONMENT,
- environment)
- span.set_attribute(SERVICE_NAME,
- application_name)
- span.set_attribute(SemanticConvention.GEN_AI_USAGE_COST,
- cost)
- 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: str(kwargs.get('text', '')),
- },
- )
-
- 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_AUDIO,
- system=SemanticConvention.GEN_AI_SYSTEM_ELEVENLABS,
- request_model=request_model,
- server_address=server_address,
- server_port=server_port,
- response_model=request_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
+ response = process_audio_response(
+ response=response,
+ gen_ai_endpoint=gen_ai_endpoint,
+ pricing_info=pricing_info,
+ server_port=server_port,
+ server_address=server_address,
+ environment=environment,
+ application_name=application_name,
+ metrics=metrics,
+ start_time=start_time,
+ span=span,
+ args=args,
+ kwargs=kwargs,
+ capture_message_content=capture_message_content,
+ disable_metrics=disable_metrics,
+ version=version
+ )
except Exception as e:
handle_exception(span, e)
- logger.error('Error in trace creation: %s', e)
- # Return original response
- return response
+ return response
return wrapper
diff --git a/sdk/python/src/openlit/instrumentation/elevenlabs/utils.py b/sdk/python/src/openlit/instrumentation/elevenlabs/utils.py
new file mode 100644
index 00000000..2a83d952
--- /dev/null
+++ b/sdk/python/src/openlit/instrumentation/elevenlabs/utils.py
@@ -0,0 +1,133 @@
+"""
+ElevenLabs 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 (
+ get_audio_model_cost,
+ create_metrics_attributes,
+)
+from openlit.semcov import SemanticConvention
+
+def format_content(text):
+ """
+ Process text input to extract content.
+ """
+ return str(text) if text else ""
+
+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_audio_metrics(metrics, gen_ai_operation, gen_ai_system, server_address, server_port,
+ request_model, response_model, environment, application_name, start_time, end_time, cost):
+ """
+ Record audio generation 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_cost"].record(cost, attributes)
+
+def common_audio_logic(scope, gen_ai_endpoint, pricing_info, environment, application_name,
+ metrics, capture_message_content, disable_metrics, version):
+ """
+ Process audio generation request and generate Telemetry
+ """
+
+ text = format_content(scope._kwargs.get("text", ""))
+ request_model = scope._kwargs.get("model", scope._kwargs.get("model_id", "eleven_multilingual_v2"))
+ is_stream = False # ElevenLabs audio generation is not streaming
+
+ cost = get_audio_model_cost(request_model, pricing_info, text)
+
+ # Common Span Attributes
+ common_span_attributes(scope,
+ SemanticConvention.GEN_AI_OPERATION_TYPE_AUDIO, SemanticConvention.GEN_AI_SYSTEM_ELEVENLABS,
+ scope._server_address, scope._server_port, request_model, request_model,
+ environment, application_name, is_stream, scope._tbt, scope._ttft, version)
+
+ # Span Attributes for Cost and Tokens
+ scope._span.set_attribute(SemanticConvention.GEN_AI_USAGE_COST, cost)
+
+ # Span Attributes for Response parameters
+ scope._span.set_attribute(SemanticConvention.GEN_AI_OUTPUT_TYPE, scope._kwargs.get("output_format", "mp3_44100_128"))
+
+ # Audio-specific span attributes
+ scope._span.set_attribute(SemanticConvention.GEN_AI_REQUEST_AUDIO_VOICE, scope._kwargs.get("voice_id", ""))
+ scope._span.set_attribute(SemanticConvention.GEN_AI_REQUEST_AUDIO_SETTINGS, str(scope._kwargs.get("voice_settings", "")))
+
+ # Span Attributes for Content
+ if capture_message_content:
+ scope._span.set_attribute(SemanticConvention.GEN_AI_CONTENT_PROMPT, text)
+
+ # To be removed once 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: text,
+ },
+ )
+
+ scope._span.set_status(Status(StatusCode.OK))
+
+ # Metrics
+ if not disable_metrics:
+ record_audio_metrics(metrics, SemanticConvention.GEN_AI_OPERATION_TYPE_AUDIO, SemanticConvention.GEN_AI_SYSTEM_ELEVENLABS,
+ scope._server_address, scope._server_port, request_model, request_model, environment,
+ application_name, scope._start_time, scope._end_time, cost)
+
+def process_audio_response(response, gen_ai_endpoint, 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 audio generation request and generate Telemetry
+ """
+
+ scope = type("GenericScope", (), {})()
+
+ scope._start_time = start_time
+ scope._end_time = time.time()
+ scope._span = span
+ scope._server_address, scope._server_port = server_address, server_port
+ scope._kwargs = kwargs
+ scope._args = args
+
+ # Initialize streaming and timing values for ElevenLabs audio generation
+ scope._response_model = kwargs.get("model", kwargs.get("model_id", "eleven_multilingual_v2"))
+ scope._tbt = 0.0
+ scope._ttft = scope._end_time - scope._start_time
+
+ common_audio_logic(scope, gen_ai_endpoint, pricing_info, environment, application_name,
+ metrics, capture_message_content, disable_metrics, version)
+
+ return response
diff --git a/sdk/python/src/openlit/instrumentation/gpt4all/utils.py b/sdk/python/src/openlit/instrumentation/gpt4all/utils.py
index 1dfc380e..56481687 100644
--- a/sdk/python/src/openlit/instrumentation/gpt4all/utils.py
+++ b/sdk/python/src/openlit/instrumentation/gpt4all/utils.py
@@ -109,7 +109,7 @@ def record_embedding_metrics(metrics, gen_ai_operation, gen_ai_system, server_ad
metrics["genai_prompt_tokens"].add(input_tokens, attributes)
metrics["genai_cost"].record(cost, attributes)
-def common_generate_logic(scope, pricing_info, environment, application_name, metrics,
+def common_t2s_logic(scope, pricing_info, environment, application_name, metrics,
capture_message_content, disable_metrics, version, is_stream):
"""
Process generate request and generate Telemetry
@@ -228,7 +228,7 @@ def process_streaming_generate_response(scope, pricing_info, environment, applic
"""
Process generate request and generate Telemetry
"""
- common_generate_logic(scope, pricing_info, environment, application_name, metrics,
+ common_t2s_logic(scope, pricing_info, environment, application_name, metrics,
capture_message_content, disable_metrics, version, is_stream=True)
def process_generate_response(response, request_model, pricing_info, server_port, server_address,
@@ -252,7 +252,7 @@ def process_generate_response(response, request_model, pricing_info, server_port
scope._args = args
scope._tools = None
- common_generate_logic(scope, pricing_info, environment, application_name, metrics,
+ common_t2s_logic(scope, pricing_info, environment, application_name, metrics,
capture_message_content, disable_metrics, version, is_stream=False)
return response
diff --git a/sdk/python/tests/test_elevenlabs.py.hold b/sdk/python/tests/test_elevenlabs.py
similarity index 55%
rename from sdk/python/tests/test_elevenlabs.py.hold
rename to sdk/python/tests/test_elevenlabs.py
index 0ef7c21c..76bf4b68 100644
--- a/sdk/python/tests/test_elevenlabs.py.hold
+++ b/sdk/python/tests/test_elevenlabs.py
@@ -28,36 +28,6 @@ openlit.init(
application_name="openlit-python-elevenlabs-test"
)
-def test_sync_elevenlabs_generate():
- """
- Tests synchronous generate text-to-speech with the 'eleven_multilingual_v2' model.
-
- Raises:
- AssertionError: If the generate text-to-speech response object is not as expected.
- """
-
- try:
- audio = sync_client.generate(
- text="Say LLM Monitoring",
- voice="Sarah",
- model="eleven_multilingual_v2"
- )
- assert isinstance(audio, types.GeneratorType)
-
- audio = sync_client.generate(
- text="Say LLM Observability!",
- voice="Sarah",
- model="eleven_multilingual_v2",
- stream=True
- )
- assert isinstance(audio, types.GeneratorType)
-
- # pylint: disable=broad-exception-caught
- except Exception as e:
- if "rate limit" in str(e).lower():
- print("Rate Limited:", e)
- else:
- raise
def test_sync_elevenlabs_t2s():
"""
@@ -83,38 +53,6 @@ def test_sync_elevenlabs_t2s():
else:
raise
-async def test_async_elevenlabs_generate():
- """
- Tests synchronous generate text-to-speech with the 'eleven_multilingual_v2' model.
-
- Raises:
- AssertionError: If the generate text-to-speech response object is not as expected.
- """
-
- try:
- audio = await async_client.generate(
- text="Say LLM Monitoring",
- voice="Sarah",
- model="eleven_multilingual_v2"
- )
- assert isinstance(audio, types.AsyncGeneratorType)
-
- audio = await async_client.generate(
- text="Say LLM Observability!",
- voice="Sarah",
- model="eleven_multilingual_v2",
- stream=True
- )
- assert isinstance(audio, types.AsyncGeneratorType)
-
- # pylint: disable=broad-exception-caught
- except Exception as e:
- if "rate limit" in str(e).lower():
- print("Rate Limited:", e)
- else:
- raise
-
@pytest.mark.asyncio
async def test_async_elevenlabs_t2s():
"""