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: Support custom attributes (#1089)

Ishan Jain7060348ff421
diff --git a/README.md b/README.md
index 49ef6907..f3dcdc7f 100644
--- a/README.md
+++ b/README.md
@@ -177,7 +177,7 @@ Just head over to OpenLIT at `127.0.0.1:3000` on your browser to start exploring
## 📦 Supported Integrations
-OpenLIT auto-instruments **44+ LLM providers, AI frameworks, and vector databases** with a single line of code. Each integration produces [OpenTelemetry-native](https://opentelemetry.io/) traces and metrics. Click any card to view the integration docs.
+OpenLIT auto-instruments **50+ LLM providers, AI frameworks, and vector databases** with a single line of code. Each integration produces [OpenTelemetry-native](https://opentelemetry.io/) traces and metrics. Click any card to view the integration docs.
<sub>
<img src="https://img.shields.io/badge/Python-3776AB?logo=python&logoColor=white&style=flat-square" height="16"> Python SDK &nbsp;&nbsp;
@@ -232,7 +232,7 @@ OpenLIT auto-instruments **44+ LLM providers, AI frameworks, and vector database
<td align="center" width="160"><a href="https://docs.openlit.io/latest/sdk/integrations/pydantic"><b>Pydantic AI</b></a><br/><img src="https://img.shields.io/badge/Python-3776AB?logo=python&logoColor=white&style=flat-square" height="18"></td>
</tr>
<tr>
-<td align="center" width="160"><a href="https://docs.openlit.io/latest/sdk/integrations/phidata"><b>Agno</b></a><br/><img src="https://img.shields.io/badge/Python-3776AB?logo=python&logoColor=white&style=flat-square" height="18"></td>
+<td align="center" width="160"><a href="https://docs.openlit.io/latest/sdk/integrations/agno"><b>Agno</b></a><br/><img src="https://img.shields.io/badge/Python-3776AB?logo=python&logoColor=white&style=flat-square" height="18"></td>
<td align="center" width="160"><a href="https://docs.openlit.io/latest/sdk/integrations/browser-use"><b>Browser Use</b></a><br/><img src="https://img.shields.io/badge/Python-3776AB?logo=python&logoColor=white&style=flat-square" height="18"></td>
<td align="center" width="160"><a href="https://docs.openlit.io/latest/sdk/integrations/haystack"><b>Haystack</b></a><br/><img src="https://img.shields.io/badge/Python-3776AB?logo=python&logoColor=white&style=flat-square" height="18"></td>
<td align="center" width="160"><a href="https://docs.openlit.io/latest/sdk/integrations/letta"><b>Letta</b></a><br/><img src="https://img.shields.io/badge/Python-3776AB?logo=python&logoColor=white&style=flat-square" height="18"></td>
@@ -247,6 +247,16 @@ OpenLIT auto-instruments **44+ LLM providers, AI frameworks, and vector database
<td align="center" width="160"><a href="https://docs.openlit.io/latest/sdk/integrations/dynamiq"><b>Dynamiq</b></a><br/><img src="https://img.shields.io/badge/Python-3776AB?logo=python&logoColor=white&style=flat-square" height="18"></td>
<td align="center" width="160"><a href="https://docs.openlit.io/latest/sdk/integrations/openai-agents"><b>OpenAI Agents</b></a><br/><img src="https://img.shields.io/badge/Python-3776AB?logo=python&logoColor=white&style=flat-square" height="18"></td>
<td align="center" width="160"><a href="https://docs.openlit.io/latest/sdk/integrations/firecrawl"><b>Firecrawl</b></a><br/><img src="https://img.shields.io/badge/Python-3776AB?logo=python&logoColor=white&style=flat-square" height="18"></td>
+<td align="center" width="160"><a href="https://docs.openlit.io/latest/sdk/integrations/google-adk"><b>Google ADK</b></a><br/><img src="https://img.shields.io/badge/Python-3776AB?logo=python&logoColor=white&style=flat-square" height="18"></td>
+</tr>
+<tr>
+<td align="center" width="160"><a href="https://docs.openlit.io/latest/sdk/integrations/langgraph"><b>LangGraph</b></a><br/><img src="https://img.shields.io/badge/Python-3776AB?logo=python&logoColor=white&style=flat-square" height="18"></td>
+<td align="center" width="160"><a href="https://docs.openlit.io/latest/sdk/integrations/smolagents"><b>Smolagents</b></a><br/><img src="https://img.shields.io/badge/Python-3776AB?logo=python&logoColor=white&style=flat-square" height="18"></td>
+<td align="center" width="160"><a href="https://docs.openlit.io/latest/sdk/integrations/strands"><b>Strands Agents</b></a><br/><img src="https://img.shields.io/badge/Python-3776AB?logo=python&logoColor=white&style=flat-square" height="18"></td>
+<td align="center" width="160"><a href="https://docs.openlit.io/latest/sdk/integrations/claude-agent-sdk"><b>Claude Agent SDK</b></a><br/><img src="https://img.shields.io/badge/Python-3776AB?logo=python&logoColor=white&style=flat-square" height="18"></td>
+</tr>
+<tr>
+<td align="center" width="160"><a href="https://docs.openlit.io/latest/sdk/integrations/agent-framework"><b>MS Agent Framework</b></a><br/><img src="https://img.shields.io/badge/Python-3776AB?logo=python&logoColor=white&style=flat-square" height="18"></td>
</tr>
</table>
@@ -271,6 +281,7 @@ OpenLIT auto-instruments **44+ LLM providers, AI frameworks, and vector database
<tr>
<td align="center" width="160"><a href="https://docs.openlit.io/latest/sdk/integrations/elevenlabs"><b>ElevenLabs</b></a><br/><img src="https://img.shields.io/badge/Python-3776AB?logo=python&logoColor=white&style=flat-square" height="18"></td>
<td align="center" width="160"><a href="https://docs.openlit.io/latest/sdk/integrations/assemblyai"><b>AssemblyAI</b></a><br/><img src="https://img.shields.io/badge/Python-3776AB?logo=python&logoColor=white&style=flat-square" height="18"></td>
+<td align="center" width="160"><a href="https://docs.openlit.io/latest/sdk/integrations/mcp"><b>MCP</b></a><br/><img src="https://img.shields.io/badge/Python-3776AB?logo=python&logoColor=white&style=flat-square" height="18"></td>
</tr>
</table>
diff --git a/docs/latest/sdk/configuration.mdx b/docs/latest/sdk/configuration.mdx
index 6a945d98..d9173e10 100644
--- a/docs/latest/sdk/configuration.mdx
+++ b/docs/latest/sdk/configuration.mdx
@@ -45,11 +45,8 @@ Customize OpenLIT SDK behavior for your specific instrumentation needs:
| `disable_metrics` | `--disable_metrics` | `OPENLIT_DISABLE_METRICS` | Disable cost tracking and performance metrics collection | `False` | No |
| `max_content_length` | `--max_content_length` | `OPENLIT_MAX_CONTENT_LENGTH` | Maximum character length for captured prompt/completion content. `None` (default) means no truncation. Set to a positive integer to truncate content exceeding that length. `0` or `-1` also disable truncation. | `None` | No |
| `pricing_json` | `--pricing_json` | `OPENLIT_PRICING_JSON` | Custom pricing configuration for accurate LLM cost tracking | `None` | No |
-| `detailed_tracing` | `--detailed_tracing` | `OPENLIT_DETAILED_TRACING` | Enable detailed AI framework and component-level tracing | `True` | No |
+| `disable_events` | `--disable_events` | `OPENLIT_DISABLE_EVENTS` | Disable OTel Logger event emission | `False` | No |
| `collect_system_metrics` | `--collect_system_metrics` | `OPENLIT_COLLECT_SYSTEM_METRICS` | Comprehensive system monitoring (CPU, memory, disk, network, GPU) for AI workloads | `False` | No |
-| `tracer` | N/A | N/A | An instance of OpenTelemetry Tracer for tracing operations | `None` | No |
-| `event_logger` | N/A | N/A | EventLoggerProvider instance | `None` | No |
-| `meter` | N/A | N/A | OpenTelemetry Metrics instance | `None` | No |
### Database instrumentation options
@@ -57,8 +54,7 @@ These options apply to database instrumentations like PostgreSQL (psycopg3):
| Parameter | CLI Argument | Environment Variable | Description | Default | Required |
|-----------|--------------|---------------------|-------------|---------|----------|
-| `capture_parameters` | `--capture_parameters` | `OPENLIT_CAPTURE_PARAMETERS` | Capture database query parameters in spans (security risk - may expose sensitive data) | `False` | No |
-| `enable_sqlcommenter` | `--enable_sqlcommenter` | `OPENLIT_ENABLE_SQLCOMMENTER` | Inject OpenTelemetry trace context as SQL comments for database log correlation | `False` | No |
+| `capture_db_parameters` | `--capture_db_parameters` | `OPENLIT_CAPTURE_DB_PARAMETERS` | Capture database query parameters in OTel per-key format (`db.query.parameter.<key>`) | `False` | No |
### Evaluation export options
@@ -69,23 +65,9 @@ Configure how evaluation results are exported:
| `evals_logs_export` | `--evals_logs_export` | `OPENLIT_EVALS_LOGS_EXPORT` | Emit evaluation results as OTel Log Records instead of OTel Events. Useful for backends like Grafana Loki that handle logs better than events. | `True` | No |
<Warning>
-**Security Notice**: Enabling `capture_parameters` records query parameters (the values passed to `$1`, `$2`, etc.) in your traces. This may expose sensitive data like passwords, API keys, or personal information. Only enable in development environments or when you're certain parameters don't contain sensitive data.
+**Security Notice**: Enabling `capture_db_parameters` records query parameters (the values passed to `$1`, `$2`, etc.) in your traces using the OTel per-key format (`db.query.parameter.<key>`). This may expose sensitive data like passwords, API keys, or personal information. Only enable in development environments or when you're certain parameters don't contain sensitive data.
</Warning>
-**SQLCommenter Example:**
-
-When `enable_sqlcommenter` is enabled, queries are automatically modified to include trace context:
-
-```sql
--- Original
-SELECT * FROM users WHERE id = $1;
-
--- With SQLCommenter
-SELECT * FROM users WHERE id = $1 /*traceparent='00-abc123def456-789xyz-01',application='my_app'*/;
-```
-
-This enables correlation between application traces and database logs (e.g., `pg_stat_statements`, `auto_explain`).
-
### Deprecated parameters
| Parameter | CLI Argument | Environment Variable | Description | Default | Required |
diff --git a/docs/latest/sdk/integrations/psycopg.mdx b/docs/latest/sdk/integrations/psycopg.mdx
index 6f7231e6..1aec6abb 100644
--- a/docs/latest/sdk/integrations/psycopg.mdx
+++ b/docs/latest/sdk/integrations/psycopg.mdx
@@ -51,48 +51,22 @@ OpenLIT provides additional configuration options for database instrumentation:
| Parameter | Environment Variable | Description | Default |
|-----------|---------------------|-------------|---------|
-| `capture_parameters` | `OPENLIT_CAPTURE_PARAMETERS` | Capture query parameters in spans | `False` |
-| `enable_sqlcommenter` | `OPENLIT_ENABLE_SQLCOMMENTER` | Inject trace context as SQL comments | `False` |
+| `capture_db_parameters` | `OPENLIT_CAPTURE_DB_PARAMETERS` | Capture query parameters in OTel per-key format (`db.query.parameter.<key>`) | `False` |
-### capture_parameters
+### capture_db_parameters
-When enabled, query parameters are recorded in span attributes for debugging purposes.
+When enabled, query parameters are recorded as per-key span attributes following the OTel semantic convention `db.query.parameter.<key>`.
```python
import openlit
-openlit.init(capture_parameters=True)
+openlit.init(capture_db_parameters=True)
```
<Warning>
-**Security Risk**: Enabling `capture_parameters` may expose sensitive data like passwords, tokens, or PII in your traces. Only enable in development environments or when you're certain parameters don't contain sensitive information.
+**Security Risk**: Enabling `capture_db_parameters` may expose sensitive data like passwords, tokens, or PII in your traces. Only enable in development environments or when you're certain parameters don't contain sensitive information.
</Warning>
-### enable_sqlcommenter (SQLCommenter)
-
-When enabled, OpenLIT injects OpenTelemetry trace context into SQL queries as comments. This enables correlation between application traces and database logs.
-
-```python
-import openlit
-
-openlit.init(enable_sqlcommenter=True)
-```
-
-**Example query transformation:**
-
-```sql
--- Original query
-SELECT * FROM users WHERE id = $1;
-
--- With SQLCommenter enabled
-SELECT * FROM users WHERE id = $1 /*traceparent='00-abc123def456-789xyz-01',application='my_app'*/;
-```
-
-**Benefits:**
-- Correlate slow queries in `pg_stat_statements` with application traces
-- Link `EXPLAIN ANALYZE` output to specific requests
-- Debug performance issues across application and database layers
-
---
<CardGroup cols={3}>
diff --git a/sdk/python/src/openlit/__helpers.py b/sdk/python/src/openlit/__helpers.py
index f78381dd..e884024a 100644
--- a/sdk/python/src/openlit/__helpers.py
+++ b/sdk/python/src/openlit/__helpers.py
@@ -52,6 +52,12 @@ _langgraph_wrapper_active: ContextVar[bool] = ContextVar(
"openlit_langgraph_wrapper_active", default=False
)
+# User-supplied custom span attributes propagated via context managers,
+# decorators, or the inject_additional_attributes() helper.
+_custom_span_attributes: ContextVar[Optional[Dict[str, Any]]] = ContextVar(
+ "openlit_custom_span_attributes", default=None
+)
+
def set_framework_llm_active():
"""Set by framework LLM callbacks; returns a token to reset later."""
@@ -564,7 +570,14 @@ def otel_event(name, attributes, body):
Returns an OpenTelemetry LogRecord representing an event.
"""
- base_attrs = attributes or {}
+ base_attrs = dict(attributes) if attributes else {}
+ global_attrs = OpenlitConfig.custom_span_attributes
+ if global_attrs:
+ for key, value in global_attrs.items():
+ base_attrs.setdefault(key, value)
+ context_attrs = _custom_span_attributes.get()
+ if context_attrs:
+ base_attrs.update(context_attrs)
return LogRecord(
attributes=base_attrs,
body=body,
@@ -722,6 +735,7 @@ def common_span_attributes(
scope._span.set_attribute(SemanticConvention.GEN_AI_SERVER_TBT, tbt)
scope._span.set_attribute(SemanticConvention.GEN_AI_SERVER_TTFT, ttft)
scope._span.set_attribute(SemanticConvention.GEN_AI_SDK_VERSION, version)
+ _apply_custom_span_attributes(scope._span)
def record_completion_metrics(
@@ -854,6 +868,38 @@ def get_agent_name() -> Optional[str]:
return _current_agent_name.get()
+def set_custom_attributes(attrs: Dict[str, Any]):
+ """Set custom span attributes in context. Returns a token for reset."""
+ return _custom_span_attributes.set(attrs)
+
+
+def reset_custom_attributes(token):
+ """Reset custom span attributes context to its previous value."""
+ _custom_span_attributes.reset(token)
+
+
+def get_custom_attributes() -> Optional[Dict[str, Any]]:
+ """Get custom span attributes from context, or None."""
+ return _custom_span_attributes.get()
+
+
+def _apply_custom_span_attributes(span):
+ """
+ Apply global and context-scoped custom attributes to a span.
+ Global attributes (from init) are applied first; context attributes
+ (from using_attributes / inject_additional_attributes) override on conflict.
+ """
+ global_attrs = OpenlitConfig.custom_span_attributes
+ if global_attrs:
+ for key, value in global_attrs.items():
+ span.set_attribute(key, value)
+
+ context_attrs = _custom_span_attributes.get()
+ if context_attrs:
+ for key, value in context_attrs.items():
+ span.set_attribute(key, value)
+
+
def record_agent_duration(
metrics, agent_name, duration, operation="chat", system=None, error_type=None
):
@@ -1055,6 +1101,7 @@ def common_db_span_attributes(
scope._span.set_attribute(DEPLOYMENT_ENVIRONMENT, environment)
scope._span.set_attribute(SERVICE_NAME, application_name)
scope._span.set_attribute(SemanticConvention.DB_SDK_VERSION, version)
+ _apply_custom_span_attributes(scope._span)
def format_system_instructions(text):
@@ -1121,6 +1168,7 @@ def common_framework_span_attributes(
SemanticConvention.GEN_AI_CLIENT_OPERATION_DURATION,
scope._end_time - scope._start_time,
)
+ _apply_custom_span_attributes(scope._span)
def record_mcp_metrics(
diff --git a/sdk/python/src/openlit/__init__.py b/sdk/python/src/openlit/__init__.py
index e0ca7811..c986319f 100644
--- a/sdk/python/src/openlit/__init__.py
+++ b/sdk/python/src/openlit/__init__.py
@@ -5,12 +5,12 @@ This module sets up the openLIT configuration and instrumentation for various
large language models (LLMs).
"""
-from typing import Dict
+from typing import Any, Dict
import logging
import os
from importlib.util import find_spec
from functools import wraps
-from contextlib import contextmanager
+from contextlib import ContextDecorator, contextmanager
import requests
# Import internal modules for setting up tracing and fetching pricing info.
@@ -26,6 +26,8 @@ from openlit.__helpers import (
get_env_variable,
set_agent_name,
reset_agent_name,
+ set_custom_attributes,
+ reset_custom_attributes,
record_agent_invocation,
record_agent_tool_error,
)
@@ -96,15 +98,11 @@ def instrument_if_available(
instrumentor_instance.instrument(
environment=config.environment,
application_name=config.application_name,
- tracer=config.tracer,
- event_provider=config.event_provider,
pricing_info=config.pricing_info,
capture_message_content=config.capture_message_content,
- metrics_dict=config.metrics_dict,
disable_metrics=config.disable_metrics,
- detailed_tracing=config.detailed_tracing,
- capture_parameters=config.capture_parameters,
- enable_sqlcommenter=config.enable_sqlcommenter,
+ disable_events=config.disable_events,
+ capture_db_parameters=config.capture_db_parameters,
)
else:
logger.info(
@@ -120,49 +118,49 @@ def init(
environment="default",
application_name="default",
service_name="default",
- tracer=None,
- event_logger=None,
otlp_endpoint=None,
otlp_headers=None,
disable_batch=False,
capture_message_content=True,
disabled_instrumentors=None,
- meter=None,
disable_metrics=False,
+ disable_events=False,
pricing_json=None,
collect_gpu_stats=False,
- detailed_tracing=True,
collect_system_metrics=False,
- capture_parameters=False,
- enable_sqlcommenter=False,
+ capture_db_parameters=False,
evals_logs_export=True,
max_content_length=None,
+ custom_span_attributes=None,
):
"""
Initializes the openLIT configuration and setups tracing.
This function sets up the openLIT environment with provided configurations
- and initializes instrumentors for tracing.
+ and initializes instrumentors for tracing. Existing OTel providers
+ (TracerProvider, MeterProvider, LoggerProvider) are auto-detected and
+ reused when already configured.
Args:
environment (str): Deployment environment.
application_name (str): Application name.
- tracer: Tracer instance (Optional).
- event_logger: OTel Logger instance for emitting events (Optional).
- meter: OpenTelemetry Metrics Instance (Optional).
otlp_endpoint (str): OTLP endpoint for exporter (Optional).
otlp_headers (Dict[str, str]): OTLP headers for exporter (Optional).
disable_batch (bool): Flag to disable batch span processing (Optional).
capture_message_content (bool): Flag to trace content (Optional).
disabled_instrumentors (List[str]): Optional. List of instrumentor names to disable.
disable_metrics (bool): Flag to disable metrics (Optional).
+ disable_events (bool): Flag to disable OTel Logger event emission (Optional).
pricing_json(str): File path or url to the pricing json (Optional).
collect_gpu_stats (bool): Flag to enable or disable GPU metrics collection.
- detailed_tracing (bool): Enable detailed component-level tracing for debugging and optimization.
- Defaults to False to use workflow-level tracing with minimal storage overhead.
+ capture_db_parameters (bool): Capture database query parameters in per-key OTel format
+ (db.query.parameter.<key>). WARNING: may expose sensitive data.
max_content_length (int): Maximum character length for captured content attributes (prompts,
completions, tool output, etc.). None (default) means no truncation.
Set to a positive integer to truncate content to that length.
+ custom_span_attributes (dict): Custom key-value attributes applied to every auto-instrumented
+ span. Values must be valid OTel attribute types (str, int,
+ float, bool, or sequences thereof). Optional.
"""
disabled_instrumentors = disabled_instrumentors if disabled_instrumentors else []
logger.info("Starting openLIT initialization...")
@@ -207,22 +205,22 @@ def init(
disabled_instrumentors = env_config["disabled_instrumentors"]
if disable_metrics is False and "disable_metrics" in env_config:
disable_metrics = env_config["disable_metrics"]
+ if disable_events is False and "disable_events" in env_config:
+ disable_events = env_config["disable_events"]
if pricing_json is None and "pricing_json" in env_config:
pricing_json = env_config["pricing_json"]
if collect_gpu_stats is False and "collect_gpu_stats" in env_config:
collect_gpu_stats = env_config["collect_gpu_stats"]
- if detailed_tracing is True and "detailed_tracing" in env_config:
- detailed_tracing = env_config["detailed_tracing"]
if collect_system_metrics is False and "collect_system_metrics" in env_config:
collect_system_metrics = env_config["collect_system_metrics"]
- if capture_parameters is False and "capture_parameters" in env_config:
- capture_parameters = env_config["capture_parameters"]
- if enable_sqlcommenter is False and "enable_sqlcommenter" in env_config:
- enable_sqlcommenter = env_config["enable_sqlcommenter"]
+ if capture_db_parameters is False and "capture_db_parameters" in env_config:
+ capture_db_parameters = env_config["capture_db_parameters"]
if evals_logs_export is True and "evals_logs_export" in env_config:
evals_logs_export = env_config["evals_logs_export"]
if max_content_length is None and "max_content_length" in env_config:
max_content_length = env_config["max_content_length"]
+ if custom_span_attributes is None and "custom_span_attributes" in env_config:
+ custom_span_attributes = env_config["custom_span_attributes"]
except ImportError:
# Fallback if config module is not available - continue without env var support
@@ -245,7 +243,7 @@ def init(
tracer = setup_tracing(
application_name=final_service_name,
environment=environment,
- tracer=tracer,
+ tracer=None,
otlp_endpoint=otlp_endpoint,
otlp_headers=otlp_headers,
disable_batch=disable_batch,
@@ -259,7 +257,7 @@ def init(
event_provider = setup_events(
application_name=final_service_name,
environment=environment,
- event_logger=event_logger,
+ event_logger=None,
otlp_endpoint=None,
otlp_headers=None,
disable_batch=disable_batch,
@@ -272,7 +270,7 @@ def init(
metrics_dict, err = setup_meter(
application_name=final_service_name,
environment=environment,
- meter=meter,
+ meter=None,
otlp_endpoint=otlp_endpoint,
otlp_headers=otlp_headers,
)
@@ -295,8 +293,6 @@ def init(
config.update_config(
environment,
final_service_name,
- tracer,
- event_provider,
otlp_endpoint,
otlp_headers,
disable_batch,
@@ -304,11 +300,11 @@ def init(
metrics_dict,
disable_metrics,
fetch_pricing_info(pricing_json),
- detailed_tracing,
- capture_parameters,
- enable_sqlcommenter,
+ disable_events,
+ capture_db_parameters,
evals_logs_export,
max_content_length,
+ custom_span_attributes,
)
# Create instrumentor instances dynamically
@@ -596,6 +592,56 @@ def agent_context(name):
reset_agent_name(token)
+class using_attributes(ContextDecorator):
+ """
+ Context manager and decorator to add custom attributes to all
+ auto-instrumented spans created within its scope.
+
+ Attributes are only applied to spans created while the context is active.
+ Values must be valid OTel attribute types (str, int, float, bool, or
+ sequences thereof).
+
+ As context manager:
+ with openlit.using_attributes({"user.id": "u1", "team": "ml"}):
+ client.chat.completions.create(...)
+
+ As decorator:
+ @openlit.using_attributes({"user.id": "u1"})
+ def my_func():
+ client.chat.completions.create(...)
+ """
+
+ def __init__(self, attributes: Dict[str, Any]):
+ self._attributes = attributes
+ self._token = None
+
+ def __enter__(self):
+ self._token = set_custom_attributes(self._attributes)
+ return self
+
+ def __exit__(self, *exc):
+ reset_custom_attributes(self._token)
+ return False
+
+
+def inject_additional_attributes(fn, attributes: Dict[str, Any]):
+ """
+ Execute *fn()* with custom span attributes attached to all
+ auto-instrumented spans created during its execution.
+
+ Usage:
+ response = openlit.inject_additional_attributes(
+ lambda: client.chat.completions.create(...),
+ {"user.id": "u123", "experiment": "v2"},
+ )
+ """
+ token = set_custom_attributes(attributes)
+ try:
+ return fn()
+ finally:
+ reset_custom_attributes(token)
+
+
def trace(wrapped):
"""
Generates a telemetry wrapper for messages to collect metrics.
diff --git a/sdk/python/src/openlit/_config.py b/sdk/python/src/openlit/_config.py
index c977718f..55529ef2 100644
--- a/sdk/python/src/openlit/_config.py
+++ b/sdk/python/src/openlit/_config.py
@@ -17,13 +17,11 @@ class OpenlitConfig:
environment (str): Deployment environment of the application.
application_name (str): Name of the application using openLIT.
pricing_info (Dict[str, Any]): Pricing information.
- tracer (Optional[Any]): Tracer instance for OpenTelemetry.
- event_provider (Optional[Any]): Event logger provider for OpenTelemetry.
otlp_endpoint (Optional[str]): Endpoint for OTLP.
otlp_headers (Optional[Dict[str, str]]): Headers for OTLP.
disable_batch (bool): Flag to disable batch span processing in tracing.
capture_message_content (bool): Flag to enable or disable tracing of content.
- detailed_tracing (bool): Flag to enable detailed component-level tracing.
+ disable_events (bool): Flag to disable OTel Logger event emission.
"""
_instance = None
@@ -41,27 +39,23 @@ class OpenlitConfig:
cls.environment = "default"
cls.application_name = "default"
cls.pricing_info = {}
- cls.tracer = None
- cls.event_provider = None
cls.metrics_dict = {}
cls.otlp_endpoint = None
cls.otlp_headers = None
cls.disable_batch = False
cls.capture_message_content = True
cls.disable_metrics = False
- cls.detailed_tracing = True
- cls.capture_parameters = False
- cls.enable_sqlcommenter = False
+ cls.disable_events = False
+ cls.capture_db_parameters = False
cls.evals_logs_export = True
cls.max_content_length = None # None = no truncation
+ cls.custom_span_attributes = {}
@classmethod
def update_config(
cls,
environment,
application_name,
- tracer,
- event_provider,
otlp_endpoint,
otlp_headers,
disable_batch,
@@ -69,11 +63,11 @@ class OpenlitConfig:
metrics_dict,
disable_metrics,
pricing_info,
- detailed_tracing,
- capture_parameters=False,
- enable_sqlcommenter=False,
+ disable_events=False,
+ capture_db_parameters=False,
evals_logs_export=True,
max_content_length=None,
+ custom_span_attributes=None,
):
"""
Updates the configuration based on provided parameters.
@@ -81,34 +75,30 @@ class OpenlitConfig:
Args:
environment (str): Deployment environment.
application_name (str): Application name.
- tracer: Tracer instance.
- event_provider: Event logger provider instance.
otlp_endpoint (str): OTLP endpoint.
otlp_headers (Dict[str, str]): OTLP headers.
disable_batch (bool): Disable batch span processing flag.
capture_message_content (bool): Enable or disable content tracing.
- metrics_dict: Dictionary of metrics.
+ metrics_dict: Dictionary of metrics instruments.
disable_metrics (bool): Flag to disable metrics.
pricing_info (dict): Already-resolved pricing information dict.
- detailed_tracing (bool): Flag to enable detailed component-level tracing.
- capture_parameters (bool): Capture database query parameters (security risk).
- enable_sqlcommenter (bool): Inject trace context as SQL comments.
+ disable_events (bool): Flag to disable OTel Logger event emission.
+ capture_db_parameters (bool): Capture database query parameters (security risk).
evals_logs_export (bool): Emit evaluation results as OTEL Log Records instead of OTEL Events.
max_content_length: Maximum character length for captured content (None = no limit).
+ custom_span_attributes (dict): Custom key-value attributes applied to every span.
"""
cls.environment = environment
cls.application_name = application_name
cls.pricing_info = pricing_info
- cls.tracer = tracer
- cls.event_provider = event_provider
cls.metrics_dict = metrics_dict
cls.otlp_endpoint = otlp_endpoint
cls.otlp_headers = otlp_headers
cls.disable_batch = disable_batch
cls.capture_message_content = capture_message_content
cls.disable_metrics = disable_metrics
- cls.detailed_tracing = detailed_tracing
- cls.capture_parameters = capture_parameters
- cls.enable_sqlcommenter = enable_sqlcommenter
+ cls.disable_events = disable_events
+ cls.capture_db_parameters = capture_db_parameters
cls.evals_logs_export = evals_logs_export
cls.max_content_length = max_content_length
+ cls.custom_span_attributes = custom_span_attributes or {}
diff --git a/sdk/python/src/openlit/cli/bootstrap/sitecustomize.py b/sdk/python/src/openlit/cli/bootstrap/sitecustomize.py
index 69004fac..2c296f42 100644
--- a/sdk/python/src/openlit/cli/bootstrap/sitecustomize.py
+++ b/sdk/python/src/openlit/cli/bootstrap/sitecustomize.py
@@ -35,11 +35,13 @@ except ImportError:
"OPENLIT_DISABLED_INSTRUMENTORS": "disabled_instrumentors",
"OPENLIT_DISABLE_BATCH": "disable_batch",
"OPENLIT_DISABLE_METRICS": "disable_metrics",
+ "OPENLIT_DISABLE_EVENTS": "disable_events",
"OPENLIT_COLLECT_GPU_STATS": "collect_gpu_stats",
- "OPENLIT_DETAILED_TRACING": "detailed_tracing",
"OPENLIT_PRICING_JSON": "pricing_json",
- "OPENLIT_CAPTURE_PARAMETERS": "capture_parameters",
- "OPENLIT_ENABLE_SQLCOMMENTER": "enable_sqlcommenter",
+ "OPENLIT_CAPTURE_DB_PARAMETERS": "capture_db_parameters",
+ "OPENLIT_MAX_CONTENT_LENGTH": "max_content_length",
+ "OPENLIT_EVALS_LOGS_EXPORT": "evals_logs_export",
+ "OPENLIT_CUSTOM_SPAN_ATTRIBUTES": "custom_span_attributes",
}
for env_var, param_name in env_mappings.items():
@@ -49,10 +51,10 @@ except ImportError:
"OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT",
"OPENLIT_DISABLE_BATCH",
"OPENLIT_DISABLE_METRICS",
+ "OPENLIT_DISABLE_EVENTS",
"OPENLIT_COLLECT_GPU_STATS",
- "OPENLIT_DETAILED_TRACING",
- "OPENLIT_CAPTURE_PARAMETERS",
- "OPENLIT_ENABLE_SQLCOMMENTER",
+ "OPENLIT_CAPTURE_DB_PARAMETERS",
+ "OPENLIT_EVALS_LOGS_EXPORT",
]:
config[param_name] = env_value.lower() in ("true", "1", "yes")
# Handle CSV values
@@ -63,13 +65,22 @@ except ImportError:
if item.strip()
]
# Handle JSON values
- elif env_var == "OTEL_EXPORTER_OTLP_HEADERS":
+ elif env_var in [
+ "OTEL_EXPORTER_OTLP_HEADERS",
+ "OPENLIT_CUSTOM_SPAN_ATTRIBUTES",
+ ]:
try:
import json
config[param_name] = json.loads(env_value)
except (json.JSONDecodeError, ImportError):
pass
+ # Handle integer values
+ elif env_var == "OPENLIT_MAX_CONTENT_LENGTH":
+ try:
+ config[param_name] = int(env_value)
+ except ValueError:
+ pass
else:
config[param_name] = env_value
diff --git a/sdk/python/src/openlit/cli/config.py b/sdk/python/src/openlit/cli/config.py
index c443dd87..5a02dce3 100644
--- a/sdk/python/src/openlit/cli/config.py
+++ b/sdk/python/src/openlit/cli/config.py
@@ -73,6 +73,12 @@ PARAMETER_CONFIG = {
"cli_help": "Disable metrics collection",
"cli_type": bool,
},
+ "disable_events": {
+ "default": False,
+ "env_var": "OPENLIT_DISABLE_EVENTS",
+ "cli_help": "Disable OTel Logger event emission",
+ "cli_type": bool,
+ },
"pricing_json": {
"default": None,
"env_var": "OPENLIT_PRICING_JSON",
@@ -85,29 +91,16 @@ PARAMETER_CONFIG = {
"cli_help": "Enable GPU statistics collection",
"cli_type": bool,
},
- "detailed_tracing": {
- "default": True,
- "env_var": "OPENLIT_DETAILED_TRACING",
- "cli_help": "Enable detailed component-level tracing",
- "cli_type": bool,
- "has_negation": True, # Supports --no_detailed_tracing
- },
"collect_system_metrics": {
"default": False,
"env_var": "OPENLIT_COLLECT_SYSTEM_METRICS",
"cli_help": "Enable comprehensive system metrics (CPU, memory, disk, network, GPU if detected)",
"cli_type": bool,
},
- "capture_parameters": {
- "default": False,
- "env_var": "OPENLIT_CAPTURE_PARAMETERS",
- "cli_help": "Capture database query parameters in spans (security risk - may expose sensitive data)",
- "cli_type": bool,
- },
- "enable_sqlcommenter": {
+ "capture_db_parameters": {
"default": False,
- "env_var": "OPENLIT_ENABLE_SQLCOMMENTER",
- "cli_help": "Inject OpenTelemetry trace context as SQL comments for database log correlation",
+ "env_var": "OPENLIT_CAPTURE_DB_PARAMETERS",
+ "cli_help": "Capture database query parameters in OTel per-key format (security risk - may expose sensitive data)",
"cli_type": bool,
},
"evals_logs_export": {
@@ -122,18 +115,12 @@ PARAMETER_CONFIG = {
"cli_help": "Maximum character length for captured content (None = no limit)",
"cli_type": int,
},
- # Parameters that are not exposed via CLI (internal use only)
- "tracer": {
- "default": None,
- "internal": True, # Skip in CLI
- },
- "event_logger": {
+ "custom_span_attributes": {
"default": None,
- "internal": True, # Skip in CLI
- },
- "meter": {
- "default": None,
- "internal": True, # Skip in CLI
+ "env_var": "OPENLIT_CUSTOM_SPAN_ATTRIBUTES",
+ "cli_help": 'Custom span attributes as JSON string (e.g. \'{"team": "ml"}\')',
+ "cli_type": str,
+ "parser": "json",
},
}
diff --git a/sdk/python/src/openlit/evals/utils.py b/sdk/python/src/openlit/evals/utils.py
index 91cd173d..76345116 100644
--- a/sdk/python/src/openlit/evals/utils.py
+++ b/sdk/python/src/openlit/evals/utils.py
@@ -251,18 +251,24 @@ def parse_llm_response(response) -> JsonOutput:
def get_event_provider():
"""
- Safely retrieve the event provider from OpenLIT's global configuration.
+ Retrieve the event provider (OTel Logger) from the global LoggerProvider.
This function enables evaluators to auto-wire event emission without storing
references that cause cyclic imports. The provider is retrieved at call time,
allowing OpenLIT initialization to complete before evaluation measure() calls.
Returns:
- The event provider if OpenLIT has been initialized with telemetry, else None.
+ The OTel Logger if a LoggerProvider has been configured, else None.
"""
try:
- return OpenlitConfig.event_provider
- except AttributeError:
+ from opentelemetry import _logs
+ from opentelemetry.sdk._logs import LoggerProvider as SDKLoggerProvider
+
+ provider = _logs.get_logger_provider()
+ if isinstance(provider, SDKLoggerProvider):
+ return provider.get_logger("openlit.evals")
+ return None
+ except Exception:
return None
diff --git a/sdk/python/src/openlit/instrumentation/ag2/__init__.py b/sdk/python/src/openlit/instrumentation/ag2/__init__.py
index 80267054..090a3141 100644
--- a/sdk/python/src/openlit/instrumentation/ag2/__init__.py
+++ b/sdk/python/src/openlit/instrumentation/ag2/__init__.py
@@ -2,9 +2,11 @@
from typing import Collection
import importlib.metadata
+from opentelemetry import trace
from opentelemetry.instrumentation.instrumentor import BaseInstrumentor
from wrapt import wrap_function_wrapper
+from openlit._config import OpenlitConfig
from openlit.instrumentation.ag2.ag2 import (
conversable_agent,
agent_run,
@@ -37,10 +39,10 @@ class AG2Instrumentor(BaseInstrumentor):
version = importlib.metadata.version("ag2")
environment = kwargs.get("environment", "default")
application_name = kwargs.get("application_name", "default")
- tracer = kwargs.get("tracer")
+ tracer = trace.get_tracer(__name__)
pricing_info = kwargs.get("pricing_info", {})
capture_message_content = kwargs.get("capture_message_content", False)
- metrics = kwargs.get("metrics_dict")
+ metrics = OpenlitConfig.metrics_dict
disable_metrics = kwargs.get("disable_metrics")
# sync conversable agent
diff --git a/sdk/python/src/openlit/instrumentation/agent_framework/__init__.py b/sdk/python/src/openlit/instrumentation/agent_framework/__init__.py
index 19781c96..ae87a83a 100644
--- a/sdk/python/src/openlit/instrumentation/agent_framework/__init__.py
+++ b/sdk/python/src/openlit/instrumentation/agent_framework/__init__.py
@@ -5,8 +5,8 @@ convention compliant.
Provides auto-instrumentation for Microsoft Agent Framework including:
- Agent execution (Agent.run -> invoke_agent spans)
- Tool execution (FunctionTool.invoke -> execute_tool spans)
-- Agent construction (Agent.__init__ -> create_agent spans, detailed_tracing only)
-- Workflow execution (Workflow.run -> invoke_workflow spans, detailed_tracing only)
+- Agent construction (Agent.__init__ -> create_agent spans)
+- Workflow execution (Workflow.run -> invoke_workflow spans)
Disables AF's built-in telemetry (AgentTelemetryLayer / ChatTelemetryLayer)
via the global OBSERVABILITY_SETTINGS singleton to avoid duplicate spans, then
@@ -18,11 +18,17 @@ import threading
from typing import Collection
import importlib.metadata
+from opentelemetry import trace
from opentelemetry.instrumentation.instrumentor import BaseInstrumentor
from opentelemetry.trace import SpanKind, Status, StatusCode
from wrapt import wrap_function_wrapper
-from openlit.__helpers import handle_exception, truncate_content
+from openlit.__helpers import (
+ handle_exception,
+ truncate_content,
+ _apply_custom_span_attributes,
+)
+from openlit._config import OpenlitConfig
from openlit.semcov import SemanticConvention
_instruments = ("agent-framework >= 1.0.0rc1",)
@@ -159,6 +165,8 @@ def _wrap_agent_init(
)
span.set_status(Status(StatusCode.OK))
+ _apply_custom_span_attributes(span)
+
creation_ctx = span.get_span_context()
instance._openlit_creation_context = creation_ctx
registry.register(str(name), creation_ctx)
@@ -217,13 +225,11 @@ class AgentFrameworkInstrumentor(BaseInstrumentor):
version = importlib.metadata.version("agent-framework")
environment = kwargs.get("environment", "default")
application_name = kwargs.get("application_name", "default")
- tracer = kwargs.get("tracer")
+ tracer = trace.get_tracer(__name__)
pricing_info = kwargs.get("pricing_info", {})
capture_message_content = kwargs.get("capture_message_content", False)
- metrics = kwargs.get("metrics_dict")
+ metrics = OpenlitConfig.metrics_dict
disable_metrics = kwargs.get("disable_metrics")
- detailed_tracing = kwargs.get("detailed_tracing", False)
-
agent_registry = _AgentCreationRegistry()
self._previous_af_telemetry = _disable_af_telemetry()
@@ -269,36 +275,35 @@ class AgentFrameworkInstrumentor(BaseInstrumentor):
except Exception:
pass
- if detailed_tracing:
- for module, method, op_key, _sync_type in DETAILED_OPERATIONS:
- try:
- if op_key == "agent_init":
- wrapper = _wrap_agent_init(
- tracer,
- environment,
- application_name,
- capture_message_content,
- agent_registry,
- )
- elif op_key == "workflow_run":
- wrapper = workflow_run_wrap(
- op_key,
- version,
- environment,
- application_name,
- tracer,
- pricing_info,
- capture_message_content,
- metrics,
- disable_metrics,
- agent_registry,
- )
- else:
- continue
+ for module, method, op_key, _sync_type in DETAILED_OPERATIONS:
+ try:
+ if op_key == "agent_init":
+ wrapper = _wrap_agent_init(
+ tracer,
+ environment,
+ application_name,
+ capture_message_content,
+ agent_registry,
+ )
+ elif op_key == "workflow_run":
+ wrapper = workflow_run_wrap(
+ op_key,
+ version,
+ environment,
+ application_name,
+ tracer,
+ pricing_info,
+ capture_message_content,
+ metrics,
+ disable_metrics,
+ agent_registry,
+ )
+ else:
+ continue
- wrap_function_wrapper(module, method, wrapper)
- except Exception:
- pass
+ wrap_function_wrapper(module, method, wrapper)
+ except Exception:
+ pass
def _uninstrument(self, **kwargs):
"""Restore AF's built-in telemetry."""
diff --git a/sdk/python/src/openlit/instrumentation/agno/__init__.py b/sdk/python/src/openlit/instrumentation/agno/__init__.py
index 8aa93ffa..5bb09ce9 100644
--- a/sdk/python/src/openlit/instrumentation/agno/__init__.py
+++ b/sdk/python/src/openlit/instrumentation/agno/__init__.py
@@ -7,9 +7,11 @@ wrappers with OPERATION_MAP-driven span names, kinds, and attributes.
from typing import Collection
import importlib.metadata
+from opentelemetry import trace
from opentelemetry.instrumentation.instrumentor import BaseInstrumentor
from wrapt import wrap_function_wrapper
+from openlit._config import OpenlitConfig
from openlit.instrumentation.agno.agno import general_wrap
from openlit.instrumentation.agno.async_agno import (
async_general_wrap,
@@ -35,7 +37,6 @@ WORKFLOW_OPERATIONS = [
]
# === DETAILED-TRACING OPERATIONS ===
-# Wrapped only when detailed_tracing=True
DETAILED_OPERATIONS = [
# Tool execution — execute_tool (FunctionCall.execute/aexecute)
("agno.tools.function", "FunctionCall.execute", "tool_execute", "sync"),
@@ -58,13 +59,11 @@ class AgnoInstrumentor(BaseInstrumentor):
def _instrument(self, **kwargs):
application_name = kwargs.get("application_name", "default_application")
environment = kwargs.get("environment", "default_environment")
- tracer = kwargs.get("tracer")
- metrics = kwargs.get("metrics_dict")
+ tracer = trace.get_tracer(__name__)
+ metrics = OpenlitConfig.metrics_dict
pricing_info = kwargs.get("pricing_info", {})
capture_message_content = kwargs.get("capture_message_content", False)
disable_metrics = kwargs.get("disable_metrics")
- detailed_tracing = kwargs.get("detailed_tracing", False)
-
try:
version = importlib.metadata.version("agno")
except importlib.metadata.PackageNotFoundError:
@@ -127,145 +126,144 @@ class AgnoInstrumentor(BaseInstrumentor):
pass
# -- detailed-tracing operations --
- if detailed_tracing:
- # Tool execution via FunctionCall
- for module, method, op_key, sync_type in [
- ("agno.tools.function", "FunctionCall.execute", "tool_execute", "sync"),
- (
- "agno.tools.function",
- "FunctionCall.aexecute",
- "tool_aexecute",
- "async",
- ),
- ]:
- try:
- if sync_type == "async":
- wrapper = async_general_wrap(op_key, *wrap_args)
- else:
- wrapper = general_wrap(op_key, *wrap_args)
- wrap_function_wrapper(module, method, wrapper)
- except Exception:
- pass
-
- # Team operations
+ # Tool execution via FunctionCall
+ for module, method, op_key, sync_type in [
+ ("agno.tools.function", "FunctionCall.execute", "tool_execute", "sync"),
+ (
+ "agno.tools.function",
+ "FunctionCall.aexecute",
+ "tool_aexecute",
+ "async",
+ ),
+ ]:
try:
- from agno.team.team import Team # pylint: disable=import-error
- except ImportError:
- Team = None
-
- if Team is not None:
- # Team._arun_stream (agno < 2.5.3 private methods)
- if hasattr(Team, "_arun_stream"):
- try:
- wrap_function_wrapper(
- "agno.team.team",
- "Team._arun_stream",
- async_general_wrap("team_arun", *wrap_args),
- )
- wrap_function_wrapper(
- "agno.team.team",
- "Team._arun",
- async_general_wrap("team_arun", *wrap_args),
- )
- except Exception:
- pass
+ if sync_type == "async":
+ wrapper = async_general_wrap(op_key, *wrap_args)
else:
- try:
- wrap_function_wrapper(
- "agno.team.team",
- "Team.arun",
- async_general_wrap("team_arun", *wrap_args),
- )
- except Exception:
- pass
+ wrapper = general_wrap(op_key, *wrap_args)
+ wrap_function_wrapper(module, method, wrapper)
+ except Exception:
+ pass
+
+ # Team operations
+ try:
+ from agno.team.team import Team # pylint: disable=import-error
+ except ImportError:
+ Team = None
+ if Team is not None:
+ # Team._arun_stream (agno < 2.5.3 private methods)
+ if hasattr(Team, "_arun_stream"):
+ try:
+ wrap_function_wrapper(
+ "agno.team.team",
+ "Team._arun_stream",
+ async_general_wrap("team_arun", *wrap_args),
+ )
+ wrap_function_wrapper(
+ "agno.team.team",
+ "Team._arun",
+ async_general_wrap("team_arun", *wrap_args),
+ )
+ except Exception:
+ pass
+ else:
try:
wrap_function_wrapper(
"agno.team.team",
- "Team.run",
- general_wrap("team_run", *wrap_args),
+ "Team.arun",
+ async_general_wrap("team_arun", *wrap_args),
)
except Exception:
pass
- # Workflow operations
try:
- from agno.workflow.workflow import Workflow # pylint: disable=import-error
- except ImportError:
- Workflow = None
+ wrap_function_wrapper(
+ "agno.team.team",
+ "Team.run",
+ general_wrap("team_run", *wrap_args),
+ )
+ except Exception:
+ pass
- if Workflow is not None:
- if hasattr(Workflow, "run_workflow"):
- try:
- wrap_function_wrapper(
- "agno.workflow.workflow",
- "Workflow.run_workflow",
- general_wrap("workflow_run", *wrap_args),
- )
- except Exception:
- pass
- if hasattr(Workflow, "arun_workflow"):
- try:
- wrap_function_wrapper(
- "agno.workflow.workflow",
- "Workflow.arun_workflow",
- async_workflow_wrap("workflow_arun", *wrap_args),
- )
- except Exception:
- pass
+ # Workflow operations
+ try:
+ from agno.workflow.workflow import Workflow # pylint: disable=import-error
+ except ImportError:
+ Workflow = None
+ if Workflow is not None:
+ if hasattr(Workflow, "run_workflow"):
try:
wrap_function_wrapper(
"agno.workflow.workflow",
- "Workflow.arun",
- async_workflow_wrap("workflow_arun", *wrap_args),
+ "Workflow.run_workflow",
+ general_wrap("workflow_run", *wrap_args),
)
except Exception:
pass
+ if hasattr(Workflow, "arun_workflow"):
+ try:
+ wrap_function_wrapper(
+ "agno.workflow.workflow",
+ "Workflow.arun_workflow",
+ async_workflow_wrap("workflow_arun", *wrap_args),
+ )
+ except Exception:
+ pass
- # VectorDB operations
try:
wrap_function_wrapper(
- "agno.vectordb.base",
- "VectorDb.search",
- general_wrap("vectordb_search", *wrap_args),
+ "agno.workflow.workflow",
+ "Workflow.arun",
+ async_workflow_wrap("workflow_arun", *wrap_args),
)
+ except Exception:
+ pass
+
+ # VectorDB operations
+ try:
+ wrap_function_wrapper(
+ "agno.vectordb.base",
+ "VectorDb.search",
+ general_wrap("vectordb_search", *wrap_args),
+ )
+ wrap_function_wrapper(
+ "agno.vectordb.base",
+ "VectorDb.upsert",
+ general_wrap("vectordb_upsert", *wrap_args),
+ )
+ except Exception:
+ pass
+
+ # Memory operations
+ memory_module, memory_class = resolve_agno_memory_target()
+ if memory_module is not None:
+ try:
wrap_function_wrapper(
- "agno.vectordb.base",
- "VectorDb.upsert",
- general_wrap("vectordb_upsert", *wrap_args),
+ memory_module,
+ f"{memory_class}.add_user_memory",
+ general_wrap("memory_add", *wrap_args),
+ )
+ wrap_function_wrapper(
+ memory_module,
+ f"{memory_class}.search_user_memories",
+ general_wrap("memory_search", *wrap_args),
)
except Exception:
pass
- # Memory operations
- memory_module, memory_class = resolve_agno_memory_target()
- if memory_module is not None:
- try:
- wrap_function_wrapper(
- memory_module,
- f"{memory_class}.add_user_memory",
- general_wrap("memory_add", *wrap_args),
- )
- wrap_function_wrapper(
- memory_module,
- f"{memory_class}.search_user_memories",
- general_wrap("memory_search", *wrap_args),
- )
- except Exception:
- pass
-
- # Knowledge operations
- knowledge_module, knowledge_class = resolve_agno_knowledge_target()
- if knowledge_module is not None:
- try:
- wrap_function_wrapper(
- knowledge_module,
- f"{knowledge_class}.search",
- general_wrap("knowledge_search", *wrap_args),
- )
- except Exception:
- pass
+ # Knowledge operations
+ knowledge_module, knowledge_class = resolve_agno_knowledge_target()
+ if knowledge_module is not None:
+ try:
+ wrap_function_wrapper(
+ knowledge_module,
+ f"{knowledge_class}.search",
+ general_wrap("knowledge_search", *wrap_args),
+ )
+ except Exception:
+ pass
def _uninstrument(self, **kwargs):
pass
diff --git a/sdk/python/src/openlit/instrumentation/agno/utils.py b/sdk/python/src/openlit/instrumentation/agno/utils.py
index 6642e6af..41199b3d 100644
--- a/sdk/python/src/openlit/instrumentation/agno/utils.py
+++ b/sdk/python/src/openlit/instrumentation/agno/utils.py
@@ -22,6 +22,7 @@ from openlit.__helpers import (
format_system_instructions,
get_server_address_for_provider,
truncate_content,
+ _apply_custom_span_attributes,
)
from openlit.semcov import SemanticConvention
@@ -710,6 +711,8 @@ def emit_create_agent_spans(
)
span.set_status(Status(StatusCode.OK))
+ _apply_custom_span_attributes(span)
+
return span.get_span_context()
except Exception:
return None
diff --git a/sdk/python/src/openlit/instrumentation/ai21/__init__.py b/sdk/python/src/openlit/instrumentation/ai21/__init__.py
index 45cd1113..56176001 100644
--- a/sdk/python/src/openlit/instrumentation/ai21/__init__.py
+++ b/sdk/python/src/openlit/instrumentation/ai21/__init__.py
@@ -2,9 +2,11 @@
from typing import Collection
import importlib.metadata
+from opentelemetry import trace, _logs
from opentelemetry.instrumentation.instrumentor import BaseInstrumentor
from wrapt import wrap_function_wrapper
+from openlit._config import OpenlitConfig
from openlit.instrumentation.ai21.ai21 import chat, chat_rag
from openlit.instrumentation.ai21.async_ai21 import async_chat, async_chat_rag
@@ -22,12 +24,12 @@ class AI21Instrumentor(BaseInstrumentor):
def _instrument(self, **kwargs):
application_name = kwargs.get("application_name", "default")
environment = kwargs.get("environment", "default")
- tracer = kwargs.get("tracer")
- metrics = kwargs.get("metrics_dict")
+ tracer = trace.get_tracer(__name__)
+ metrics = OpenlitConfig.metrics_dict
pricing_info = kwargs.get("pricing_info", {})
capture_message_content = kwargs.get("capture_message_content", False)
disable_metrics = kwargs.get("disable_metrics")
- event_provider = kwargs.get("event_provider")
+ event_provider = _logs.get_logger_provider().get_logger(__name__)
version = importlib.metadata.version("ai21")
# Chat completions
diff --git a/sdk/python/src/openlit/instrumentation/ai21/utils.py b/sdk/python/src/openlit/instrumentation/ai21/utils.py
index 35b686a9..72199d1a 100644
--- a/sdk/python/src/openlit/instrumentation/ai21/utils.py
+++ b/sdk/python/src/openlit/instrumentation/ai21/utils.py
@@ -19,6 +19,7 @@ from openlit.__helpers import (
otel_event,
truncate_message_content,
)
+from openlit._config import OpenlitConfig
from openlit.semcov import SemanticConvention
logger = logging.getLogger(__name__)
@@ -215,7 +216,8 @@ def emit_inference_event(
attributes=attributes,
body="",
)
- event_provider.emit(event)
+ if not OpenlitConfig.disable_events:
+ event_provider.emit(event)
except Exception as e:
logger.warning("Failed to emit inference event: %s", e, exc_info=True)
diff --git a/sdk/python/src/openlit/instrumentation/anthropic/__init__.py b/sdk/python/src/openlit/instrumentation/anthropic/__init__.py
index 9f04e69d..a69da305 100644
--- a/sdk/python/src/openlit/instrumentation/anthropic/__init__.py
+++ b/sdk/python/src/openlit/instrumentation/anthropic/__init__.py
@@ -2,9 +2,11 @@
from typing import Collection
import importlib.metadata
+from opentelemetry import trace, _logs
from opentelemetry.instrumentation.instrumentor import BaseInstrumentor
from wrapt import wrap_function_wrapper
+from openlit._config import OpenlitConfig
from openlit.instrumentation.anthropic.anthropic import messages
from openlit.instrumentation.anthropic.async_anthropic import async_messages
@@ -23,12 +25,12 @@ class AnthropicInstrumentor(BaseInstrumentor):
version = importlib.metadata.version("anthropic")
environment = kwargs.get("environment", "default")
application_name = kwargs.get("application_name", "default")
- tracer = kwargs.get("tracer")
+ tracer = trace.get_tracer(__name__)
pricing_info = kwargs.get("pricing_info", {})
capture_message_content = kwargs.get("capture_message_content", False)
- metrics = kwargs.get("metrics_dict")
+ metrics = OpenlitConfig.metrics_dict
disable_metrics = kwargs.get("disable_metrics")
- event_provider = kwargs.get("event_provider")
+ event_provider = _logs.get_logger_provider().get_logger(__name__)
# sync
wrap_function_wrapper(
diff --git a/sdk/python/src/openlit/instrumentation/anthropic/utils.py b/sdk/python/src/openlit/instrumentation/anthropic/utils.py
index bbba71e9..3276287a 100644
--- a/sdk/python/src/openlit/instrumentation/anthropic/utils.py
+++ b/sdk/python/src/openlit/instrumentation/anthropic/utils.py
@@ -20,6 +20,7 @@ from openlit.__helpers import (
truncate_message_content,
)
from openlit.semcov import SemanticConvention
+from openlit._config import OpenlitConfig
logger = logging.getLogger(__name__)
@@ -420,7 +421,8 @@ def emit_inference_event(
body="",
)
- event_provider.emit(event)
+ if not OpenlitConfig.disable_events:
+ event_provider.emit(event)
except Exception as e:
logger.warning("Failed to emit inference event: %s", e, exc_info=True)
diff --git a/sdk/python/src/openlit/instrumentation/assemblyai/__init__.py b/sdk/python/src/openlit/instrumentation/assemblyai/__init__.py
index 730fb65a..aa1ddd3a 100644
--- a/sdk/python/src/openlit/instrumentation/assemblyai/__init__.py
+++ b/sdk/python/src/openlit/instrumentation/assemblyai/__init__.py
@@ -2,9 +2,11 @@
from typing import Collection
import importlib.metadata
+from opentelemetry import trace, _logs
from opentelemetry.instrumentation.instrumentor import BaseInstrumentor
from wrapt import wrap_function_wrapper
+from openlit._config import OpenlitConfig
from openlit.instrumentation.assemblyai.assemblyai import transcribe
_instruments = ("assemblyai >= 0.35.1",)
@@ -21,12 +23,12 @@ class AssemblyAIInstrumentor(BaseInstrumentor):
def _instrument(self, **kwargs):
application_name = kwargs.get("application_name", "default")
environment = kwargs.get("environment", "default")
- tracer = kwargs.get("tracer")
- metrics = kwargs.get("metrics_dict")
+ tracer = trace.get_tracer(__name__)
+ metrics = OpenlitConfig.metrics_dict
pricing_info = kwargs.get("pricing_info", {})
capture_message_content = kwargs.get("capture_message_content", False)
disable_metrics = kwargs.get("disable_metrics")
- event_provider = kwargs.get("event_provider")
+ event_provider = _logs.get_logger_provider().get_logger(__name__)
version = importlib.metadata.version("assemblyai")
# sync transcribe
diff --git a/sdk/python/src/openlit/instrumentation/assemblyai/utils.py b/sdk/python/src/openlit/instrumentation/assemblyai/utils.py
index 11d1f71e..1a45fe1b 100644
--- a/sdk/python/src/openlit/instrumentation/assemblyai/utils.py
+++ b/sdk/python/src/openlit/instrumentation/assemblyai/utils.py
@@ -8,6 +8,7 @@ import time
from opentelemetry.trace import Status, StatusCode
+from openlit._config import OpenlitConfig
from openlit.__helpers import (
common_span_attributes,
get_audio_model_cost,
@@ -187,7 +188,8 @@ def emit_inference_event(
attributes=attributes,
body="",
)
- event_provider.emit(event)
+ if not OpenlitConfig.disable_events:
+ event_provider.emit(event)
except Exception as e:
logger.warning("Failed to emit inference event: %s", e, exc_info=True)
diff --git a/sdk/python/src/openlit/instrumentation/astra/__init__.py b/sdk/python/src/openlit/instrumentation/astra/__init__.py
index b7ae3874..4b955420 100644
--- a/sdk/python/src/openlit/instrumentation/astra/__init__.py
+++ b/sdk/python/src/openlit/instrumentation/astra/__init__.py
@@ -4,9 +4,11 @@ OpenLIT AstraDB Instrumentation
from typing import Collection
import importlib.metadata
+from opentelemetry import trace
from opentelemetry.instrumentation.instrumentor import BaseInstrumentor
from wrapt import wrap_function_wrapper
+from openlit._config import OpenlitConfig
from openlit.instrumentation.astra.astra import general_wrap
from openlit.instrumentation.astra.async_astra import async_general_wrap
@@ -77,10 +79,10 @@ class AstraInstrumentor(BaseInstrumentor):
version = importlib.metadata.version("astrapy")
environment = kwargs.get("environment", "default")
application_name = kwargs.get("application_name", "default")
- tracer = kwargs.get("tracer")
+ tracer = trace.get_tracer(__name__)
pricing_info = kwargs.get("pricing_info", {})
capture_message_content = kwargs.get("capture_message_content", False)
- metrics = kwargs.get("metrics_dict")
+ metrics = OpenlitConfig.metrics_dict
disable_metrics = kwargs.get("disable_metrics")
# Wrap sync operations
diff --git a/sdk/python/src/openlit/instrumentation/azure_ai_inference/__init__.py b/sdk/python/src/openlit/instrumentation/azure_ai_inference/__init__.py
index 2229964c..35412b2b 100644
--- a/sdk/python/src/openlit/instrumentation/azure_ai_inference/__init__.py
+++ b/sdk/python/src/openlit/instrumentation/azure_ai_inference/__init__.py
@@ -2,8 +2,10 @@
from typing import Collection
import importlib.metadata
+from opentelemetry import trace, _logs
from opentelemetry.instrumentation.instrumentor import BaseInstrumentor
from wrapt import wrap_function_wrapper
+from openlit._config import OpenlitConfig
from openlit.instrumentation.azure_ai_inference.azure_ai_inference import (
complete,
embed,
@@ -27,12 +29,12 @@ class AzureAIInferenceInstrumentor(BaseInstrumentor):
def _instrument(self, **kwargs):
application_name = kwargs.get("application_name", "default")
environment = kwargs.get("environment", "default")
- tracer = kwargs.get("tracer")
- metrics = kwargs.get("metrics_dict")
+ tracer = trace.get_tracer(__name__)
+ metrics = OpenlitConfig.metrics_dict
pricing_info = kwargs.get("pricing_info", {})
capture_message_content = kwargs.get("capture_message_content", False)
disable_metrics = kwargs.get("disable_metrics")
- event_provider = kwargs.get("event_provider")
+ event_provider = _logs.get_logger_provider().get_logger(__name__)
version = importlib.metadata.version("azure-ai-inference")
# sync chat completions
diff --git a/sdk/python/src/openlit/instrumentation/azure_ai_inference/utils.py b/sdk/python/src/openlit/instrumentation/azure_ai_inference/utils.py
index 51623cbd..63f7a9da 100644
--- a/sdk/python/src/openlit/instrumentation/azure_ai_inference/utils.py
+++ b/sdk/python/src/openlit/instrumentation/azure_ai_inference/utils.py
@@ -21,6 +21,7 @@ from openlit.__helpers import (
otel_event,
truncate_message_content,
)
+from openlit._config import OpenlitConfig
from openlit.semcov import SemanticConvention
logger = logging.getLogger(__name__)
@@ -341,7 +342,8 @@ def emit_inference_event(
attributes=attributes,
body="",
)
- event_provider.emit(event)
+ if not OpenlitConfig.disable_events:
+ event_provider.emit(event)
except Exception as e:
logger.warning("Failed to emit inference event: %s", e, exc_info=True)
diff --git a/sdk/python/src/openlit/instrumentation/bedrock/__init__.py b/sdk/python/src/openlit/instrumentation/bedrock/__init__.py
index e690fd8f..e618ca17 100644
--- a/sdk/python/src/openlit/instrumentation/bedrock/__init__.py
+++ b/sdk/python/src/openlit/instrumentation/bedrock/__init__.py
@@ -2,9 +2,11 @@
from typing import Collection
import importlib.metadata
+from opentelemetry import trace, _logs
from opentelemetry.instrumentation.instrumentor import BaseInstrumentor
from wrapt import wrap_function_wrapper
+from openlit._config import OpenlitConfig
from openlit.instrumentation.bedrock.bedrock import converse, converse_stream
_instruments = ("boto3 >= 1.34.138",)
@@ -22,12 +24,12 @@ class BedrockInstrumentor(BaseInstrumentor):
version = importlib.metadata.version("boto3")
environment = kwargs.get("environment", "default")
application_name = kwargs.get("application_name", "default")
- tracer = kwargs.get("tracer")
+ tracer = trace.get_tracer(__name__)
pricing_info = kwargs.get("pricing_info", {})
capture_message_content = kwargs.get("capture_message_content", False)
- metrics = kwargs.get("metrics_dict")
+ metrics = OpenlitConfig.metrics_dict
disable_metrics = kwargs.get("disable_metrics")
- event_provider = kwargs.get("event_provider")
+ event_provider = _logs.get_logger_provider().get_logger(__name__)
# sync
wrap_function_wrapper(
diff --git a/sdk/python/src/openlit/instrumentation/bedrock/utils.py b/sdk/python/src/openlit/instrumentation/bedrock/utils.py
index 9fbef871..9c156515 100644
--- a/sdk/python/src/openlit/instrumentation/bedrock/utils.py
+++ b/sdk/python/src/openlit/instrumentation/bedrock/utils.py
@@ -20,6 +20,7 @@ from openlit.__helpers import (
otel_event,
truncate_message_content,
)
+from openlit._config import OpenlitConfig
from openlit.semcov import SemanticConvention
logger = logging.getLogger(__name__)
@@ -331,7 +332,8 @@ def emit_inference_event(
attributes=attributes,
body="",
)
- event_provider.emit(event)
+ if not OpenlitConfig.disable_events:
+ event_provider.emit(event)
except Exception as e:
logger.warning("Failed to emit inference event: %s", e, exc_info=True)
diff --git a/sdk/python/src/openlit/instrumentation/browser_use/__init__.py b/sdk/python/src/openlit/instrumentation/browser_use/__init__.py
index ff082b8e..ae1c6d6d 100644
--- a/sdk/python/src/openlit/instrumentation/browser_use/__init__.py
+++ b/sdk/python/src/openlit/instrumentation/browser_use/__init__.py
@@ -8,6 +8,7 @@ import importlib.metadata
from typing import Collection
from wrapt import wrap_function_wrapper
+from opentelemetry import trace
from opentelemetry.instrumentation.instrumentor import BaseInstrumentor
from openlit.semcov import SemanticConvention
@@ -29,7 +30,7 @@ class BrowserUseInstrumentor(BaseInstrumentor):
"""Instrument Browser-Use operations"""
# Get configuration
- tracer = kwargs.get("tracer")
+ tracer = trace.get_tracer(__name__)
application_name = kwargs.get("application_name", "default_application")
environment = kwargs.get("environment", "default_environment")
pricing_info = kwargs.get("pricing_info", {})
diff --git a/sdk/python/src/openlit/instrumentation/chroma/__init__.py b/sdk/python/src/openlit/instrumentation/chroma/__init__.py
index e561ba98..8d81da2b 100644
--- a/sdk/python/src/openlit/instrumentation/chroma/__init__.py
+++ b/sdk/python/src/openlit/instrumentation/chroma/__init__.py
@@ -4,9 +4,11 @@ OpenLIT ChromaDB Instrumentation
from typing import Collection
import importlib.metadata
+from opentelemetry import trace
from opentelemetry.instrumentation.instrumentor import BaseInstrumentor
from wrapt import wrap_function_wrapper
+from openlit._config import OpenlitConfig
from openlit.instrumentation.chroma.chroma import general_wrap
_instruments = ("chromadb >= 0.4.0",)
@@ -24,10 +26,10 @@ class ChromaInstrumentor(BaseInstrumentor):
version = importlib.metadata.version("chromadb")
environment = kwargs.get("environment", "default")
application_name = kwargs.get("application_name", "default")
- tracer = kwargs.get("tracer")
+ tracer = trace.get_tracer(__name__)
pricing_info = kwargs.get("pricing_info", {})
capture_message_content = kwargs.get("capture_message_content", False)
- metrics = kwargs.get("metrics_dict")
+ metrics = OpenlitConfig.metrics_dict
disable_metrics = kwargs.get("disable_metrics")
# Sync operations
diff --git a/sdk/python/src/openlit/instrumentation/claude_agent_sdk/__init__.py b/sdk/python/src/openlit/instrumentation/claude_agent_sdk/__init__.py
index bfa3ef5f..80859d5e 100644
--- a/sdk/python/src/openlit/instrumentation/claude_agent_sdk/__init__.py
+++ b/sdk/python/src/openlit/instrumentation/claude_agent_sdk/__init__.py
@@ -10,9 +10,11 @@ import importlib
import importlib.metadata
import sys
from typing import Collection
+from opentelemetry import trace, _logs
from opentelemetry.instrumentation.instrumentor import BaseInstrumentor
from wrapt import wrap_function_wrapper
+from openlit._config import OpenlitConfig
from openlit.instrumentation.claude_agent_sdk.claude_agent_sdk import (
wrap_query,
wrap_connect,
@@ -33,12 +35,12 @@ class ClaudeAgentSDKInstrumentor(BaseInstrumentor):
version = importlib.metadata.version("claude-agent-sdk")
environment = kwargs.get("environment", "default")
application_name = kwargs.get("application_name", "default")
- tracer = kwargs.get("tracer")
+ tracer = trace.get_tracer(__name__)
pricing_info = kwargs.get("pricing_info", {})
capture_message_content = kwargs.get("capture_message_content", False)
- metrics = kwargs.get("metrics_dict")
+ metrics = OpenlitConfig.metrics_dict
disable_metrics = kwargs.get("disable_metrics")
- event_provider = kwargs.get("event_provider")
+ event_provider = _logs.get_logger_provider().get_logger(__name__)
wrap_args = (
version,
diff --git a/sdk/python/src/openlit/instrumentation/claude_agent_sdk/claude_agent_sdk.py b/sdk/python/src/openlit/instrumentation/claude_agent_sdk/claude_agent_sdk.py
index abb42c59..fa30116a 100644
--- a/sdk/python/src/openlit/instrumentation/claude_agent_sdk/claude_agent_sdk.py
+++ b/sdk/python/src/openlit/instrumentation/claude_agent_sdk/claude_agent_sdk.py
@@ -15,7 +15,7 @@ from opentelemetry import context as context_api
from opentelemetry import trace as trace_api
from opentelemetry.trace import SpanKind, Status, StatusCode
-from openlit.__helpers import handle_exception
+from openlit.__helpers import handle_exception, _apply_custom_span_attributes
from openlit.semcov import SemanticConvention
from openlit.instrumentation.claude_agent_sdk.utils import (
generate_span_name,
@@ -761,6 +761,7 @@ def wrap_connect(
application_name,
agent_name=span_entity,
)
+ _apply_custom_span_attributes(span)
try:
result = await wrapped(*args, **kwargs)
span.set_status(Status(StatusCode.OK))
diff --git a/sdk/python/src/openlit/instrumentation/claude_agent_sdk/utils.py b/sdk/python/src/openlit/instrumentation/claude_agent_sdk/utils.py
index 6644a723..6a8c97da 100644
--- a/sdk/python/src/openlit/instrumentation/claude_agent_sdk/utils.py
+++ b/sdk/python/src/openlit/instrumentation/claude_agent_sdk/utils.py
@@ -12,6 +12,7 @@ import time
from opentelemetry.trace import SpanKind, Status, StatusCode
+from openlit._config import OpenlitConfig
from openlit.__helpers import (
common_framework_span_attributes,
get_chat_model_cost,
@@ -479,7 +480,8 @@ def _emit_chat_inference_event(
attributes=attributes,
body="",
)
- event_provider.emit(event)
+ if not OpenlitConfig.disable_events:
+ event_provider.emit(event)
except Exception as exc:
logger.debug("Failed to emit chat inference event: %s", exc)
diff --git a/sdk/python/src/openlit/instrumentation/cohere/__init__.py b/sdk/python/src/openlit/instrumentation/cohere/__init__.py
index 1a555285..6b7ea318 100644
--- a/sdk/python/src/openlit/instrumentation/cohere/__init__.py
+++ b/sdk/python/src/openlit/instrumentation/cohere/__init__.py
@@ -2,9 +2,11 @@
from typing import Collection
import importlib.metadata
+from opentelemetry import trace, _logs
from opentelemetry.instrumentation.instrumentor import BaseInstrumentor
from wrapt import wrap_function_wrapper
+from openlit._config import OpenlitConfig
from openlit.instrumentation.cohere.cohere import chat, chat_stream, embed
from openlit.instrumentation.cohere.async_cohere import (
async_chat,
@@ -26,12 +28,12 @@ class CohereInstrumentor(BaseInstrumentor):
def _instrument(self, **kwargs):
application_name = kwargs.get("application_name", "default")
environment = kwargs.get("environment", "default")
- tracer = kwargs.get("tracer")
- metrics = kwargs.get("metrics_dict")
+ tracer = trace.get_tracer(__name__)
+ metrics = OpenlitConfig.metrics_dict
pricing_info = kwargs.get("pricing_info", {})
capture_message_content = kwargs.get("capture_message_content", False)
disable_metrics = kwargs.get("disable_metrics")
- event_provider = kwargs.get("event_provider")
+ event_provider = _logs.get_logger_provider().get_logger(__name__)
version = importlib.metadata.version("cohere")
# sync chat completions
diff --git a/sdk/python/src/openlit/instrumentation/cohere/utils.py b/sdk/python/src/openlit/instrumentation/cohere/utils.py
index 4b4226ce..8d169e44 100644
--- a/sdk/python/src/openlit/instrumentation/cohere/utils.py
+++ b/sdk/python/src/openlit/instrumentation/cohere/utils.py
@@ -21,6 +21,7 @@ from openlit.__helpers import (
truncate_message_content,
)
from openlit.semcov import SemanticConvention
+from openlit._config import OpenlitConfig
logger = logging.getLogger(__name__)
@@ -222,7 +223,8 @@ def emit_inference_event(
attributes=attributes,
body="",
)
- event_provider.emit(event)
+ if not OpenlitConfig.disable_events:
+ event_provider.emit(event)
except Exception as e:
logger.warning("Failed to emit inference event: %s", e, exc_info=True)
diff --git a/sdk/python/src/openlit/instrumentation/controlflow/__init__.py b/sdk/python/src/openlit/instrumentation/controlflow/__init__.py
index 01009753..d451f661 100644
--- a/sdk/python/src/openlit/instrumentation/controlflow/__init__.py
+++ b/sdk/python/src/openlit/instrumentation/controlflow/__init__.py
@@ -3,9 +3,11 @@
from typing import Collection
import importlib.metadata
+from opentelemetry import trace
from opentelemetry.instrumentation.instrumentor import BaseInstrumentor
from wrapt import wrap_function_wrapper
+from openlit._config import OpenlitConfig
from openlit.instrumentation.controlflow.controlflow import wrap_controlflow
_instruments = ("controlflow >= 0.3.2",)
@@ -22,8 +24,8 @@ class ControlFlowInstrumentor(BaseInstrumentor):
def _instrument(self, **kwargs):
application_name = kwargs.get("application_name", "default_application")
environment = kwargs.get("environment", "default_environment")
- tracer = kwargs.get("tracer")
- metrics = kwargs.get("metrics_dict")
+ tracer = trace.get_tracer(__name__)
+ metrics = OpenlitConfig.metrics_dict
pricing_info = kwargs.get("pricing_info", {})
capture_message_content = kwargs.get("capture_message_content", False)
disable_metrics = kwargs.get("disable_metrics")
diff --git a/sdk/python/src/openlit/instrumentation/controlflow/controlflow.py b/sdk/python/src/openlit/instrumentation/controlflow/controlflow.py
index d0097342..97dbd685 100644
--- a/sdk/python/src/openlit/instrumentation/controlflow/controlflow.py
+++ b/sdk/python/src/openlit/instrumentation/controlflow/controlflow.py
@@ -10,7 +10,7 @@ from opentelemetry.sdk.resources import (
TELEMETRY_SDK_NAME,
DEPLOYMENT_ENVIRONMENT,
)
-from openlit.__helpers import handle_exception
+from openlit.__helpers import _apply_custom_span_attributes, handle_exception
from openlit.semcov import SemanticConvention
# Initialize logger for logging potential issues and operations
@@ -131,6 +131,7 @@ def wrap_controlflow(
str(kwargs.get("context", "")),
)
+ _apply_custom_span_attributes(span)
span.set_status(Status(StatusCode.OK))
# Return original response
diff --git a/sdk/python/src/openlit/instrumentation/crawl4ai/__init__.py b/sdk/python/src/openlit/instrumentation/crawl4ai/__init__.py
index b3612d46..1b36acc6 100644
--- a/sdk/python/src/openlit/instrumentation/crawl4ai/__init__.py
+++ b/sdk/python/src/openlit/instrumentation/crawl4ai/__init__.py
@@ -6,9 +6,11 @@ Supports Crawl4AI 0.7.x with comprehensive operation coverage.
from typing import Collection
import importlib.metadata
+from opentelemetry import trace
from opentelemetry.instrumentation.instrumentor import BaseInstrumentor
from wrapt import wrap_function_wrapper
+from openlit._config import OpenlitConfig
from openlit.instrumentation.crawl4ai.crawl4ai import general_wrap
from openlit.instrumentation.crawl4ai.async_crawl4ai import async_general_wrap
@@ -28,8 +30,8 @@ class Crawl4AIInstrumentor(BaseInstrumentor):
def _instrument(self, **kwargs):
application_name = kwargs.get("application_name", "default_application")
environment = kwargs.get("environment", "default_environment")
- tracer = kwargs.get("tracer")
- metrics = kwargs.get("metrics_dict")
+ tracer = trace.get_tracer(__name__)
+ metrics = OpenlitConfig.metrics_dict
pricing_info = kwargs.get("pricing_info", {})
capture_message_content = kwargs.get("capture_message_content", False)
disable_metrics = kwargs.get("disable_metrics")
diff --git a/sdk/python/src/openlit/instrumentation/crawl4ai/utils.py b/sdk/python/src/openlit/instrumentation/crawl4ai/utils.py
index 072c3479..8fa84796 100644
--- a/sdk/python/src/openlit/instrumentation/crawl4ai/utils.py
+++ b/sdk/python/src/openlit/instrumentation/crawl4ai/utils.py
@@ -13,7 +13,11 @@ from opentelemetry.sdk.resources import (
DEPLOYMENT_ENVIRONMENT,
)
-from openlit.__helpers import handle_exception, truncate_content
+from openlit.__helpers import (
+ _apply_custom_span_attributes,
+ handle_exception,
+ truncate_content,
+)
from openlit.semcov import SemanticConvention
# Initialize logger for logging potential issues and operations
@@ -370,6 +374,8 @@ def set_crawl_attributes(
config.deep_crawl_strategy.max_depth,
)
+ _apply_custom_span_attributes(span)
+
def process_crawl_response(
span, response, ctx: Crawl4AIInstrumentationContext, **kwargs
diff --git a/sdk/python/src/openlit/instrumentation/crewai/__init__.py b/sdk/python/src/openlit/instrumentation/crewai/__init__.py
index a2970161..895bfe22 100644
--- a/sdk/python/src/openlit/instrumentation/crewai/__init__.py
+++ b/sdk/python/src/openlit/instrumentation/crewai/__init__.py
@@ -7,9 +7,11 @@ All module paths verified against the actual CrewAI SDK.
from typing import Collection
import importlib.metadata
+from opentelemetry import trace
from opentelemetry.instrumentation.instrumentor import BaseInstrumentor
from wrapt import wrap_function_wrapper
+from openlit._config import OpenlitConfig
from openlit.instrumentation.crewai.crewai import general_wrap
from openlit.instrumentation.crewai.async_crewai import async_general_wrap
@@ -98,13 +100,11 @@ class CrewAIInstrumentor(BaseInstrumentor):
version = importlib.metadata.version("crewai")
environment = kwargs.get("environment", "default")
application_name = kwargs.get("application_name", "default")
- tracer = kwargs.get("tracer")
+ tracer = trace.get_tracer(__name__)
pricing_info = kwargs.get("pricing_info", {})
capture_message_content = kwargs.get("capture_message_content", False)
- metrics = kwargs.get("metrics_dict")
+ metrics = OpenlitConfig.metrics_dict
disable_metrics = kwargs.get("disable_metrics")
- detailed_tracing = kwargs.get("detailed_tracing", False)
-
wrap_args = (
version,
environment,
@@ -128,16 +128,15 @@ class CrewAIInstrumentor(BaseInstrumentor):
pass
# -- detailed-tracing operations --
- if detailed_tracing:
- for module, method, op_key, sync_type in DETAILED_OPERATIONS:
- try:
- if sync_type == "async":
- wrapper = async_general_wrap(op_key, *wrap_args)
- else:
- wrapper = general_wrap(op_key, *wrap_args)
- wrap_function_wrapper(module, method, wrapper)
- except Exception:
- pass
+ for module, method, op_key, sync_type in DETAILED_OPERATIONS:
+ try:
+ if sync_type == "async":
+ wrapper = async_general_wrap(op_key, *wrap_args)
+ else:
+ wrapper = general_wrap(op_key, *wrap_args)
+ wrap_function_wrapper(module, method, wrapper)
+ except Exception:
+ pass
# -- thread context propagation --
self._install_context_propagation()
diff --git a/sdk/python/src/openlit/instrumentation/crewai/utils.py b/sdk/python/src/openlit/instrumentation/crewai/utils.py
index 97820222..f3ce12fc 100644
--- a/sdk/python/src/openlit/instrumentation/crewai/utils.py
+++ b/sdk/python/src/openlit/instrumentation/crewai/utils.py
@@ -18,6 +18,7 @@ from openlit.__helpers import (
format_system_instructions,
get_server_address_for_provider,
truncate_content,
+ _apply_custom_span_attributes,
)
from openlit.semcov import SemanticConvention
@@ -657,6 +658,8 @@ def emit_create_agent_spans(
span.set_attribute(SemanticConvention.GEN_AI_SDK_VERSION, version)
span.set_status(Status(StatusCode.OK))
+ _apply_custom_span_attributes(span)
+
creation_contexts.append(span.get_span_context())
return creation_contexts
diff --git a/sdk/python/src/openlit/instrumentation/dynamiq/__init__.py b/sdk/python/src/openlit/instrumentation/dynamiq/__init__.py
index d627023b..5b2a243b 100644
--- a/sdk/python/src/openlit/instrumentation/dynamiq/__init__.py
+++ b/sdk/python/src/openlit/instrumentation/dynamiq/__init__.py
@@ -3,9 +3,11 @@
from typing import Collection
import importlib.metadata
+from opentelemetry import trace
from opentelemetry.instrumentation.instrumentor import BaseInstrumentor
from wrapt import wrap_function_wrapper
+from openlit._config import OpenlitConfig
from openlit.instrumentation.dynamiq.dynamiq import dynamiq_wrap
_instruments = ("dynamiq >= 0.4.0",)
@@ -22,8 +24,8 @@ class DynamiqInstrumentor(BaseInstrumentor):
def _instrument(self, **kwargs):
application_name = kwargs.get("application_name", "default_application")
environment = kwargs.get("environment", "default_environment")
- tracer = kwargs.get("tracer")
- metrics = kwargs.get("metrics_dict")
+ tracer = trace.get_tracer(__name__)
+ metrics = OpenlitConfig.metrics_dict
pricing_info = kwargs.get("pricing_info", {})
capture_message_content = kwargs.get("capture_message_content", False)
disable_metrics = kwargs.get("disable_metrics")
diff --git a/sdk/python/src/openlit/instrumentation/dynamiq/dynamiq.py b/sdk/python/src/openlit/instrumentation/dynamiq/dynamiq.py
index 65f47855..df6e54ec 100644
--- a/sdk/python/src/openlit/instrumentation/dynamiq/dynamiq.py
+++ b/sdk/python/src/openlit/instrumentation/dynamiq/dynamiq.py
@@ -11,6 +11,7 @@ from opentelemetry.sdk.resources import (
DEPLOYMENT_ENVIRONMENT,
)
from openlit.__helpers import (
+ _apply_custom_span_attributes,
handle_exception,
)
from openlit.semcov import SemanticConvention
@@ -136,6 +137,7 @@ def dynamiq_wrap(
)
span.set_attribute(SemanticConvention.DB_STATEMENT, query_value)
+ _apply_custom_span_attributes(span)
span.set_status(Status(StatusCode.OK))
# Return original response
diff --git a/sdk/python/src/openlit/instrumentation/elevenlabs/__init__.py b/sdk/python/src/openlit/instrumentation/elevenlabs/__init__.py
index 3deda45b..bcf2195e 100644
--- a/sdk/python/src/openlit/instrumentation/elevenlabs/__init__.py
+++ b/sdk/python/src/openlit/instrumentation/elevenlabs/__init__.py
@@ -2,9 +2,11 @@
from typing import Collection
import importlib.metadata
+from opentelemetry import trace, _logs
from opentelemetry.instrumentation.instrumentor import BaseInstrumentor
from wrapt import wrap_function_wrapper
+from openlit._config import OpenlitConfig
from openlit.instrumentation.elevenlabs.elevenlabs import generate
from openlit.instrumentation.elevenlabs.async_elevenlabs import async_generate
@@ -22,12 +24,12 @@ class ElevenLabsInstrumentor(BaseInstrumentor):
def _instrument(self, **kwargs):
application_name = kwargs.get("application_name", "default")
environment = kwargs.get("environment", "default")
- tracer = kwargs.get("tracer")
- metrics = kwargs.get("metrics_dict")
+ tracer = trace.get_tracer(__name__)
+ metrics = OpenlitConfig.metrics_dict
pricing_info = kwargs.get("pricing_info", {})
capture_message_content = kwargs.get("capture_message_content", False)
disable_metrics = kwargs.get("disable_metrics")
- event_provider = kwargs.get("event_provider")
+ event_provider = _logs.get_logger_provider().get_logger(__name__)
version = importlib.metadata.version("elevenlabs")
# sync text_to_speech.convert
diff --git a/sdk/python/src/openlit/instrumentation/elevenlabs/utils.py b/sdk/python/src/openlit/instrumentation/elevenlabs/utils.py
index 7704b882..6113b647 100644
--- a/sdk/python/src/openlit/instrumentation/elevenlabs/utils.py
+++ b/sdk/python/src/openlit/instrumentation/elevenlabs/utils.py
@@ -15,6 +15,7 @@ from openlit.__helpers import (
otel_event,
truncate_message_content,
)
+from openlit._config import OpenlitConfig
from openlit.semcov import SemanticConvention
logger = logging.getLogger(__name__)
@@ -161,7 +162,8 @@ def emit_inference_event(
attributes=attributes,
body="",
)
- event_provider.emit(event)
+ if not OpenlitConfig.disable_events:
+ event_provider.emit(event)
except Exception as e:
logger.warning("Failed to emit inference event: %s", e, exc_info=True)
diff --git a/sdk/python/src/openlit/instrumentation/firecrawl/__init__.py b/sdk/python/src/openlit/instrumentation/firecrawl/__init__.py
index 83403a83..c07a4b19 100644
--- a/sdk/python/src/openlit/instrumentation/firecrawl/__init__.py
+++ b/sdk/python/src/openlit/instrumentation/firecrawl/__init__.py
@@ -5,6 +5,7 @@ Supports comprehensive Firecrawl API operations with enhanced business intellige
from typing import Collection
import importlib.metadata
+from opentelemetry import trace
from opentelemetry.instrumentation.instrumentor import BaseInstrumentor
from wrapt import wrap_function_wrapper
@@ -27,7 +28,7 @@ class FireCrawlInstrumentor(BaseInstrumentor):
"""Instrument the firecrawl-py library functions."""
application_name = kwargs.get("application_name", "default")
environment = kwargs.get("environment", "default")
- tracer = kwargs.get("tracer")
+ tracer = trace.get_tracer(__name__)
pricing_info = kwargs.get("pricing_info")
trace_content = kwargs.get("trace_content", True)
disable_metrics = kwargs.get("disable_metrics")
diff --git a/sdk/python/src/openlit/instrumentation/google_adk/__init__.py b/sdk/python/src/openlit/instrumentation/google_adk/__init__.py
index 098fe6c8..0009f611 100644
--- a/sdk/python/src/openlit/instrumentation/google_adk/__init__.py
+++ b/sdk/python/src/openlit/instrumentation/google_adk/__init__.py
@@ -21,11 +21,17 @@ import threading
from typing import Collection
import importlib.metadata
+from opentelemetry import trace
from opentelemetry.instrumentation.instrumentor import BaseInstrumentor
from opentelemetry.trace import SpanKind, Status, StatusCode
from wrapt import wrap_function_wrapper
-from openlit.__helpers import handle_exception, truncate_content
+from openlit.__helpers import (
+ handle_exception,
+ truncate_content,
+ _apply_custom_span_attributes,
+)
+from openlit._config import OpenlitConfig
from openlit.semcov import SemanticConvention
from openlit.instrumentation.google_adk.utils import (
_PassthroughTracer,
@@ -171,6 +177,8 @@ def _wrap_agent_init(
)
span.set_status(Status(StatusCode.OK))
+ _apply_custom_span_attributes(span)
+
creation_ctx = span.get_span_context()
instance._openlit_creation_context = creation_ctx
registry.register(str(name), creation_ctx)
@@ -231,9 +239,7 @@ def _wrap_trace_call_llm(capture_message_content):
# ADK signature: trace_call_llm(invocation_context, event_id, llm_request, llm_response, span=None)
result = original_fn(*args, **kwargs)
try:
- from opentelemetry import trace as trace_api
-
- span = trace_api.get_current_span()
+ span = trace.get_current_span()
llm_request = args[2] if len(args) > 2 else kwargs.get("llm_request")
llm_response = args[3] if len(args) > 3 else kwargs.get("llm_response")
enrich_llm_span(
@@ -270,9 +276,7 @@ def _wrap_trace_tool_call(capture_message_content):
# ADK signature: trace_tool_call(tool, args, function_response_event, error=None)
result = original_fn(*args, **kwargs)
try:
- from opentelemetry import trace as trace_api
-
- span = trace_api.get_current_span()
+ span = trace.get_current_span()
tool = args[0] if len(args) > 0 else kwargs.get("tool")
function_args = args[1] if len(args) > 1 else kwargs.get("args")
function_response_event = (
@@ -318,9 +322,7 @@ def _wrap_trace_merged_tool_calls(capture_message_content):
# ADK signature: trace_merged_tool_calls(response_event_id, function_response_event)
result = original_fn(*args, **kwargs)
try:
- from opentelemetry import trace as trace_api
-
- span = trace_api.get_current_span()
+ span = trace.get_current_span()
response_event_id = (
args[0] if len(args) > 0 else kwargs.get("response_event_id")
)
@@ -361,13 +363,11 @@ class GoogleADKInstrumentor(BaseInstrumentor):
version = importlib.metadata.version("google-adk")
environment = kwargs.get("environment", "default")
application_name = kwargs.get("application_name", "default")
- tracer = kwargs.get("tracer")
+ tracer = trace.get_tracer(__name__)
pricing_info = kwargs.get("pricing_info", {})
capture_message_content = kwargs.get("capture_message_content", False)
- metrics = kwargs.get("metrics_dict")
+ metrics = OpenlitConfig.metrics_dict
disable_metrics = kwargs.get("disable_metrics")
- detailed_tracing = kwargs.get("detailed_tracing", False)
-
agent_registry = _AgentCreationRegistry()
self._original_tracers = _disable_existing_tracers()
@@ -440,24 +440,23 @@ class GoogleADKInstrumentor(BaseInstrumentor):
except Exception:
pass
- if detailed_tracing:
- for module, method, op_key, _ in DETAILED_OPERATIONS:
- try:
- wrapper = async_runner_wrap(
- op_key,
- version,
- environment,
- application_name,
- tracer,
- pricing_info,
- capture_message_content,
- metrics,
- disable_metrics,
- agent_registry,
- )
- wrap_function_wrapper(module, method, wrapper)
- except Exception:
- pass
+ for module, method, op_key, _ in DETAILED_OPERATIONS:
+ try:
+ wrapper = async_runner_wrap(
+ op_key,
+ version,
+ environment,
+ application_name,
+ tracer,
+ pricing_info,
+ capture_message_content,
+ metrics,
+ disable_metrics,
+ agent_registry,
+ )
+ wrap_function_wrapper(module, method, wrapper)
+ except Exception:
+ pass
def _uninstrument(self, **kwargs):
"""Restore original ADK tracers and tracing functions."""
diff --git a/sdk/python/src/openlit/instrumentation/google_ai_studio/__init__.py b/sdk/python/src/openlit/instrumentation/google_ai_studio/__init__.py
index 4411400d..ebf413de 100644
--- a/sdk/python/src/openlit/instrumentation/google_ai_studio/__init__.py
+++ b/sdk/python/src/openlit/instrumentation/google_ai_studio/__init__.py
@@ -2,9 +2,11 @@
from typing import Collection
import importlib.metadata
+from opentelemetry import _logs, trace
from opentelemetry.instrumentation.instrumentor import BaseInstrumentor
from wrapt import wrap_function_wrapper
+from openlit._config import OpenlitConfig
from openlit.instrumentation.google_ai_studio.google_ai_studio import (
generate,
generate_stream,
@@ -29,12 +31,12 @@ class GoogleAIStudioInstrumentor(BaseInstrumentor):
def _instrument(self, **kwargs):
application_name = kwargs.get("application_name", "default")
environment = kwargs.get("environment", "default")
- tracer = kwargs.get("tracer")
- metrics = kwargs.get("metrics_dict")
+ tracer = trace.get_tracer(__name__)
+ metrics = OpenlitConfig.metrics_dict
pricing_info = kwargs.get("pricing_info", {})
capture_message_content = kwargs.get("capture_message_content", False)
disable_metrics = kwargs.get("disable_metrics")
- event_provider = kwargs.get("event_provider")
+ event_provider = _logs.get_logger_provider().get_logger(__name__)
version = importlib.metadata.version("google-genai")
# sync generate
diff --git a/sdk/python/src/openlit/instrumentation/google_ai_studio/utils.py b/sdk/python/src/openlit/instrumentation/google_ai_studio/utils.py
index a318eeaf..7ac127e2 100644
--- a/sdk/python/src/openlit/instrumentation/google_ai_studio/utils.py
+++ b/sdk/python/src/openlit/instrumentation/google_ai_studio/utils.py
@@ -19,6 +19,7 @@ from openlit.__helpers import (
record_completion_metrics,
truncate_message_content,
)
+from openlit._config import OpenlitConfig
from openlit.semcov import SemanticConvention
logger = logging.getLogger(__name__)
@@ -427,7 +428,8 @@ def emit_inference_event(
body="",
)
- event_provider.emit(event)
+ if not OpenlitConfig.disable_events:
+ event_provider.emit(event)
except Exception as e:
logger.warning("Failed to emit inference event: %s", e, exc_info=True)
diff --git a/sdk/python/src/openlit/instrumentation/gpt4all/__init__.py b/sdk/python/src/openlit/instrumentation/gpt4all/__init__.py
index e1dc05be..c86c8ce3 100644
--- a/sdk/python/src/openlit/instrumentation/gpt4all/__init__.py
+++ b/sdk/python/src/openlit/instrumentation/gpt4all/__init__.py
@@ -2,9 +2,11 @@
from typing import Collection
import importlib.metadata
+from opentelemetry import _logs, trace
from opentelemetry.instrumentation.instrumentor import BaseInstrumentor
from wrapt import wrap_function_wrapper
+from openlit._config import OpenlitConfig
from openlit.instrumentation.gpt4all.gpt4all import embed, generate
_instruments = ("gpt4all >= 2.6.0",)
@@ -21,12 +23,12 @@ class GPT4AllInstrumentor(BaseInstrumentor):
def _instrument(self, **kwargs):
application_name = kwargs.get("application_name", "default")
environment = kwargs.get("environment", "default")
- tracer = kwargs.get("tracer")
- metrics = kwargs.get("metrics_dict")
+ tracer = trace.get_tracer(__name__)
+ metrics = OpenlitConfig.metrics_dict
pricing_info = kwargs.get("pricing_info", {})
capture_message_content = kwargs.get("capture_message_content", False)
disable_metrics = kwargs.get("disable_metrics")
- event_provider = kwargs.get("event_provider")
+ event_provider = _logs.get_logger_provider().get_logger(__name__)
version = importlib.metadata.version("gpt4all")
# generate
diff --git a/sdk/python/src/openlit/instrumentation/gpt4all/utils.py b/sdk/python/src/openlit/instrumentation/gpt4all/utils.py
index eb258f75..43bb1c02 100644
--- a/sdk/python/src/openlit/instrumentation/gpt4all/utils.py
+++ b/sdk/python/src/openlit/instrumentation/gpt4all/utils.py
@@ -20,6 +20,7 @@ from openlit.__helpers import (
otel_event,
truncate_message_content,
)
+from openlit._config import OpenlitConfig
from openlit.semcov import SemanticConvention
logger = logging.getLogger(__name__)
@@ -170,7 +171,8 @@ def emit_inference_event(
attributes=attributes,
body="",
)
- event_provider.emit(event)
+ if not OpenlitConfig.disable_events:
+ event_provider.emit(event)
except Exception as e:
logger.warning("Failed to emit inference event: %s", e, exc_info=True)
diff --git a/sdk/python/src/openlit/instrumentation/groq/__init__.py b/sdk/python/src/openlit/instrumentation/groq/__init__.py
index 31791c44..d3db33f3 100644
--- a/sdk/python/src/openlit/instrumentation/groq/__init__.py
+++ b/sdk/python/src/openlit/instrumentation/groq/__init__.py
@@ -2,9 +2,11 @@
from typing import Collection
import importlib.metadata
+from opentelemetry import _logs, trace
from opentelemetry.instrumentation.instrumentor import BaseInstrumentor
from wrapt import wrap_function_wrapper
+from openlit._config import OpenlitConfig
from openlit.instrumentation.groq.groq import chat
from openlit.instrumentation.groq.async_groq import async_chat
@@ -22,12 +24,12 @@ class GroqInstrumentor(BaseInstrumentor):
def _instrument(self, **kwargs):
application_name = kwargs.get("application_name", "default")
environment = kwargs.get("environment", "default")
- tracer = kwargs.get("tracer")
- metrics = kwargs.get("metrics_dict")
+ tracer = trace.get_tracer(__name__)
+ metrics = OpenlitConfig.metrics_dict
pricing_info = kwargs.get("pricing_info", {})
capture_message_content = kwargs.get("capture_message_content", False)
disable_metrics = kwargs.get("disable_metrics")
- event_provider = kwargs.get("event_provider")
+ event_provider = _logs.get_logger_provider().get_logger(__name__)
version = importlib.metadata.version("groq")
# Chat completions
diff --git a/sdk/python/src/openlit/instrumentation/groq/utils.py b/sdk/python/src/openlit/instrumentation/groq/utils.py
index eabe9ae8..2b54d6e6 100644
--- a/sdk/python/src/openlit/instrumentation/groq/utils.py
+++ b/sdk/python/src/openlit/instrumentation/groq/utils.py
@@ -20,6 +20,7 @@ from openlit.__helpers import (
truncate_message_content,
)
from openlit.semcov import SemanticConvention
+from openlit._config import OpenlitConfig
logger = logging.getLogger(__name__)
@@ -247,7 +248,8 @@ def emit_inference_event(
attributes=attributes,
body="",
)
- event_provider.emit(event)
+ if not OpenlitConfig.disable_events:
+ event_provider.emit(event)
except Exception as e:
logger.warning("Failed to emit inference event: %s", e, exc_info=True)
diff --git a/sdk/python/src/openlit/instrumentation/haystack/__init__.py b/sdk/python/src/openlit/instrumentation/haystack/__init__.py
index 943c13f9..1e32eca2 100644
--- a/sdk/python/src/openlit/instrumentation/haystack/__init__.py
+++ b/sdk/python/src/openlit/instrumentation/haystack/__init__.py
@@ -4,9 +4,11 @@ OpenLIT Haystack Instrumentation
from typing import Collection
import importlib.metadata
+from opentelemetry import trace
from opentelemetry.instrumentation.instrumentor import BaseInstrumentor
from wrapt import wrap_function_wrapper
+from openlit._config import OpenlitConfig
from openlit.instrumentation.haystack.haystack import general_wrap
from openlit.instrumentation.haystack.async_haystack import async_general_wrap
@@ -23,12 +25,11 @@ class HaystackInstrumentor(BaseInstrumentor):
version = importlib.metadata.version("haystack-ai")
environment = kwargs.get("environment", "default")
application_name = kwargs.get("application_name", "default")
- tracer = kwargs.get("tracer")
+ tracer = trace.get_tracer(__name__)
pricing_info = kwargs.get("pricing_info", {})
capture_message_content = kwargs.get("capture_message_content", False)
- metrics = kwargs.get("metrics_dict")
+ metrics = OpenlitConfig.metrics_dict
disable_metrics = kwargs.get("disable_metrics")
- detailed_tracing = kwargs.get("detailed_tracing", False)
# Pipeline operations (always enabled)
try:
@@ -65,60 +66,59 @@ class HaystackInstrumentor(BaseInstrumentor):
except Exception:
pass
- # Component operations (only if detailed_tracing enabled)
- if detailed_tracing:
- components = [
- (
- "haystack.components.retrievers.in_memory",
- "InMemoryBM25Retriever.run",
- "bm25_retriever",
- ),
- (
- "haystack.components.builders.prompt_builder",
- "PromptBuilder.run",
- "prompt_builder",
- ),
- (
- "haystack.components.generators.openai",
- "OpenAIGenerator.run",
- "openai_generator",
- ),
- (
- "haystack.components.generators.chat.openai",
- "OpenAIChatGenerator.run",
- "openai_chat_generator",
- ),
- (
- "haystack.components.embedders.openai_text_embedder",
- "OpenAITextEmbedder.run",
- "text_embedder",
- ),
- (
- "haystack.components.embedders.openai_document_embedder",
- "OpenAIDocumentEmbedder.run",
- "document_embedder",
- ),
- ]
+ # Component operations
+ components = [
+ (
+ "haystack.components.retrievers.in_memory",
+ "InMemoryBM25Retriever.run",
+ "bm25_retriever",
+ ),
+ (
+ "haystack.components.builders.prompt_builder",
+ "PromptBuilder.run",
+ "prompt_builder",
+ ),
+ (
+ "haystack.components.generators.openai",
+ "OpenAIGenerator.run",
+ "openai_generator",
+ ),
+ (
+ "haystack.components.generators.chat.openai",
+ "OpenAIChatGenerator.run",
+ "openai_chat_generator",
+ ),
+ (
+ "haystack.components.embedders.openai_text_embedder",
+ "OpenAITextEmbedder.run",
+ "text_embedder",
+ ),
+ (
+ "haystack.components.embedders.openai_document_embedder",
+ "OpenAIDocumentEmbedder.run",
+ "document_embedder",
+ ),
+ ]
- for module, method, component_type in components:
- try:
- wrap_function_wrapper(
- module,
- method,
- general_wrap(
- component_type,
- version,
- environment,
- application_name,
- tracer,
- pricing_info,
- capture_message_content,
- metrics,
- disable_metrics,
- ),
- )
- except Exception:
- pass
+ for module, method, component_type in components:
+ try:
+ wrap_function_wrapper(
+ module,
+ method,
+ general_wrap(
+ component_type,
+ version,
+ environment,
+ application_name,
+ tracer,
+ pricing_info,
+ capture_message_content,
+ metrics,
+ disable_metrics,
+ ),
+ )
+ except Exception:
+ pass
def _uninstrument(self, **kwargs):
pass
diff --git a/sdk/python/src/openlit/instrumentation/julep/__init__.py b/sdk/python/src/openlit/instrumentation/julep/__init__.py
index 59bdb594..ba630541 100644
--- a/sdk/python/src/openlit/instrumentation/julep/__init__.py
+++ b/sdk/python/src/openlit/instrumentation/julep/__init__.py
@@ -3,9 +3,11 @@
from typing import Collection
import importlib.metadata
+from opentelemetry import trace
from opentelemetry.instrumentation.instrumentor import BaseInstrumentor
from wrapt import wrap_function_wrapper
+from openlit._config import OpenlitConfig
from openlit.instrumentation.julep.julep import wrap_julep
from openlit.instrumentation.julep.async_julep import async_wrap_julep
@@ -24,8 +26,8 @@ class JulepInstrumentor(BaseInstrumentor):
def _instrument(self, **kwargs):
application_name = kwargs.get("application_name", "default_application")
environment = kwargs.get("environment", "default_environment")
- tracer = kwargs.get("tracer")
- metrics = kwargs.get("metrics_dict")
+ tracer = trace.get_tracer(__name__)
+ metrics = OpenlitConfig.metrics_dict
pricing_info = kwargs.get("pricing_info", {})
capture_message_content = kwargs.get("capture_message_content", False)
disable_metrics = kwargs.get("disable_metrics")
diff --git a/sdk/python/src/openlit/instrumentation/julep/julep.py b/sdk/python/src/openlit/instrumentation/julep/julep.py
index f5a9ead2..9e217ac2 100644
--- a/sdk/python/src/openlit/instrumentation/julep/julep.py
+++ b/sdk/python/src/openlit/instrumentation/julep/julep.py
@@ -10,7 +10,7 @@ from opentelemetry.sdk.resources import (
TELEMETRY_SDK_NAME,
DEPLOYMENT_ENVIRONMENT,
)
-from openlit.__helpers import handle_exception
+from openlit.__helpers import _apply_custom_span_attributes, handle_exception
from openlit.semcov import SemanticConvention
# Initialize logger for logging potential issues and operations
@@ -122,6 +122,7 @@ def wrap_julep(
},
)
+ _apply_custom_span_attributes(span)
span.set_status(Status(StatusCode.OK))
# Return original response
diff --git a/sdk/python/src/openlit/instrumentation/langchain/__init__.py b/sdk/python/src/openlit/instrumentation/langchain/__init__.py
index 32f4cebf..b6bb8413 100644
--- a/sdk/python/src/openlit/instrumentation/langchain/__init__.py
+++ b/sdk/python/src/openlit/instrumentation/langchain/__init__.py
@@ -11,6 +11,7 @@ from typing import Any, Collection, Dict, List, Optional, Literal, cast
from uuid import UUID
import importlib.metadata
+from opentelemetry import _logs, trace
from opentelemetry.instrumentation.instrumentor import BaseInstrumentor
from opentelemetry.trace import SpanKind, Status, StatusCode
@@ -18,6 +19,7 @@ from opentelemetry.trace import SpanKind, Status, StatusCode
from opentelemetry.trace import set_span_in_context
from wrapt import wrap_function_wrapper
+from openlit._config import OpenlitConfig
from openlit.instrumentation.langchain.utils import (
build_input_messages,
common_chat_logic,
@@ -1985,6 +1987,7 @@ def _wrap_create_agent(tracer, version, environment, application_name):
set_create_agent_active,
reset_create_agent_active,
get_server_address_for_provider,
+ _apply_custom_span_attributes,
)
def wrapper(wrapped, instance, args, kwargs):
@@ -2062,6 +2065,8 @@ def _wrap_create_agent(tracer, version, environment, application_name):
description = "LangChain agent"
span.set_attribute(SemanticConvention.GEN_AI_AGENT_DESCRIPTION, description)
+ _apply_custom_span_attributes(span)
+
ca_token = set_create_agent_active()
try:
result = wrapped(*args, **kwargs)
@@ -2444,12 +2449,12 @@ class LangChainInstrumentor(BaseInstrumentor):
environment = kwargs.get("environment", "default")
application_name = kwargs.get("application_name", "default")
- tracer = kwargs.get("tracer")
+ tracer = trace.get_tracer(__name__)
pricing_info = kwargs.get("pricing_info", {})
capture_message_content = kwargs.get("capture_message_content", False)
- metrics = kwargs.get("metrics_dict")
+ metrics = OpenlitConfig.metrics_dict
disable_metrics = kwargs.get("disable_metrics", False)
- event_provider = kwargs.get("event_provider")
+ event_provider = _logs.get_logger_provider().get_logger(__name__)
handler_class = _create_callback_handler_class(
tracer,
diff --git a/sdk/python/src/openlit/instrumentation/langchain/utils.py b/sdk/python/src/openlit/instrumentation/langchain/utils.py
index a7705557..bbc49912 100644
--- a/sdk/python/src/openlit/instrumentation/langchain/utils.py
+++ b/sdk/python/src/openlit/instrumentation/langchain/utils.py
@@ -9,6 +9,7 @@ from typing import Any, List
from opentelemetry.trace import Status, StatusCode
+from openlit._config import OpenlitConfig
from openlit.__helpers import (
common_span_attributes,
get_chat_model_cost,
@@ -319,7 +320,8 @@ def emit_inference_event(
attributes=attributes,
body="",
)
- event_provider.emit(event)
+ if not OpenlitConfig.disable_events:
+ event_provider.emit(event)
except Exception as e:
logger.warning("Failed to emit inference event: %s", e, exc_info=True)
diff --git a/sdk/python/src/openlit/instrumentation/langgraph/__init__.py b/sdk/python/src/openlit/instrumentation/langgraph/__init__.py
index 067c8c83..192b40b7 100644
--- a/sdk/python/src/openlit/instrumentation/langgraph/__init__.py
+++ b/sdk/python/src/openlit/instrumentation/langgraph/__init__.py
@@ -10,9 +10,11 @@ Provides comprehensive instrumentation for LangGraph applications including:
from typing import Collection
import importlib.metadata
+from opentelemetry import trace
from opentelemetry.instrumentation.instrumentor import BaseInstrumentor
from wrapt import wrap_function_wrapper
+from openlit._config import OpenlitConfig
from openlit.instrumentation.langgraph.langgraph import (
general_wrap,
wrap_compile,
@@ -49,7 +51,7 @@ EXECUTION_OPERATIONS_ALT = [
("langgraph.pregel.main", "Pregel.aget_state", "graph_aget_state", "async"),
]
-# === GRAPH CONSTRUCTION OPERATIONS (Detailed tracing only) ===
+# === GRAPH CONSTRUCTION OPERATIONS ===
# graph_init and graph_add_edge are excluded: they produce orphaned spans
# during graph building that add no monitoring value.
CONSTRUCTION_OPERATIONS = [
@@ -57,7 +59,7 @@ CONSTRUCTION_OPERATIONS = [
("langgraph.graph.state", "StateGraph.compile", "graph_compile", "special"),
]
-# === CHECKPOINTING OPERATIONS (Detailed tracing only) ===
+# === CHECKPOINTING OPERATIONS ===
CHECKPOINT_OPERATIONS = [
# Async PostgresSaver
(
@@ -121,14 +123,13 @@ class LangGraphInstrumentor(BaseInstrumentor):
environment = kwargs.get("environment", "default")
application_name = kwargs.get("application_name", "default")
- tracer = kwargs.get("tracer")
+ tracer = trace.get_tracer(__name__)
pricing_info = kwargs.get("pricing_info", {})
capture_message_content = kwargs.get("capture_message_content", False)
- metrics = kwargs.get("metrics_dict")
+ metrics = OpenlitConfig.metrics_dict
disable_metrics = kwargs.get("disable_metrics", False)
- detailed_tracing = kwargs.get("detailed_tracing", False)
- # === EXECUTION OPERATIONS (Always enabled) ===
+ # === EXECUTION OPERATIONS ===
self._wrap_execution_operations(
EXECUTION_OPERATIONS,
version,
@@ -154,43 +155,29 @@ class LangGraphInstrumentor(BaseInstrumentor):
disable_metrics,
)
- # === CONSTRUCTION OPERATIONS (Detailed tracing or always for key operations) ===
- if detailed_tracing:
- self._wrap_construction_operations(
- version,
- environment,
- application_name,
- tracer,
- pricing_info,
- capture_message_content,
- metrics,
- disable_metrics,
- )
- else:
- # Always wrap compile and add_node for graph structure and per-node tracing
- self._wrap_key_construction_operations(
- version,
- environment,
- application_name,
- tracer,
- pricing_info,
- capture_message_content,
- metrics,
- disable_metrics,
- )
+ # === CONSTRUCTION OPERATIONS ===
+ self._wrap_construction_operations(
+ version,
+ environment,
+ application_name,
+ tracer,
+ pricing_info,
+ capture_message_content,
+ metrics,
+ disable_metrics,
+ )
- # === CHECKPOINTING OPERATIONS (Detailed tracing only) ===
- if detailed_tracing:
- self._wrap_checkpoint_operations(
- version,
- environment,
- application_name,
- tracer,
- pricing_info,
- capture_message_content,
- metrics,
- disable_metrics,
- )
+ # === CHECKPOINTING OPERATIONS ===
+ self._wrap_checkpoint_operations(
+ version,
+ environment,
+ application_name,
+ tracer,
+ pricing_info,
+ capture_message_content,
+ metrics,
+ disable_metrics,
+ )
def _wrap_execution_operations(
self,
@@ -305,61 +292,6 @@ class LangGraphInstrumentor(BaseInstrumentor):
except Exception:
pass
- def _wrap_key_construction_operations(
- self,
- version,
- environment,
- application_name,
- tracer,
- pricing_info,
- capture_message_content,
- metrics,
- disable_metrics,
- ):
- """Wrap only key construction operations (compile and add_node)."""
- key_operations = [
- (
- "langgraph.graph.state",
- "StateGraph.add_node",
- "graph_add_node",
- "special",
- ),
- ("langgraph.graph.state", "StateGraph.compile", "graph_compile", "special"),
- ]
-
- for module, method, operation_type, _ in key_operations:
- try:
- if "compile" in method:
- wrapper = wrap_compile(
- operation_type,
- version,
- environment,
- application_name,
- tracer,
- pricing_info,
- capture_message_content,
- metrics,
- disable_metrics,
- )
- elif "add_node" in method:
- wrapper = wrap_add_node(
- operation_type,
- version,
- environment,
- application_name,
- tracer,
- pricing_info,
- capture_message_content,
- metrics,
- disable_metrics,
- )
- else:
- continue
-
- wrap_function_wrapper(module, method, wrapper)
- except Exception:
- pass
-
def _wrap_checkpoint_operations(
self,
version,
diff --git a/sdk/python/src/openlit/instrumentation/langgraph/langgraph.py b/sdk/python/src/openlit/instrumentation/langgraph/langgraph.py
index 510363c6..14ed066f 100644
--- a/sdk/python/src/openlit/instrumentation/langgraph/langgraph.py
+++ b/sdk/python/src/openlit/instrumentation/langgraph/langgraph.py
@@ -13,6 +13,7 @@ from openlit.__helpers import (
set_langgraph_conversation_id,
reset_langgraph_conversation_id,
get_langgraph_conversation_id,
+ _apply_custom_span_attributes,
)
from openlit.instrumentation.langgraph.utils import (
process_langgraph_response,
@@ -511,6 +512,8 @@ def wrap_compile(
span.set_status(Status(StatusCode.OK))
+ _apply_custom_span_attributes(span)
+
result._openlit_creation_context = span.get_span_context()
return result
@@ -598,6 +601,7 @@ def wrap_add_node(
span.set_attribute(
SemanticConvention.GEN_AI_OUTPUT_TYPE, "text"
)
+ _apply_custom_span_attributes(span)
try:
result = await original_func(
@@ -665,6 +669,7 @@ def wrap_add_node(
span.set_attribute(
SemanticConvention.GEN_AI_OUTPUT_TYPE, "text"
)
+ _apply_custom_span_attributes(span)
try:
result = original_func(state, *node_args, **node_kwargs)
diff --git a/sdk/python/src/openlit/instrumentation/letta/__init__.py b/sdk/python/src/openlit/instrumentation/letta/__init__.py
index c9d78df0..c5ffde40 100644
--- a/sdk/python/src/openlit/instrumentation/letta/__init__.py
+++ b/sdk/python/src/openlit/instrumentation/letta/__init__.py
@@ -6,9 +6,11 @@ Following OpenTelemetry patterns and comprehensive API coverage
from typing import Collection
import importlib.metadata
+from opentelemetry import trace
from opentelemetry.instrumentation.instrumentor import BaseInstrumentor
from wrapt import wrap_function_wrapper
+from openlit._config import OpenlitConfig
from openlit.instrumentation.letta.letta import (
create_agent,
send_message,
@@ -112,7 +114,7 @@ LETTA_OPERATIONS = {
): memory_operation,
}
-# Extended operations for detailed_tracing=True
+# Extended operations
EXTENDED_OPERATIONS = {
# Tool Operations
("letta_client.agents.tools.client", "ToolsClient.list", "tool"): tool_operation,
@@ -207,7 +209,7 @@ EXTENDED_OPERATIONS = {
): create_agent,
}
-# Async operations for detailed_tracing=True
+# Async operations
ASYNC_OPERATIONS = {
# Async Agent Operations
(
@@ -267,8 +269,8 @@ class LettaInstrumentor(BaseInstrumentor):
# Extract configuration
application_name = kwargs.get("application_name", "default_application")
environment = kwargs.get("environment", "default_environment")
- tracer = kwargs.get("tracer")
- metrics = kwargs.get("metrics_dict")
+ tracer = trace.get_tracer(__name__)
+ metrics = OpenlitConfig.metrics_dict
pricing_info = kwargs.get("pricing_info", {})
capture_message_content = kwargs.get("capture_message_content", False)
disable_metrics = kwargs.get("disable_metrics")
@@ -304,58 +306,55 @@ class LettaInstrumentor(BaseInstrumentor):
# Continue if specific operation fails to instrument
pass
- # Instrument extended operations (detailed_tracing=True only)
- if kwargs.get("detailed_tracing", False):
- for (
- module_name,
- method_name,
- _operation_type,
- ), wrapper_func in EXTENDED_OPERATIONS.items():
- try:
- wrap_function_wrapper(
- module_name,
- method_name,
- wrapper_func(
- f"letta.{method_name.rsplit('.', maxsplit=1)[-1]}",
- version,
- environment,
- application_name,
- tracer,
- pricing_info,
- capture_message_content,
- metrics,
- disable_metrics,
- ),
- )
- except Exception:
- # Continue if specific operation fails to instrument
- pass
+ # Instrument extended operations
+ for (
+ module_name,
+ method_name,
+ _operation_type,
+ ), wrapper_func in EXTENDED_OPERATIONS.items():
+ try:
+ wrap_function_wrapper(
+ module_name,
+ method_name,
+ wrapper_func(
+ f"letta.{method_name.rsplit('.', maxsplit=1)[-1]}",
+ version,
+ environment,
+ application_name,
+ tracer,
+ pricing_info,
+ capture_message_content,
+ metrics,
+ disable_metrics,
+ ),
+ )
+ except Exception:
+ pass
- # Instrument async operations
- for (
- module_name,
- method_name,
- _operation_type,
- ), wrapper_func in ASYNC_OPERATIONS.items():
- try:
- wrap_function_wrapper(
- module_name,
- method_name,
- wrapper_func(
- f"letta.{method_name.rsplit('.', maxsplit=1)[-1]}",
- version,
- environment,
- application_name,
- tracer,
- pricing_info,
- capture_message_content,
- metrics,
- disable_metrics,
- ),
- )
- except Exception:
- # Continue if specific operation fails to instrument
- pass
+ # Instrument async operations
+ for (
+ module_name,
+ method_name,
+ _operation_type,
+ ), wrapper_func in ASYNC_OPERATIONS.items():
+ try:
+ wrap_function_wrapper(
+ module_name,
+ method_name,
+ wrapper_func(
+ f"letta.{method_name.rsplit('.', maxsplit=1)[-1]}",
+ version,
+ environment,
+ application_name,
+ tracer,
+ pricing_info,
+ capture_message_content,
+ metrics,
+ disable_metrics,
+ ),
+ )
+ except Exception:
+ pass
def _uninstrument(self, **kwargs):
"""Uninstrumentation would restore original functions."""
diff --git a/sdk/python/src/openlit/instrumentation/litellm/__init__.py b/sdk/python/src/openlit/instrumentation/litellm/__init__.py
index 3e0ee0b5..eb9b9da6 100644
--- a/sdk/python/src/openlit/instrumentation/litellm/__init__.py
+++ b/sdk/python/src/openlit/instrumentation/litellm/__init__.py
@@ -2,9 +2,11 @@
from typing import Collection
import importlib.metadata
+from opentelemetry import _logs, trace
from opentelemetry.instrumentation.instrumentor import BaseInstrumentor
from wrapt import wrap_function_wrapper
+from openlit._config import OpenlitConfig
from openlit.instrumentation.litellm.litellm import completion, embedding
from openlit.instrumentation.litellm.async_litellm import acompletion, aembedding
@@ -22,12 +24,12 @@ class LiteLLMInstrumentor(BaseInstrumentor):
def _instrument(self, **kwargs):
application_name = kwargs.get("application_name", "default")
environment = kwargs.get("environment", "default")
- tracer = kwargs.get("tracer")
- metrics = kwargs.get("metrics_dict")
+ tracer = trace.get_tracer(__name__)
+ metrics = OpenlitConfig.metrics_dict
pricing_info = kwargs.get("pricing_info", {})
capture_message_content = kwargs.get("capture_message_content", False)
disable_metrics = kwargs.get("disable_metrics")
- event_provider = kwargs.get("event_provider")
+ event_provider = _logs.get_logger_provider().get_logger(__name__)
version = importlib.metadata.version("litellm")
for target_module in ["litellm", "litellm.main"]:
diff --git a/sdk/python/src/openlit/instrumentation/litellm/utils.py b/sdk/python/src/openlit/instrumentation/litellm/utils.py
index 80abcdf1..a9432ebe 100644
--- a/sdk/python/src/openlit/instrumentation/litellm/utils.py
+++ b/sdk/python/src/openlit/instrumentation/litellm/utils.py
@@ -21,6 +21,7 @@ from openlit.__helpers import (
otel_event,
truncate_message_content,
)
+from openlit._config import OpenlitConfig
from openlit.semcov import SemanticConvention
logger = logging.getLogger(__name__)
@@ -319,7 +320,8 @@ def emit_inference_event(
attributes=attributes,
body="",
)
- event_provider.emit(event)
+ if not OpenlitConfig.disable_events:
+ event_provider.emit(event)
except Exception as e:
logger.warning("Failed to emit inference event: %s", e, exc_info=True)
diff --git a/sdk/python/src/openlit/instrumentation/llamaindex/__init__.py b/sdk/python/src/openlit/instrumentation/llamaindex/__init__.py
index ebd462a9..71b32dab 100644
--- a/sdk/python/src/openlit/instrumentation/llamaindex/__init__.py
+++ b/sdk/python/src/openlit/instrumentation/llamaindex/__init__.py
@@ -4,9 +4,11 @@ OpenLIT LlamaIndex Instrumentation
from typing import Collection
import importlib.metadata
+from opentelemetry import trace
from opentelemetry.instrumentation.instrumentor import BaseInstrumentor
from wrapt import wrap_function_wrapper
+from openlit._config import OpenlitConfig
from openlit.instrumentation.llamaindex.llamaindex import general_wrap
from openlit.instrumentation.llamaindex.async_llamaindex import async_general_wrap
@@ -23,12 +25,11 @@ class LlamaIndexInstrumentor(BaseInstrumentor):
version = importlib.metadata.version("llama-index")
environment = kwargs.get("environment", "default")
application_name = kwargs.get("application_name", "default")
- tracer = kwargs.get("tracer")
+ tracer = trace.get_tracer(__name__)
pricing_info = kwargs.get("pricing_info", {})
capture_message_content = kwargs.get("capture_message_content", False)
- metrics = kwargs.get("metrics_dict")
+ metrics = OpenlitConfig.metrics_dict
disable_metrics = kwargs.get("disable_metrics")
- detailed_tracing = kwargs.get("detailed_tracing", False)
# === WORKFLOW OPERATIONS (Always enabled) - 17 operations ===
workflow_operations = [
@@ -165,7 +166,7 @@ class LlamaIndexInstrumentor(BaseInstrumentor):
),
]
- # === COMPONENT OPERATIONS (Detailed tracing only) - 25 operations ===
+ # === COMPONENT OPERATIONS - 25 operations ===
component_operations = [
# Text Processing Components
(
@@ -331,30 +332,26 @@ class LlamaIndexInstrumentor(BaseInstrumentor):
except Exception:
pass
- # Wrap component operations (detailed tracing only)
- if detailed_tracing:
- for module, method, operation_type in component_operations:
- try:
- wrap_function_wrapper(
- module,
- method,
- general_wrap(
- operation_type,
- version,
- environment,
- application_name,
- tracer,
- pricing_info,
- capture_message_content,
- metrics,
- disable_metrics,
- ),
- )
- except Exception:
- pass
-
- # Total operations: 17 workflow + 13 async + (25 component if detailed) = 30 baseline, 55 with detailed tracing
- # Beats OpenInference (~20 operations) by 175-275%
+ # Wrap component operations
+ for module, method, operation_type in component_operations:
+ try:
+ wrap_function_wrapper(
+ module,
+ method,
+ general_wrap(
+ operation_type,
+ version,
+ environment,
+ application_name,
+ tracer,
+ pricing_info,
+ capture_message_content,
+ metrics,
+ disable_metrics,
+ ),
+ )
+ except Exception:
+ pass
def _uninstrument(self, **kwargs):
pass
diff --git a/sdk/python/src/openlit/instrumentation/mcp/__init__.py b/sdk/python/src/openlit/instrumentation/mcp/__init__.py
index 93b28553..579e5d3b 100644
--- a/sdk/python/src/openlit/instrumentation/mcp/__init__.py
+++ b/sdk/python/src/openlit/instrumentation/mcp/__init__.py
@@ -5,9 +5,11 @@ Optimized Auto Instrumentation of MCP (Model Context Protocol) Functions followi
from typing import Collection
import importlib.metadata
+from opentelemetry import trace
from opentelemetry.instrumentation.instrumentor import BaseInstrumentor
from wrapt import wrap_function_wrapper
+from openlit._config import OpenlitConfig
from openlit.instrumentation.mcp.mcp import mcp_wrap
from openlit.instrumentation.mcp.async_mcp import async_mcp_wrap
from openlit.instrumentation.mcp.utils import (
@@ -507,17 +509,15 @@ class MCPInstrumentor(BaseInstrumentor):
return _instruments
def _instrument(self, **kwargs):
- """Optimized instrumentation with performance considerations and detailed tracing support."""
+ """Optimized instrumentation with performance considerations."""
# Extract configuration
application_name = kwargs.get("application_name")
environment = kwargs.get("environment")
- tracer = kwargs.get("tracer")
+ tracer = trace.get_tracer(__name__)
pricing_info = kwargs.get("pricing_info")
capture_message_content = kwargs.get("capture_message_content")
- metrics = kwargs.get("metrics_dict")
+ metrics = OpenlitConfig.metrics_dict
disable_metrics = kwargs.get("disable_metrics")
- detailed_tracing = kwargs.get("detailed_tracing", True)
-
# Cache version lookup
try:
version = importlib.metadata.version("mcp")
@@ -590,17 +590,15 @@ class MCPInstrumentor(BaseInstrumentor):
self._wrap_methods(high_priority_methods, mcp_wrap, wrapper_args)
self._wrap_methods(async_high_priority_methods, async_mcp_wrap, wrapper_args)
- # Only instrument component operations if detailed_tracing is enabled
- if detailed_tracing:
- component_methods = [
- m for m in SYNC_METHODS if m["priority"] in ["medium", "low"]
- ]
- async_component_methods = [
- m for m in ASYNC_METHODS if m["priority"] in ["medium", "low"]
- ]
+ component_methods = [
+ m for m in SYNC_METHODS if m["priority"] in ["medium", "low"]
+ ]
+ async_component_methods = [
+ m for m in ASYNC_METHODS if m["priority"] in ["medium", "low"]
+ ]
- self._wrap_methods(component_methods, mcp_wrap, wrapper_args)
- self._wrap_methods(async_component_methods, async_mcp_wrap, wrapper_args)
+ self._wrap_methods(component_methods, mcp_wrap, wrapper_args)
+ self._wrap_methods(async_component_methods, async_mcp_wrap, wrapper_args)
def _wrap_methods(self, methods, wrapper_func, wrapper_args):
"""Efficiently wrap methods with error handling following OpenLIT patterns."""
diff --git a/sdk/python/src/openlit/instrumentation/mcp/utils.py b/sdk/python/src/openlit/instrumentation/mcp/utils.py
index c5443427..f21292d6 100644
--- a/sdk/python/src/openlit/instrumentation/mcp/utils.py
+++ b/sdk/python/src/openlit/instrumentation/mcp/utils.py
@@ -14,6 +14,7 @@ from opentelemetry.trace.status import Status, StatusCode
from openlit.semcov import SemanticConvention
from openlit.__helpers import (
+ _apply_custom_span_attributes,
handle_exception,
record_mcp_metrics,
)
@@ -636,6 +637,8 @@ def set_mcp_span_attributes(
# Extract new enhanced attributes
_extract_enhanced_mcp_attributes(span, ctx, endpoint, response, **kwargs)
+ _apply_custom_span_attributes(span)
+
def _capture_mcp_content(span, ctx: MCPInstrumentationContext, response: Any, **kwargs):
"""Capture MCP request and response content with MIME types (OpenLIT enhancement)."""
diff --git a/sdk/python/src/openlit/instrumentation/mem0/__init__.py b/sdk/python/src/openlit/instrumentation/mem0/__init__.py
index 369cbae9..b53e8d53 100644
--- a/sdk/python/src/openlit/instrumentation/mem0/__init__.py
+++ b/sdk/python/src/openlit/instrumentation/mem0/__init__.py
@@ -5,6 +5,7 @@ Optimized Auto Instrumentation of mem0 Functions following OpenLIT Framework Gui
from typing import Collection
import importlib.metadata
+from opentelemetry import trace
from opentelemetry.instrumentation.instrumentor import BaseInstrumentor
from wrapt import wrap_function_wrapper
@@ -260,7 +261,7 @@ class Mem0Instrumentor(BaseInstrumentor):
# Extract configuration
application_name = kwargs.get("application_name")
environment = kwargs.get("environment")
- tracer = kwargs.get("tracer")
+ tracer = trace.get_tracer(__name__)
pricing_info = kwargs.get("pricing_info")
capture_message_content = kwargs.get("capture_message_content")
diff --git a/sdk/python/src/openlit/instrumentation/mem0/utils.py b/sdk/python/src/openlit/instrumentation/mem0/utils.py
index 810b312d..88b33b20 100644
--- a/sdk/python/src/openlit/instrumentation/mem0/utils.py
+++ b/sdk/python/src/openlit/instrumentation/mem0/utils.py
@@ -15,6 +15,7 @@ from opentelemetry.sdk.resources import (
TELEMETRY_SDK_NAME,
DEPLOYMENT_ENVIRONMENT,
)
+from openlit.__helpers import _apply_custom_span_attributes
from openlit.semcov import SemanticConvention
# Initialize logger
@@ -208,6 +209,8 @@ def set_mem0_span_attributes(
# Response attributes
_set_response_attributes(span, response)
+ _apply_custom_span_attributes(span)
+
def _set_operation_attributes(span, operation_name: str, ctx: Mem0Context):
"""Set operation-specific attributes efficiently."""
diff --git a/sdk/python/src/openlit/instrumentation/milvus/__init__.py b/sdk/python/src/openlit/instrumentation/milvus/__init__.py
index 4a71d49a..3add30c7 100644
--- a/sdk/python/src/openlit/instrumentation/milvus/__init__.py
+++ b/sdk/python/src/openlit/instrumentation/milvus/__init__.py
@@ -4,9 +4,11 @@ OpenLIT Milvus Instrumentation
from typing import Collection
import importlib.metadata
+from opentelemetry import trace
from opentelemetry.instrumentation.instrumentor import BaseInstrumentor
from wrapt import wrap_function_wrapper
+from openlit._config import OpenlitConfig
from openlit.instrumentation.milvus.milvus import general_wrap
_instruments = ("pymilvus >= 2.4.3",)
@@ -36,10 +38,10 @@ class MilvusInstrumentor(BaseInstrumentor):
version = importlib.metadata.version("pymilvus")
environment = kwargs.get("environment", "default")
application_name = kwargs.get("application_name", "default")
- tracer = kwargs.get("tracer")
+ tracer = trace.get_tracer(__name__)
pricing_info = kwargs.get("pricing_info", {})
capture_message_content = kwargs.get("capture_message_content", False)
- metrics = kwargs.get("metrics_dict")
+ metrics = OpenlitConfig.metrics_dict
disable_metrics = kwargs.get("disable_metrics")
# Wrap operations
diff --git a/sdk/python/src/openlit/instrumentation/mistral/__init__.py b/sdk/python/src/openlit/instrumentation/mistral/__init__.py
index d8e5131d..6c758325 100644
--- a/sdk/python/src/openlit/instrumentation/mistral/__init__.py
+++ b/sdk/python/src/openlit/instrumentation/mistral/__init__.py
@@ -2,9 +2,12 @@
from typing import Collection
import importlib.metadata
+from opentelemetry import _logs
+from opentelemetry import trace
from opentelemetry.instrumentation.instrumentor import BaseInstrumentor
from wrapt import wrap_function_wrapper
+from openlit._config import OpenlitConfig
from openlit.instrumentation.mistral.mistral import complete, stream, embed
from openlit.instrumentation.mistral.async_mistral import (
async_complete,
@@ -26,12 +29,12 @@ class MistralInstrumentor(BaseInstrumentor):
def _instrument(self, **kwargs):
application_name = kwargs.get("application_name", "default")
environment = kwargs.get("environment", "default")
- tracer = kwargs.get("tracer")
- metrics = kwargs.get("metrics_dict")
+ tracer = trace.get_tracer(__name__)
+ metrics = OpenlitConfig.metrics_dict
pricing_info = kwargs.get("pricing_info", {})
capture_message_content = kwargs.get("capture_message_content", False)
disable_metrics = kwargs.get("disable_metrics")
- event_provider = kwargs.get("event_provider")
+ event_provider = _logs.get_logger_provider().get_logger(__name__)
version = importlib.metadata.version("mistralai")
# sync chat completions
diff --git a/sdk/python/src/openlit/instrumentation/mistral/utils.py b/sdk/python/src/openlit/instrumentation/mistral/utils.py
index 4501fd62..c1f23c44 100644
--- a/sdk/python/src/openlit/instrumentation/mistral/utils.py
+++ b/sdk/python/src/openlit/instrumentation/mistral/utils.py
@@ -21,6 +21,7 @@ from openlit.__helpers import (
truncate_message_content,
)
from openlit.semcov import SemanticConvention
+from openlit._config import OpenlitConfig
logger = logging.getLogger(__name__)
@@ -268,7 +269,8 @@ def emit_inference_event(
attributes=attributes,
body="",
)
- event_provider.emit(event)
+ if not OpenlitConfig.disable_events:
+ event_provider.emit(event)
except Exception as e:
logger.warning("Failed to emit inference event: %s", e, exc_info=True)
diff --git a/sdk/python/src/openlit/instrumentation/multion/__init__.py b/sdk/python/src/openlit/instrumentation/multion/__init__.py
index 9e1c19de..ebfa722b 100644
--- a/sdk/python/src/openlit/instrumentation/multion/__init__.py
+++ b/sdk/python/src/openlit/instrumentation/multion/__init__.py
@@ -3,9 +3,11 @@
from typing import Collection
import importlib.metadata
+from opentelemetry import trace
from opentelemetry.instrumentation.instrumentor import BaseInstrumentor
from wrapt import wrap_function_wrapper
+from openlit._config import OpenlitConfig
from openlit.instrumentation.multion.multion import multion_wrap
from openlit.instrumentation.multion.async_multion import async_multion_wrap
@@ -24,8 +26,8 @@ class MultiOnInstrumentor(BaseInstrumentor):
def _instrument(self, **kwargs):
application_name = kwargs.get("application_name", "default_application")
environment = kwargs.get("environment", "default_environment")
- tracer = kwargs.get("tracer")
- metrics = kwargs.get("metrics_dict")
+ tracer = trace.get_tracer(__name__)
+ metrics = OpenlitConfig.metrics_dict
pricing_info = kwargs.get("pricing_info", {})
capture_message_content = kwargs.get("capture_message_content", False)
disable_metrics = kwargs.get("disable_metrics")
diff --git a/sdk/python/src/openlit/instrumentation/multion/multion.py b/sdk/python/src/openlit/instrumentation/multion/multion.py
index 7e99c4ce..067c891c 100644
--- a/sdk/python/src/openlit/instrumentation/multion/multion.py
+++ b/sdk/python/src/openlit/instrumentation/multion/multion.py
@@ -11,6 +11,7 @@ from opentelemetry.sdk.resources import (
DEPLOYMENT_ENVIRONMENT,
)
from openlit.__helpers import (
+ _apply_custom_span_attributes,
handle_exception,
)
from openlit.semcov import SemanticConvention
@@ -149,6 +150,7 @@ def multion_wrap(
},
)
+ _apply_custom_span_attributes(span)
span.set_status(Status(StatusCode.OK))
# Return original response
diff --git a/sdk/python/src/openlit/instrumentation/ollama/__init__.py b/sdk/python/src/openlit/instrumentation/ollama/__init__.py
index d50ad1b8..e15185ec 100644
--- a/sdk/python/src/openlit/instrumentation/ollama/__init__.py
+++ b/sdk/python/src/openlit/instrumentation/ollama/__init__.py
@@ -4,9 +4,12 @@ Initializer of Auto Instrumentation of Ollama Functions
from typing import Collection
import importlib.metadata
+from opentelemetry import _logs
+from opentelemetry import trace
from opentelemetry.instrumentation.instrumentor import BaseInstrumentor
from wrapt import wrap_function_wrapper
+from openlit._config import OpenlitConfig
from openlit.instrumentation.ollama.ollama import chat, embeddings, generate
from openlit.instrumentation.ollama.async_ollama import (
async_chat,
@@ -59,12 +62,12 @@ class OllamaInstrumentor(BaseInstrumentor):
def _instrument(self, **kwargs):
application_name = kwargs.get("application_name", "default_application")
environment = kwargs.get("environment", "default_environment")
- tracer = kwargs.get("tracer")
- metrics = kwargs.get("metrics_dict")
+ tracer = trace.get_tracer(__name__)
+ metrics = OpenlitConfig.metrics_dict
pricing_info = kwargs.get("pricing_info", {})
capture_message_content = kwargs.get("capture_message_content", False)
disable_metrics = kwargs.get("disable_metrics")
- event_provider = kwargs.get("event_provider")
+ event_provider = _logs.get_logger_provider().get_logger(__name__)
version = importlib.metadata.version("ollama")
# Build wrapper factories for chat and embeddings
diff --git a/sdk/python/src/openlit/instrumentation/ollama/utils.py b/sdk/python/src/openlit/instrumentation/ollama/utils.py
index c6ae585f..c4afe04c 100644
--- a/sdk/python/src/openlit/instrumentation/ollama/utils.py
+++ b/sdk/python/src/openlit/instrumentation/ollama/utils.py
@@ -22,6 +22,7 @@ from openlit.__helpers import (
truncate_message_content,
)
from openlit.semcov import SemanticConvention
+from openlit._config import OpenlitConfig
logger = logging.getLogger(__name__)
@@ -251,7 +252,8 @@ def emit_inference_event(
attributes=attributes,
body="",
)
- event_provider.emit(event)
+ if not OpenlitConfig.disable_events:
+ event_provider.emit(event)
except Exception as e:
logger.warning("Failed to emit inference event: %s", e, exc_info=True)
diff --git a/sdk/python/src/openlit/instrumentation/openai/__init__.py b/sdk/python/src/openlit/instrumentation/openai/__init__.py
index bd9c2e0e..9197d4cc 100644
--- a/sdk/python/src/openlit/instrumentation/openai/__init__.py
+++ b/sdk/python/src/openlit/instrumentation/openai/__init__.py
@@ -2,9 +2,12 @@
from typing import Collection
import importlib.metadata
+from opentelemetry import _logs
+from opentelemetry import trace
from opentelemetry.instrumentation.instrumentor import BaseInstrumentor
from wrapt import wrap_function_wrapper
+from openlit._config import OpenlitConfig
from openlit.instrumentation.openai.openai import (
chat_completions,
embedding,
@@ -39,12 +42,12 @@ class OpenAIInstrumentor(BaseInstrumentor):
version = importlib.metadata.version("openai")
environment = kwargs.get("environment", "default")
application_name = kwargs.get("application_name", "default")
- tracer = kwargs.get("tracer")
+ tracer = trace.get_tracer(__name__)
pricing_info = kwargs.get("pricing_info", {})
capture_message_content = kwargs.get("capture_message_content", False)
- metrics = kwargs.get("metrics_dict")
+ metrics = OpenlitConfig.metrics_dict
disable_metrics = kwargs.get("disable_metrics")
- event_provider = kwargs.get("event_provider")
+ event_provider = _logs.get_logger_provider().get_logger(__name__)
# chat completions
wrap_function_wrapper(
diff --git a/sdk/python/src/openlit/instrumentation/openai/utils.py b/sdk/python/src/openlit/instrumentation/openai/utils.py
index 04d257c5..ff37f8ef 100644
--- a/sdk/python/src/openlit/instrumentation/openai/utils.py
+++ b/sdk/python/src/openlit/instrumentation/openai/utils.py
@@ -26,6 +26,7 @@ from openlit.__helpers import (
truncate_message_content,
)
from openlit.semcov import SemanticConvention
+from openlit._config import OpenlitConfig
logger = logging.getLogger(__name__)
@@ -595,7 +596,8 @@ def emit_inference_event(
body="", # Per spec, all data in attributes
)
- event_provider.emit(event)
+ if not OpenlitConfig.disable_events:
+ event_provider.emit(event)
except Exception as e:
logger.warning("Failed to emit inference event: %s", e, exc_info=True)
diff --git a/sdk/python/src/openlit/instrumentation/openai_agents/__init__.py b/sdk/python/src/openlit/instrumentation/openai_agents/__init__.py
index 1863f4d3..952bad36 100644
--- a/sdk/python/src/openlit/instrumentation/openai_agents/__init__.py
+++ b/sdk/python/src/openlit/instrumentation/openai_agents/__init__.py
@@ -7,11 +7,17 @@ import threading
from typing import Collection
import importlib.metadata
+from opentelemetry import trace
from opentelemetry.instrumentation.instrumentor import BaseInstrumentor
from opentelemetry.trace import SpanKind
from wrapt import wrap_function_wrapper
-from openlit.__helpers import handle_exception, format_system_instructions
+from openlit.__helpers import (
+ handle_exception,
+ format_system_instructions,
+ _apply_custom_span_attributes,
+)
+from openlit._config import OpenlitConfig
from openlit.semcov import SemanticConvention
from openlit.instrumentation.openai_agents.processor import OpenLITTracingProcessor
@@ -110,6 +116,8 @@ def _wrap_agent_init(
SemanticConvention.GEN_AI_APPLICATION_NAME, application_name
)
+ _apply_custom_span_attributes(span)
+
creation_ctx = span.get_span_context()
instance._openlit_creation_context = creation_ctx
registry.register(str(name), creation_ctx)
@@ -131,12 +139,11 @@ class OpenAIAgentsInstrumentor(BaseInstrumentor):
version = importlib.metadata.version("openai-agents")
environment = kwargs.get("environment", "default")
application_name = kwargs.get("application_name", "default")
- tracer = kwargs.get("tracer")
+ tracer = trace.get_tracer(__name__)
pricing_info = kwargs.get("pricing_info", {})
capture_message_content = kwargs.get("capture_message_content", False)
- metrics = kwargs.get("metrics_dict")
+ metrics = OpenlitConfig.metrics_dict
disable_metrics = kwargs.get("disable_metrics")
- detailed_tracing = kwargs.get("detailed_tracing", False)
# Shared registry: create_agent span contexts keyed by agent name
agent_registry = _AgentCreationRegistry()
@@ -167,7 +174,6 @@ class OpenAIAgentsInstrumentor(BaseInstrumentor):
capture_message_content=capture_message_content,
metrics=metrics,
disable_metrics=disable_metrics,
- detailed_tracing=detailed_tracing,
agent_creation_registry=agent_registry,
)
diff --git a/sdk/python/src/openlit/instrumentation/openai_agents/processor.py b/sdk/python/src/openlit/instrumentation/openai_agents/processor.py
index 82df1b7c..5d02a084 100644
--- a/sdk/python/src/openlit/instrumentation/openai_agents/processor.py
+++ b/sdk/python/src/openlit/instrumentation/openai_agents/processor.py
@@ -25,7 +25,6 @@ from openlit.instrumentation.openai_agents.utils import (
get_operation_type,
get_span_kind,
generate_span_name,
- is_detailed_only,
process_span_end,
)
@@ -77,7 +76,6 @@ class OpenLITTracingProcessor(TracingProcessor):
capture_message_content,
metrics,
disable_metrics,
- detailed_tracing,
agent_creation_registry=None,
**kwargs,
):
@@ -91,7 +89,6 @@ class OpenLITTracingProcessor(TracingProcessor):
self.capture_message_content = capture_message_content
self.metrics = metrics
self.disable_metrics = disable_metrics
- self.detailed_tracing = detailed_tracing
self._agent_creation_registry = agent_creation_registry
self._lock = threading.Lock()
@@ -232,9 +229,6 @@ class OpenLITTracingProcessor(TracingProcessor):
if span_type in self._LLM_SPAN_TYPES:
return
- if is_detailed_only(span_type) and not self.detailed_tracing:
- return
-
trace_id = getattr(sdk_span, "trace_id", "unknown")
sdk_span_id = getattr(sdk_span, "span_id", None)
parent_sdk_id = getattr(sdk_span, "parent_id", None)
@@ -292,9 +286,6 @@ class OpenLITTracingProcessor(TracingProcessor):
if span_type in self._LLM_SPAN_TYPES:
return
- if is_detailed_only(span_type) and not self.detailed_tracing:
- return
-
sdk_span_id = getattr(sdk_span, "span_id", None)
trace_id = getattr(sdk_span, "trace_id", "unknown")
diff --git a/sdk/python/src/openlit/instrumentation/openai_agents/utils.py b/sdk/python/src/openlit/instrumentation/openai_agents/utils.py
index 06ce2d7a..3e21cf3f 100644
--- a/sdk/python/src/openlit/instrumentation/openai_agents/utils.py
+++ b/sdk/python/src/openlit/instrumentation/openai_agents/utils.py
@@ -54,10 +54,6 @@ SPAN_KIND_MAP = {
SemanticConvention.GEN_AI_OPERATION_TYPE_CHAT: SpanKind.CLIENT,
}
-_DETAILED_SPAN_TYPES = frozenset(
- {"custom", "transcription", "speech", "speech_group", "mcp_tools"}
-)
-
_MAX_HANDOFFS = 1000
@@ -118,11 +114,6 @@ def generate_span_name(span_data):
return operation
-def is_detailed_only(span_type):
- """Return True if *span_type* should only be traced under detailed_tracing."""
- return span_type in _DETAILED_SPAN_TYPES
-
-
# ---------------------------------------------------------------------------
# Main dispatcher -- called from ``on_span_end``
# ---------------------------------------------------------------------------
diff --git a/sdk/python/src/openlit/instrumentation/pinecone/__init__.py b/sdk/python/src/openlit/instrumentation/pinecone/__init__.py
index 42d62ad1..cb7106ca 100644
--- a/sdk/python/src/openlit/instrumentation/pinecone/__init__.py
+++ b/sdk/python/src/openlit/instrumentation/pinecone/__init__.py
@@ -2,9 +2,11 @@
from typing import Collection
import importlib.metadata
+from opentelemetry import trace
from opentelemetry.instrumentation.instrumentor import BaseInstrumentor
from wrapt import wrap_function_wrapper
+from openlit._config import OpenlitConfig
from openlit.instrumentation.pinecone.pinecone import general_wrap
from openlit.instrumentation.pinecone.async_pinecone import async_general_wrap
@@ -71,10 +73,10 @@ class PineconeInstrumentor(BaseInstrumentor):
version = importlib.metadata.version("pinecone")
environment = kwargs.get("environment", "default")
application_name = kwargs.get("application_name", "default")
- tracer = kwargs.get("tracer")
+ tracer = trace.get_tracer(__name__)
pricing_info = kwargs.get("pricing_info", {})
capture_message_content = kwargs.get("capture_message_content", False)
- metrics = kwargs.get("metrics_dict")
+ metrics = OpenlitConfig.metrics_dict
disable_metrics = kwargs.get("disable_metrics")
# Wrap sync operations
diff --git a/sdk/python/src/openlit/instrumentation/premai/__init__.py b/sdk/python/src/openlit/instrumentation/premai/__init__.py
index 09b1556d..8c3a6464 100644
--- a/sdk/python/src/openlit/instrumentation/premai/__init__.py
+++ b/sdk/python/src/openlit/instrumentation/premai/__init__.py
@@ -2,9 +2,12 @@
from typing import Collection
import importlib.metadata
+from opentelemetry import _logs
+from opentelemetry import trace
from opentelemetry.instrumentation.instrumentor import BaseInstrumentor
from wrapt import wrap_function_wrapper
+from openlit._config import OpenlitConfig
from openlit.instrumentation.premai.premai import chat, embedding
_instruments = ("premai >= 0.3.79",)
@@ -21,12 +24,12 @@ class PremAIInstrumentor(BaseInstrumentor):
def _instrument(self, **kwargs):
application_name = kwargs.get("application_name", "default")
environment = kwargs.get("environment", "default")
- tracer = kwargs.get("tracer")
- metrics = kwargs.get("metrics_dict")
+ tracer = trace.get_tracer(__name__)
+ metrics = OpenlitConfig.metrics_dict
pricing_info = kwargs.get("pricing_info", {})
capture_message_content = kwargs.get("capture_message_content", False)
disable_metrics = kwargs.get("disable_metrics")
- event_provider = kwargs.get("event_provider")
+ event_provider = _logs.get_logger_provider().get_logger(__name__)
version = importlib.metadata.version("premai")
# sync chat
diff --git a/sdk/python/src/openlit/instrumentation/premai/utils.py b/sdk/python/src/openlit/instrumentation/premai/utils.py
index 111a99e4..047405e2 100644
--- a/sdk/python/src/openlit/instrumentation/premai/utils.py
+++ b/sdk/python/src/openlit/instrumentation/premai/utils.py
@@ -21,6 +21,7 @@ from openlit.__helpers import (
record_embedding_metrics,
truncate_message_content,
)
+from openlit._config import OpenlitConfig
from openlit.semcov import SemanticConvention
logger = logging.getLogger(__name__)
@@ -269,7 +270,8 @@ def emit_inference_event(
attributes=attributes,
body="",
)
- event_provider.emit(event)
+ if not OpenlitConfig.disable_events:
+ event_provider.emit(event)
except Exception as e:
logger.warning("Failed to emit inference event: %s", e, exc_info=True)
diff --git a/sdk/python/src/openlit/instrumentation/psycopg/__init__.py b/sdk/python/src/openlit/instrumentation/psycopg/__init__.py
index d23ad9e2..d306d351 100644
--- a/sdk/python/src/openlit/instrumentation/psycopg/__init__.py
+++ b/sdk/python/src/openlit/instrumentation/psycopg/__init__.py
@@ -5,9 +5,11 @@ OpenLIT Psycopg (PostgreSQL) Instrumentation
from typing import Collection, Any, Optional
import importlib.metadata
import functools
+from opentelemetry import trace
from opentelemetry.instrumentation.instrumentor import BaseInstrumentor
from wrapt import wrap_function_wrapper
+from openlit._config import OpenlitConfig
from openlit.instrumentation.psycopg.psycopg import (
execute_wrap,
executemany_wrap,
@@ -95,15 +97,10 @@ class PsycopgInstrumentor(BaseInstrumentor):
- ConnectionPool operations (optional, from psycopg_pool)
Configuration Options:
- - capture_parameters: If True, captures query parameters in spans.
+ - capture_db_parameters: If True, captures query parameters in spans.
WARNING: This may expose sensitive data like passwords, PII, tokens.
Only enable in development or when you're certain parameters are safe.
Default: False
-
- - enable_sqlcommenter: If True, injects OpenTelemetry trace context as SQL
- comments (SQLCommenter format). This enables correlation between
- application traces and database logs (pg_stat_statements, auto_explain).
- Default: False
"""
def instrumentation_dependencies(self) -> Collection[str]:
@@ -118,15 +115,13 @@ class PsycopgInstrumentor(BaseInstrumentor):
environment = kwargs.get("environment", "default")
application_name = kwargs.get("application_name", "default")
- tracer = kwargs.get("tracer")
+ tracer = trace.get_tracer(__name__)
pricing_info = kwargs.get("pricing_info", {})
capture_message_content = kwargs.get("capture_message_content", False)
- metrics = kwargs.get("metrics_dict")
+ metrics = OpenlitConfig.metrics_dict
disable_metrics = kwargs.get("disable_metrics")
- # New configuration options
- capture_parameters = kwargs.get("capture_parameters", False)
- enable_sqlcommenter = kwargs.get("enable_sqlcommenter", False)
+ capture_db_parameters = kwargs.get("capture_db_parameters", False)
# Wrap sync cursor operations
for cursor_class in SYNC_CURSOR_CLASSES:
@@ -147,8 +142,7 @@ class PsycopgInstrumentor(BaseInstrumentor):
capture_message_content,
metrics,
disable_metrics,
- capture_parameters,
- enable_sqlcommenter,
+ capture_db_parameters,
),
)
except Exception:
@@ -174,8 +168,7 @@ class PsycopgInstrumentor(BaseInstrumentor):
capture_message_content,
metrics,
disable_metrics,
- capture_parameters,
- enable_sqlcommenter,
+ capture_db_parameters,
),
)
except Exception:
@@ -200,8 +193,7 @@ class PsycopgInstrumentor(BaseInstrumentor):
capture_message_content,
metrics,
disable_metrics,
- capture_parameters,
- enable_sqlcommenter,
+ capture_db_parameters,
),
)
except Exception:
@@ -225,8 +217,7 @@ class PsycopgInstrumentor(BaseInstrumentor):
capture_message_content,
metrics,
disable_metrics,
- capture_parameters,
- enable_sqlcommenter,
+ capture_db_parameters,
),
)
except Exception:
@@ -242,8 +233,7 @@ class PsycopgInstrumentor(BaseInstrumentor):
capture_message_content,
metrics,
disable_metrics,
- capture_parameters,
- enable_sqlcommenter,
+ capture_db_parameters,
)
def _instrument_pool(
@@ -256,8 +246,7 @@ class PsycopgInstrumentor(BaseInstrumentor):
capture_message_content,
metrics,
disable_metrics,
- capture_parameters=False,
- enable_sqlcommenter=False,
+ capture_db_parameters=False,
):
"""
Instrument psycopg_pool connection pool operations.
@@ -284,8 +273,7 @@ class PsycopgInstrumentor(BaseInstrumentor):
capture_message_content,
metrics,
disable_metrics,
- capture_parameters,
- enable_sqlcommenter,
+ capture_db_parameters,
),
)
except Exception:
@@ -306,8 +294,7 @@ class PsycopgInstrumentor(BaseInstrumentor):
capture_message_content,
metrics,
disable_metrics,
- capture_parameters,
- enable_sqlcommenter,
+ capture_db_parameters,
),
)
except Exception:
@@ -320,8 +307,7 @@ class PsycopgInstrumentor(BaseInstrumentor):
tracer: Optional[Any] = None,
environment: str = "default",
application_name: str = "default",
- capture_parameters: bool = False,
- enable_sqlcommenter: bool = False,
+ capture_db_parameters: bool = False,
capture_message_content: bool = True,
**kwargs,
) -> Any:
@@ -340,8 +326,7 @@ class PsycopgInstrumentor(BaseInstrumentor):
tracer: Optional OpenTelemetry tracer instance
environment: Deployment environment name
application_name: Application name for tracing
- capture_parameters: Capture query parameters in spans (security risk!)
- enable_sqlcommenter: Inject trace context as SQL comments
+ capture_db_parameters: Capture query parameters in spans (security risk!)
capture_message_content: Capture SQL query text
Returns:
@@ -355,8 +340,7 @@ class PsycopgInstrumentor(BaseInstrumentor):
conn = psycopg.connect("postgresql://...")
PsycopgInstrumentor.instrument_connection(
conn,
- capture_parameters=True, # Enable for this connection only
- enable_sqlcommenter=True,
+ capture_db_parameters=True, # Enable for this connection only
)
```
"""
@@ -367,7 +351,7 @@ class PsycopgInstrumentor(BaseInstrumentor):
version = "unknown"
pricing_info = kwargs.get("pricing_info", {})
- metrics = kwargs.get("metrics_dict")
+ metrics = OpenlitConfig.metrics_dict
disable_metrics = kwargs.get("disable_metrics", False)
# Determine if this is an async connection
@@ -397,8 +381,7 @@ class PsycopgInstrumentor(BaseInstrumentor):
capture_message_content,
metrics,
disable_metrics,
- capture_parameters,
- enable_sqlcommenter,
+ capture_db_parameters,
)
# Create a bound wrapper for this instance
@@ -446,8 +429,7 @@ class PsycopgInstrumentor(BaseInstrumentor):
capture_message_content,
metrics,
disable_metrics,
- capture_parameters,
- enable_sqlcommenter,
+ capture_db_parameters,
is_async=True,
)
return cursor
@@ -467,8 +449,7 @@ class PsycopgInstrumentor(BaseInstrumentor):
capture_message_content,
metrics,
disable_metrics,
- capture_parameters,
- enable_sqlcommenter,
+ capture_db_parameters,
is_async=False,
)
return cursor
@@ -495,8 +476,7 @@ class PsycopgInstrumentor(BaseInstrumentor):
capture_message_content: bool,
metrics: Optional[Any],
disable_metrics: bool,
- capture_parameters: bool,
- enable_sqlcommenter: bool,
+ capture_db_parameters: bool,
is_async: bool,
):
"""Instrument a cursor instance's methods."""
@@ -515,8 +495,7 @@ class PsycopgInstrumentor(BaseInstrumentor):
capture_message_content,
metrics,
disable_metrics,
- capture_parameters,
- enable_sqlcommenter,
+ capture_db_parameters,
)
# Create a bound wrapper for this cursor instance
diff --git a/sdk/python/src/openlit/instrumentation/psycopg/async_psycopg.py b/sdk/python/src/openlit/instrumentation/psycopg/async_psycopg.py
index d8521ed5..37766f0b 100644
--- a/sdk/python/src/openlit/instrumentation/psycopg/async_psycopg.py
+++ b/sdk/python/src/openlit/instrumentation/psycopg/async_psycopg.py
@@ -14,7 +14,6 @@ from openlit.instrumentation.psycopg.utils import (
extract_database_name,
process_cursor_response,
process_connection_response,
- inject_sql_comment,
)
from openlit.semcov import SemanticConvention
@@ -29,15 +28,13 @@ def async_execute_wrap(
capture_message_content,
metrics,
disable_metrics,
- capture_parameters=False,
- enable_sqlcommenter=False,
+ capture_db_parameters=False,
):
"""
Generates a telemetry wrapper for AsyncCursor.execute operations.
Args:
- capture_parameters: If True, captures query parameters in spans (security risk!)
- enable_sqlcommenter: If True, injects trace context as SQL comments
+ capture_db_parameters: If True, captures query parameters in spans (security risk!)
"""
async def wrapper(wrapped, instance, args, kwargs):
@@ -70,13 +67,6 @@ def async_execute_wrap(
with tracer.start_as_current_span(span_name, kind=SpanKind.CLIENT) as span:
start_time = time.time()
- # Inject SQLCommenter if enabled (must be done inside span context)
- modified_query = inject_sql_comment(
- query, application_name, enable_sqlcommenter
- )
- if modified_query != query:
- args = (modified_query,) + args[1:] if args else args
-
response = await wrapped(*args, **kwargs)
try:
@@ -85,7 +75,7 @@ def async_execute_wrap(
response,
db_operation,
table_name,
- query, # Use original query for logging
+ query,
server_address,
server_port,
database_name,
@@ -100,7 +90,7 @@ def async_execute_wrap(
cursor=instance,
connection=connection,
endpoint=gen_ai_endpoint,
- capture_parameters=capture_parameters,
+ capture_db_parameters=capture_db_parameters,
params=params,
)
@@ -122,13 +112,12 @@ def async_executemany_wrap(
capture_message_content,
metrics,
disable_metrics,
- capture_parameters=False,
- enable_sqlcommenter=False,
+ capture_db_parameters=False,
):
"""
Generates a telemetry wrapper for AsyncCursor.executemany operations.
- Note: For executemany, capture_parameters only captures first batch item
+ Note: For executemany, capture_db_parameters only captures first batch item
to avoid huge traces.
"""
@@ -164,13 +153,6 @@ def async_executemany_wrap(
with tracer.start_as_current_span(span_name, kind=SpanKind.CLIENT) as span:
start_time = time.time()
- # Inject SQLCommenter if enabled
- modified_query = inject_sql_comment(
- query, application_name, enable_sqlcommenter
- )
- if modified_query != query:
- args = (modified_query,) + args[1:] if args else args
-
response = await wrapped(*args, **kwargs)
try:
@@ -200,7 +182,7 @@ def async_executemany_wrap(
cursor=instance,
connection=connection,
endpoint=gen_ai_endpoint,
- capture_parameters=capture_parameters,
+ capture_db_parameters=capture_db_parameters,
params=first_params,
)
@@ -222,14 +204,13 @@ def async_copy_wrap(
capture_message_content,
metrics,
disable_metrics,
- capture_parameters=False,
- enable_sqlcommenter=False,
+ capture_db_parameters=False,
):
"""
Generates a telemetry wrapper for AsyncCursor.copy operations.
- Note: COPY operations don't typically have parameters, so capture_parameters
- has limited effect here. SQLCommenter is also not injected for COPY statements.
+ Note: COPY operations don't typically have parameters, so capture_db_parameters
+ has limited effect here.
"""
async def wrapper(wrapped, instance, args, kwargs):
@@ -303,14 +284,13 @@ def async_commit_wrap(
capture_message_content,
metrics,
disable_metrics,
- capture_parameters=False,
- enable_sqlcommenter=False,
+ capture_db_parameters=False,
):
"""
Generates a telemetry wrapper for AsyncConnection.commit operations.
- Note: capture_parameters and enable_sqlcommenter are accepted for API
- consistency but not used for commit operations.
+ Note: capture_db_parameters is accepted for API consistency but not used
+ for commit operations.
"""
async def wrapper(wrapped, instance, args, kwargs):
@@ -373,14 +353,13 @@ def async_rollback_wrap(
capture_message_content,
metrics,
disable_metrics,
- capture_parameters=False,
- enable_sqlcommenter=False,
+ capture_db_parameters=False,
):
"""
Generates a telemetry wrapper for AsyncConnection.rollback operations.
- Note: capture_parameters and enable_sqlcommenter are accepted for API
- consistency but not used for rollback operations.
+ Note: capture_db_parameters is accepted for API consistency but not used
+ for rollback operations.
"""
async def wrapper(wrapped, instance, args, kwargs):
@@ -443,14 +422,12 @@ def async_callproc_wrap(
capture_message_content,
metrics,
disable_metrics,
- capture_parameters=False,
- enable_sqlcommenter=False,
+ capture_db_parameters=False,
):
"""
Generates a telemetry wrapper for AsyncCursor.callproc operations (stored procedures).
- Note: enable_sqlcommenter is not applicable to callproc (procedure calls
- don't use SQL strings). capture_parameters captures procedure arguments.
+ Note: capture_db_parameters captures procedure arguments.
"""
async def wrapper(wrapped, instance, args, kwargs):
@@ -504,7 +481,7 @@ def async_callproc_wrap(
cursor=instance,
connection=connection,
endpoint=gen_ai_endpoint,
- capture_parameters=capture_parameters,
+ capture_db_parameters=capture_db_parameters,
params=proc_params,
)
@@ -526,14 +503,13 @@ def async_pool_getconn_wrap(
capture_message_content,
metrics,
disable_metrics,
- capture_parameters=False,
- enable_sqlcommenter=False,
+ capture_db_parameters=False,
):
"""
Generates a telemetry wrapper for AsyncConnectionPool.getconn operations.
- Note: capture_parameters and enable_sqlcommenter are accepted for API
- consistency but not used for pool operations.
+ Note: capture_db_parameters is accepted for API consistency but not used
+ for pool operations.
"""
async def wrapper(wrapped, instance, args, kwargs):
diff --git a/sdk/python/src/openlit/instrumentation/psycopg/psycopg.py b/sdk/python/src/openlit/instrumentation/psycopg/psycopg.py
index 1e2061c7..6590495a 100644
--- a/sdk/python/src/openlit/instrumentation/psycopg/psycopg.py
+++ b/sdk/python/src/openlit/instrumentation/psycopg/psycopg.py
@@ -14,7 +14,6 @@ from openlit.instrumentation.psycopg.utils import (
extract_database_name,
process_cursor_response,
process_connection_response,
- inject_sql_comment,
)
from openlit.semcov import SemanticConvention
@@ -29,15 +28,13 @@ def execute_wrap(
capture_message_content,
metrics,
disable_metrics,
- capture_parameters=False,
- enable_sqlcommenter=False,
+ capture_db_parameters=False,
):
"""
Generates a telemetry wrapper for Cursor.execute operations.
Args:
- capture_parameters: If True, captures query parameters in spans (security risk!)
- enable_sqlcommenter: If True, injects trace context as SQL comments
+ capture_db_parameters: If True, captures query parameters in spans (security risk!)
"""
def wrapper(wrapped, instance, args, kwargs):
@@ -70,14 +67,6 @@ def execute_wrap(
with tracer.start_as_current_span(span_name, kind=SpanKind.CLIENT) as span:
start_time = time.time()
- # Inject SQLCommenter if enabled (must be done inside span context)
- modified_query = inject_sql_comment(
- query, application_name, enable_sqlcommenter
- )
- if modified_query != query:
- # Update args with modified query
- args = (modified_query,) + args[1:] if args else args
-
response = wrapped(*args, **kwargs)
try:
@@ -86,7 +75,7 @@ def execute_wrap(
response,
db_operation,
table_name,
- query, # Use original query for logging
+ query,
server_address,
server_port,
database_name,
@@ -101,7 +90,7 @@ def execute_wrap(
cursor=instance,
connection=connection,
endpoint=gen_ai_endpoint,
- capture_parameters=capture_parameters,
+ capture_db_parameters=capture_db_parameters,
params=params,
)
@@ -123,13 +112,12 @@ def executemany_wrap(
capture_message_content,
metrics,
disable_metrics,
- capture_parameters=False,
- enable_sqlcommenter=False,
+ capture_db_parameters=False,
):
"""
Generates a telemetry wrapper for Cursor.executemany operations.
- Note: For executemany, capture_parameters only captures first batch item
+ Note: For executemany, capture_db_parameters only captures first batch item
to avoid huge traces.
"""
@@ -165,13 +153,6 @@ def executemany_wrap(
with tracer.start_as_current_span(span_name, kind=SpanKind.CLIENT) as span:
start_time = time.time()
- # Inject SQLCommenter if enabled
- modified_query = inject_sql_comment(
- query, application_name, enable_sqlcommenter
- )
- if modified_query != query:
- args = (modified_query,) + args[1:] if args else args
-
response = wrapped(*args, **kwargs)
try:
@@ -201,7 +182,7 @@ def executemany_wrap(
cursor=instance,
connection=connection,
endpoint=gen_ai_endpoint,
- capture_parameters=capture_parameters,
+ capture_db_parameters=capture_db_parameters,
params=first_params,
)
@@ -223,14 +204,13 @@ def copy_wrap(
capture_message_content,
metrics,
disable_metrics,
- capture_parameters=False,
- enable_sqlcommenter=False,
+ capture_db_parameters=False,
):
"""
Generates a telemetry wrapper for Cursor.copy operations.
- Note: COPY operations don't typically have parameters, so capture_parameters
- has limited effect here. SQLCommenter is also not injected for COPY statements.
+ Note: COPY operations don't typically have parameters, so capture_db_parameters
+ has limited effect here.
"""
def wrapper(wrapped, instance, args, kwargs):
@@ -304,14 +284,13 @@ def commit_wrap(
capture_message_content,
metrics,
disable_metrics,
- capture_parameters=False,
- enable_sqlcommenter=False,
+ capture_db_parameters=False,
):
"""
Generates a telemetry wrapper for Connection.commit operations.
- Note: capture_parameters and enable_sqlcommenter are accepted for API
- consistency but not used for commit operations.
+ Note: capture_db_parameters is accepted for API consistency but not used
+ for commit operations.
"""
def wrapper(wrapped, instance, args, kwargs):
@@ -374,14 +353,13 @@ def rollback_wrap(
capture_message_content,
metrics,
disable_metrics,
- capture_parameters=False,
- enable_sqlcommenter=False,
+ capture_db_parameters=False,
):
"""
Generates a telemetry wrapper for Connection.rollback operations.
- Note: capture_parameters and enable_sqlcommenter are accepted for API
- consistency but not used for rollback operations.
+ Note: capture_db_parameters is accepted for API consistency but not used
+ for rollback operations.
"""
def wrapper(wrapped, instance, args, kwargs):
@@ -444,14 +422,12 @@ def callproc_wrap(
capture_message_content,
metrics,
disable_metrics,
- capture_parameters=False,
- enable_sqlcommenter=False,
+ capture_db_parameters=False,
):
"""
Generates a telemetry wrapper for Cursor.callproc operations (stored procedures).
- Note: enable_sqlcommenter is not applicable to callproc (procedure calls
- don't use SQL strings). capture_parameters captures procedure arguments.
+ Note: capture_db_parameters captures procedure arguments.
"""
def wrapper(wrapped, instance, args, kwargs):
@@ -505,7 +481,7 @@ def callproc_wrap(
cursor=instance,
connection=connection,
endpoint=gen_ai_endpoint,
- capture_parameters=capture_parameters,
+ capture_db_parameters=capture_db_parameters,
params=proc_params,
)
@@ -527,14 +503,13 @@ def pool_getconn_wrap(
capture_message_content,
metrics,
disable_metrics,
- capture_parameters=False,
- enable_sqlcommenter=False,
+ capture_db_parameters=False,
):
"""
Generates a telemetry wrapper for ConnectionPool.getconn operations.
- Note: capture_parameters and enable_sqlcommenter are accepted for API
- consistency but not used for pool operations.
+ Note: capture_db_parameters is accepted for API consistency but not used
+ for pool operations.
"""
def wrapper(wrapped, instance, args, kwargs):
diff --git a/sdk/python/src/openlit/instrumentation/psycopg/utils.py b/sdk/python/src/openlit/instrumentation/psycopg/utils.py
index de8bbaa0..78c0de72 100644
--- a/sdk/python/src/openlit/instrumentation/psycopg/utils.py
+++ b/sdk/python/src/openlit/instrumentation/psycopg/utils.py
@@ -4,8 +4,8 @@ Utilities for Psycopg (PostgreSQL) instrumentation.
import re
import time
-from typing import Tuple, Any, Optional
-from opentelemetry.trace import Status, StatusCode, get_current_span
+from typing import Tuple, Any
+from opentelemetry.trace import Status, StatusCode
from openlit.__helpers import (
common_db_span_attributes,
record_db_metrics,
@@ -214,7 +214,7 @@ def sanitize_parameter(value: Any, max_length: int = MAX_PARAM_LENGTH) -> str:
Truncates long values and converts to string representation.
Does NOT mask sensitive data - that's the user's responsibility
- to not enable capture_parameters with sensitive queries.
+ to not enable capture_db_parameters with sensitive queries.
Args:
value: Parameter value
@@ -247,177 +247,6 @@ def sanitize_parameter(value: Any, max_length: int = MAX_PARAM_LENGTH) -> str:
return str_value
-def format_parameters(
- params: Any,
- max_count: int = MAX_PARAMS_COUNT,
- max_length: int = MAX_PARAM_LENGTH,
-) -> Optional[str]:
- """
- Format query parameters for span attributes.
-
- Args:
- params: Query parameters (tuple, list, dict, or None)
- max_count: Maximum number of parameters to include
- max_length: Maximum length per parameter value
-
- Returns:
- Formatted string or None if no parameters
- """
- if params is None:
- return None
-
- try:
- if isinstance(params, dict):
- # Named parameters: {"name": "value", ...}
- items = list(params.items())[:max_count]
- formatted = {k: sanitize_parameter(v, max_length) for k, v in items}
- if len(params) > max_count:
- formatted["..."] = f"<{len(params) - max_count} more>"
- return str(formatted)
-
- elif isinstance(params, (list, tuple)):
- # Positional parameters: ($1, $2, ...)
- items = list(params)[:max_count]
- formatted = [sanitize_parameter(v, max_length) for v in items]
- if len(params) > max_count:
- formatted.append(f"<{len(params) - max_count} more>")
- return str(formatted)
-
- else:
- # Single parameter
- return sanitize_parameter(params, max_length)
-
- except Exception:
- return "<error formatting parameters>"
-
-
-def generate_sql_comment(
- traceparent: Optional[str] = None,
- tracestate: Optional[str] = None,
- application_name: Optional[str] = None,
-) -> str:
- """
- Generate a SQL comment with trace context (SQLCommenter format).
-
- This allows database logs to be correlated with application traces.
- Format follows the SQLCommenter specification:
- https://google.github.io/sqlcommenter/
-
- Args:
- traceparent: W3C Trace Context traceparent header value
- tracestate: W3C Trace Context tracestate header value
- application_name: Application name to include
-
- Returns:
- SQL comment string to append to queries
- """
- parts = []
-
- if traceparent:
- # URL-encode single quotes for safety
- parts.append(f"traceparent='{traceparent}'")
-
- if tracestate:
- parts.append(f"tracestate='{tracestate}'")
-
- if application_name:
- # Sanitize application name (alphanumeric and underscores only)
- safe_name = re.sub(r"[^a-zA-Z0-9_]", "_", application_name)
- parts.append(f"application='{safe_name}'")
-
- if not parts:
- return ""
-
- return "/*" + ",".join(parts) + "*/"
-
-
-def get_trace_context_for_comment() -> Tuple[Optional[str], Optional[str]]:
- """
- Extract current trace context for SQLCommenter.
-
- Returns:
- Tuple of (traceparent, tracestate) or (None, None) if no active span
- """
- try:
- span = get_current_span()
- if span is None or not span.is_recording():
- return None, None
-
- ctx = span.get_span_context()
- if ctx is None or not ctx.is_valid:
- return None, None
-
- # Format traceparent: version-trace_id-span_id-flags
- # Version is always 00
- trace_id = format(ctx.trace_id, "032x")
- span_id = format(ctx.span_id, "016x")
- flags = format(ctx.trace_flags, "02x")
- traceparent = f"00-{trace_id}-{span_id}-{flags}"
-
- # Get tracestate if available
- tracestate = None
- if ctx.trace_state:
- # Convert trace state to string
- tracestate_items = []
- for key, value in ctx.trace_state.items():
- tracestate_items.append(f"{key}={value}")
- if tracestate_items:
- tracestate = ",".join(tracestate_items)
-
- return traceparent, tracestate
-
- except Exception:
- return None, None
-
-
-def inject_sql_comment(
- query: Any,
- application_name: Optional[str] = None,
- enable_sqlcommenter: bool = False,
-) -> Any:
- """
- Inject SQLCommenter trace context into a SQL query.
-
- Only modifies string queries. SQL composition objects are returned as-is.
- Only injects if enable_sqlcommenter is True.
-
- Args:
- query: Original SQL query
- application_name: Application name to include in comment
- enable_sqlcommenter: Whether SQLCommenter is enabled
-
- Returns:
- Modified query with comment appended, or original query
- """
- if not enable_sqlcommenter:
- return query
-
- # Only inject into string queries
- if not isinstance(query, str):
- return query
-
- # Don't inject if query already has a comment at the end
- stripped = query.rstrip()
- if stripped.endswith("*/"):
- return query
-
- # Get current trace context
- traceparent, tracestate = get_trace_context_for_comment()
-
- # Generate comment
- comment = generate_sql_comment(traceparent, tracestate, application_name)
-
- if not comment:
- return query
-
- # Append comment to query
- # Handle queries that end with semicolon
- if stripped.endswith(";"):
- return stripped[:-1] + " " + comment + ";"
- else:
- return query + " " + comment
-
-
def common_psycopg_logic(
scope,
environment,
@@ -428,7 +257,7 @@ def common_psycopg_logic(
version,
connection=None,
endpoint=None,
- capture_parameters=False,
+ capture_db_parameters=False,
params=None,
):
"""
@@ -444,8 +273,8 @@ def common_psycopg_logic(
version: SDK version
connection: Database connection object
endpoint: API endpoint name
- capture_parameters: Whether to capture query parameters
- params: Query parameters (if capture_parameters is True)
+ capture_db_parameters: Whether to capture query parameters
+ params: Query parameters (if capture_db_parameters is True)
"""
scope._end_time = time.time()
@@ -482,13 +311,18 @@ def common_psycopg_logic(
query_str = truncate_content(scope._query)
scope._span.set_attribute(SemanticConvention.DB_QUERY_TEXT, query_str)
- # Set query parameters if capture is enabled
- if capture_parameters and params is not None:
- formatted_params = format_parameters(params)
- if formatted_params:
- scope._span.set_attribute(
- SemanticConvention.DB_QUERY_PARAMETER, formatted_params
- )
+ # Set query parameters if capture is enabled (OTel per-key convention)
+ if capture_db_parameters and params is not None:
+ if isinstance(params, dict):
+ for key, value in list(params.items())[:MAX_PARAMS_COUNT]:
+ scope._span.set_attribute(
+ f"db.query.parameter.{key}", sanitize_parameter(value)
+ )
+ elif isinstance(params, (list, tuple)):
+ for idx, value in enumerate(list(params)[:MAX_PARAMS_COUNT]):
+ scope._span.set_attribute(
+ f"db.query.parameter.{idx}", sanitize_parameter(value)
+ )
# Set query summary
scope._span.set_attribute(
@@ -550,7 +384,7 @@ def process_cursor_response(
cursor=None,
connection=None,
endpoint=None,
- capture_parameters=False,
+ capture_db_parameters=False,
params=None,
):
"""
@@ -575,7 +409,7 @@ def process_cursor_response(
cursor: Cursor object
connection: Connection object
endpoint: API endpoint name
- capture_parameters: Whether to capture query parameters
+ capture_db_parameters: Whether to capture query parameters
params: Query parameters (tuple, list, dict, or None)
"""
# Create scope object
@@ -609,7 +443,7 @@ def process_cursor_response(
version,
connection=connection,
endpoint=endpoint,
- capture_parameters=capture_parameters,
+ capture_db_parameters=capture_db_parameters,
params=params,
)
diff --git a/sdk/python/src/openlit/instrumentation/pydantic_ai/__init__.py b/sdk/python/src/openlit/instrumentation/pydantic_ai/__init__.py
index 6f019b82..3c1d2864 100644
--- a/sdk/python/src/openlit/instrumentation/pydantic_ai/__init__.py
+++ b/sdk/python/src/openlit/instrumentation/pydantic_ai/__init__.py
@@ -2,9 +2,11 @@
from typing import Collection
import importlib.metadata
+from opentelemetry import trace
from opentelemetry.instrumentation.instrumentor import BaseInstrumentor
from wrapt import wrap_function_wrapper
+from openlit._config import OpenlitConfig
from openlit.instrumentation.pydantic_ai.pydantic_ai import (
agent_create,
agent_run,
@@ -31,8 +33,8 @@ class PydanticAIInstrumentor(BaseInstrumentor):
def _instrument(self, **kwargs):
application_name = kwargs.get("application_name", "default_application")
environment = kwargs.get("environment", "default_environment")
- tracer = kwargs.get("tracer")
- metrics = kwargs.get("metrics_dict")
+ tracer = trace.get_tracer(__name__)
+ metrics = OpenlitConfig.metrics_dict
pricing_info = kwargs.get("pricing_info", {})
capture_message_content = kwargs.get("capture_message_content", False)
disable_metrics = kwargs.get("disable_metrics")
diff --git a/sdk/python/src/openlit/instrumentation/pydantic_ai/utils.py b/sdk/python/src/openlit/instrumentation/pydantic_ai/utils.py
index 21aa154b..74519eb8 100644
--- a/sdk/python/src/openlit/instrumentation/pydantic_ai/utils.py
+++ b/sdk/python/src/openlit/instrumentation/pydantic_ai/utils.py
@@ -13,7 +13,11 @@ from opentelemetry.sdk.resources import (
)
from opentelemetry.trace import Status, StatusCode, SpanKind
from opentelemetry import context as context_api
-from openlit.__helpers import handle_exception, truncate_content
+from openlit.__helpers import (
+ _apply_custom_span_attributes,
+ handle_exception,
+ truncate_content,
+)
from openlit.semcov import SemanticConvention
# Try to import enhanced helpers for business intelligence
@@ -227,6 +231,8 @@ def set_span_attributes(
for key, value in additional_attrs.items():
span.set_attribute(key, value)
+ _apply_custom_span_attributes(span)
+
def add_message_tracking(span, messages: List[Dict], message_type: str = "input"):
"""
diff --git a/sdk/python/src/openlit/instrumentation/qdrant/__init__.py b/sdk/python/src/openlit/instrumentation/qdrant/__init__.py
index 90fe8ce7..0faf5386 100644
--- a/sdk/python/src/openlit/instrumentation/qdrant/__init__.py
+++ b/sdk/python/src/openlit/instrumentation/qdrant/__init__.py
@@ -4,9 +4,11 @@ OpenLIT Qdrant Instrumentation
from typing import Collection
import importlib.metadata
+from opentelemetry import trace
from opentelemetry.instrumentation.instrumentor import BaseInstrumentor
from wrapt import wrap_function_wrapper
+from openlit._config import OpenlitConfig
from openlit.instrumentation.qdrant.qdrant import general_wrap
from openlit.instrumentation.qdrant.async_qdrant import async_general_wrap
@@ -56,10 +58,10 @@ class QdrantInstrumentor(BaseInstrumentor):
version = importlib.metadata.version("qdrant-client")
environment = kwargs.get("environment", "default")
application_name = kwargs.get("application_name", "default")
- tracer = kwargs.get("tracer")
+ tracer = trace.get_tracer(__name__)
pricing_info = kwargs.get("pricing_info", {})
capture_message_content = kwargs.get("capture_message_content", False)
- metrics = kwargs.get("metrics_dict")
+ metrics = OpenlitConfig.metrics_dict
disable_metrics = kwargs.get("disable_metrics")
# Import QdrantClient to check method availability
diff --git a/sdk/python/src/openlit/instrumentation/reka/__init__.py b/sdk/python/src/openlit/instrumentation/reka/__init__.py
index 7a112714..527197fc 100644
--- a/sdk/python/src/openlit/instrumentation/reka/__init__.py
+++ b/sdk/python/src/openlit/instrumentation/reka/__init__.py
@@ -2,9 +2,12 @@
from typing import Collection
import importlib.metadata
+from opentelemetry import _logs
+from opentelemetry import trace
from opentelemetry.instrumentation.instrumentor import BaseInstrumentor
from wrapt import wrap_function_wrapper
+from openlit._config import OpenlitConfig
from openlit.instrumentation.reka.reka import chat
from openlit.instrumentation.reka.async_reka import async_chat
@@ -22,12 +25,12 @@ class RekaInstrumentor(BaseInstrumentor):
def _instrument(self, **kwargs):
application_name = kwargs.get("application_name", "default")
environment = kwargs.get("environment", "default")
- tracer = kwargs.get("tracer")
- metrics = kwargs.get("metrics_dict")
+ tracer = trace.get_tracer(__name__)
+ metrics = OpenlitConfig.metrics_dict
pricing_info = kwargs.get("pricing_info", {})
capture_message_content = kwargs.get("capture_message_content", False)
disable_metrics = kwargs.get("disable_metrics")
- event_provider = kwargs.get("event_provider")
+ event_provider = _logs.get_logger_provider().get_logger(__name__)
version = importlib.metadata.version("reka-api")
# Chat completions
diff --git a/sdk/python/src/openlit/instrumentation/reka/utils.py b/sdk/python/src/openlit/instrumentation/reka/utils.py
index df9a7b8e..f35401dd 100644
--- a/sdk/python/src/openlit/instrumentation/reka/utils.py
+++ b/sdk/python/src/openlit/instrumentation/reka/utils.py
@@ -18,6 +18,7 @@ from openlit.__helpers import (
otel_event,
truncate_message_content,
)
+from openlit._config import OpenlitConfig
from openlit.semcov import SemanticConvention
logger = logging.getLogger(__name__)
@@ -253,7 +254,8 @@ def emit_inference_event(
attributes=attributes,
body="",
)
- event_provider.emit(event)
+ if not OpenlitConfig.disable_events:
+ event_provider.emit(event)
except Exception as e:
logger.warning("Failed to emit inference event: %s", e, exc_info=True)
diff --git a/sdk/python/src/openlit/instrumentation/sarvam/__init__.py b/sdk/python/src/openlit/instrumentation/sarvam/__init__.py
index 6928ec1e..b09b2507 100644
--- a/sdk/python/src/openlit/instrumentation/sarvam/__init__.py
+++ b/sdk/python/src/openlit/instrumentation/sarvam/__init__.py
@@ -2,9 +2,11 @@
from typing import Collection
import importlib.metadata
+from opentelemetry import _logs, trace
from opentelemetry.instrumentation.instrumentor import BaseInstrumentor
from wrapt import wrap_function_wrapper
+from openlit._config import OpenlitConfig
from openlit.instrumentation.sarvam.sarvam import (
chat_completions,
text_translate,
@@ -39,12 +41,12 @@ class SarvamInstrumentor(BaseInstrumentor):
version = importlib.metadata.version("sarvamai")
environment = kwargs.get("environment", "default")
application_name = kwargs.get("application_name", "default")
- tracer = kwargs.get("tracer")
+ tracer = trace.get_tracer(__name__)
pricing_info = kwargs.get("pricing_info", {})
capture_message_content = kwargs.get("capture_message_content", False)
- metrics = kwargs.get("metrics_dict")
+ metrics = OpenlitConfig.metrics_dict
disable_metrics = kwargs.get("disable_metrics")
- event_provider = kwargs.get("event_provider")
+ event_provider = _logs.get_logger_provider().get_logger(__name__)
# Chat completions - sync
try:
diff --git a/sdk/python/src/openlit/instrumentation/sarvam/utils.py b/sdk/python/src/openlit/instrumentation/sarvam/utils.py
index 09428b6a..00bef34d 100644
--- a/sdk/python/src/openlit/instrumentation/sarvam/utils.py
+++ b/sdk/python/src/openlit/instrumentation/sarvam/utils.py
@@ -8,6 +8,7 @@ import time
from opentelemetry.trace import Status, StatusCode
+from openlit._config import OpenlitConfig
from openlit.__helpers import (
calculate_ttft,
response_as_dict,
@@ -196,7 +197,8 @@ def emit_inference_event(
attributes=attributes,
body="",
)
- event_provider.emit(event)
+ if not OpenlitConfig.disable_events:
+ event_provider.emit(event)
except Exception as e:
logger.warning("Failed to emit inference event: %s", e, exc_info=True)
diff --git a/sdk/python/src/openlit/instrumentation/smolagents/__init__.py b/sdk/python/src/openlit/instrumentation/smolagents/__init__.py
index f92eea7c..8e614bb3 100644
--- a/sdk/python/src/openlit/instrumentation/smolagents/__init__.py
+++ b/sdk/python/src/openlit/instrumentation/smolagents/__init__.py
@@ -9,9 +9,11 @@ Patches ThreadPoolExecutor for correct context propagation in CodeAgent.
from typing import Collection
import importlib.metadata
+from opentelemetry import trace
from opentelemetry.instrumentation.instrumentor import BaseInstrumentor
from wrapt import wrap_function_wrapper
+from openlit._config import OpenlitConfig
from openlit.instrumentation.smolagents.smolagents import general_wrap
_instruments = ("smolagents >= 1.0.0",)
@@ -52,13 +54,11 @@ class SmolAgentsInstrumentor(BaseInstrumentor):
environment = kwargs.get("environment", "default")
application_name = kwargs.get("application_name", "default")
- tracer = kwargs.get("tracer")
+ tracer = trace.get_tracer(__name__)
pricing_info = kwargs.get("pricing_info", {})
capture_message_content = kwargs.get("capture_message_content", False)
- metrics = kwargs.get("metrics_dict")
+ metrics = OpenlitConfig.metrics_dict
disable_metrics = kwargs.get("disable_metrics")
- detailed_tracing = kwargs.get("detailed_tracing", False)
-
wrap_args = (
version,
environment,
@@ -79,13 +79,12 @@ class SmolAgentsInstrumentor(BaseInstrumentor):
pass
# -- Detailed-tracing operations --
- if detailed_tracing:
- for module, method, op_key in DETAILED_OPERATIONS:
- try:
- wrapper = general_wrap(op_key, *wrap_args)
- wrap_function_wrapper(module, method, wrapper)
- except Exception:
- pass
+ for module, method, op_key in DETAILED_OPERATIONS:
+ try:
+ wrapper = general_wrap(op_key, *wrap_args)
+ wrap_function_wrapper(module, method, wrapper)
+ except Exception:
+ pass
# -- ThreadPoolExecutor context propagation --
self._install_context_propagation()
diff --git a/sdk/python/src/openlit/instrumentation/smolagents/smolagents.py b/sdk/python/src/openlit/instrumentation/smolagents/smolagents.py
index febf537a..7aec0d58 100644
--- a/sdk/python/src/openlit/instrumentation/smolagents/smolagents.py
+++ b/sdk/python/src/openlit/instrumentation/smolagents/smolagents.py
@@ -120,7 +120,7 @@ def general_wrap(
disable_metrics,
)
- # --- step-level spans (detailed_tracing) ---
+ # --- step-level spans ---
if gen_ai_endpoint in ("code_step", "tool_calling_step"):
return _handle_step(
wrapped,
@@ -495,7 +495,7 @@ def _handle_tool_call(
# ---------------------------------------------------------------------------
-# Per-step handler (detailed_tracing)
+# Per-step handler
# ---------------------------------------------------------------------------
@@ -596,7 +596,7 @@ def _handle_step(
# ---------------------------------------------------------------------------
-# Planning step handler (detailed_tracing)
+# Planning step handler
# ---------------------------------------------------------------------------
diff --git a/sdk/python/src/openlit/instrumentation/smolagents/utils.py b/sdk/python/src/openlit/instrumentation/smolagents/utils.py
index 58ae2117..f7ab8eec 100644
--- a/sdk/python/src/openlit/instrumentation/smolagents/utils.py
+++ b/sdk/python/src/openlit/instrumentation/smolagents/utils.py
@@ -18,6 +18,7 @@ from openlit.__helpers import (
format_system_instructions,
get_server_address_for_provider,
truncate_content,
+ _apply_custom_span_attributes,
)
from openlit.semcov import SemanticConvention
@@ -593,6 +594,8 @@ def emit_create_agent_span(
span.set_attribute(SemanticConvention.GEN_AI_SDK_VERSION, version)
span.set_status(Status(StatusCode.OK))
+ _apply_custom_span_attributes(span)
+
return span.get_span_context()
except Exception:
return None
diff --git a/sdk/python/src/openlit/instrumentation/strands/__init__.py b/sdk/python/src/openlit/instrumentation/strands/__init__.py
index 2680db39..d9efdb2a 100644
--- a/sdk/python/src/openlit/instrumentation/strands/__init__.py
+++ b/sdk/python/src/openlit/instrumentation/strands/__init__.py
@@ -10,9 +10,10 @@ import importlib.metadata
import logging
from typing import Collection
-from opentelemetry import trace
+from opentelemetry import _logs, trace
from opentelemetry.instrumentation.instrumentor import BaseInstrumentor
+from openlit._config import OpenlitConfig
from openlit.instrumentation.strands.processor import StrandsSpanProcessor
logger = logging.getLogger(__name__)
@@ -39,9 +40,9 @@ class StrandsInstrumentor(BaseInstrumentor):
environment = kwargs.get("environment", "default")
application_name = kwargs.get("application_name", "default")
capture_message_content = kwargs.get("capture_message_content", False)
- metrics = kwargs.get("metrics_dict")
+ metrics = OpenlitConfig.metrics_dict
disable_metrics = kwargs.get("disable_metrics")
- event_provider = kwargs.get("event_provider")
+ event_provider = _logs.get_logger_provider().get_logger(__name__)
pricing_info = kwargs.get("pricing_info")
self._processor = StrandsSpanProcessor(
diff --git a/sdk/python/src/openlit/instrumentation/strands/processor.py b/sdk/python/src/openlit/instrumentation/strands/processor.py
index 29d1350a..d8f935fc 100644
--- a/sdk/python/src/openlit/instrumentation/strands/processor.py
+++ b/sdk/python/src/openlit/instrumentation/strands/processor.py
@@ -26,6 +26,7 @@ from opentelemetry.trace import SpanKind
from opentelemetry.trace.status import StatusCode
from openlit.__helpers import (
+ _apply_custom_span_attributes,
get_chat_model_cost,
set_framework_llm_active,
reset_framework_llm_active,
@@ -144,6 +145,7 @@ class StrandsSpanProcessor(SpanProcessor):
span.set_attribute(SemanticConvention.GEN_AI_SDK_VERSION, self._version)
span.set_attribute(DEPLOYMENT_ENVIRONMENT, self._environment)
span.set_attribute(SERVICE_NAME, self._application_name)
+ _apply_custom_span_attributes(span)
except Exception:
pass
diff --git a/sdk/python/src/openlit/instrumentation/strands/utils.py b/sdk/python/src/openlit/instrumentation/strands/utils.py
index dc096b83..5e27f0a3 100644
--- a/sdk/python/src/openlit/instrumentation/strands/utils.py
+++ b/sdk/python/src/openlit/instrumentation/strands/utils.py
@@ -7,6 +7,7 @@ extraction from Strands native span events, and metrics recording.
import json
import logging
+from openlit._config import OpenlitConfig
from openlit.__helpers import (
get_server_address_for_provider,
otel_event,
@@ -286,7 +287,8 @@ def emit_strands_inference_event(
attributes=attributes,
body="",
)
- event_provider.emit(event)
+ if not OpenlitConfig.disable_events:
+ event_provider.emit(event)
except Exception as e:
logger.warning("Failed to emit Strands inference event: %s", e, exc_info=True)
diff --git a/sdk/python/src/openlit/instrumentation/together/__init__.py b/sdk/python/src/openlit/instrumentation/together/__init__.py
index dc25e4f6..c81f643a 100644
--- a/sdk/python/src/openlit/instrumentation/together/__init__.py
+++ b/sdk/python/src/openlit/instrumentation/together/__init__.py
@@ -2,9 +2,11 @@
from typing import Collection
import importlib.metadata
+from opentelemetry import trace
from opentelemetry.instrumentation.instrumentor import BaseInstrumentor
from wrapt import wrap_function_wrapper
+from openlit._config import OpenlitConfig
from openlit.instrumentation.together.together import completion, image_generate
from openlit.instrumentation.together.async_together import (
async_completion,
@@ -25,8 +27,8 @@ class TogetherInstrumentor(BaseInstrumentor):
def _instrument(self, **kwargs):
application_name = kwargs.get("application_name", "default")
environment = kwargs.get("environment", "default")
- tracer = kwargs.get("tracer")
- metrics = kwargs.get("metrics_dict")
+ tracer = trace.get_tracer(__name__)
+ metrics = OpenlitConfig.metrics_dict
pricing_info = kwargs.get("pricing_info", {})
capture_message_content = kwargs.get("capture_message_content", False)
disable_metrics = kwargs.get("disable_metrics")
diff --git a/sdk/python/src/openlit/instrumentation/together/utils.py b/sdk/python/src/openlit/instrumentation/together/utils.py
index 901a721f..66966c31 100644
--- a/sdk/python/src/openlit/instrumentation/together/utils.py
+++ b/sdk/python/src/openlit/instrumentation/together/utils.py
@@ -12,6 +12,7 @@ from opentelemetry.sdk.resources import (
from opentelemetry.trace import Status, StatusCode
from openlit.__helpers import (
+ _apply_custom_span_attributes,
calculate_ttft,
response_as_dict,
calculate_tbt,
@@ -112,6 +113,7 @@ def common_span_attributes(
scope._span.set_attribute(SemanticConvention.GEN_AI_SERVER_TBT, tbt)
scope._span.set_attribute(SemanticConvention.GEN_AI_SERVER_TTFT, ttft)
scope._span.set_attribute(SemanticConvention.GEN_AI_SDK_VERSION, version)
+ _apply_custom_span_attributes(scope._span)
def record_common_metrics(
diff --git a/sdk/python/src/openlit/instrumentation/transformers/__init__.py b/sdk/python/src/openlit/instrumentation/transformers/__init__.py
index 74d8df89..b734428c 100644
--- a/sdk/python/src/openlit/instrumentation/transformers/__init__.py
+++ b/sdk/python/src/openlit/instrumentation/transformers/__init__.py
@@ -4,9 +4,11 @@ Initializer of Auto Instrumentation of HuggingFace Transformer Functions
from typing import Collection
import importlib.metadata
+from opentelemetry import _logs, trace
from opentelemetry.instrumentation.instrumentor import BaseInstrumentor
from wrapt import wrap_function_wrapper
+from openlit._config import OpenlitConfig
from openlit.instrumentation.transformers.transformers import pipeline_wrapper
_instruments = ("transformers >= 4.48.0",)
@@ -23,12 +25,12 @@ class TransformersInstrumentor(BaseInstrumentor):
def _instrument(self, **kwargs):
application_name = kwargs.get("application_name")
environment = kwargs.get("environment")
- tracer = kwargs.get("tracer")
- metrics = kwargs.get("metrics_dict")
+ tracer = trace.get_tracer(__name__)
+ metrics = OpenlitConfig.metrics_dict
pricing_info = kwargs.get("pricing_info")
capture_message_content = kwargs.get("capture_message_content")
disable_metrics = kwargs.get("disable_metrics")
- event_provider = kwargs.get("event_provider")
+ event_provider = _logs.get_logger_provider().get_logger(__name__)
version = importlib.metadata.version("transformers")
wrap_function_wrapper(
diff --git a/sdk/python/src/openlit/instrumentation/transformers/utils.py b/sdk/python/src/openlit/instrumentation/transformers/utils.py
index 4ed97e72..9c932d8e 100644
--- a/sdk/python/src/openlit/instrumentation/transformers/utils.py
+++ b/sdk/python/src/openlit/instrumentation/transformers/utils.py
@@ -16,6 +16,7 @@ from openlit.__helpers import (
record_completion_metrics,
truncate_message_content,
)
+from openlit._config import OpenlitConfig
from openlit.semcov import SemanticConvention
logger = logging.getLogger(__name__)
@@ -248,7 +249,8 @@ def emit_inference_event(
attributes=attributes,
body="",
)
- event_provider.emit(event)
+ if not OpenlitConfig.disable_events:
+ event_provider.emit(event)
except Exception as e:
logger.warning("Failed to emit inference event: %s", e, exc_info=True)
diff --git a/sdk/python/src/openlit/instrumentation/vertexai/__init__.py b/sdk/python/src/openlit/instrumentation/vertexai/__init__.py
index 625f9369..45b6e821 100644
--- a/sdk/python/src/openlit/instrumentation/vertexai/__init__.py
+++ b/sdk/python/src/openlit/instrumentation/vertexai/__init__.py
@@ -2,9 +2,11 @@
from typing import Collection
import importlib.metadata
+from opentelemetry import _logs, trace
from opentelemetry.instrumentation.instrumentor import BaseInstrumentor
from wrapt import wrap_function_wrapper
+from openlit._config import OpenlitConfig
from openlit.instrumentation.vertexai.vertexai import send_message
from openlit.instrumentation.vertexai.async_vertexai import async_send_message
@@ -23,12 +25,12 @@ class VertexAIInstrumentor(BaseInstrumentor):
version = importlib.metadata.version("google-cloud-aiplatform")
environment = kwargs.get("environment", "default")
application_name = kwargs.get("application_name", "default")
- tracer = kwargs.get("tracer")
+ tracer = trace.get_tracer(__name__)
pricing_info = kwargs.get("pricing_info", {})
capture_message_content = kwargs.get("capture_message_content", False)
- metrics = kwargs.get("metrics_dict")
+ metrics = OpenlitConfig.metrics_dict
disable_metrics = kwargs.get("disable_metrics")
- event_provider = kwargs.get("event_provider")
+ event_provider = _logs.get_logger_provider().get_logger(__name__)
# sync generative models
wrap_function_wrapper(
diff --git a/sdk/python/src/openlit/instrumentation/vertexai/utils.py b/sdk/python/src/openlit/instrumentation/vertexai/utils.py
index 0394b1a5..6cff727d 100644
--- a/sdk/python/src/openlit/instrumentation/vertexai/utils.py
+++ b/sdk/python/src/openlit/instrumentation/vertexai/utils.py
@@ -18,6 +18,7 @@ from openlit.__helpers import (
otel_event,
truncate_message_content,
)
+from openlit._config import OpenlitConfig
from openlit.semcov import SemanticConvention
logger = logging.getLogger(__name__)
@@ -245,7 +246,8 @@ def emit_inference_event(
attributes=attributes,
body="",
)
- event_provider.emit(event)
+ if not OpenlitConfig.disable_events:
+ event_provider.emit(event)
except Exception as e:
logger.warning("Failed to emit inference event: %s", e, exc_info=True)
diff --git a/sdk/python/src/openlit/instrumentation/vllm/__init__.py b/sdk/python/src/openlit/instrumentation/vllm/__init__.py
index 0a2cd6d1..69b71796 100644
--- a/sdk/python/src/openlit/instrumentation/vllm/__init__.py
+++ b/sdk/python/src/openlit/instrumentation/vllm/__init__.py
@@ -2,9 +2,11 @@
from typing import Collection
import importlib.metadata
+from opentelemetry import _logs, trace
from opentelemetry.instrumentation.instrumentor import BaseInstrumentor
from wrapt import wrap_function_wrapper
+from openlit._config import OpenlitConfig
from openlit.instrumentation.vllm.vllm import generate
_instruments = ("vllm >= 0.5.4",)
@@ -21,12 +23,12 @@ class VLLMInstrumentor(BaseInstrumentor):
def _instrument(self, **kwargs):
application_name = kwargs.get("application_name", "default")
environment = kwargs.get("environment", "default")
- tracer = kwargs.get("tracer")
- metrics = kwargs.get("metrics_dict")
+ tracer = trace.get_tracer(__name__)
+ metrics = OpenlitConfig.metrics_dict
pricing_info = kwargs.get("pricing_info", {})
capture_message_content = kwargs.get("capture_message_content", False)
disable_metrics = kwargs.get("disable_metrics")
- event_provider = kwargs.get("event_provider")
+ event_provider = _logs.get_logger_provider().get_logger(__name__)
version = importlib.metadata.version("vllm")
# Chat completions
diff --git a/sdk/python/src/openlit/instrumentation/vllm/utils.py b/sdk/python/src/openlit/instrumentation/vllm/utils.py
index a2b13781..e2e29349 100644
--- a/sdk/python/src/openlit/instrumentation/vllm/utils.py
+++ b/sdk/python/src/openlit/instrumentation/vllm/utils.py
@@ -16,6 +16,7 @@ from openlit.__helpers import (
otel_event,
truncate_message_content,
)
+from openlit._config import OpenlitConfig
from openlit.semcov import SemanticConvention
logger = logging.getLogger(__name__)
@@ -184,7 +185,8 @@ def emit_inference_event(
attributes=attributes,
body="",
)
- event_provider.emit(event)
+ if not OpenlitConfig.disable_events:
+ event_provider.emit(event)
except Exception as e:
logger.warning("Failed to emit inference event: %s", e, exc_info=True)