Same agent Smaller bill. The tools and infrastructure to get more work from your AI. Fewer tokens. Less compute. Lower cost.
TypeScript agent-harnessagent-harness-engineeringai-engineeringai-observabilityamd-gpuclaude-codeclickhousecodexcoding-agentcoding-agentscursorgenaigpu-monitoringllm-observabilityllmopsnvidia-smiobservabilityopen-sourceopenaiopentelemetry
fix: `smolagents` and `AWS Strands` OpenTelemetry Instrumentation to follow OTel Semantic conventions (#1088)
Ishan Jain84a731382040
diff --git a/contributors/STREAMING_SPAN_FIX.md b/contributors/STREAMING_SPAN_FIX.mddeleted file mode 100644index 3feecd26..00000000--- a/contributors/STREAMING_SPAN_FIX.md+++ /dev/null@@ -1,388 +0,0 @@-# Fix: Streaming Span Ordering Across All LLM Providers--## Problem--When OpenLIT instruments streaming LLM calls, the HTTP `POST` span (created by `opentelemetry-instrumentation-httpx` / `opentelemetry-instrumentation-requests` / etc.) should be a **child** of the OpenLIT `chat` span. This works correctly for **non-streaming** calls because the `chat` span is created via `tracer.start_as_current_span(...)` inside a `with` block — meaning it's the active span when `wrapped()` fires the HTTP request.--However, for **streaming** calls, the current code does:--```python-# BUG: wrapped() fires the HTTP POST *before* the span exists-awaited_wrapped = wrapped(*args, **kwargs) # <-- HTTP POST happens here-span = tracer.start_span(span_name, kind=SpanKind.CLIENT) # <-- span created after--return TracedSyncStream(awaited_wrapped, span, ...)-```--Because the `chat` span doesn't exist yet when `wrapped()` executes, the HTTP `POST` span has **no parent** and appears as a root span in a separate trace — breaking the span hierarchy.--### Non-streaming (correct)--```-invoke_agent- └── chat gpt-4o-mini ← start_as_current_span, then wrapped()- └── POST https://... ← correctly parented-```--### Streaming (buggy)--```-invoke_agent- └── chat gpt-4o-mini ← span created AFTER wrapped()--POST https://... ← orphaned root span, different trace-```--## Solution--Create the `chat` span **first**, attach it to the OTel context, **then** call `wrapped()`. Detach the context token immediately after `wrapped()` returns (the stream object is just initialized, the actual iteration happens later).--### Fixed pattern--```python-from opentelemetry import trace as trace_api, context as context_api--# ...--if streaming:- # 1. Create span FIRST- span = tracer.start_span(span_name, kind=SpanKind.CLIENT)- # 2. Make it the active span so HTTP instrumentation picks it up- ctx = trace_api.set_span_in_context(span)- token = context_api.attach(ctx)- try:- # 3. NOW call wrapped — HTTP POST will be a child of our span- awaited_wrapped = wrapped(*args, **kwargs)- except Exception as e:- handle_exception(span, e)- context_api.detach(token)- span.end()- raise- # 4. Detach — the span stays open, TracedStream will end it later- context_api.detach(token)-- return TracedSyncStream(awaited_wrapped, span, ...)-```--### Streaming (fixed)--```-invoke_agent- └── chat gpt-4o-mini ← span created BEFORE wrapped()- └── POST https://... ← correctly parented-```--## Reference Implementation--The fix has already been applied to **OpenAI** (both sync and async). Use these as the canonical reference:--- `sdk/python/src/openlit/instrumentation/openai/openai.py` — sync: `chat_completions` and `responses` wrappers-- `sdk/python/src/openlit/instrumentation/openai/async_openai.py` — async: same two wrappers-------## Files That Need the Fix--All files below follow the same buggy pattern: `wrapped()` is called before `tracer.start_span()`. Each entry documents the exact location and any provider-specific nuances.--### Batch 1: Anthropic & VertexAI--| File | Function | Notes |-|------|----------|-------|-| `instrumentation/anthropic/anthropic.py` | `messages()` → `wrapper()` | Standard pattern. Add `trace_api`, `context_api` imports. |-| `instrumentation/anthropic/async_anthropic.py` | `messages()` → `async_wrapper()` | Same, but `await wrapped(...)`. |-| `instrumentation/vertexai/vertexai.py` | `generate_content()` → `wrapper()` | Standard pattern. |-| `instrumentation/vertexai/async_vertexai.py` | `generate_content()` → `async_wrapper()` | Async variant. |--**Current buggy code** (Anthropic sync example):--```python-if streaming:- awaited_wrapped = wrapped(*args, **kwargs)- span = tracer.start_span(span_name, kind=SpanKind.CLIENT)-- return TracedSyncStream(awaited_wrapped, span, ...)-```--**Fixed code**:--```python-if streaming:- span = tracer.start_span(span_name, kind=SpanKind.CLIENT)- ctx = trace_api.set_span_in_context(span)- token = context_api.attach(ctx)- try:- awaited_wrapped = wrapped(*args, **kwargs)- except Exception as e:- handle_exception(span, e)- context_api.detach(token)- span.end()- raise- context_api.detach(token)-- return TracedSyncStream(awaited_wrapped, span, ...)-```--### Batch 2: Together & Groq--| File | Function | Notes |-|------|----------|-------|-| `instrumentation/together/together.py` | `chat_completions()` → `wrapper()` | Standard pattern. |-| `instrumentation/together/async_together.py` | `chat_completions()` → `async_wrapper()` | Async variant. |-| `instrumentation/groq/groq.py` | `chat_completions()` → `wrapper()` | Standard pattern. |-| `instrumentation/groq/async_groq.py` | `chat_completions()` → `async_wrapper()` | Async variant. |--Same fix pattern as Batch 1.--### Batch 3: AI21, Azure AI Inference & PremAI--| File | Function | Notes |-|------|----------|-------|-| `instrumentation/ai21/ai21.py` | `chat()` → `wrapper()` | Standard pattern. |-| `instrumentation/ai21/async_ai21.py` | `chat()` → `async_wrapper()` | Async variant. |-| `instrumentation/azure_ai_inference/azure_ai_inference.py` | `complete()` → `wrapper()` | Standard pattern. |-| `instrumentation/azure_ai_inference/async_azure_ai_inference.py` | `complete()` → `async_wrapper()` | Async variant. |-| `instrumentation/premai/premai.py` | `chat_completions()` → `wrapper()` | Standard pattern (sync only, no async file). |--Same fix pattern as Batch 1.--### Batch 4: Sarvam & GPT4All--| File | Function | Notes |-|------|----------|-------|-| `instrumentation/sarvam/sarvam.py` | `translate()` → `wrapper()` | **Already imports `context_api`** — only add `trace_api` import. |-| `instrumentation/sarvam/async_sarvam.py` | `translate()` → `async_wrapper()` | Same — `context_api` already present. |-| `instrumentation/gpt4all/gpt4all.py` | `chat_completions()` → `wrapper()` | Standard pattern. |--### Batch 5: Ollama (2 streaming paths per file)--| File | Functions | Notes |-|------|-----------|-------|-| `instrumentation/ollama/ollama.py` | `chat()` → `wrapper()` AND `generate()` → `wrapper()` | **Two** streaming blocks to fix per file. |-| `instrumentation/ollama/async_ollama.py` | `chat()` → `async_wrapper()` AND `generate()` → `async_wrapper()` | Same — two async streaming blocks. |--Each of the two wrapper functions (`chat` and `generate`) has its own `if streaming:` block that needs the fix.--### Batch 6: Mistral & Cohere (dedicated stream functions)--| File | Function | Notes |-|------|----------|-------|-| `instrumentation/mistral/mistral.py` | `stream()` → `wrapper()` | This is a **dedicated streaming function** — no `if streaming:` check, the entire wrapper always streams. Apply the same span-first pattern. |-| `instrumentation/mistral/async_mistral.py` | `stream()` → `async_wrapper()` | Async variant of above. |-| `instrumentation/cohere/cohere.py` | `chat_stream()` → `wrapper()` | Dedicated streaming function, same approach. |-| `instrumentation/cohere/async_cohere.py` | `chat_stream()` → `async_wrapper()` | Async variant. |--**Current buggy code** (Mistral sync example):--```python-def wrapper(wrapped, instance, args, kwargs):- # ...- awaited_wrapped = wrapped(*args, **kwargs)- span = tracer.start_span(span_name, kind=SpanKind.CLIENT)-- return TracedSyncStream(awaited_wrapped, span, ...)-```--**Fixed code**:--```python-def wrapper(wrapped, instance, args, kwargs):- # ...- span = tracer.start_span(span_name, kind=SpanKind.CLIENT)- ctx = trace_api.set_span_in_context(span)- token = context_api.attach(ctx)- try:- awaited_wrapped = wrapped(*args, **kwargs)- except Exception as e:- handle_exception(span, e)- context_api.detach(token)- span.end()- raise- context_api.detach(token)-- return TracedSyncStream(awaited_wrapped, span, ...)-```--### Batch 7: LiteLLM, Bedrock & Google AI Studio (special patterns)--These providers have unique code structures requiring slightly different application of the fix.--#### LiteLLM--| File | Function | Notes |-|------|----------|-------|-| `instrumentation/litellm/litellm.py` | `completion()` → `wrapper()` | Has `set_framework_llm_active()` / `reset_framework_llm_active()` calls around `wrapped()`. |-| `instrumentation/litellm/async_litellm.py` | `completion()` → `async_wrapper()` | Async variant with same pattern. |--**Current buggy code**:--```python-if streaming:- fw_token = set_framework_llm_active()- try:- awaited_wrapped = wrapped(*args, **kwargs)- finally:- reset_framework_llm_active(fw_token)- span = tracer.start_span(span_name, kind=SpanKind.CLIENT)- return TracedSyncStream(awaited_wrapped, span, ...)-```--**Fixed code** — create span first, keep the `fw_token` logic intact:--```python-if streaming:- span = tracer.start_span(span_name, kind=SpanKind.CLIENT)- ctx = trace_api.set_span_in_context(span)- otel_token = context_api.attach(ctx)- fw_token = set_framework_llm_active()- try:- awaited_wrapped = wrapped(*args, **kwargs)- except Exception as e:- handle_exception(span, e)- context_api.detach(otel_token)- span.end()- raise- finally:- reset_framework_llm_active(fw_token)- context_api.detach(otel_token)- return TracedSyncStream(awaited_wrapped, span, ...)-```--**Important**: The original code also has `reset_framework_llm_active(fw_token)` in both `except` and `finally` blocks elsewhere, causing a double-call on errors. When applying this fix, ensure `reset_framework_llm_active` is only in `finally` — never duplicated in `except`.--#### Bedrock--| File | Function | Notes |-|------|----------|-------|-| `instrumentation/bedrock/bedrock.py` | `converse_stream()` → `converse_stream_wrapper()` | Uses `original_method(...)` instead of `wrapped(...)`. The wrapper is nested inside the main `wrapper()` function. |--**Current buggy code**:--```python-def converse_stream_wrapper(original_method, *method_args, **method_kwargs):- # ...- stream_response = original_method(*method_args, **method_kwargs)- span = tracer.start_span(span_name, kind=SpanKind.CLIENT)-- return TracedSyncStream(stream_response, span, ...)-```--**Fixed code**:--```python-def converse_stream_wrapper(original_method, *method_args, **method_kwargs):- # ...- span = tracer.start_span(span_name, kind=SpanKind.CLIENT)- ctx = trace_api.set_span_in_context(span)- token = context_api.attach(ctx)- try:- stream_response = original_method(*method_args, **method_kwargs)- except Exception as e:- handle_exception(span, e)- context_api.detach(token)- span.end()- raise- context_api.detach(token)-- return TracedSyncStream(stream_response, span, ...)-```--#### Google AI Studio--| File | Function | Notes |-|------|----------|-------|-| `instrumentation/google_ai_studio/google_ai_studio.py` | `generate_stream()` → `wrapper()` | Uses `tracer.start_as_current_span(...)` without a `with` block — needs to be changed to `tracer.start_span(...)` + explicit `attach/detach`. |-| `instrumentation/google_ai_studio/async_google_ai_studio.py` | `generate_stream()` → `async_wrapper()` | Async variant with same issue. |--**Current buggy code**:--```python-awaited_wrapped = wrapped(*args, **kwargs)-span = tracer.start_as_current_span(span_name, kind=SpanKind.CLIENT)--return TracedSyncStream(awaited_wrapped, span, ...)-```--**Fixed code**:--```python-span = tracer.start_span(span_name, kind=SpanKind.CLIENT)-ctx = trace_api.set_span_in_context(span)-token = context_api.attach(ctx)-try:- awaited_wrapped = wrapped(*args, **kwargs)-except Exception as e:- handle_exception(span, e)- context_api.detach(token)- span.end()- raise-context_api.detach(token)--return TracedSyncStream(awaited_wrapped, span, ...)-```--**Note**: `start_as_current_span` without `with` returns a context manager, not a span — so `TracedSyncStream` would receive the wrong type. The fix switches to `start_span` which correctly returns a `Span` object.-------## Import Changes Required--For every file that gets this fix, ensure these imports are present at the top:--```python-from opentelemetry import trace as trace_api, context as context_api-```--**Exceptions**:-- `sarvam/sarvam.py` and `sarvam/async_sarvam.py` already import `context as context_api` — only add `trace as trace_api`-- `openai/openai.py` and `openai/async_openai.py` already have both imports (fix is already applied)-------## Complete File List (27 call sites across 25 files)--All paths are relative to `sdk/python/src/openlit/`:--| # | File | Streaming call sites |-|---|------|---------------------|-| 1 | `instrumentation/anthropic/anthropic.py` | 1 |-| 2 | `instrumentation/anthropic/async_anthropic.py` | 1 |-| 3 | `instrumentation/vertexai/vertexai.py` | 1 |-| 4 | `instrumentation/vertexai/async_vertexai.py` | 1 |-| 5 | `instrumentation/together/together.py` | 1 |-| 6 | `instrumentation/together/async_together.py` | 1 |-| 7 | `instrumentation/groq/groq.py` | 1 |-| 8 | `instrumentation/groq/async_groq.py` | 1 |-| 9 | `instrumentation/ai21/ai21.py` | 1 |-| 10 | `instrumentation/ai21/async_ai21.py` | 1 |-| 11 | `instrumentation/azure_ai_inference/azure_ai_inference.py` | 1 |-| 12 | `instrumentation/azure_ai_inference/async_azure_ai_inference.py` | 1 |-| 13 | `instrumentation/premai/premai.py` | 1 |-| 14 | `instrumentation/sarvam/sarvam.py` | 1 |-| 15 | `instrumentation/sarvam/async_sarvam.py` | 1 |-| 16 | `instrumentation/gpt4all/gpt4all.py` | 1 |-| 17 | `instrumentation/ollama/ollama.py` | 2 (chat + generate) |-| 18 | `instrumentation/ollama/async_ollama.py` | 2 (chat + generate) |-| 19 | `instrumentation/mistral/mistral.py` | 1 (dedicated `stream()`) |-| 20 | `instrumentation/mistral/async_mistral.py` | 1 (dedicated `stream()`) |-| 21 | `instrumentation/cohere/cohere.py` | 1 (dedicated `chat_stream()`) |-| 22 | `instrumentation/cohere/async_cohere.py` | 1 (dedicated `chat_stream()`) |-| 23 | `instrumentation/litellm/litellm.py` | 1 (has `fw_token` logic) |-| 24 | `instrumentation/litellm/async_litellm.py` | 1 (has `fw_token` logic) |-| 25 | `instrumentation/bedrock/bedrock.py` | 1 (`converse_stream_wrapper`) |-| 26 | `instrumentation/google_ai_studio/google_ai_studio.py` | 1 (`start_as_current_span` → `start_span`) |-| 27 | `instrumentation/google_ai_studio/async_google_ai_studio.py` | 1 (`start_as_current_span` → `start_span`) |--**Total: 27 call sites across 25 files** (Ollama has 2 per file).-------## Verification--After applying the fix to each provider, verify with a streaming call:--1. Enable HTTP instrumentation (e.g., `opentelemetry-instrumentation-httpx` for httpx-based SDKs, or `opentelemetry-instrumentation-requests` for requests-based SDKs)-2. Make a streaming API call through the provider-3. Check that the `POST` span is a **child** of the `chat` span, not a root span-4. Confirm the `chat` span has correct attributes (model, tokens, finish_reason, etc.)-5. Confirm non-streaming calls still work correctly (they should be unaffected)diff --git a/langgraph_methods_report.md b/langgraph_methods_report.mddeleted file mode 100644index e91b7577..00000000--- a/langgraph_methods_report.md+++ /dev/null@@ -1,68 +0,0 @@-# LangGraph Methods Report--**Project:** AI Agent Core-**LangGraph:** 0.6.6 | **Checkpoint:** langgraph-checkpoint-postgres 2.0.23-------## Graph Structure--```-START → extract_user_query → retrieve_rag_documents → plan_troubleshooting_steps- → classify_user_intent → process_user_intent → generate_model_response → END-```-------## Methods Used--### Imports--| Import | File |-|--------|------|-| `StateGraph`, `START`, `END` | `app/infrastructure/agent/graph.py:13` |-| `add_messages` | `app/infrastructure/agent/initial_state.py:10` |-| `AsyncPostgresSaver` | `app/main.py:23` |--### Graph Construction--| Method | Location |-|--------|----------|-| `StateGraph(State)` | `graph.py:38` |-| `.add_node()` | `graph.py:41-46` |-| `.add_edge()` | `graph.py:49-55` |-| `.compile(checkpointer)` | `graph.py:58` |--### Graph Execution--| Method | Location | Mode |-|--------|----------|------|-| `.ainvoke()` | `agent.py:83` | Sync execution |-| `.astream()` | `agent.py:124` | Streaming (`stream_mode="messages"`) |-| `.aget_state()` | `agent.py:69,105` / `message.py:93,224,274` | State retrieval |--### Checkpointing--| Method | Location |-|--------|----------|-| `AsyncPostgresSaver(conn)` | `main.py:73` |-| `.setup()` | `main.py:77` |--### State Reducers--| Reducer | Field |-|---------|-------|-| `add_messages` (langgraph) | `messages` |-| `add_last_3` (custom) | `user_intents` |-------## Instrumentation Targets--| Target | File | Metrics |-|--------|------|---------|-| `ainvoke()` | `agent.py:83` | Latency, tokens |-| `astream()` | `agent.py:124` | TTFT, chunk count |-| `aget_state()` | `agent.py:69` | Retrieval latency |-| `AsyncPostgresSaver` | `main.py:73` | Write latency |-| Node functions (6) | `graph.py:41-46` | Per-node execution time |diff --git a/sdk/python/pyproject.toml b/sdk/python/pyproject.tomlindex 57b4a11b..8cd0b1ec 100644--- a/sdk/python/pyproject.toml+++ b/sdk/python/pyproject.toml@@ -21,10 +21,10 @@ pydantic = "^2.0.0"xmltodict = ">=0.13.0,<1.0.0"boto3 = "^1.34.0"botocore = "^1.34.0"-opentelemetry-api = "^1.39.0"-opentelemetry-sdk = "^1.39.0"-opentelemetry-exporter-otlp = "^1.39.0"-opentelemetry-semantic-conventions = ">=0.60b1,<1.0.0"+opentelemetry-api = ">=1.38.0,<2.0.0"+opentelemetry-sdk = ">=1.38.0,<2.0.0"+opentelemetry-exporter-otlp = ">=1.38.0,<2.0.0"+opentelemetry-semantic-conventions = ">=0.59b0,<1.0.0"opentelemetry-instrumentation = ">=0.52b0,<1.0.0"# Official OpenTelemetry HTTP Framework instrumentationsopentelemetry-instrumentation-asgi = ">=0.52b0,<1.0.0"@@ -45,7 +45,6 @@ opentelemetry-instrumentation-urllib3 = ">=0.52b0,<1.0.0"opentelemetry-instrumentation-system-metrics = {version = ">=0.52b0,<1.0.0", optional = true}openai = "^1.1.1"anthropic = ">=0.42.0,<1.0.0"-openai-agents = ">=0.0.3"[tool.poetry.scripts]openlit-instrument = "openlit.cli.main:run"diff --git a/sdk/python/src/openlit/__helpers.py b/sdk/python/src/openlit/__helpers.pyindex eede6987..f78381dd 100644--- a/sdk/python/src/openlit/__helpers.py+++ b/sdk/python/src/openlit/__helpers.py@@ -265,10 +265,16 @@ def get_chat_model_cost(model, pricing_info, prompt_tokens, completion_tokens):"""try:- cost = ((prompt_tokens / 1000) * pricing_info["chat"][model]["promptPrice"]) + (- (completion_tokens / 1000) * pricing_info["chat"][model]["completionPrice"]+ chat_pricing = pricing_info["chat"]+ model_pricing = chat_pricing.get(model)+ if model_pricing is None and "/" in model:+ model_pricing = chat_pricing.get(model.split("/", 1)[1])+ if model_pricing is None:+ return 0+ cost = ((prompt_tokens / 1000) * model_pricing["promptPrice"]) + (+ (completion_tokens / 1000) * model_pricing["completionPrice"])- except:+ except Exception:cost = 0return cost@@ -279,8 +285,14 @@ def get_embed_model_cost(model, pricing_info, prompt_tokens):"""try:- cost = (prompt_tokens / 1000) * pricing_info["embeddings"][model]- except:+ embed_pricing = pricing_info["embeddings"]+ unit_cost = embed_pricing.get(model)+ if unit_cost is None and "/" in model:+ unit_cost = embed_pricing.get(model.split("/", 1)[1])+ if unit_cost is None:+ return 0+ cost = (prompt_tokens / 1000) * unit_cost+ except Exception:cost = 0return cost@@ -1045,6 +1057,38 @@ def common_db_span_attributes(scope._span.set_attribute(SemanticConvention.DB_SDK_VERSION, version)+def format_system_instructions(text):+ """Format system instructions per OTel GenAI content schema.++ Returns a JSON string ``[{"type": "text", "content": "..."}]`` or *None*+ when *text* is falsy. Handles lists/tuples by joining their string elements.+ """+ if not text:+ return None+ if isinstance(text, (list, tuple)):+ text = " ".join(str(item) for item in text)+ return json.dumps([{"type": "text", "content": truncate_content(str(text))}])+++def format_input_message(role, content):+ """Return a single message dict following the OTel GenAI parts schema."""+ return {+ "role": role,+ "parts": [{"type": "text", "content": truncate_content(str(content))}],+ }+++def format_output_message(content, finish_reason=None):+ """Return an assistant message dict following the OTel GenAI parts schema."""+ msg = {+ "role": "assistant",+ "parts": [{"type": "text", "content": truncate_content(str(content))}],+ }+ if finish_reason:+ msg["finish_reason"] = finish_reason+ return msg++def common_framework_span_attributes(scope,framework_system,@@ -1064,12 +1108,13 @@ def common_framework_span_attributes(scope._span.set_attribute(SemanticConvention.GEN_AI_SDK_VERSION, version)scope._span.set_attribute(SemanticConvention.GEN_AI_PROVIDER_NAME, framework_system)scope._span.set_attribute(SemanticConvention.GEN_AI_OPERATION, endpoint)- scope._span.set_attribute(- SemanticConvention.GEN_AI_REQUEST_MODEL,- getattr(instance, "model_name", "unknown") if instance else "unknown",- )- scope._span.set_attribute(SemanticConvention.SERVER_ADDRESS, server_address)- scope._span.set_attribute(SemanticConvention.SERVER_PORT, server_port)+ model_name = getattr(instance, "model_name", None) if instance else None+ if model_name:+ scope._span.set_attribute(SemanticConvention.GEN_AI_REQUEST_MODEL, model_name)+ if server_address:+ scope._span.set_attribute(SemanticConvention.SERVER_ADDRESS, server_address)+ if server_port:+ scope._span.set_attribute(SemanticConvention.SERVER_PORT, server_port)scope._span.set_attribute(DEPLOYMENT_ENVIRONMENT, environment)scope._span.set_attribute(SERVICE_NAME, application_name)scope._span.set_attribute(diff --git a/sdk/python/src/openlit/_instrumentors.py b/sdk/python/src/openlit/_instrumentors.pyindex c57d8d54..6bb25dec 100644--- a/sdk/python/src/openlit/_instrumentors.py+++ b/sdk/python/src/openlit/_instrumentors.py@@ -57,6 +57,8 @@ MODULE_NAME_MAP = {"google-adk": "google.adk","claude-agent-sdk": "claude_agent_sdk","agent-framework": "agent_framework",+ "strands": "strands",+ "smolagents": "smolagents",# Database instrumentations"psycopg": "psycopg","psycopg-pool": "psycopg_pool",@@ -130,6 +132,8 @@ INSTRUMENTOR_MAP = {"google-adk": "openlit.instrumentation.google_adk.GoogleADKInstrumentor","claude-agent-sdk": "openlit.instrumentation.claude_agent_sdk.ClaudeAgentSDKInstrumentor","agent-framework": "openlit.instrumentation.agent_framework.AgentFrameworkInstrumentor",+ "strands": "openlit.instrumentation.strands.StrandsInstrumentor",+ "smolagents": "openlit.instrumentation.smolagents.SmolAgentsInstrumentor",# Database instrumentations"psycopg": "openlit.instrumentation.psycopg.PsycopgInstrumentor","psycopg-pool": "openlit.instrumentation.psycopg.PsycopgInstrumentor",diff --git a/sdk/python/src/openlit/instrumentation/agno/utils.py b/sdk/python/src/openlit/instrumentation/agno/utils.pyindex 3c9d8635..6642e6af 100644--- a/sdk/python/src/openlit/instrumentation/agno/utils.py+++ b/sdk/python/src/openlit/instrumentation/agno/utils.py@@ -17,6 +17,9 @@ from opentelemetry.trace import SpanKind, Status, StatusCodefrom openlit.__helpers import (common_framework_span_attributes,+ format_input_message,+ format_output_message,+ format_system_instructions,get_server_address_for_provider,truncate_content,)@@ -117,7 +120,7 @@ def _infer_provider_from_model(model_name):def _extract_model_name(instance):"""Walk the instance hierarchy to find the LLM model name."""if not instance:- return "unknown"+ return Nonemodel = getattr(instance, "model", None)if model:@@ -146,7 +149,7 @@ def _extract_model_name(instance):if model_info:return model_info[0]- return "unknown"+ return Nonedef set_server_address_and_port(instance):@@ -302,10 +305,12 @@ def _set_agent_attributes(span, instance, endpoint, capture_message_content):instructions = getattr(instance, "instructions", None)if instructions and capture_message_content:- span.set_attribute(- SemanticConvention.GEN_AI_SYSTEM_INSTRUCTIONS,- truncate_content(str(instructions)),- )+ formatted = format_system_instructions(instructions)+ if formatted:+ span.set_attribute(+ SemanticConvention.GEN_AI_SYSTEM_INSTRUCTIONS,+ formatted,+ )_set_tool_definitions(span, getattr(instance, "tools", None) or [])@@ -561,9 +566,7 @@ def _capture_content_as_attributes(span, instance, response, endpoint, args, kwaif input_content:span.set_attribute(SemanticConvention.GEN_AI_INPUT_MESSAGES,- json.dumps(- [{"role": "user", "content": truncate_content(input_content)}]- ),+ json.dumps([format_input_message("user", input_content)]),)# Output messages@@ -581,14 +584,7 @@ def _capture_content_as_attributes(span, instance, response, endpoint, args, kwaif output_content:span.set_attribute(SemanticConvention.GEN_AI_OUTPUT_MESSAGES,- json.dumps(- [- {- "role": "assistant",- "content": truncate_content(output_content),- }- ]- ),+ json.dumps([format_output_message(output_content)]),)except Exception:pass@@ -615,7 +611,7 @@ def _record_agno_metrics("service.name": application_name,"deployment.environment": environment,}- if request_model and request_model != "unknown":+ if request_model:attributes[SemanticConvention.GEN_AI_REQUEST_MODEL] = request_modelif server_address:attributes[SemanticConvention.SERVER_ADDRESS] = server_address@@ -669,8 +665,9 @@ def emit_create_agent_spans(span.set_attribute(SemanticConvention.GEN_AI_AGENT_NAME, str(name))model_name = _extract_model_name(instance)- if model_name and model_name != "unknown":+ if model_name:span.set_attribute(SemanticConvention.GEN_AI_REQUEST_MODEL, model_name)+ span.set_attribute(SemanticConvention.GEN_AI_RESPONSE_MODEL, model_name)agent_id = getattr(instance, "agent_id", None) or getattr(instance, "id", None@@ -689,10 +686,12 @@ def emit_create_agent_spans(instructions = getattr(instance, "instructions", None)if instructions and capture_message_content:- span.set_attribute(- SemanticConvention.GEN_AI_SYSTEM_INSTRUCTIONS,- truncate_content(str(instructions)),- )+ formatted = format_system_instructions(instructions)+ if formatted:+ span.set_attribute(+ SemanticConvention.GEN_AI_SYSTEM_INSTRUCTIONS,+ formatted,+ )_set_tool_definitions(span, getattr(instance, "tools", None) or [])@@ -772,6 +771,9 @@ def process_agno_response(proxy,)+ if request_model:+ span.set_attribute(SemanticConvention.GEN_AI_RESPONSE_MODEL, request_model)+# Override raw endpoint with standard OTel operation namespan.set_attribute(SemanticConvention.GEN_AI_OPERATION, operation_type)diff --git a/sdk/python/src/openlit/instrumentation/ai21/ai21.py b/sdk/python/src/openlit/instrumentation/ai21/ai21.pyindex 79b25630..e10fbb48 100644--- a/sdk/python/src/openlit/instrumentation/ai21/ai21.py+++ b/sdk/python/src/openlit/instrumentation/ai21/ai21.py@@ -3,6 +3,7 @@ Module for monitoring AI21 API calls."""import time+from opentelemetry import trace as trace_api, context as context_apifrom opentelemetry.trace import SpanKindfrom openlit.__helpers import (handle_exception,@@ -124,9 +125,17 @@ def chat(span_name = f"{SemanticConvention.GEN_AI_OPERATION_TYPE_CHAT} {request_model}"if streaming:- # Special handling for streaming response- awaited_wrapped = wrapped(*args, **kwargs)span = tracer.start_span(span_name, kind=SpanKind.CLIENT)+ ctx = trace_api.set_span_in_context(span)+ token = context_api.attach(ctx)+ try:+ awaited_wrapped = wrapped(*args, **kwargs)+ except Exception as e:+ handle_exception(span, e)+ context_api.detach(token)+ span.end()+ raise+ context_api.detach(token)return TracedSyncStream(awaited_wrapped, span, span_name, kwargs, server_address, server_port)diff --git a/sdk/python/src/openlit/instrumentation/ai21/async_ai21.py b/sdk/python/src/openlit/instrumentation/ai21/async_ai21.pyindex 5f606a6e..62319bd8 100644--- a/sdk/python/src/openlit/instrumentation/ai21/async_ai21.py+++ b/sdk/python/src/openlit/instrumentation/ai21/async_ai21.py@@ -3,6 +3,7 @@ Module for monitoring AI21 API calls (async version)."""import time+from opentelemetry import trace as trace_api, context as context_apifrom opentelemetry.trace import SpanKindfrom openlit.__helpers import (handle_exception,@@ -124,9 +125,17 @@ def async_chat(span_name = f"{SemanticConvention.GEN_AI_OPERATION_TYPE_CHAT} {request_model}"if streaming:- # Special handling for streaming response- awaited_wrapped = await wrapped(*args, **kwargs)span = tracer.start_span(span_name, kind=SpanKind.CLIENT)+ ctx = trace_api.set_span_in_context(span)+ token = context_api.attach(ctx)+ try:+ awaited_wrapped = await wrapped(*args, **kwargs)+ except Exception as e:+ handle_exception(span, e)+ context_api.detach(token)+ span.end()+ raise+ context_api.detach(token)return TracedAsyncStream(awaited_wrapped, span, span_name, kwargs, server_address, server_port)diff --git a/sdk/python/src/openlit/instrumentation/anthropic/anthropic.py b/sdk/python/src/openlit/instrumentation/anthropic/anthropic.pyindex b226b886..c84fd760 100644--- a/sdk/python/src/openlit/instrumentation/anthropic/anthropic.py+++ b/sdk/python/src/openlit/instrumentation/anthropic/anthropic.py@@ -3,6 +3,7 @@ Module for monitoring Anthropic API calls."""import time+from opentelemetry import trace as trace_api, context as context_apifrom opentelemetry.trace import SpanKindfrom openlit.__helpers import (handle_exception,@@ -129,8 +130,17 @@ def messages(# pylint: disable=no-else-returnif streaming:- awaited_wrapped = wrapped(*args, **kwargs)span = tracer.start_span(span_name, kind=SpanKind.CLIENT)+ ctx = trace_api.set_span_in_context(span)+ token = context_api.attach(ctx)+ try:+ awaited_wrapped = wrapped(*args, **kwargs)+ except Exception as e:+ handle_exception(span, e)+ context_api.detach(token)+ span.end()+ raise+ context_api.detach(token)return TracedSyncStream(awaited_wrapped,diff --git a/sdk/python/src/openlit/instrumentation/anthropic/async_anthropic.py b/sdk/python/src/openlit/instrumentation/anthropic/async_anthropic.pyindex aa8377c9..cd081168 100644--- a/sdk/python/src/openlit/instrumentation/anthropic/async_anthropic.py+++ b/sdk/python/src/openlit/instrumentation/anthropic/async_anthropic.py@@ -3,6 +3,7 @@ Module for monitoring Anthropic API calls."""import time+from opentelemetry import trace as trace_api, context as context_apifrom opentelemetry.trace import SpanKindfrom openlit.__helpers import (handle_exception,@@ -129,8 +130,17 @@ def async_messages(# pylint: disable=no-else-returnif streaming:- awaited_wrapped = await wrapped(*args, **kwargs)span = tracer.start_span(span_name, kind=SpanKind.CLIENT)+ ctx = trace_api.set_span_in_context(span)+ token = context_api.attach(ctx)+ try:+ awaited_wrapped = await wrapped(*args, **kwargs)+ except Exception as e:+ handle_exception(span, e)+ context_api.detach(token)+ span.end()+ raise+ context_api.detach(token)return TracedAsyncStream(awaited_wrapped,diff --git a/sdk/python/src/openlit/instrumentation/azure_ai_inference/async_azure_ai_inference.py b/sdk/python/src/openlit/instrumentation/azure_ai_inference/async_azure_ai_inference.pyindex 23f68ccf..00feb5d1 100644--- a/sdk/python/src/openlit/instrumentation/azure_ai_inference/async_azure_ai_inference.py+++ b/sdk/python/src/openlit/instrumentation/azure_ai_inference/async_azure_ai_inference.py@@ -4,6 +4,7 @@ Module for monitoring Azure AI Inference API calls.import loggingimport time+from opentelemetry import trace as trace_api, context as context_apifrom opentelemetry.trace import SpanKindfrom openlit.__helpers import (handle_exception,@@ -123,8 +124,17 @@ def async_complete(span_name = f"{SemanticConvention.GEN_AI_OPERATION_TYPE_CHAT} {request_model}"if streaming:- awaited_wrapped = await wrapped(*args, **kwargs)span = tracer.start_span(span_name, kind=SpanKind.CLIENT)+ ctx = trace_api.set_span_in_context(span)+ token = context_api.attach(ctx)+ try:+ awaited_wrapped = await wrapped(*args, **kwargs)+ except Exception as e:+ handle_exception(span, e)+ context_api.detach(token)+ span.end()+ raise+ context_api.detach(token)return TracedAsyncStream(awaited_wrapped,diff --git a/sdk/python/src/openlit/instrumentation/azure_ai_inference/azure_ai_inference.py b/sdk/python/src/openlit/instrumentation/azure_ai_inference/azure_ai_inference.pyindex 3e048382..7d2841de 100644--- a/sdk/python/src/openlit/instrumentation/azure_ai_inference/azure_ai_inference.py+++ b/sdk/python/src/openlit/instrumentation/azure_ai_inference/azure_ai_inference.py@@ -4,6 +4,7 @@ Module for monitoring Azure AI Inference API calls.import loggingimport time+from opentelemetry import trace as trace_api, context as context_apifrom opentelemetry.trace import SpanKindfrom openlit.__helpers import (handle_exception,@@ -123,8 +124,17 @@ def complete(span_name = f"{SemanticConvention.GEN_AI_OPERATION_TYPE_CHAT} {request_model}"if streaming:- awaited_wrapped = wrapped(*args, **kwargs)span = tracer.start_span(span_name, kind=SpanKind.CLIENT)+ ctx = trace_api.set_span_in_context(span)+ token = context_api.attach(ctx)+ try:+ awaited_wrapped = wrapped(*args, **kwargs)+ except Exception as e:+ handle_exception(span, e)+ context_api.detach(token)+ span.end()+ raise+ context_api.detach(token)return TracedSyncStream(awaited_wrapped,diff --git a/sdk/python/src/openlit/instrumentation/bedrock/bedrock.py b/sdk/python/src/openlit/instrumentation/bedrock/bedrock.pyindex 83034dee..5bfb5339 100644--- a/sdk/python/src/openlit/instrumentation/bedrock/bedrock.py+++ b/sdk/python/src/openlit/instrumentation/bedrock/bedrock.py@@ -3,6 +3,7 @@ Module for monitoring Amazon Bedrock API calls."""import time+from opentelemetry import trace as trace_api, context as context_apifrom opentelemetry.trace import SpanKindfrom openlit.__helpers import (handle_exception,@@ -252,9 +253,17 @@ def converse_stream(f"{SemanticConvention.GEN_AI_OPERATION_TYPE_CHAT} {request_model}")- # Get the streaming response- stream_response = original_method(*method_args, **method_kwargs)span = tracer.start_span(span_name, kind=SpanKind.CLIENT)+ ctx = trace_api.set_span_in_context(span)+ token = context_api.attach(ctx)+ try:+ stream_response = original_method(*method_args, **method_kwargs)+ except Exception as e:+ handle_exception(span, e)+ context_api.detach(token)+ span.end()+ raise+ context_api.detach(token)return TracedSyncStream(stream_response,diff --git a/sdk/python/src/openlit/instrumentation/browser_use/async_browser_use.py b/sdk/python/src/openlit/instrumentation/browser_use/async_browser_use.pyindex 7704a0dc..ef0302cd 100644--- a/sdk/python/src/openlit/instrumentation/browser_use/async_browser_use.py+++ b/sdk/python/src/openlit/instrumentation/browser_use/async_browser_use.py@@ -247,7 +247,7 @@ def _add_browser_use_attributes(span.set_attribute(SemanticConvention.GEN_AI_AGENT_ID, str(instance.id))if hasattr(instance, "task_id"):span.set_attribute(- SemanticConvention.GEN_AI_AGENT_TASK_ID, str(instance.task_id)+ SemanticConvention.GEN_AI_BROWSER_AGENT_TASK_ID, str(instance.task_id))if hasattr(instance, "session_id"):span.set_attribute(@@ -369,7 +369,8 @@ def _add_agent_configuration_attributes(# Task ID and session informationif hasattr(agent_instance, "task_id"):span.set_attribute(- SemanticConvention.GEN_AI_AGENT_TASK_ID, str(agent_instance.task_id)+ SemanticConvention.GEN_AI_BROWSER_AGENT_TASK_ID,+ str(agent_instance.task_id),)if hasattr(agent_instance, "session_id"):span.set_attribute(@@ -726,7 +727,7 @@ async def _create_individual_action_spans()if hasattr(step.state, "title") and step.state.title:action_span.set_attribute(- SemanticConvention.GEN_AI_BROWSER_PAGE_TITLE,+ SemanticConvention.GEN_AI_BROWSER_CURRENT_PAGE_TITLE,truncate_content(step.state.title),)if hasattr(step.state, "tabs") and step.state.tabs:diff --git a/sdk/python/src/openlit/instrumentation/browser_use/browser_use.py b/sdk/python/src/openlit/instrumentation/browser_use/browser_use.pyindex d16c94f8..b959f4b1 100644--- a/sdk/python/src/openlit/instrumentation/browser_use/browser_use.py+++ b/sdk/python/src/openlit/instrumentation/browser_use/browser_use.py@@ -228,7 +228,7 @@ def _add_browser_use_attributes(span.set_attribute(SemanticConvention.GEN_AI_AGENT_ID, str(instance.id))if hasattr(instance, "task_id"):span.set_attribute(- SemanticConvention.GEN_AI_AGENT_TASK_ID, str(instance.task_id)+ SemanticConvention.GEN_AI_BROWSER_AGENT_TASK_ID, str(instance.task_id))if hasattr(instance, "session_id"):span.set_attribute(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.pyindex 879dd917..abb42c59 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@@ -19,6 +19,7 @@ from openlit.__helpers import handle_exceptionfrom openlit.semcov import SemanticConventionfrom openlit.instrumentation.claude_agent_sdk.utils import (generate_span_name,+ resolve_agent_display_name,set_initial_span_attributes,update_root_from_assistant,has_llm_call_data,@@ -609,7 +610,9 @@ def wrap_query(yield msgreturn- span_name = generate_span_name("query")+ options, kwargs = _get_or_create_options(kwargs)+ agent_entity = resolve_agent_display_name(options)+ span_name = generate_span_name("query", agent_entity)span = tracer.start_span(span_name, kind=SpanKind.INTERNAL)ctx = trace_api.set_span_in_context(span)token = context_api.attach(ctx)@@ -634,7 +637,6 @@ def wrap_query(aggregate_usage = {"input_tokens": 0, "output_tokens": 0}try:- options, kwargs = _get_or_create_options(kwargs)prompt = kwargs.get("prompt")if prompt and capture_message_content:@@ -747,13 +749,17 @@ def wrap_connect(except Exception:pass- span_name = generate_span_name("create_agent", "claude_agent_sdk")+ options = kwargs.get("options")+ agent_entity = resolve_agent_display_name(options)+ span_entity = agent_entity or SemanticConvention.GEN_AI_SYSTEM_CLAUDE_AGENT_SDK+ span_name = generate_span_name("create_agent", span_entity)with tracer.start_as_current_span(span_name, kind=SpanKind.CLIENT) as span:set_create_agent_attributes(span,version,environment,application_name,+ agent_name=span_entity,)try:result = await wrapped(*args, **kwargs)@@ -816,7 +822,9 @@ def wrap_receive_response(yield msgreturn- span_name = generate_span_name("receive_response")+ options = getattr(instance, "_options", None)+ agent_entity = resolve_agent_display_name(options)+ span_name = generate_span_name("receive_response", agent_entity)span = tracer.start_span(span_name, kind=SpanKind.INTERNAL)ctx = trace_api.set_span_in_context(span)token = context_api.attach(ctx)@@ -842,7 +850,6 @@ def wrap_receive_response(try:prompt = getattr(instance, _PROMPT_ATTR, None)- options = getattr(instance, "_options", None)if prompt and capture_message_content:chat_state["pending_input"] = [diff --git a/sdk/python/src/openlit/instrumentation/claude_agent_sdk/utils.py b/sdk/python/src/openlit/instrumentation/claude_agent_sdk/utils.pyindex ed439ce1..6644a723 100644--- a/sdk/python/src/openlit/instrumentation/claude_agent_sdk/utils.py+++ b/sdk/python/src/openlit/instrumentation/claude_agent_sdk/utils.py@@ -15,6 +15,7 @@ from opentelemetry.trace import SpanKind, Status, StatusCodefrom openlit.__helpers import (common_framework_span_attributes,get_chat_model_cost,+ get_server_address_for_provider,handle_exception,otel_event,truncate_content,@@ -45,8 +46,7 @@ SPAN_KIND_MAP = {SemanticConvention.GEN_AI_OPERATION_TYPE_CREATE_AGENT: SpanKind.CLIENT,}-SERVER_ADDRESS = "api.anthropic.com"-SERVER_PORT = 443+SERVER_ADDRESS, SERVER_PORT = get_server_address_for_provider("anthropic")GEN_AI_SYSTEM_ATTR = "gen_ai.system"GEN_AI_SYSTEM_VALUE = "anthropic"@@ -70,16 +70,40 @@ def get_span_kind(operation_type):return SPAN_KIND_MAP.get(operation_type, SpanKind.INTERNAL)+# Endpoints where the second span-name segment should reflect a tool, model, or agent id.+_SPAN_NAME_ENTITY_ENDPOINTS = frozenset(+ (+ "execute_tool",+ "subagent",+ "chat",+ "create_agent",+ "query",+ "receive_response",+ )+)+++def resolve_agent_display_name(options):+ """Return a short label for the root agent span (e.g. configured model), or None."""+ if options is None:+ return None+ model = getattr(options, "model", None)+ if model is not None and str(model).strip():+ return str(model)+ return None++def generate_span_name(endpoint, entity_name=None):"""Return an OTel-compliant span name: ``{operation} {entity}``."""operation = OPERATION_MAP.get(endpoint, SemanticConvention.GEN_AI_OPERATION_TYPE_AGENT)+ fallback = SemanticConvention.GEN_AI_SYSTEM_CLAUDE_AGENT_SDK- if endpoint in ("execute_tool", "subagent", "chat", "create_agent") and entity_name:+ if endpoint in _SPAN_NAME_ENTITY_ENDPOINTS and entity_name:return f"{operation} {entity_name}"- return f"{operation} claude_agent_sdk"+ return f"{operation} {fallback}"# ---------------------------------------------------------------------------@@ -556,7 +580,9 @@ def process_result_message(span, message, capture_message_content):return result_usage-def set_create_agent_attributes(span, version, environment, application_name):+def set_create_agent_attributes(+ span, version, environment, application_name, agent_name=None+):"""Set OTel-compliant attributes on a create_agent span."""try:span.set_attribute(@@ -568,7 +594,10 @@ def set_create_agent_attributes(span, version, environment, application_name):SemanticConvention.GEN_AI_SYSTEM_CLAUDE_AGENT_SDK,)span.set_attribute(GEN_AI_SYSTEM_ATTR, GEN_AI_SYSTEM_VALUE)- span.set_attribute(SemanticConvention.GEN_AI_AGENT_NAME, "claude_agent_sdk")+ span.set_attribute(+ SemanticConvention.GEN_AI_AGENT_NAME,+ agent_name or SemanticConvention.GEN_AI_SYSTEM_CLAUDE_AGENT_SDK,+ )span.set_attribute(SemanticConvention.SERVER_ADDRESS, SERVER_ADDRESS)span.set_attribute(SemanticConvention.SERVER_PORT, SERVER_PORT)span.set_attribute(SemanticConvention.GEN_AI_ENVIRONMENT, environment)@@ -622,7 +651,11 @@ def set_initial_span_attributes(SemanticConvention.GEN_AI_SYSTEM_CLAUDE_AGENT_SDK,)span.set_attribute(GEN_AI_SYSTEM_ATTR, GEN_AI_SYSTEM_VALUE)- span.set_attribute(SemanticConvention.GEN_AI_AGENT_NAME, "claude_agent_sdk")+ agent_label = resolve_agent_display_name(options)+ span.set_attribute(+ SemanticConvention.GEN_AI_AGENT_NAME,+ agent_label or SemanticConvention.GEN_AI_SYSTEM_CLAUDE_AGENT_SDK,+ )if model:span.set_attribute(SemanticConvention.GEN_AI_REQUEST_MODEL, str(model))diff --git a/sdk/python/src/openlit/instrumentation/cohere/async_cohere.py b/sdk/python/src/openlit/instrumentation/cohere/async_cohere.pyindex 0fe469c5..c3aae0f4 100644--- a/sdk/python/src/openlit/instrumentation/cohere/async_cohere.py+++ b/sdk/python/src/openlit/instrumentation/cohere/async_cohere.py@@ -3,6 +3,7 @@ Module for monitoring Cohere API calls (async version)."""import time+from opentelemetry import trace as trace_api, context as context_apifrom opentelemetry.trace import SpanKindfrom openlit.__helpers import (handle_exception,@@ -205,9 +206,17 @@ def async_chat_stream(span_name = f"{SemanticConvention.GEN_AI_OPERATION_TYPE_CHAT} {request_model}"- # Stream endpoint is always streaming- awaited_wrapped = await wrapped(*args, **kwargs)span = tracer.start_span(span_name, kind=SpanKind.CLIENT)+ ctx = trace_api.set_span_in_context(span)+ token = context_api.attach(ctx)+ try:+ awaited_wrapped = await wrapped(*args, **kwargs)+ except Exception as e:+ handle_exception(span, e)+ context_api.detach(token)+ span.end()+ raise+ context_api.detach(token)return TracedAsyncStream(awaited_wrapped,diff --git a/sdk/python/src/openlit/instrumentation/cohere/cohere.py b/sdk/python/src/openlit/instrumentation/cohere/cohere.pyindex 78d97e39..d05b5bba 100644--- a/sdk/python/src/openlit/instrumentation/cohere/cohere.py+++ b/sdk/python/src/openlit/instrumentation/cohere/cohere.py@@ -3,6 +3,7 @@ Module for monitoring Cohere API calls."""import time+from opentelemetry import trace as trace_api, context as context_apifrom opentelemetry.trace import SpanKindfrom openlit.__helpers import (handle_exception,@@ -205,9 +206,17 @@ def chat_stream(span_name = f"{SemanticConvention.GEN_AI_OPERATION_TYPE_CHAT} {request_model}"- # Stream endpoint is always streaming- awaited_wrapped = wrapped(*args, **kwargs)span = tracer.start_span(span_name, kind=SpanKind.CLIENT)+ ctx = trace_api.set_span_in_context(span)+ token = context_api.attach(ctx)+ try:+ awaited_wrapped = wrapped(*args, **kwargs)+ except Exception as e:+ handle_exception(span, e)+ context_api.detach(token)+ span.end()+ raise+ context_api.detach(token)return TracedSyncStream(awaited_wrapped,diff --git a/sdk/python/src/openlit/instrumentation/crewai/utils.py b/sdk/python/src/openlit/instrumentation/crewai/utils.pyindex 34b0cc51..97820222 100644--- a/sdk/python/src/openlit/instrumentation/crewai/utils.py+++ b/sdk/python/src/openlit/instrumentation/crewai/utils.py@@ -13,6 +13,9 @@ import contextvarsfrom opentelemetry.trace import SpanKind, Status, StatusCodefrom openlit.__helpers import (common_framework_span_attributes,+ format_input_message,+ format_output_message,+ format_system_instructions,get_server_address_for_provider,truncate_content,)@@ -90,6 +93,14 @@ def _infer_provider_from_model(model_name):if not model_name:return Nonelower = model_name.lower()++ # Handle LiteLLM-style "provider/model" prefixes (e.g. "openai/gpt-4.1-nano")+ if "/" in lower:+ provider_prefix = lower.split("/", 1)[0]+ if provider_prefix in _MODEL_PREFIX_TO_PROVIDER.values():+ return provider_prefix+ lower = lower.split("/", 1)[1]+for prefix, provider in _MODEL_PREFIX_TO_PROVIDER.items():if lower.startswith(prefix):return provider@@ -262,6 +273,11 @@ def process_crewai_response(SemanticConvention.GEN_AI_OUTPUT_TYPE_TEXT,)+ # -- recommended response attributes --+ if request_model:+ span.set_attribute(SemanticConvention.GEN_AI_RESPONSE_MODEL, request_model)+ _set_response_usage(span, response)+# -- metrics --if not disable_metrics and metrics:_record_crewai_metrics(@@ -282,10 +298,40 @@ def process_crewai_response(# ---------------------------------------------------------------------------# Internal helpers# ---------------------------------------------------------------------------+++def _set_response_usage(span, response):+ """Extract token usage from CrewAI TaskOutput / CrewOutput and set OTel attrs."""+ try:+ token_usage = getattr(response, "token_usage", None)+ if not token_usage:+ return+ prompt_tokens = getattr(token_usage, "prompt_tokens", None) or getattr(+ token_usage, "total_prompt_tokens", None+ )+ completion_tokens = getattr(token_usage, "completion_tokens", None) or getattr(+ token_usage, "total_completion_tokens", None+ )+ if prompt_tokens is not None:+ span.set_attribute(+ SemanticConvention.GEN_AI_USAGE_INPUT_TOKENS, int(prompt_tokens)+ )+ if completion_tokens is not None:+ span.set_attribute(+ SemanticConvention.GEN_AI_USAGE_OUTPUT_TOKENS, int(completion_tokens)+ )+ span.set_attribute(SemanticConvention.GEN_AI_RESPONSE_FINISH_REASON, ["stop"])+ except Exception:+ pass++def _extract_model_name(instance):- """Walk the instance hierarchy to find the LLM model name."""+ """Walk the instance hierarchy to find the LLM model name.++ Returns the model name string or *None* when it cannot be determined.+ """if not instance:- return "unknown"+ return Nonellm = getattr(instance, "llm", None)if not llm:@@ -316,7 +362,7 @@ def _extract_model_name(instance):)if name:return str(name)- return "unknown"+ return Nonedef _set_crew_attributes(span, instance, endpoint):@@ -386,10 +432,12 @@ def _set_agent_attributes(span, instance, endpoint, capture_message_content):backstory = getattr(instance, "backstory", None)if backstory and capture_message_content:- span.set_attribute(- SemanticConvention.GEN_AI_SYSTEM_INSTRUCTIONS,- truncate_content(str(backstory)),- )+ formatted = format_system_instructions(backstory)+ if formatted:+ span.set_attribute(+ SemanticConvention.GEN_AI_SYSTEM_INSTRUCTIONS,+ formatted,+ )_set_tool_definitions(span, getattr(instance, "tools", None) or [])except Exception:@@ -426,10 +474,12 @@ def _set_task_attributes(span, instance, endpoint, capture_message_content):backstory = getattr(agent, "backstory", None)if backstory and capture_message_content:- span.set_attribute(- SemanticConvention.GEN_AI_SYSTEM_INSTRUCTIONS,- truncate_content(str(backstory)),- )+ formatted = format_system_instructions(backstory)+ if formatted:+ span.set_attribute(+ SemanticConvention.GEN_AI_SYSTEM_INSTRUCTIONS,+ formatted,+ )_set_tool_definitions(span, getattr(agent, "tools", None) or [])except Exception:@@ -527,9 +577,7 @@ def _capture_content_as_attributes(span, instance, response, endpoint):if desc:span.set_attribute(SemanticConvention.GEN_AI_INPUT_MESSAGES,- json.dumps(- [{"role": "user", "content": truncate_content(str(desc))}]- ),+ json.dumps([format_input_message("user", desc)]),)if response is not None:@@ -537,7 +585,7 @@ def _capture_content_as_attributes(span, instance, response, endpoint):if output:span.set_attribute(SemanticConvention.GEN_AI_OUTPUT_MESSAGES,- json.dumps([{"role": "assistant", "content": output}]),+ json.dumps([format_output_message(output)]),)except Exception:pass@@ -593,10 +641,12 @@ def emit_create_agent_spans(backstory = getattr(agent, "backstory", None)if backstory and capture_message_content:- span.set_attribute(- SemanticConvention.GEN_AI_SYSTEM_INSTRUCTIONS,- truncate_content(str(backstory)),- )+ formatted = format_system_instructions(backstory)+ if formatted:+ span.set_attribute(+ SemanticConvention.GEN_AI_SYSTEM_INSTRUCTIONS,+ formatted,+ )_set_tool_definitions(span, getattr(agent, "tools", None) or [])diff --git a/sdk/python/src/openlit/instrumentation/google_adk/__init__.py b/sdk/python/src/openlit/instrumentation/google_adk/__init__.pyindex 27cf244c..098fe6c8 100644--- a/sdk/python/src/openlit/instrumentation/google_adk/__init__.py+++ b/sdk/python/src/openlit/instrumentation/google_adk/__init__.py@@ -102,6 +102,9 @@ def _wrap_agent_init(SemanticConvention.GEN_AI_SYSTEM_GOOGLE_ADK,)span.set_attribute(SemanticConvention.GEN_AI_AGENT_NAME, str(name))+ span.set_attribute(+ SemanticConvention.GEN_AI_AGENT_ID, str(id(instance))+ )description = getattr(instance, "description", None)if description:diff --git a/sdk/python/src/openlit/instrumentation/google_adk/utils.py b/sdk/python/src/openlit/instrumentation/google_adk/utils.pyindex 008f1d5d..4ce03f7d 100644--- a/sdk/python/src/openlit/instrumentation/google_adk/utils.py+++ b/sdk/python/src/openlit/instrumentation/google_adk/utils.py@@ -25,6 +25,7 @@ from opentelemetry.trace import SpanKind, Status, StatusCodefrom openlit.__helpers import (common_framework_span_attributes,+ get_server_address_for_provider,truncate_content,truncate_message_content,)@@ -116,13 +117,13 @@ class _PassthroughTracer(wrapt.ObjectProxy): # pylint: disable=too-few-public-m# ---------------------------------------------------------------------------# Server address resolution# ----------------------------------------------------------------------------_NON_GOOGLE_PROVIDERS = {- "anthropic": ("api.anthropic.com", 443, "anthropic"),- "claude": ("api.anthropic.com", 443, "anthropic"),- "openai": ("api.openai.com", 443, "openai"),- "gpt": ("api.openai.com", 443, "openai"),- "mistral": ("api.mistral.ai", 443, "mistral"),- "cohere": ("api.cohere.ai", 443, "cohere"),+_PREFIX_TO_PROVIDER = {+ "anthropic": "anthropic",+ "claude": "anthropic",+ "openai": "openai",+ "gpt": "openai",+ "mistral": "mistral_ai",+ "cohere": "cohere",}@@ -132,7 +133,13 @@ def _detect_provider_from_model_str(model_str):return Nonelower = model_str.lower()prefix = lower.split("/")[0] if "/" in lower else lower.split("-")[0]- return _NON_GOOGLE_PROVIDERS.get(prefix)+ provider_key = _PREFIX_TO_PROVIDER.get(prefix)+ if provider_key is None:+ return None+ addr, port = get_server_address_for_provider(provider_key)+ if not addr:+ return None+ return addr, port, provider_keydef resolve_server_info(instance=None, model_name=None):@@ -165,8 +172,10 @@ def resolve_server_info(instance=None, model_name=None):passif os.getenv("GOOGLE_GENAI_USE_VERTEXAI", "").lower() in ("true", "1"):- return "aiplatform.googleapis.com", 443, "gcp.vertex_ai"- return "generativelanguage.googleapis.com", 443, "gcp.gemini"+ addr, port = get_server_address_for_provider("gcp.vertex_ai")+ return addr, port, "gcp.vertex_ai"+ addr, port = get_server_address_for_provider("gcp.gemini")+ return addr, port, "gcp.gemini"# ---------------------------------------------------------------------------@@ -598,6 +607,21 @@ def _is_adk_event(obj):# ---------------------------------------------------------------------------# Tool span enrichment (called from trace_tool_call wrapper)# ---------------------------------------------------------------------------+def _otel_gen_ai_tool_type(tool):+ """Map an ADK tool instance's class name to OTel ``gen_ai.tool.type`` values.++ OTel allows: ``function``, ``extension``, ``datastore``. ADK exposes Python+ types like ``FunctionTool``, ``AgentTool``; we map by substring on the+ class name.+ """+ name = type(tool).__name__+ if "Function" in name:+ return "function"+ if "Agent" in name:+ return "extension"+ return "function"++def enrich_tool_span(span,tool,@@ -625,7 +649,9 @@ def enrich_tool_span(if tool:tool_name = getattr(tool, "name", None) or type(tool).__name__span.set_attribute(SemanticConvention.GEN_AI_TOOL_NAME, str(tool_name))- span.set_attribute(SemanticConvention.GEN_AI_TOOL_TYPE, type(tool).__name__)+ span.set_attribute(+ SemanticConvention.GEN_AI_TOOL_TYPE, _otel_gen_ai_tool_type(tool)+ )tool_desc = getattr(tool, "description", None)if tool_desc:span.set_attribute(@@ -822,6 +848,7 @@ def _set_runner_agent_attributes(span, instance, endpoint):or "google_adk")span.set_attribute(SemanticConvention.GEN_AI_AGENT_NAME, str(app_name))+ span.set_attribute(SemanticConvention.GEN_AI_AGENT_ID, str(id(instance)))if endpoint == "runner_run_live":span.set_attribute(SemanticConvention.GEN_AI_EXECUTION_MODE, "live")@@ -840,6 +867,8 @@ def _set_agent_attributes(span, instance):if name:span.set_attribute(SemanticConvention.GEN_AI_AGENT_NAME, str(name))+ span.set_attribute(SemanticConvention.GEN_AI_AGENT_ID, str(id(instance)))+description = getattr(instance, "description", None)if description:span.set_attribute(diff --git a/sdk/python/src/openlit/instrumentation/google_ai_studio/async_google_ai_studio.py b/sdk/python/src/openlit/instrumentation/google_ai_studio/async_google_ai_studio.pyindex 93d0c5a8..88513a1b 100644--- a/sdk/python/src/openlit/instrumentation/google_ai_studio/async_google_ai_studio.py+++ b/sdk/python/src/openlit/instrumentation/google_ai_studio/async_google_ai_studio.py@@ -3,6 +3,7 @@ Module for monitoring Google AI Studio API calls."""import time+from opentelemetry import trace as trace_api, context as context_apifrom opentelemetry.trace import SpanKindfrom openlit.__helpers import (handle_exception,@@ -206,8 +207,17 @@ def async_generate_stream(span_name = f"{SemanticConvention.GEN_AI_OPERATION_TYPE_CHAT} {request_model}"- awaited_wrapped = await wrapped(*args, **kwargs)- span = tracer.start_as_current_span(span_name, kind=SpanKind.CLIENT)+ span = tracer.start_span(span_name, kind=SpanKind.CLIENT)+ ctx = trace_api.set_span_in_context(span)+ token = context_api.attach(ctx)+ try:+ awaited_wrapped = await wrapped(*args, **kwargs)+ except Exception as e:+ handle_exception(span, e)+ context_api.detach(token)+ span.end()+ raise+ context_api.detach(token)return TracedAsyncStream(awaited_wrapped,diff --git a/sdk/python/src/openlit/instrumentation/google_ai_studio/google_ai_studio.py b/sdk/python/src/openlit/instrumentation/google_ai_studio/google_ai_studio.pyindex aaf4a822..a4907055 100644--- a/sdk/python/src/openlit/instrumentation/google_ai_studio/google_ai_studio.py+++ b/sdk/python/src/openlit/instrumentation/google_ai_studio/google_ai_studio.py@@ -3,6 +3,7 @@ Module for monitoring Google AI Studio API calls."""import time+from opentelemetry import trace as trace_api, context as context_apifrom opentelemetry.trace import SpanKindfrom openlit.__helpers import (handle_exception,@@ -206,8 +207,17 @@ def generate_stream(span_name = f"{SemanticConvention.GEN_AI_OPERATION_TYPE_CHAT} {request_model}"- awaited_wrapped = wrapped(*args, **kwargs)- span = tracer.start_as_current_span(span_name, kind=SpanKind.CLIENT)+ span = tracer.start_span(span_name, kind=SpanKind.CLIENT)+ ctx = trace_api.set_span_in_context(span)+ token = context_api.attach(ctx)+ try:+ awaited_wrapped = wrapped(*args, **kwargs)+ except Exception as e:+ handle_exception(span, e)+ context_api.detach(token)+ span.end()+ raise+ context_api.detach(token)return TracedSyncStream(awaited_wrapped,diff --git a/sdk/python/src/openlit/instrumentation/gpt4all/gpt4all.py b/sdk/python/src/openlit/instrumentation/gpt4all/gpt4all.pyindex 325acf0e..d79c1d67 100644--- a/sdk/python/src/openlit/instrumentation/gpt4all/gpt4all.py+++ b/sdk/python/src/openlit/instrumentation/gpt4all/gpt4all.py@@ -3,6 +3,7 @@ Module for monitoring GPT4All API calls."""import time+from opentelemetry import trace as trace_api, context as context_apifrom opentelemetry.trace import SpanKindfrom openlit.__helpers import (handle_exception,@@ -130,9 +131,17 @@ def generate(span_name = f"{SemanticConvention.GEN_AI_OPERATION_TYPE_CHAT} {request_model}"if streaming:- # Special handling for streaming response to accommodate the nature of data flow- awaited_wrapped = wrapped(*args, **kwargs)span = tracer.start_span(span_name, kind=SpanKind.CLIENT)+ ctx = trace_api.set_span_in_context(span)+ token = context_api.attach(ctx)+ try:+ awaited_wrapped = wrapped(*args, **kwargs)+ except Exception as e:+ handle_exception(span, e)+ context_api.detach(token)+ span.end()+ raise+ context_api.detach(token)return TracedSyncStream(awaited_wrapped,span,diff --git a/sdk/python/src/openlit/instrumentation/groq/async_groq.py b/sdk/python/src/openlit/instrumentation/groq/async_groq.pyindex 16d5221a..18e742fc 100644--- a/sdk/python/src/openlit/instrumentation/groq/async_groq.py+++ b/sdk/python/src/openlit/instrumentation/groq/async_groq.py@@ -3,6 +3,7 @@ Module for monitoring Groq API calls (async version)."""import time+from opentelemetry import trace as trace_api, context as context_apifrom opentelemetry.trace import SpanKindfrom openlit.__helpers import (handle_exception,@@ -125,9 +126,17 @@ def async_chat(span_name = f"{SemanticConvention.GEN_AI_OPERATION_TYPE_CHAT} {request_model}"if streaming:- # Special handling for streaming response- awaited_wrapped = await wrapped(*args, **kwargs)span = tracer.start_span(span_name, kind=SpanKind.CLIENT)+ ctx = trace_api.set_span_in_context(span)+ token = context_api.attach(ctx)+ try:+ awaited_wrapped = await wrapped(*args, **kwargs)+ except Exception as e:+ handle_exception(span, e)+ context_api.detach(token)+ span.end()+ raise+ context_api.detach(token)return TracedAsyncStream(awaited_wrapped, span, span_name, kwargs, server_address, server_port)diff --git a/sdk/python/src/openlit/instrumentation/groq/groq.py b/sdk/python/src/openlit/instrumentation/groq/groq.pyindex 87c0cde4..7d53c075 100644--- a/sdk/python/src/openlit/instrumentation/groq/groq.py+++ b/sdk/python/src/openlit/instrumentation/groq/groq.py@@ -3,6 +3,7 @@ Module for monitoring Groq API calls."""import time+from opentelemetry import trace as trace_api, context as context_apifrom opentelemetry.trace import SpanKindfrom openlit.__helpers import (handle_exception,@@ -125,9 +126,17 @@ def chat(span_name = f"{SemanticConvention.GEN_AI_OPERATION_TYPE_CHAT} {request_model}"if streaming:- # Special handling for streaming response- awaited_wrapped = wrapped(*args, **kwargs)span = tracer.start_span(span_name, kind=SpanKind.CLIENT)+ ctx = trace_api.set_span_in_context(span)+ token = context_api.attach(ctx)+ try:+ awaited_wrapped = wrapped(*args, **kwargs)+ except Exception as e:+ handle_exception(span, e)+ context_api.detach(token)+ span.end()+ raise+ context_api.detach(token)return TracedSyncStream(awaited_wrapped, span, span_name, kwargs, server_address, server_port)diff --git a/sdk/python/src/openlit/instrumentation/langchain/__init__.py b/sdk/python/src/openlit/instrumentation/langchain/__init__.pyindex a2a6a4d5..32f4cebf 100644--- a/sdk/python/src/openlit/instrumentation/langchain/__init__.py+++ b/sdk/python/src/openlit/instrumentation/langchain/__init__.py@@ -29,7 +29,7 @@ logger = logging.getLogger(__name__)_instruments = ("langchain-core >= 0.1.20",)-class SpanHolder:+class SpanHolder: # pylint: disable=too-many-instance-attributes"""Container for span and related metadata with performance optimization via __slots__."""__slots__ = (@@ -58,6 +58,7 @@ class SpanHolder:"server_port","tool_calls","finish_reason",+ "is_agent_chain",)def __init__(self, span, token=None, start_time=None):@@ -86,6 +87,7 @@ class SpanHolder:self.server_port: int = 0self.tool_calls: Optional[List[Dict[str, Any]]] = Noneself.finish_reason: str = "stop"+ self.is_agent_chain: bool = Falsedef get_duration(self) -> float:"""Calculate duration from start time to now."""@@ -254,6 +256,32 @@ def extract_model_name(return class_name or "unknown"+def _extract_response_model_from_chain_outputs(+ outputs: Optional[Dict[str, Any]],+) -> Optional[str]:+ """Return an LLM model identifier from chain outputs when present."""+ if not outputs or not isinstance(outputs, dict):+ return None+ for key in ("model", "model_name"):+ val = outputs.get(key)+ if isinstance(val, str) and val.strip() and val != "unknown":+ return val+ llm_out = outputs.get("llm_output")+ if isinstance(llm_out, dict):+ val = llm_out.get("model_name") or llm_out.get("model")+ if val:+ return str(val)+ messages = outputs.get("messages")+ if isinstance(messages, list) and messages:+ last = messages[-1]+ rm = getattr(last, "response_metadata", None)+ if isinstance(rm, dict):+ val = rm.get("model_name") or rm.get("model")+ if val:+ return str(val)+ return None++def extract_model_parameters(kwargs: Dict[str, Any]) -> Dict[str, Any]:"""Extract model parameters from invocation_params (based on Langfuse's approach).@@ -842,6 +870,9 @@ def _create_callback_handler_class(span = self._create_span(run_id, parent_run_id, span_name)+ if obs_type == "agent" and run_id in self.spans:+ self.spans[run_id].is_agent_chain = True+span.set_attribute(SemanticConvention.GEN_AI_PROVIDER_NAME,SemanticConvention.GEN_AI_SYSTEM_LANGCHAIN,@@ -850,6 +881,7 @@ def _create_callback_handler_class(if obs_type == "agent":span.set_attribute(SemanticConvention.GEN_AI_AGENT_NAME, name)+ span.set_attribute(SemanticConvention.GEN_AI_AGENT_ID, str(run_id))else:span.set_attribute(SemanticConvention.GEN_AI_WORKFLOW_NAME, name)@@ -903,6 +935,13 @@ def _create_callback_handler_class(SemanticConvention.GEN_AI_WORKFLOW_OUTPUT, output_str)+ if holder.is_agent_chain and outputs:+ resp_model = _extract_response_model_from_chain_outputs(outputs)+ if resp_model:+ span.set_attribute(+ SemanticConvention.GEN_AI_RESPONSE_MODEL, resp_model+ )+# Record metricsif not self._disable_metrics and self._metrics:try:@@ -943,6 +982,12 @@ def _create_callback_handler_class(SemanticConvention.GEN_AI_FRAMEWORK_ERROR_MESSAGE,truncate_content(error),)+ error_type = (+ type(error).__name__+ if hasattr(type(error), "__name__")+ else "_OTHER"+ )+ span.set_attribute(SemanticConvention.ERROR_TYPE, error_type)self._end_span(run_id, str(error))except Exception as e:logger.debug("Error in on_chain_error: %s", e)@@ -1479,6 +1524,12 @@ def _create_callback_handler_class(SemanticConvention.GEN_AI_FRAMEWORK_ERROR_MESSAGE,truncate_content(error),)+ error_type = (+ type(error).__name__+ if hasattr(type(error), "__name__")+ else "_OTHER"+ )+ holder.span.set_attribute(SemanticConvention.ERROR_TYPE, error_type)if holder.token and isinstance(holder.token, tuple):fw_token, ctx_token = holder.tokentry:@@ -1519,6 +1570,7 @@ def _create_callback_handler_class()span.set_attribute(SemanticConvention.GEN_AI_TOOL_NAME, name)span.set_attribute(SemanticConvention.GEN_AI_TOOL_TYPE, "function")+ span.set_attribute(SemanticConvention.GEN_AI_TOOL_CALL_ID, str(run_id))description = (serialized or {}).get("description")if description:@@ -1619,6 +1671,12 @@ def _create_callback_handler_class(SemanticConvention.GEN_AI_FRAMEWORK_ERROR_MESSAGE,truncate_content(error),)+ error_type = (+ type(error).__name__+ if hasattr(type(error), "__name__")+ else "_OTHER"+ )+ span.set_attribute(SemanticConvention.ERROR_TYPE, error_type)self._end_span(run_id, str(error))except Exception as e:logger.debug("Error in on_tool_error: %s", e)@@ -1750,6 +1808,12 @@ def _create_callback_handler_class(SemanticConvention.GEN_AI_FRAMEWORK_ERROR_MESSAGE,truncate_content(error),)+ error_type = (+ type(error).__name__+ if hasattr(type(error), "__name__")+ else "_OTHER"+ )+ span.set_attribute(SemanticConvention.ERROR_TYPE, error_type)self._end_span(run_id, str(error))except Exception as e:logger.debug("Error in on_retriever_error: %s", e)diff --git a/sdk/python/src/openlit/instrumentation/langgraph/async_langgraph.py b/sdk/python/src/openlit/instrumentation/langgraph/async_langgraph.pyindex 1fbf087c..3ae8140a 100644--- a/sdk/python/src/openlit/instrumentation/langgraph/async_langgraph.py+++ b/sdk/python/src/openlit/instrumentation/langgraph/async_langgraph.py@@ -412,13 +412,20 @@ def _finalize_async_stream_span()if execution_state["final_response"] and capture_message_content:+ output_msgs = [+ {+ "role": "assistant",+ "parts": [+ {+ "type": "text",+ "content": truncate_content(execution_state["final_response"]),+ }+ ],+ }+ ]span.set_attribute(SemanticConvention.GEN_AI_OUTPUT_MESSAGES,- truncate_content(execution_state["final_response"]),- )- span.set_attribute(- SemanticConvention.GEN_AI_OUTPUT_MESSAGES,- truncate_content(execution_state["final_response"]),+ json.dumps(output_msgs),)span.set_attribute(SemanticConvention.GEN_AI_GRAPH_STATUS, "success")diff --git a/sdk/python/src/openlit/instrumentation/langgraph/langgraph.py b/sdk/python/src/openlit/instrumentation/langgraph/langgraph.pyindex 9bdfe882..510363c6 100644--- a/sdk/python/src/openlit/instrumentation/langgraph/langgraph.py+++ b/sdk/python/src/openlit/instrumentation/langgraph/langgraph.py@@ -247,9 +247,10 @@ def _handle_stream(SemanticConvention.GEN_AI_PROVIDER_NAME,SemanticConvention.GEN_AI_SYSTEM_LANGGRAPH,)- span.set_attribute(SemanticConvention.GEN_AI_REQUEST_MODEL, "unknown")- span.set_attribute(SemanticConvention.SERVER_ADDRESS, server_address)- span.set_attribute(SemanticConvention.SERVER_PORT, server_port)+ if server_address:+ span.set_attribute(SemanticConvention.SERVER_ADDRESS, server_address)+ if server_port:+ span.set_attribute(SemanticConvention.SERVER_PORT, server_port)span.set_attribute(SemanticConvention.GEN_AI_ENVIRONMENT, environment)span.set_attribute(SemanticConvention.GEN_AI_APPLICATION_NAME, application_name@@ -394,13 +395,20 @@ def _finalize_stream_span(span, execution_state, capture_message_content, start_)if execution_state["final_response"] and capture_message_content:+ output_msgs = [+ {+ "role": "assistant",+ "parts": [+ {+ "type": "text",+ "content": truncate_content(execution_state["final_response"]),+ }+ ],+ }+ ]span.set_attribute(SemanticConvention.GEN_AI_OUTPUT_MESSAGES,- truncate_content(execution_state["final_response"]),- )- span.set_attribute(- SemanticConvention.GEN_AI_OUTPUT_MESSAGES,- truncate_content(execution_state["final_response"]),+ json.dumps(output_msgs),)span.set_attribute(SemanticConvention.GEN_AI_GRAPH_STATUS, "success")@@ -560,7 +568,7 @@ def wrap_add_node(span_name = f"invoke_agent {node_name}"with tracer.start_as_current_span(- span_name, kind=SpanKind.CLIENT+ span_name, kind=SpanKind.INTERNAL) as span:start_time = time.time()span.set_attribute(@@ -574,6 +582,9 @@ def wrap_add_node(span.set_attribute(SemanticConvention.GEN_AI_AGENT_NAME, node_name)+ span.set_attribute(+ SemanticConvention.GEN_AI_AGENT_ID, str(node_name)+ )span.set_attribute(SemanticConvention.GEN_AI_ENVIRONMENT, environment)@@ -624,7 +635,7 @@ def wrap_add_node(span_name = f"invoke_agent {node_name}"with tracer.start_as_current_span(- span_name, kind=SpanKind.CLIENT+ span_name, kind=SpanKind.INTERNAL) as span:start_time = time.time()span.set_attribute(@@ -638,6 +649,9 @@ def wrap_add_node(span.set_attribute(SemanticConvention.GEN_AI_AGENT_NAME, node_name)+ span.set_attribute(+ SemanticConvention.GEN_AI_AGENT_ID, str(node_name)+ )span.set_attribute(SemanticConvention.GEN_AI_ENVIRONMENT, environment)diff --git a/sdk/python/src/openlit/instrumentation/langgraph/utils.py b/sdk/python/src/openlit/instrumentation/langgraph/utils.pyindex 28e339a3..9a32b6d3 100644--- a/sdk/python/src/openlit/instrumentation/langgraph/utils.py+++ b/sdk/python/src/openlit/instrumentation/langgraph/utils.py@@ -214,7 +214,12 @@ def extract_llm_info_from_result(span, state, result):input_msgs.append({"role": role,- "content": truncate_content(content),+ "parts": [+ {+ "type": "text",+ "content": truncate_content(content),+ }+ ],})if input_msgs:@@ -271,7 +276,7 @@ def extract_llm_info_from_result(span, state, result):if "finish_reason" in metadata:span.set_attribute(SemanticConvention.GEN_AI_RESPONSE_FINISH_REASON,- metadata["finish_reason"],+ [metadata["finish_reason"]],)# Response IDdiff --git a/sdk/python/src/openlit/instrumentation/litellm/async_litellm.py b/sdk/python/src/openlit/instrumentation/litellm/async_litellm.pyindex 0b31c2f0..ef158dc0 100644--- a/sdk/python/src/openlit/instrumentation/litellm/async_litellm.py+++ b/sdk/python/src/openlit/instrumentation/litellm/async_litellm.py@@ -4,6 +4,7 @@ Module for monitoring LiteLLM API calls (async version).import timeimport asyncio+from opentelemetry import trace as trace_api, context as context_apifrom opentelemetry.trace import SpanKindfrom openlit.__helpers import (handle_exception,@@ -163,12 +164,20 @@ def acompletion()if streaming:+ span = tracer.start_span(span_name, kind=SpanKind.CLIENT)+ ctx = trace_api.set_span_in_context(span)+ otel_token = context_api.attach(ctx)fw_token = set_framework_llm_active()try:awaited_wrapped = await wrapped(*args, **kwargs)+ except Exception as e:+ handle_exception(span, e)+ context_api.detach(otel_token)+ span.end()+ raisefinally:reset_framework_llm_active(fw_token)- span = tracer.start_span(span_name, kind=SpanKind.CLIENT)+ context_api.detach(otel_token)return TracedAsyncStream(awaited_wrapped,span,diff --git a/sdk/python/src/openlit/instrumentation/litellm/litellm.py b/sdk/python/src/openlit/instrumentation/litellm/litellm.pyindex d6e53627..830d22de 100644--- a/sdk/python/src/openlit/instrumentation/litellm/litellm.py+++ b/sdk/python/src/openlit/instrumentation/litellm/litellm.py@@ -3,6 +3,7 @@ Module for monitoring LiteLLM API calls."""import time+from opentelemetry import trace as trace_api, context as context_apifrom opentelemetry.trace import SpanKindfrom openlit.__helpers import (handle_exception,@@ -140,12 +141,20 @@ def completion()if streaming:+ span = tracer.start_span(span_name, kind=SpanKind.CLIENT)+ ctx = trace_api.set_span_in_context(span)+ otel_token = context_api.attach(ctx)fw_token = set_framework_llm_active()try:awaited_wrapped = wrapped(*args, **kwargs)+ except Exception as e:+ handle_exception(span, e)+ context_api.detach(otel_token)+ span.end()+ raisefinally:reset_framework_llm_active(fw_token)- span = tracer.start_span(span_name, kind=SpanKind.CLIENT)+ context_api.detach(otel_token)return TracedSyncStream(awaited_wrapped,span,diff --git a/sdk/python/src/openlit/instrumentation/mistral/async_mistral.py b/sdk/python/src/openlit/instrumentation/mistral/async_mistral.pyindex eb2a6a78..7c65f4ad 100644--- a/sdk/python/src/openlit/instrumentation/mistral/async_mistral.py+++ b/sdk/python/src/openlit/instrumentation/mistral/async_mistral.py@@ -3,6 +3,7 @@ Module for monitoring Mistral API calls (async version)."""import time+from opentelemetry import trace as trace_api, context as context_apifrom opentelemetry.trace import SpanKindfrom openlit.__helpers import (handle_exception,@@ -202,9 +203,17 @@ def async_stream(span_name = f"{SemanticConvention.GEN_AI_OPERATION_TYPE_CHAT} {request_model}"- # Stream endpoint is always streaming- awaited_wrapped = await wrapped(*args, **kwargs)span = tracer.start_span(span_name, kind=SpanKind.CLIENT)+ ctx = trace_api.set_span_in_context(span)+ token = context_api.attach(ctx)+ try:+ awaited_wrapped = await wrapped(*args, **kwargs)+ except Exception as e:+ handle_exception(span, e)+ context_api.detach(token)+ span.end()+ raise+ context_api.detach(token)return TracedAsyncStream(awaited_wrapped, span, span_name, kwargs, server_address, server_portdiff --git a/sdk/python/src/openlit/instrumentation/mistral/mistral.py b/sdk/python/src/openlit/instrumentation/mistral/mistral.pyindex cff73f0e..eada7487 100644--- a/sdk/python/src/openlit/instrumentation/mistral/mistral.py+++ b/sdk/python/src/openlit/instrumentation/mistral/mistral.py@@ -3,6 +3,7 @@ Module for monitoring Mistral API calls."""import time+from opentelemetry import trace as trace_api, context as context_apifrom opentelemetry.trace import SpanKindfrom openlit.__helpers import (handle_exception,@@ -202,9 +203,17 @@ def stream(span_name = f"{SemanticConvention.GEN_AI_OPERATION_TYPE_CHAT} {request_model}"- # Stream endpoint is always streaming- awaited_wrapped = wrapped(*args, **kwargs)span = tracer.start_span(span_name, kind=SpanKind.CLIENT)+ ctx = trace_api.set_span_in_context(span)+ token = context_api.attach(ctx)+ try:+ awaited_wrapped = wrapped(*args, **kwargs)+ except Exception as e:+ handle_exception(span, e)+ context_api.detach(token)+ span.end()+ raise+ context_api.detach(token)return TracedSyncStream(awaited_wrapped, span, span_name, kwargs, server_address, server_portdiff --git a/sdk/python/src/openlit/instrumentation/ollama/async_ollama.py b/sdk/python/src/openlit/instrumentation/ollama/async_ollama.pyindex e7bb846d..14c4bfde 100644--- a/sdk/python/src/openlit/instrumentation/ollama/async_ollama.py+++ b/sdk/python/src/openlit/instrumentation/ollama/async_ollama.py@@ -3,6 +3,7 @@ Module for monitoring Ollama API calls."""import time+from opentelemetry import trace as trace_api, context as context_apifrom opentelemetry.trace import SpanKindfrom openlit.__helpers import (handle_exception,@@ -131,8 +132,17 @@ def async_chat(span_name = f"{SemanticConvention.GEN_AI_OPERATION_TYPE_CHAT} {request_model}"if streaming:- awaited_wrapped = await wrapped(*args, **kwargs)span = tracer.start_span(span_name, kind=SpanKind.CLIENT)+ ctx = trace_api.set_span_in_context(span)+ token = context_api.attach(ctx)+ try:+ awaited_wrapped = await wrapped(*args, **kwargs)+ except Exception as e:+ handle_exception(span, e)+ context_api.detach(token)+ span.end()+ raise+ context_api.detach(token)return TracedAsyncStream(awaited_wrapped,span,@@ -306,8 +316,17 @@ def async_generate(span_name = f"{SemanticConvention.GEN_AI_OPERATION_TYPE_TEXT_COMPLETION} {request_model}"if streaming:- awaited_wrapped = await wrapped(*args, **kwargs)span = tracer.start_span(span_name, kind=SpanKind.CLIENT)+ ctx = trace_api.set_span_in_context(span)+ token = context_api.attach(ctx)+ try:+ awaited_wrapped = await wrapped(*args, **kwargs)+ except Exception as e:+ handle_exception(span, e)+ context_api.detach(token)+ span.end()+ raise+ context_api.detach(token)return TracedAsyncStream(awaited_wrapped,span,diff --git a/sdk/python/src/openlit/instrumentation/ollama/ollama.py b/sdk/python/src/openlit/instrumentation/ollama/ollama.pyindex a25d51a9..cd5894f4 100644--- a/sdk/python/src/openlit/instrumentation/ollama/ollama.py+++ b/sdk/python/src/openlit/instrumentation/ollama/ollama.py@@ -3,6 +3,7 @@ Module for monitoring Ollama API calls."""import time+from opentelemetry import trace as trace_api, context as context_apifrom opentelemetry.trace import SpanKindfrom openlit.__helpers import (handle_exception,@@ -131,8 +132,17 @@ def chat(span_name = f"{SemanticConvention.GEN_AI_OPERATION_TYPE_CHAT} {request_model}"if streaming:- awaited_wrapped = wrapped(*args, **kwargs)span = tracer.start_span(span_name, kind=SpanKind.CLIENT)+ ctx = trace_api.set_span_in_context(span)+ token = context_api.attach(ctx)+ try:+ awaited_wrapped = wrapped(*args, **kwargs)+ except Exception as e:+ handle_exception(span, e)+ context_api.detach(token)+ span.end()+ raise+ context_api.detach(token)return TracedSyncStream(awaited_wrapped,span,@@ -306,8 +316,17 @@ def generate(span_name = f"{SemanticConvention.GEN_AI_OPERATION_TYPE_TEXT_COMPLETION} {request_model}"if streaming:- awaited_wrapped = wrapped(*args, **kwargs)span = tracer.start_span(span_name, kind=SpanKind.CLIENT)+ ctx = trace_api.set_span_in_context(span)+ token = context_api.attach(ctx)+ try:+ awaited_wrapped = wrapped(*args, **kwargs)+ except Exception as e:+ handle_exception(span, e)+ context_api.detach(token)+ span.end()+ raise+ context_api.detach(token)return TracedSyncStream(awaited_wrapped,span,diff --git a/sdk/python/src/openlit/instrumentation/openai_agents/__init__.py b/sdk/python/src/openlit/instrumentation/openai_agents/__init__.pyindex 7331fd42..1863f4d3 100644--- a/sdk/python/src/openlit/instrumentation/openai_agents/__init__.py+++ b/sdk/python/src/openlit/instrumentation/openai_agents/__init__.py@@ -11,7 +11,7 @@ from opentelemetry.instrumentation.instrumentor import BaseInstrumentorfrom opentelemetry.trace import SpanKindfrom wrapt import wrap_function_wrapper-from openlit.__helpers import handle_exception+from openlit.__helpers import handle_exception, format_system_instructionsfrom openlit.semcov import SemanticConventionfrom openlit.instrumentation.openai_agents.processor import OpenLITTracingProcessor@@ -63,6 +63,9 @@ def _wrap_agent_init(SemanticConvention.GEN_AI_SYSTEM_OPENAI,)span.set_attribute(SemanticConvention.GEN_AI_AGENT_NAME, str(name))+ span.set_attribute(+ SemanticConvention.GEN_AI_AGENT_ID, str(id(instance))+ )model = getattr(instance, "model", None)if model:@@ -72,10 +75,12 @@ def _wrap_agent_init(instructions = getattr(instance, "instructions", None)if instructions and capture_message_content:- span.set_attribute(- SemanticConvention.GEN_AI_SYSTEM_INSTRUCTIONS,- str(instructions)[:4096],- )+ formatted = format_system_instructions(instructions)+ if formatted:+ span.set_attribute(+ SemanticConvention.GEN_AI_SYSTEM_INSTRUCTIONS,+ formatted,+ )tools = getattr(instance, "tools", None)if tools:diff --git a/sdk/python/src/openlit/instrumentation/openai_agents/processor.py b/sdk/python/src/openlit/instrumentation/openai_agents/processor.pyindex 7e915cc6..82df1b7c 100644--- a/sdk/python/src/openlit/instrumentation/openai_agents/processor.py+++ b/sdk/python/src/openlit/instrumentation/openai_agents/processor.py@@ -17,6 +17,7 @@ from opentelemetry.trace import SpanKind, Status, StatusCode, Link, set_span_in_from openlit.__helpers import (common_framework_span_attributes,+ get_server_address_for_provider,handle_exception,)from openlit.semcov import SemanticConvention@@ -28,6 +29,8 @@ from openlit.instrumentation.openai_agents.utils import (process_span_end,)+_OPENAI_SERVER_ADDRESS, _OPENAI_SERVER_PORT = get_server_address_for_provider("openai")+try:from agents import TracingProcessor@@ -158,8 +161,8 @@ class OpenLITTracingProcessor(TracingProcessor):common_framework_span_attributes(scope,SemanticConvention.GEN_AI_SYSTEM_OPENAI,- "api.openai.com",- 443,+ _OPENAI_SERVER_ADDRESS,+ _OPENAI_SERVER_PORT,self.environment,self.application_name,self.version,@@ -201,8 +204,8 @@ class OpenLITTracingProcessor(TracingProcessor):self.environment,self.application_name,None,- "api.openai.com",- 443,+ _OPENAI_SERVER_ADDRESS,+ _OPENAI_SERVER_PORT,)if token is not None:diff --git a/sdk/python/src/openlit/instrumentation/openai_agents/utils.py b/sdk/python/src/openlit/instrumentation/openai_agents/utils.pyindex fb338149..06ce2d7a 100644--- a/sdk/python/src/openlit/instrumentation/openai_agents/utils.py+++ b/sdk/python/src/openlit/instrumentation/openai_agents/utils.py@@ -17,11 +17,16 @@ from opentelemetry.trace import SpanKind, Status, StatusCodefrom openlit.__helpers import (common_framework_span_attributes,+ format_input_message,+ format_output_message,+ get_server_address_for_provider,handle_exception,truncate_content,)from openlit.semcov import SemanticConvention+_OPENAI_SERVER_ADDRESS, _OPENAI_SERVER_PORT = get_server_address_for_provider("openai")+# ---------------------------------------------------------------------------# OTel GenAI operation mapping (SDK span_data.type -> gen_ai.operation.name)# ---------------------------------------------------------------------------@@ -153,8 +158,8 @@ def process_span_end(scope._start_time = start_timescope._end_time = end_time- server_address = "api.openai.com"- server_port = 443+ server_address = _OPENAI_SERVER_ADDRESS+ server_port = _OPENAI_SERVER_PORTmodel_proxy = (type("P", (), {"model_name": model_name})() if model_name else None@@ -240,6 +245,29 @@ def process_span_end(handle_exception(otel_span, e)+_OUTPUT_TYPE_MAP = {+ str: SemanticConvention.GEN_AI_OUTPUT_TYPE_TEXT,+ "str": SemanticConvention.GEN_AI_OUTPUT_TYPE_TEXT,+ dict: SemanticConvention.GEN_AI_OUTPUT_TYPE_JSON,+ "dict": SemanticConvention.GEN_AI_OUTPUT_TYPE_JSON,+}+++def _map_output_type(output_type):+ """Map a Python type or string to an OTel standard gen_ai.output.type value."""+ if output_type is None:+ return SemanticConvention.GEN_AI_OUTPUT_TYPE_TEXT+ mapped = _OUTPUT_TYPE_MAP.get(output_type)+ if mapped:+ return mapped+ type_str = str(output_type).lower()+ if "str" in type_str or "text" in type_str:+ return SemanticConvention.GEN_AI_OUTPUT_TYPE_TEXT+ if "dict" in type_str or "json" in type_str:+ return SemanticConvention.GEN_AI_OUTPUT_TYPE_JSON+ return SemanticConvention.GEN_AI_OUTPUT_TYPE_TEXT++# ---------------------------------------------------------------------------# Agent (invoke_agent)# ---------------------------------------------------------------------------@@ -249,13 +277,15 @@ def _set_agent_attributes(span, span_data, capture_message_content):if name:span.set_attribute(SemanticConvention.GEN_AI_AGENT_NAME, str(name))- output_type = getattr(span_data, "output_type", None)- span.set_attribute(- SemanticConvention.GEN_AI_OUTPUT_TYPE,- str(output_type)- if output_type- else SemanticConvention.GEN_AI_OUTPUT_TYPE_TEXT,+ agent_obj = getattr(span_data, "agent", None)+ agent_id = getattr(span_data, "agent_id", None) or (+ str(id(agent_obj)) if agent_obj is not None else str(id(span_data)))+ span.set_attribute(SemanticConvention.GEN_AI_AGENT_ID, agent_id)++ output_type = getattr(span_data, "output_type", None)+ mapped_type = _map_output_type(output_type)+ span.set_attribute(SemanticConvention.GEN_AI_OUTPUT_TYPE, mapped_type)if capture_message_content:tools = getattr(span_data, "tools", None)@@ -324,8 +354,8 @@ def _set_response_attributes(span, span_data, capture_message_content):SemanticConvention.GEN_AI_OUTPUT_TYPE,SemanticConvention.GEN_AI_OUTPUT_TYPE_TEXT,)- span.set_attribute(SemanticConvention.SERVER_ADDRESS, "api.openai.com")- span.set_attribute(SemanticConvention.SERVER_PORT, 443)+ span.set_attribute(SemanticConvention.SERVER_ADDRESS, _OPENAI_SERVER_ADDRESS)+ span.set_attribute(SemanticConvention.SERVER_PORT, _OPENAI_SERVER_PORT)if capture_message_content:_capture_response_messages(span, span_data, response)@@ -340,25 +370,18 @@ def _capture_response_messages(span, span_data, response):raw_input = getattr(span_data, "input", None)if raw_input:if isinstance(raw_input, str):- messages = [{"role": "user", "content": truncate_content(raw_input)}]+ messages = [format_input_message("user", raw_input)]elif isinstance(raw_input, (list, tuple)):messages = []for item in raw_input[:20]:if isinstance(item, dict):messages.append(item)else:- role = getattr(item, "role", "user")+ role = str(getattr(item, "role", "user"))content = getattr(item, "content", str(item))- messages.append(- {- "role": str(role),- "content": truncate_content(str(content)),- }- )+ messages.append(format_input_message(role, content))else:- messages = [- {"role": "user", "content": truncate_content(str(raw_input))}- ]+ messages = [format_input_message("user", raw_input)]span.set_attribute(SemanticConvention.GEN_AI_INPUT_MESSAGES, json.dumps(messages))@@ -376,21 +399,20 @@ def _capture_response_messages(span, span_data, response):if text:text_parts.append(truncate_content(str(text)))if text_parts:- out_messages.append(- {- "role": "assistant",- "content": " ".join(text_parts),- }- )+ out_messages.append(format_output_message(" ".join(text_parts)))elif item_type == "function_call":fname = getattr(item, "name", "unknown")fargs = getattr(item, "arguments", "")out_messages.append({"role": "assistant",- "content": json.dumps(- {"tool_call": fname, "arguments": fargs}- ),+ "parts": [+ {+ "type": "tool_call",+ "name": fname,+ "arguments": fargs,+ }+ ],})if out_messages:@@ -428,8 +450,8 @@ def _set_generation_attributes(span, span_data, capture_message_content):SemanticConvention.GEN_AI_OUTPUT_TYPE,SemanticConvention.GEN_AI_OUTPUT_TYPE_TEXT,)- span.set_attribute(SemanticConvention.SERVER_ADDRESS, "api.openai.com")- span.set_attribute(SemanticConvention.SERVER_PORT, 443)+ span.set_attribute(SemanticConvention.SERVER_ADDRESS, _OPENAI_SERVER_ADDRESS)+ span.set_attribute(SemanticConvention.SERVER_PORT, _OPENAI_SERVER_PORT)if capture_message_content:raw_input = getattr(span_data, "input", None)@@ -440,23 +462,14 @@ def _set_generation_attributes(span, span_data, capture_message_content):if isinstance(msg, dict):messages.append(msg)else:- messages.append(- {"role": "user", "content": truncate_content(str(msg))}- )+ messages.append(format_input_message("user", msg))span.set_attribute(SemanticConvention.GEN_AI_INPUT_MESSAGES, json.dumps(messages))else:span.set_attribute(SemanticConvention.GEN_AI_INPUT_MESSAGES,- json.dumps(- [- {- "role": "user",- "content": truncate_content(str(raw_input)),- }- ]- ),+ json.dumps([format_input_message("user", raw_input)]),)raw_output = getattr(span_data, "output", None)@@ -467,26 +480,14 @@ def _set_generation_attributes(span, span_data, capture_message_content):if isinstance(msg, dict):messages.append(msg)else:- messages.append(- {- "role": "assistant",- "content": truncate_content(str(msg)),- }- )+ messages.append(format_output_message(msg))span.set_attribute(SemanticConvention.GEN_AI_OUTPUT_MESSAGES, json.dumps(messages))else:span.set_attribute(SemanticConvention.GEN_AI_OUTPUT_MESSAGES,- json.dumps(- [- {- "role": "assistant",- "content": truncate_content(str(raw_output)),- }- ]- ),+ json.dumps([format_output_message(raw_output)]),)except Exception:pass@@ -574,22 +575,15 @@ def _set_transcription_attributes(span, span_data, capture_message_content):SemanticConvention.GEN_AI_OUTPUT_TYPE,SemanticConvention.GEN_AI_OUTPUT_TYPE_TEXT,)- span.set_attribute(SemanticConvention.SERVER_ADDRESS, "api.openai.com")- span.set_attribute(SemanticConvention.SERVER_PORT, 443)+ span.set_attribute(SemanticConvention.SERVER_ADDRESS, _OPENAI_SERVER_ADDRESS)+ span.set_attribute(SemanticConvention.SERVER_PORT, _OPENAI_SERVER_PORT)if capture_message_content:output = getattr(span_data, "output", None)if output:span.set_attribute(SemanticConvention.GEN_AI_OUTPUT_MESSAGES,- json.dumps(- [- {- "role": "assistant",- "content": truncate_content(str(output)),- }- ]- ),+ json.dumps([format_output_message(output)]),)except Exception:pass@@ -606,17 +600,15 @@ def _set_speech_attributes(span, span_data, capture_message_content):span.set_attribute(SemanticConvention.GEN_AI_RESPONSE_MODEL, str(model))span.set_attribute(SemanticConvention.GEN_AI_OUTPUT_TYPE, "speech")- span.set_attribute(SemanticConvention.SERVER_ADDRESS, "api.openai.com")- span.set_attribute(SemanticConvention.SERVER_PORT, 443)+ span.set_attribute(SemanticConvention.SERVER_ADDRESS, _OPENAI_SERVER_ADDRESS)+ span.set_attribute(SemanticConvention.SERVER_PORT, _OPENAI_SERVER_PORT)if capture_message_content:text_input = getattr(span_data, "input", None)if text_input:span.set_attribute(SemanticConvention.GEN_AI_INPUT_MESSAGES,- json.dumps(- [{"role": "user", "content": truncate_content(str(text_input))}]- ),+ json.dumps([format_input_message("user", text_input)]),)except Exception:passdiff --git a/sdk/python/src/openlit/instrumentation/premai/premai.py b/sdk/python/src/openlit/instrumentation/premai/premai.pyindex fbb4824f..be145e65 100644--- a/sdk/python/src/openlit/instrumentation/premai/premai.py+++ b/sdk/python/src/openlit/instrumentation/premai/premai.py@@ -3,6 +3,7 @@ Module for monitoring PremAI API calls."""import time+from opentelemetry import trace as trace_api, context as context_apifrom opentelemetry.trace import SpanKindfrom openlit.__helpers import (handle_exception,@@ -123,9 +124,17 @@ def chat(span_name = f"{SemanticConvention.GEN_AI_OPERATION_TYPE_CHAT} {request_model}"if streaming:- # Special handling for streaming response to accommodate the nature of data flow- awaited_wrapped = wrapped(*args, **kwargs)span = tracer.start_span(span_name, kind=SpanKind.CLIENT)+ ctx = trace_api.set_span_in_context(span)+ token = context_api.attach(ctx)+ try:+ awaited_wrapped = wrapped(*args, **kwargs)+ except Exception as e:+ handle_exception(span, e)+ context_api.detach(token)+ span.end()+ raise+ context_api.detach(token)return TracedSyncStream(awaited_wrapped, span, span_name, kwargs, server_address, server_port)diff --git a/sdk/python/src/openlit/instrumentation/sarvam/async_sarvam.py b/sdk/python/src/openlit/instrumentation/sarvam/async_sarvam.pyindex dd9895d3..211b9d63 100644--- a/sdk/python/src/openlit/instrumentation/sarvam/async_sarvam.py+++ b/sdk/python/src/openlit/instrumentation/sarvam/async_sarvam.py@@ -3,7 +3,7 @@ Module for monitoring async Sarvam AI API calls."""import time-from opentelemetry import context as context_api+from opentelemetry import trace as trace_api, context as context_apifrom opentelemetry.trace import SpanKindfrom openlit.__helpers import (handle_exception,@@ -132,8 +132,17 @@ def async_chat_completions(# pylint: disable=no-else-returnif streaming:- awaited_wrapped = await wrapped(*args, **kwargs)span = tracer.start_span(span_name, kind=SpanKind.CLIENT)+ ctx = trace_api.set_span_in_context(span)+ token = context_api.attach(ctx)+ try:+ awaited_wrapped = await wrapped(*args, **kwargs)+ except Exception as e:+ handle_exception(span, e)+ context_api.detach(token)+ span.end()+ raise+ context_api.detach(token)return TracedAsyncStream(awaited_wrapped,diff --git a/sdk/python/src/openlit/instrumentation/sarvam/sarvam.py b/sdk/python/src/openlit/instrumentation/sarvam/sarvam.pyindex 62dffd30..3159ccdb 100644--- a/sdk/python/src/openlit/instrumentation/sarvam/sarvam.py+++ b/sdk/python/src/openlit/instrumentation/sarvam/sarvam.py@@ -1,7 +1,7 @@"""Initializer of Auto Instrumentation of Sarvam AI Functions"""import time-from opentelemetry import context as context_api+from opentelemetry import trace as trace_api, context as context_apifrom opentelemetry.trace import SpanKindfrom openlit.__helpers import (@@ -131,8 +131,17 @@ def chat_completions(# pylint: disable=no-else-returnif streaming:- awaited_wrapped = wrapped(*args, **kwargs)span = tracer.start_span(span_name, kind=SpanKind.CLIENT)+ ctx = trace_api.set_span_in_context(span)+ token = context_api.attach(ctx)+ try:+ awaited_wrapped = wrapped(*args, **kwargs)+ except Exception as e:+ handle_exception(span, e)+ context_api.detach(token)+ span.end()+ raise+ context_api.detach(token)return TracedSyncStream(awaited_wrapped,diff --git a/sdk/python/src/openlit/instrumentation/smolagents/__init__.py b/sdk/python/src/openlit/instrumentation/smolagents/__init__.pynew file mode 100644index 00000000..f92eea7c--- /dev/null+++ b/sdk/python/src/openlit/instrumentation/smolagents/__init__.py@@ -0,0 +1,147 @@+"""+OpenLIT Smolagents Instrumentation — OTel GenAI semantic convention compliant.++Targets smolagents (HuggingFace's lightweight agent framework).+Uses wrapt monkey-patching for agent runs and tool calls.+LLM call spans are delegated to the underlying SDK instrumentors (OpenAI, etc.).+Patches ThreadPoolExecutor for correct context propagation in CodeAgent.+"""++from typing import Collection+import importlib.metadata+from opentelemetry.instrumentation.instrumentor import BaseInstrumentor+from wrapt import wrap_function_wrapper++from openlit.instrumentation.smolagents.smolagents import general_wrap++_instruments = ("smolagents >= 1.0.0",)++# === ALWAYS-ON OPERATIONS ===+# Each tuple: (module, method, operation_key)+WORKFLOW_OPERATIONS = [+ ("smolagents.agents", "MultiStepAgent.__init__", "agent_init"),+ ("smolagents.agents", "MultiStepAgent.run", "agent_run"),+ ("smolagents.agents", "ToolCallingAgent.execute_tool_call", "execute_tool_call"),+ ("smolagents.tools", "Tool.__call__", "tool_call"),+]++# === DETAILED-TRACING OPERATIONS ===+DETAILED_OPERATIONS = [+ ("smolagents.agents", "CodeAgent._step_stream", "code_step"),+ ("smolagents.agents", "ToolCallingAgent._step_stream", "tool_calling_step"),+ ("smolagents.agents", "MultiStepAgent._generate_planning_step", "planning_step"),+ ("smolagents.agents", "MultiStepAgent.__call__", "managed_agent_call"),+]+++class SmolAgentsInstrumentor(BaseInstrumentor):+ """OTel GenAI semantic convention compliant instrumentor for smolagents."""++ def __init__(self):+ super().__init__()+ self._original_executor_class = None++ def instrumentation_dependencies(self) -> Collection[str]:+ return _instruments++ def _instrument(self, **kwargs):+ try:+ version = importlib.metadata.version("smolagents")+ except importlib.metadata.PackageNotFoundError:+ version = "unknown"++ environment = kwargs.get("environment", "default")+ application_name = kwargs.get("application_name", "default")+ tracer = kwargs.get("tracer")+ pricing_info = kwargs.get("pricing_info", {})+ capture_message_content = kwargs.get("capture_message_content", False)+ metrics = kwargs.get("metrics_dict")+ disable_metrics = kwargs.get("disable_metrics")+ detailed_tracing = kwargs.get("detailed_tracing", False)++ wrap_args = (+ version,+ environment,+ application_name,+ tracer,+ pricing_info,+ capture_message_content,+ metrics,+ disable_metrics,+ )++ # -- Always-on operations --+ for module, method, op_key in WORKFLOW_OPERATIONS:+ try:+ wrapper = general_wrap(op_key, *wrap_args)+ wrap_function_wrapper(module, method, wrapper)+ except Exception:+ 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++ # -- ThreadPoolExecutor context propagation --+ self._install_context_propagation()++ def _install_context_propagation(self):+ """Patch ThreadPoolExecutor in smolagents to propagate contextvars.++ CodeAgent and ToolCallingAgent use ThreadPoolExecutor for parallel+ tool calls. Without this patch, child spans in worker threads lose+ their parent context.+ """+ try:+ import smolagents.local_python_executor as executor_module+ from concurrent.futures import ThreadPoolExecutor+ import contextvars++ original_cls = getattr(executor_module, "ThreadPoolExecutor", None)+ if original_cls is None:+ # Module may not use ThreadPoolExecutor directly; check agents+ try:+ import smolagents.agents as agents_module++ original_cls = getattr(agents_module, "ThreadPoolExecutor", None)+ if original_cls and original_cls is not ThreadPoolExecutor:+ return+ executor_module = agents_module+ except Exception:+ return++ if original_cls is None:+ return++ if getattr(original_cls, "_openlit_patched", False):+ return++ self._original_executor_class = (executor_module, original_cls)++ class _ContextAwareThreadPoolExecutor(ThreadPoolExecutor):+ """ThreadPoolExecutor that copies contextvars into workers."""++ _openlit_patched = True++ def submit(self, fn, /, *args, **kwargs):+ ctx = contextvars.copy_context()+ return super().submit(ctx.run, fn, *args, **kwargs)++ executor_module.ThreadPoolExecutor = _ContextAwareThreadPoolExecutor+ except Exception:+ pass++ def _uninstrument(self, **kwargs):+ """Best-effort restoration."""+ if self._original_executor_class is not None:+ try:+ module, cls = self._original_executor_class+ module.ThreadPoolExecutor = cls+ except Exception:+ pass+ self._original_executor_class = Nonediff --git a/sdk/python/src/openlit/instrumentation/smolagents/smolagents.py b/sdk/python/src/openlit/instrumentation/smolagents/smolagents.pynew file mode 100644index 00000000..febf537a--- /dev/null+++ b/sdk/python/src/openlit/instrumentation/smolagents/smolagents.py@@ -0,0 +1,691 @@+"""+Smolagents sync wrappers — OTel GenAI semantic convention compliant.++Handles agent runs (including streaming generators), LLM model calls,+tool execution, and per-step tracing.+"""++import time+import json+from opentelemetry import context as context_api+from opentelemetry.trace import Link, Status, StatusCode+from openlit.__helpers import (+ format_input_message,+ format_output_message,+ handle_exception,+)+from openlit.instrumentation.smolagents.utils import (+ process_smolagents_response,+ emit_create_agent_span,+ OPERATION_MAP,+ get_span_kind,+ generate_span_name,+ set_server_address_and_port,+ compute_model_info,+ _smolagents_agent_active,+ _smolagents_tool_call_active,+ _current_model_info,+ _extract_model_name,+ _record_smolagents_metrics,+ SemanticConvention,+)+++def general_wrap(+ gen_ai_endpoint,+ version,+ environment,+ application_name,+ tracer,+ pricing_info,+ capture_message_content,+ metrics,+ disable_metrics,+):+ """Create a sync wrapper for a smolagents operation."""++ def wrapper(wrapped, instance, args, kwargs):+ if context_api.get_value(context_api._SUPPRESS_INSTRUMENTATION_KEY):+ return wrapped(*args, **kwargs)++ # --- agent_init: agent construction → create_agent span ---+ if gen_ai_endpoint == "agent_init":+ result = wrapped(*args, **kwargs)+ try:+ ctx = emit_create_agent_span(+ tracer,+ instance,+ version,+ environment,+ application_name,+ capture_message_content,+ )+ if ctx is not None:+ instance._openlit_creation_context = ctx+ except Exception:+ pass+ return result++ # --- agent_run: root agent invocation ---+ if gen_ai_endpoint == "agent_run":+ return _handle_agent_run(+ wrapped,+ instance,+ args,+ kwargs,+ gen_ai_endpoint,+ version,+ environment,+ application_name,+ tracer,+ pricing_info,+ capture_message_content,+ metrics,+ disable_metrics,+ )++ # --- execute_tool_call: ToolCallingAgent dispatching a tool ---+ if gen_ai_endpoint == "execute_tool_call":+ return _handle_tool_call(+ wrapped,+ instance,+ args,+ kwargs,+ gen_ai_endpoint,+ version,+ environment,+ application_name,+ tracer,+ capture_message_content,+ metrics,+ disable_metrics,+ )++ # --- tool_call: Tool.__call__ low-level ---+ if gen_ai_endpoint == "tool_call":+ if _smolagents_tool_call_active.get():+ return wrapped(*args, **kwargs)+ return _handle_tool_call(+ wrapped,+ instance,+ args,+ kwargs,+ gen_ai_endpoint,+ version,+ environment,+ application_name,+ tracer,+ capture_message_content,+ metrics,+ disable_metrics,+ )++ # --- step-level spans (detailed_tracing) ---+ if gen_ai_endpoint in ("code_step", "tool_calling_step"):+ return _handle_step(+ wrapped,+ instance,+ args,+ kwargs,+ gen_ai_endpoint,+ version,+ environment,+ application_name,+ tracer,+ capture_message_content,+ metrics,+ disable_metrics,+ )++ # --- planning step ---+ if gen_ai_endpoint == "planning_step":+ return _handle_planning_step(+ wrapped,+ instance,+ args,+ kwargs,+ gen_ai_endpoint,+ version,+ environment,+ application_name,+ tracer,+ capture_message_content,+ metrics,+ disable_metrics,+ )++ # --- managed_agent_call: __call__ on managed sub-agent ---+ if gen_ai_endpoint == "managed_agent_call":+ if _smolagents_agent_active.get():+ return wrapped(*args, **kwargs)+ return _handle_agent_run(+ wrapped,+ instance,+ args,+ kwargs,+ gen_ai_endpoint,+ version,+ environment,+ application_name,+ tracer,+ pricing_info,+ capture_message_content,+ metrics,+ disable_metrics,+ )++ # Fallback: pass through+ return wrapped(*args, **kwargs)++ return wrapper+++# ---------------------------------------------------------------------------+# Agent run handler (supports streaming generators)+# ---------------------------------------------------------------------------+++def _handle_agent_run(+ wrapped,+ instance,+ args,+ kwargs,+ gen_ai_endpoint,+ version,+ environment,+ application_name,+ tracer,+ pricing_info,+ capture_message_content,+ metrics,+ disable_metrics,+):+ """Handle MultiStepAgent.run() with streaming and non-streaming paths."""+ server_address, server_port = set_server_address_and_port(instance)+ operation_type = OPERATION_MAP.get(gen_ai_endpoint, "invoke_agent")+ span_kind = get_span_kind(operation_type)+ span_name = generate_span_name(gen_ai_endpoint, instance, args, kwargs)++ # Propagate model info to child tool spans+ model_info_token = _current_model_info.set(compute_model_info(instance))+ agent_active_token = _smolagents_agent_active.set(True)++ # Span links: connect invoke_agent back to create_agent+ links = []+ creation_ctx = getattr(instance, "_openlit_creation_context", None)+ if creation_ctx:+ links = [Link(creation_ctx)]++ # Detect if stream=True from kwargs (or second positional arg)+ is_stream = kwargs.get("stream", False)+ if not is_stream and len(args) > 1:+ is_stream = args[1] if isinstance(args[1], bool) else False++ if is_stream:+ return _handle_agent_stream(+ wrapped,+ instance,+ args,+ kwargs,+ span_name,+ span_kind,+ tracer,+ operation_type,+ server_address,+ server_port,+ environment,+ application_name,+ metrics,+ capture_message_content,+ disable_metrics,+ version,+ gen_ai_endpoint,+ model_info_token,+ agent_active_token,+ links,+ )++ try:+ with tracer.start_as_current_span(+ span_name, kind=span_kind, links=links+ ) as span:+ start_time = time.time()+ try:+ response = wrapped(*args, **kwargs)++ # Aggregate token usage from agent monitor+ _set_agent_token_usage(span, instance)++ process_smolagents_response(+ response,+ operation_type,+ server_address,+ server_port,+ environment,+ application_name,+ metrics,+ start_time,+ span,+ capture_message_content,+ disable_metrics,+ version,+ instance,+ args,+ endpoint=gen_ai_endpoint,+ **kwargs,+ )+ return response++ except Exception as e:+ handle_exception(span, e)+ raise+ finally:+ _current_model_info.reset(model_info_token)+ _smolagents_agent_active.reset(agent_active_token)+++def _handle_agent_stream(+ wrapped,+ instance,+ args,+ kwargs,+ span_name,+ span_kind,+ tracer,+ operation_type,+ server_address,+ server_port,+ environment,+ application_name,+ metrics,+ capture_message_content,+ disable_metrics,+ version,+ gen_ai_endpoint,+ model_info_token,+ agent_active_token,+ links=None,+):+ """Wrap agent.run(stream=True) — hold span open across generator iteration."""++ def stream_wrapper():+ with tracer.start_as_current_span(+ span_name, kind=span_kind, links=links or []+ ) as span:+ start_time = time.time()++ span.set_attribute(+ SemanticConvention.GEN_AI_OPERATION,+ operation_type,+ )+ span.set_attribute(+ SemanticConvention.GEN_AI_PROVIDER_NAME,+ SemanticConvention.GEN_AI_SYSTEM_SMOLAGENTS,+ )++ model_name = _extract_model_name(instance)+ if model_name:+ span.set_attribute(SemanticConvention.GEN_AI_REQUEST_MODEL, model_name)++ agent_name = getattr(instance, "name", None) or type(instance).__name__+ span.set_attribute(SemanticConvention.GEN_AI_AGENT_NAME, str(agent_name))++ description = getattr(instance, "description", None)+ if description:+ span.set_attribute(+ SemanticConvention.GEN_AI_AGENT_DESCRIPTION, str(description)+ )++ max_steps = getattr(instance, "max_steps", None)+ if max_steps is not None:+ span.set_attribute("gen_ai.smolagents.max_steps", max_steps)++ tools = getattr(instance, "tools", None)+ if tools:+ from openlit.instrumentation.smolagents.utils import (+ _set_tool_definitions,+ )++ _set_tool_definitions(span, tools)++ if args:+ task = args[0]+ if task and capture_message_content:+ span.set_attribute(+ SemanticConvention.GEN_AI_INPUT_MESSAGES,+ json.dumps([format_input_message("user", task)]),+ )++ span.set_attribute(SemanticConvention.SERVER_ADDRESS, server_address)+ span.set_attribute(SemanticConvention.SERVER_PORT, server_port)+ span.set_attribute(SemanticConvention.GEN_AI_ENVIRONMENT, environment)+ span.set_attribute(+ SemanticConvention.GEN_AI_APPLICATION_NAME,+ application_name,+ )+ span.set_attribute(SemanticConvention.GEN_AI_SDK_VERSION, version)++ step_count = 0+ last_output = None++ try:+ stream_gen = wrapped(*args, **kwargs)+ for event in stream_gen:+ step_count += 1+ if hasattr(event, "action_output"):+ output = getattr(event, "action_output", None)+ if output is not None:+ last_output = output+ elif hasattr(event, "is_final_answer") and getattr(+ event, "is_final_answer", False+ ):+ last_output = getattr(event, "output", event)+ yield event++ # Finalize span after generator exhausted+ _set_agent_token_usage(span, instance)+ span.set_attribute("gen_ai.smolagents.step_count", step_count)++ if capture_message_content:+ output_text = None+ if last_output is not None:+ output_text = str(getattr(last_output, "output", last_output))+ elif hasattr(instance, "output") and instance.output is not None:+ output_text = str(instance.output)+ if output_text:+ span.set_attribute(+ SemanticConvention.GEN_AI_OUTPUT_MESSAGES,+ json.dumps([format_output_message(output_text)]),+ )++ span.set_attribute(+ SemanticConvention.GEN_AI_CLIENT_OPERATION_DURATION,+ time.time() - start_time,+ )+ span.set_attribute(+ SemanticConvention.GEN_AI_OUTPUT_TYPE,+ SemanticConvention.GEN_AI_OUTPUT_TYPE_TEXT,+ )+ span.set_status(Status(StatusCode.OK))++ if not disable_metrics and metrics:+ _record_smolagents_metrics(+ metrics,+ operation_type,+ time.time() - start_time,+ environment,+ application_name,+ model_name,+ server_address,+ server_port,+ )++ except Exception as e:+ handle_exception(span, e)+ raise+ finally:+ _current_model_info.reset(model_info_token)+ _smolagents_agent_active.reset(agent_active_token)++ return stream_wrapper()+++# ---------------------------------------------------------------------------+# Tool call handler+# ---------------------------------------------------------------------------+++def _handle_tool_call(+ wrapped,+ instance,+ args,+ kwargs,+ gen_ai_endpoint,+ version,+ environment,+ application_name,+ tracer,+ capture_message_content,+ metrics,+ disable_metrics,+):+ """Handle tool execution spans."""+ server_address, server_port = set_server_address_and_port(instance)+ operation_type = OPERATION_MAP.get(gen_ai_endpoint, "execute_tool")+ span_kind = get_span_kind(operation_type)+ span_name = generate_span_name(gen_ai_endpoint, instance, args, kwargs)++ # Set dedup flag so Tool.__call__ doesn't create a second span+ tool_active_token = None+ if gen_ai_endpoint == "execute_tool_call":+ tool_active_token = _smolagents_tool_call_active.set(True)++ try:+ with tracer.start_as_current_span(span_name, kind=span_kind) as span:+ start_time = time.time()+ try:+ response = wrapped(*args, **kwargs)++ process_smolagents_response(+ response,+ operation_type,+ server_address,+ server_port,+ environment,+ application_name,+ metrics,+ start_time,+ span,+ capture_message_content,+ disable_metrics,+ version,+ instance,+ args,+ endpoint=gen_ai_endpoint,+ **kwargs,+ )+ return response++ except Exception as e:+ handle_exception(span, e)+ raise+ finally:+ if tool_active_token is not None:+ _smolagents_tool_call_active.reset(tool_active_token)+++# ---------------------------------------------------------------------------+# Per-step handler (detailed_tracing)+# ---------------------------------------------------------------------------+++def _handle_step(+ wrapped,+ instance,+ args,+ kwargs,+ gen_ai_endpoint,+ version,+ environment,+ application_name,+ tracer,+ capture_message_content,+ metrics,+ disable_metrics,+):+ """Handle per-step spans for CodeAgent._step_stream / ToolCallingAgent._step_stream.++ _step_stream is a generator; we wrap it to hold the span open.+ """+ _server_address, _server_port = set_server_address_and_port(instance)+ operation_type = OPERATION_MAP.get(gen_ai_endpoint, "invoke_agent")+ span_kind = get_span_kind(operation_type)+ span_name = generate_span_name(gen_ai_endpoint, instance, args, kwargs)++ def step_generator():+ with tracer.start_as_current_span(span_name, kind=span_kind) as span:+ start_time = time.time()+ span.set_attribute(SemanticConvention.GEN_AI_OPERATION, operation_type)+ span.set_attribute(+ SemanticConvention.GEN_AI_PROVIDER_NAME,+ SemanticConvention.GEN_AI_SYSTEM_SMOLAGENTS,+ )+ agent_name = getattr(instance, "name", None) or type(instance).__name__+ span.set_attribute(SemanticConvention.GEN_AI_AGENT_NAME, str(agent_name))++ model_name = _extract_model_name(instance)+ if model_name:+ span.set_attribute(SemanticConvention.GEN_AI_REQUEST_MODEL, model_name)++ # Step number from ActionStep arg+ if args:+ step = args[0]+ step_number = getattr(step, "step_number", None)+ if step_number is not None:+ span.set_attribute(+ "gen_ai.smolagents.step_number",+ step_number,+ )++ try:+ yield from wrapped(*args, **kwargs)++ # After generator completes, capture step results+ if args:+ step = args[0]+ token_usage = getattr(step, "token_usage", None)+ if token_usage:+ input_tokens = getattr(token_usage, "input_tokens", None)+ output_tokens = getattr(token_usage, "output_tokens", None)+ if input_tokens is not None:+ span.set_attribute(+ SemanticConvention.GEN_AI_USAGE_INPUT_TOKENS,+ input_tokens,+ )+ if output_tokens is not None:+ span.set_attribute(+ SemanticConvention.GEN_AI_USAGE_OUTPUT_TOKENS,+ output_tokens,+ )++ error = getattr(step, "error", None)+ if error:+ span.set_attribute(+ SemanticConvention.ERROR_TYPE,+ type(error).__name__,+ )++ observations = getattr(step, "observations", None)+ if observations and capture_message_content:+ span.set_attribute(+ SemanticConvention.GEN_AI_OUTPUT_MESSAGES,+ json.dumps([format_output_message(observations)]),+ )++ span.set_attribute(+ SemanticConvention.GEN_AI_CLIENT_OPERATION_DURATION,+ time.time() - start_time,+ )+ span.set_status(Status(StatusCode.OK))++ except Exception as e:+ handle_exception(span, e)+ raise++ return step_generator()+++# ---------------------------------------------------------------------------+# Planning step handler (detailed_tracing)+# ---------------------------------------------------------------------------+++def _handle_planning_step(+ wrapped,+ instance,+ args,+ kwargs,+ gen_ai_endpoint,+ version,+ environment,+ application_name,+ tracer,+ capture_message_content,+ metrics,+ disable_metrics,+):+ """Handle planning step spans."""+ _server_address, _server_port = set_server_address_and_port(instance)+ operation_type = OPERATION_MAP.get(gen_ai_endpoint, "invoke_agent")+ span_kind = get_span_kind(operation_type)+ span_name = generate_span_name(gen_ai_endpoint, instance, args, kwargs)++ # _generate_planning_step is also a generator+ def planning_generator():+ with tracer.start_as_current_span(span_name, kind=span_kind) as span:+ start_time = time.time()+ span.set_attribute(SemanticConvention.GEN_AI_OPERATION, operation_type)+ span.set_attribute(+ SemanticConvention.GEN_AI_PROVIDER_NAME,+ SemanticConvention.GEN_AI_SYSTEM_SMOLAGENTS,+ )+ agent_name = getattr(instance, "name", None) or type(instance).__name__+ span.set_attribute(SemanticConvention.GEN_AI_AGENT_NAME, str(agent_name))+ span.set_attribute("gen_ai.smolagents.planning", True)++ try:+ yield from wrapped(*args, **kwargs)++ span.set_attribute(+ SemanticConvention.GEN_AI_CLIENT_OPERATION_DURATION,+ time.time() - start_time,+ )+ span.set_status(Status(StatusCode.OK))++ except Exception as e:+ handle_exception(span, e)+ raise++ return planning_generator()+++# ---------------------------------------------------------------------------+# Helpers+# ---------------------------------------------------------------------------+++def _set_agent_token_usage(span, instance):+ """Aggregate token usage from agent monitor and set on span."""+ try:+ monitor = getattr(instance, "monitor", None)+ if monitor:+ total_usage = getattr(monitor, "get_total_token_counts", None)+ if total_usage:+ usage = total_usage()+ input_tokens = getattr(usage, "input_tokens", None)+ output_tokens = getattr(usage, "output_tokens", None)+ if input_tokens:+ span.set_attribute(+ SemanticConvention.GEN_AI_USAGE_INPUT_TOKENS,+ input_tokens,+ )+ if output_tokens:+ span.set_attribute(+ SemanticConvention.GEN_AI_USAGE_OUTPUT_TOKENS,+ output_tokens,+ )+ else:+ input_count = getattr(monitor, "total_input_token_count", None)+ output_count = getattr(monitor, "total_output_token_count", None)+ if input_count:+ span.set_attribute(+ SemanticConvention.GEN_AI_USAGE_INPUT_TOKENS,+ input_count,+ )+ if output_count:+ span.set_attribute(+ SemanticConvention.GEN_AI_USAGE_OUTPUT_TOKENS,+ output_count,+ )+ except Exception:+ passdiff --git a/sdk/python/src/openlit/instrumentation/smolagents/utils.py b/sdk/python/src/openlit/instrumentation/smolagents/utils.pynew file mode 100644index 00000000..58ae2117--- /dev/null+++ b/sdk/python/src/openlit/instrumentation/smolagents/utils.py@@ -0,0 +1,631 @@+"""+Smolagents utilities for OTel GenAI semantic convention compliant telemetry.++Follows the same patterns as the CrewAI instrumentation.+All operation names, span kinds, and attributes comply with the OTel GenAI+semantic conventions (gen-ai-agent-spans).+"""++import time+import json+import uuid+import contextvars+from opentelemetry.trace import SpanKind, Status, StatusCode+from openlit.__helpers import (+ common_framework_span_attributes,+ format_input_message,+ format_output_message,+ format_system_instructions,+ get_server_address_for_provider,+ truncate_content,+)+from openlit.semcov import SemanticConvention++# ---------------------------------------------------------------------------+# Contextvars for span deduplication and model info propagation+# ---------------------------------------------------------------------------++# Prevents double-spanning when managed agent __call__ triggers run() internally+_smolagents_agent_active = contextvars.ContextVar(+ "openlit_smolagents_agent_active", default=False+)++# Prevents double tool spans: execute_tool_call wraps Tool.__call__ internally+_smolagents_tool_call_active = contextvars.ContextVar(+ "openlit_smolagents_tool_call_active", default=False+)++# Propagates the current agent's model info to child execute_tool spans+_current_model_info = contextvars.ContextVar(+ "openlit_smolagents_model_info", default=None+)++# ---------------------------------------------------------------------------+# OTel GenAI Operation Mapping+# ---------------------------------------------------------------------------+OPERATION_MAP = {+ "agent_init": "create_agent",+ "agent_run": "invoke_agent",+ "managed_agent_call": "invoke_agent",+ "code_step": "invoke_agent",+ "tool_calling_step": "invoke_agent",+ "planning_step": "invoke_agent",+ "execute_tool_call": "execute_tool",+ "tool_call": "execute_tool",+}++# ---------------------------------------------------------------------------+# SpanKind per operation type (OTel GenAI spec)+# ---------------------------------------------------------------------------+SPAN_KIND_MAP = {+ "invoke_agent": SpanKind.INTERNAL,+ "execute_tool": SpanKind.INTERNAL,+ "create_agent": SpanKind.CLIENT,+}++_MODEL_PREFIX_TO_PROVIDER = {+ "gpt-": "openai",+ "o1": "openai",+ "o3": "openai",+ "o4": "openai",+ "davinci": "openai",+ "claude": "anthropic",+ "gemini": "google",+ "mistral": "mistral_ai",+ "command": "cohere",+ "deepseek": "deepseek",+ "llama": "groq",+ "mixtral": "groq",+ "qwen": "huggingface",+}+++def get_span_kind(operation_type):+ """Return the correct SpanKind for *operation_type* per OTel GenAI spec."""+ return SPAN_KIND_MAP.get(operation_type, SpanKind.INTERNAL)+++def _infer_provider_from_model(model_name):+ """Map a model name string to a provider key."""+ if not model_name:+ return None+ lower = model_name.lower()+ for prefix, provider in _MODEL_PREFIX_TO_PROVIDER.items():+ if lower.startswith(prefix):+ return provider+ return None+++def _extract_model_name(instance):+ """Walk the instance hierarchy to find the LLM model name."""+ if not instance:+ return None++ # Direct model instance (Model.generate wrapping)+ model_id = getattr(instance, "model_id", None)+ if model_id:+ return str(model_id)++ # Agent instance: agent.model.model_id+ model = getattr(instance, "model", None)+ if model:+ model_id = getattr(model, "model_id", None)+ if model_id:+ return str(model_id)++ # Tool instance: inherit from parent agent via contextvar+ model_info = _current_model_info.get()+ if model_info:+ return model_info[0]++ return None+++def set_server_address_and_port(instance):+ """Extract server address / port from a smolagents instance's model config."""+ server_address = ""+ server_port = 0+ try:+ model = getattr(instance, "model", None) or instance++ # Try to get base_url / api_base from client+ client = getattr(model, "client", None)+ if client:+ base_url = getattr(client, "base_url", None)+ if base_url:+ from urllib.parse import urlparse++ parsed = urlparse(str(base_url))+ server_address = parsed.hostname or ""+ server_port = parsed.port or 443++ if not server_address:+ api_base = getattr(model, "api_base", None) or getattr(+ model, "base_url", None+ )+ if api_base:+ from urllib.parse import urlparse++ parsed = urlparse(str(api_base))+ server_address = parsed.hostname or ""+ server_port = parsed.port or 443++ if not server_address:+ model_name = _extract_model_name(instance)+ provider = _infer_provider_from_model(model_name)+ if provider:+ server_address, server_port = get_server_address_for_provider(provider)++ # Tool instances: inherit from parent agent via contextvar+ if not server_address:+ model_info = _current_model_info.get()+ if model_info and len(model_info) >= 3:+ server_address = model_info[1]+ server_port = model_info[2]+ except Exception:+ pass+ return server_address, server_port+++def compute_model_info(instance):+ """Return (model_name, server_address, server_port) for propagation."""+ model_name = _extract_model_name(instance)+ server_address, server_port = set_server_address_and_port(instance)+ return (model_name, server_address, server_port)+++def generate_span_name(endpoint, instance, args=None, kwargs=None):+ """Return an OTel-compliant span name: ``{operation} {entity_name}``."""+ operation = OPERATION_MAP.get(endpoint, "invoke_agent")++ if endpoint == "agent_init":+ name = getattr(instance, "name", None) or type(instance).__name__+ return f"{operation} {name}"++ if endpoint in ("agent_run", "managed_agent_call"):+ name = getattr(instance, "name", None) or type(instance).__name__+ return f"{operation} {name}"++ if endpoint in ("code_step", "tool_calling_step"):+ name = getattr(instance, "name", None) or type(instance).__name__+ step_num = ""+ if args:+ step = args[0] if args else None+ step_number = getattr(step, "step_number", None)+ if step_number is not None:+ step_num = f" step_{step_number}"+ return f"{operation} {name}{step_num}"++ if endpoint == "planning_step":+ name = getattr(instance, "name", None) or type(instance).__name__+ return f"{operation} {name} planning"++ if endpoint == "execute_tool_call":+ tool_name = args[0] if args else "unknown"+ return f"{operation} {tool_name}"++ if endpoint == "tool_call":+ name = getattr(instance, "name", None) or type(instance).__name__+ return f"{operation} {name}"++ return f"{operation} {endpoint}"+++# ---------------------------------------------------------------------------+# Main response processor+# ---------------------------------------------------------------------------+def process_smolagents_response(+ response,+ operation_type,+ server_address,+ server_port,+ environment,+ application_name,+ metrics,+ start_time,+ span,+ capture_message_content,+ disable_metrics,+ version,+ instance,+ args,+ endpoint=None,+ **kwargs,+):+ """Set OTel-compliant span attributes, capture content, and record metrics."""+ end_time = time.time()++ scope = type("Scope", (), {})()+ scope._span = span+ scope._start_time = start_time+ scope._end_time = end_time++ request_model = _extract_model_name(instance)++ class _ModelProxy: # pylint: disable=too-few-public-methods+ def __init__(self, orig, model):+ self._original = orig+ self.model_name = model++ def __getattr__(self, name):+ return getattr(self._original, name)++ proxy = _ModelProxy(instance, request_model) if instance else None++ common_framework_span_attributes(+ scope,+ SemanticConvention.GEN_AI_SYSTEM_SMOLAGENTS,+ server_address,+ server_port,+ environment,+ application_name,+ version,+ endpoint,+ proxy,+ )++ standard_operation = OPERATION_MAP.get(endpoint, "invoke_agent")+ span.set_attribute(SemanticConvention.GEN_AI_OPERATION, standard_operation)++ _set_agent_attributes(span, instance, endpoint, capture_message_content, args=args)+ _set_tool_attributes(+ span, instance, endpoint, capture_message_content, args, kwargs, response+ )++ if capture_message_content:+ _capture_content_as_attributes(span, instance, response, endpoint, args)++ span.set_attribute(+ SemanticConvention.GEN_AI_OUTPUT_TYPE,+ SemanticConvention.GEN_AI_OUTPUT_TYPE_TEXT,+ )++ if not disable_metrics and metrics:+ _record_smolagents_metrics(+ metrics,+ standard_operation,+ end_time - start_time,+ environment,+ application_name,+ request_model,+ server_address,+ server_port,+ )++ span.set_status(Status(StatusCode.OK))+ return response+++# ---------------------------------------------------------------------------+# Internal helpers for setting attributes+# ---------------------------------------------------------------------------+++def _set_agent_attributes(span, instance, endpoint, capture_message_content, args=None):+ """Agent attributes per OTel GenAI semantic conventions."""+ if endpoint not in (+ "agent_run",+ "managed_agent_call",+ "code_step",+ "tool_calling_step",+ "planning_step",+ ):+ return+ try:+ agent_name = getattr(instance, "name", None) or type(instance).__name__+ span.set_attribute(SemanticConvention.GEN_AI_AGENT_NAME, str(agent_name))+ agent_id = getattr(instance, "agent_id", None) or str(id(instance))+ span.set_attribute(SemanticConvention.GEN_AI_AGENT_ID, agent_id)++ description = getattr(instance, "description", None)+ if description:+ span.set_attribute(+ SemanticConvention.GEN_AI_AGENT_DESCRIPTION, str(description)+ )++ model = getattr(instance, "model", None)+ if model:+ model_id = getattr(model, "model_id", None)+ if model_id:+ mid = str(model_id)+ span.set_attribute(SemanticConvention.GEN_AI_REQUEST_MODEL, mid)+ span.set_attribute(SemanticConvention.GEN_AI_RESPONSE_MODEL, mid)++ instructions = getattr(instance, "instructions", None)+ if instructions and capture_message_content:+ formatted = format_system_instructions(instructions)+ if formatted:+ span.set_attribute(+ SemanticConvention.GEN_AI_SYSTEM_INSTRUCTIONS,+ formatted,+ )++ # Tool definitions+ tools = getattr(instance, "tools", None)+ if tools:+ _set_tool_definitions(span, tools)++ # Max steps+ max_steps = getattr(instance, "max_steps", None)+ if max_steps is not None:+ span.set_attribute("gen_ai.smolagents.max_steps", max_steps)++ # Step number for step-level spans+ if endpoint in ("code_step", "tool_calling_step") and args:+ step = args[0] if args else None+ step_number = getattr(step, "step_number", None)+ if step_number is not None:+ span.set_attribute("gen_ai.smolagents.step_number", step_number)+ except Exception:+ pass+++def _resolve_tool_call_id(args, kwargs):+ """Best-effort tool call id from invocation; UUID if none found."""+ if kwargs:+ for key in ("tool_call_id", "id", "call_id", "tool_use_id"):+ val = kwargs.get(key)+ if val is not None and str(val).strip():+ return str(val)+ if args and len(args) > 1:+ tool_args = args[1]+ if isinstance(tool_args, dict):+ for key in ("tool_call_id", "id", "call_id", "tool_use_id"):+ val = tool_args.get(key)+ if val is not None and str(val).strip():+ return str(val)+ return str(uuid.uuid4())+++def _set_tool_attributes(+ span, instance, endpoint, capture_message_content, args, kwargs, response+):+ """Tool attributes per OTel GenAI semantic conventions."""+ if endpoint not in ("tool_call", "execute_tool_call"):+ return+ try:+ if endpoint == "execute_tool_call":+ tool_name = args[0] if args else "unknown"+ span.set_attribute(SemanticConvention.GEN_AI_TOOL_NAME, str(tool_name))+ span.set_attribute(SemanticConvention.GEN_AI_TOOL_TYPE, "function")+ span.set_attribute(+ SemanticConvention.GEN_AI_TOOL_CALL_ID,+ _resolve_tool_call_id(args, kwargs or {}),+ )++ # Try to get tool description from agent's tools dict+ tools = getattr(instance, "tools", None) or {}+ managed = getattr(instance, "managed_agents", None) or {}+ all_tools = {**tools, **managed}+ tool = all_tools.get(tool_name)+ if tool:+ desc = getattr(tool, "description", None)+ if desc:+ span.set_attribute(+ SemanticConvention.GEN_AI_TOOL_DESCRIPTION,+ truncate_content(str(desc)),+ )++ if capture_message_content:+ tool_args = args[1] if len(args) > 1 else None+ if tool_args:+ try:+ arg_str = (+ json.dumps(tool_args)+ if isinstance(tool_args, (dict, list))+ else str(tool_args)+ )+ except (TypeError, ValueError):+ arg_str = str(tool_args)+ span.set_attribute(+ SemanticConvention.GEN_AI_TOOL_CALL_ARGUMENTS,+ truncate_content(arg_str),+ )+ if response is not None:+ span.set_attribute(+ SemanticConvention.GEN_AI_TOOL_CALL_RESULT,+ truncate_content(str(response)),+ )++ elif endpoint == "tool_call":+ name = getattr(instance, "name", None) or type(instance).__name__+ span.set_attribute(SemanticConvention.GEN_AI_TOOL_NAME, str(name))+ span.set_attribute(SemanticConvention.GEN_AI_TOOL_TYPE, "function")+ span.set_attribute(+ SemanticConvention.GEN_AI_TOOL_CALL_ID,+ _resolve_tool_call_id(args, kwargs or {}),+ )++ desc = getattr(instance, "description", None)+ if desc:+ span.set_attribute(+ SemanticConvention.GEN_AI_TOOL_DESCRIPTION,+ truncate_content(str(desc)),+ )++ if capture_message_content:+ if args or kwargs:+ try:+ call_args = (+ kwargs+ if kwargs+ else (args[0] if len(args) == 1 else list(args))+ )+ arg_str = json.dumps(call_args)+ except (TypeError, ValueError):+ arg_str = str(args) if args else str(kwargs)+ span.set_attribute(+ SemanticConvention.GEN_AI_TOOL_CALL_ARGUMENTS,+ truncate_content(arg_str),+ )+ if response is not None:+ span.set_attribute(+ SemanticConvention.GEN_AI_TOOL_CALL_RESULT,+ truncate_content(str(response)),+ )+ except Exception:+ pass+++def _set_tool_definitions(span, tools):+ """Set gen_ai.tool.definitions from agent's tools dict."""+ if not tools:+ return+ try:+ tool_list = tools.values() if isinstance(tools, dict) else tools+ tool_defs = []+ for tool in list(tool_list)[:10]:+ entry = {"type": "function"}+ name = getattr(tool, "name", None)+ if name:+ entry["name"] = str(name)+ desc = getattr(tool, "description", None)+ if desc:+ entry["description"] = truncate_content(str(desc))+ inputs = getattr(tool, "inputs", None)+ if inputs:+ entry["parameters"] = inputs+ if len(entry) > 1:+ tool_defs.append(entry)+ if tool_defs:+ span.set_attribute(+ SemanticConvention.GEN_AI_TOOL_DEFINITIONS, json.dumps(tool_defs)+ )+ except Exception:+ pass+++def _capture_content_as_attributes(span, instance, response, endpoint, args=None):+ """Record input/output as span attributes (JSON)."""+ try:+ if endpoint in ("agent_run", "managed_agent_call"):+ task = None+ if args:+ task = args[0] if args else None+ if task and hasattr(task, "task"):+ task = task.task+ if not task:+ task = getattr(instance, "task", None)+ if task:+ span.set_attribute(+ SemanticConvention.GEN_AI_INPUT_MESSAGES,+ json.dumps([format_input_message("user", task)]),+ )++ if response is not None and endpoint in ("agent_run", "managed_agent_call"):+ span.set_attribute(+ SemanticConvention.GEN_AI_OUTPUT_MESSAGES,+ json.dumps([format_output_message(response)]),+ )+ except Exception:+ pass+++def emit_create_agent_span(+ tracer,+ instance,+ version,+ environment,+ application_name,+ capture_message_content,+):+ """Emit a ``create_agent`` span for a smolagents agent instance.++ Returns the SpanContext so the caller can store it on+ ``instance._openlit_creation_context`` for linking from+ ``invoke_agent`` spans.+ """+ try:+ agent_name = getattr(instance, "name", None) or type(instance).__name__+ span_name = f"create_agent {agent_name}"++ server_address, server_port = set_server_address_and_port(instance)++ with tracer.start_as_current_span(span_name, kind=SpanKind.CLIENT) as span:+ span.set_attribute(+ SemanticConvention.GEN_AI_OPERATION,+ SemanticConvention.GEN_AI_OPERATION_TYPE_CREATE_AGENT,+ )+ span.set_attribute(+ SemanticConvention.GEN_AI_PROVIDER_NAME,+ SemanticConvention.GEN_AI_SYSTEM_SMOLAGENTS,+ )+ span.set_attribute(SemanticConvention.GEN_AI_AGENT_NAME, str(agent_name))+ span.set_attribute(SemanticConvention.GEN_AI_AGENT_ID, str(id(instance)))++ description = getattr(instance, "description", None)+ if description:+ span.set_attribute(+ SemanticConvention.GEN_AI_AGENT_DESCRIPTION,+ str(description),+ )++ model = getattr(instance, "model", None)+ if model:+ model_id = getattr(model, "model_id", None)+ if model_id:+ mid = str(model_id)+ span.set_attribute(SemanticConvention.GEN_AI_REQUEST_MODEL, mid)+ span.set_attribute(SemanticConvention.GEN_AI_RESPONSE_MODEL, mid)++ instructions = getattr(instance, "instructions", None)+ if instructions and capture_message_content:+ formatted = format_system_instructions(instructions)+ if formatted:+ span.set_attribute(+ SemanticConvention.GEN_AI_SYSTEM_INSTRUCTIONS,+ formatted,+ )++ tools = getattr(instance, "tools", None)+ if tools:+ _set_tool_definitions(span, tools)++ if server_address:+ span.set_attribute(SemanticConvention.SERVER_ADDRESS, server_address)+ if server_port:+ span.set_attribute(SemanticConvention.SERVER_PORT, server_port)++ span.set_attribute(SemanticConvention.GEN_AI_ENVIRONMENT, environment)+ span.set_attribute(+ SemanticConvention.GEN_AI_APPLICATION_NAME, application_name+ )+ span.set_attribute(SemanticConvention.GEN_AI_SDK_VERSION, version)+ span.set_status(Status(StatusCode.OK))++ return span.get_span_context()+ except Exception:+ return None+++def _record_smolagents_metrics(+ metrics,+ operation_type,+ duration,+ environment,+ application_name,+ request_model,+ server_address,+ server_port,+):+ """Record OTel-compliant metrics with correct attribute keys."""+ try:+ attributes = {+ SemanticConvention.GEN_AI_OPERATION: operation_type,+ SemanticConvention.GEN_AI_PROVIDER_NAME: (+ SemanticConvention.GEN_AI_SYSTEM_SMOLAGENTS+ ),+ "service.name": application_name,+ "deployment.environment": environment,+ }+ if request_model:+ attributes[SemanticConvention.GEN_AI_REQUEST_MODEL] = request_model+ if server_address:+ attributes[SemanticConvention.SERVER_ADDRESS] = server_address+ if server_port:+ attributes[SemanticConvention.SERVER_PORT] = server_port++ if "genai_client_operation_duration" in metrics:+ metrics["genai_client_operation_duration"].record(duration, attributes)+ except Exception:+ passdiff --git a/sdk/python/src/openlit/instrumentation/strands/__init__.py b/sdk/python/src/openlit/instrumentation/strands/__init__.pynew file mode 100644index 00000000..2680db39--- /dev/null+++ b/sdk/python/src/openlit/instrumentation/strands/__init__.py@@ -0,0 +1,77 @@+"""OpenLIT Strands Agents Instrumentation.++Uses a SpanProcessor to enrich Strands' native OTel spans with OpenLIT+attributes, content capture, inference log events, and metrics --+without any monkey-patching.+"""++import contextlib+import importlib.metadata+import logging+from typing import Collection++from opentelemetry import trace+from opentelemetry.instrumentation.instrumentor import BaseInstrumentor++from openlit.instrumentation.strands.processor import StrandsSpanProcessor++logger = logging.getLogger(__name__)++_instruments = ("strands-agents >= 0.1.0",)+++class StrandsInstrumentor(BaseInstrumentor):+ """OTel GenAI semantic-convention compliant instrumentor for Strands Agents."""++ def __init__(self):+ super().__init__()+ self._processor = None++ def instrumentation_dependencies(self) -> Collection[str]:+ return _instruments++ def _instrument(self, **kwargs):+ try:+ version = importlib.metadata.version("strands-agents")+ except importlib.metadata.PackageNotFoundError:+ version = "unknown"++ 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")+ disable_metrics = kwargs.get("disable_metrics")+ event_provider = kwargs.get("event_provider")+ pricing_info = kwargs.get("pricing_info")++ self._processor = StrandsSpanProcessor(+ version=version,+ environment=environment,+ application_name=application_name,+ capture_message_content=capture_message_content,+ metrics=metrics,+ disable_metrics=disable_metrics,+ event_provider=event_provider,+ pricing_info=pricing_info,+ )++ provider = trace.get_tracer_provider()+ multi = getattr(provider, "_active_span_processor", None)+ if multi and hasattr(multi, "_span_processors"):+ with getattr(multi, "_lock", contextlib.nullcontext()):+ multi._span_processors = (self._processor,) + multi._span_processors+ elif hasattr(provider, "add_span_processor"):+ provider.add_span_processor(self._processor)+ else:+ logger.warning(+ "TracerProvider does not support add_span_processor; "+ "Strands instrumentation will not be active."+ )++ def _uninstrument(self, **kwargs):+ if self._processor is not None:+ try:+ self._processor.shutdown()+ except Exception:+ pass+ self._processor = Nonediff --git a/sdk/python/src/openlit/instrumentation/strands/processor.py b/sdk/python/src/openlit/instrumentation/strands/processor.pynew file mode 100644index 00000000..29d1350a--- /dev/null+++ b/sdk/python/src/openlit/instrumentation/strands/processor.py@@ -0,0 +1,627 @@+"""Strands Agents SpanProcessor.++Enriches Strands' native OTel spans with OpenLIT-specific attributes,+extracts content from span events into span attributes, emits+``gen_ai.client.inference.operation.details`` log events for ``chat``+spans (matching the OpenAI instrumentation pattern), and records+OpenLIT metrics.++Provider-level chat spans (OpenAI, Anthropic, etc.) are suppressed+when they occur inside a Strands ``chat`` span via the shared+``_framework_llm_span_active`` ContextVar.+"""++import json+import logging+import threading+import types++from opentelemetry.sdk.resources import (+ SERVICE_NAME,+ TELEMETRY_SDK_NAME,+ DEPLOYMENT_ENVIRONMENT,+)+from opentelemetry.sdk.trace import SpanProcessor+from opentelemetry.trace import SpanKind+from opentelemetry.trace.status import StatusCode++from openlit.__helpers import (+ get_chat_model_cost,+ set_framework_llm_active,+ reset_framework_llm_active,+)+from openlit.semcov import SemanticConvention+from openlit.instrumentation.strands.utils import (+ emit_strands_inference_event,+ extract_content_from_events,+ infer_provider_name,+ infer_server_address,+ record_strands_metrics,+ truncate_content,+ truncate_message_content,+)++logger = logging.getLogger(__name__)++# The Strands SDK tracer uses ``__name__`` which resolves to this module path.+_STRANDS_TRACER_SCOPE = "strands.telemetry.tracer"+++class StrandsSpanProcessor(SpanProcessor):+ """Enriches Strands-generated spans with OpenLIT telemetry."""++ def __init__(+ self,+ version,+ environment,+ application_name,+ capture_message_content,+ metrics,+ disable_metrics,+ event_provider=None,+ pricing_info=None,+ ):+ self._version = version+ self._environment = environment+ self._application_name = application_name+ self._capture_message_content = capture_message_content+ self._metrics = metrics+ self._disable_metrics = disable_metrics+ self._event_provider = event_provider+ self._pricing_info = pricing_info+ self._fw_tokens_lock = threading.Lock()+ self._fw_tokens = {}+ self._chat_info_lock = threading.Lock()+ self._chat_info = {}++ # -----------------------------------------------------------------+ # Span detection+ # -----------------------------------------------------------------++ @staticmethod+ def _is_strands_span(span):+ """Return ``True`` if *span* was created by the Strands SDK tracer."""+ scope = getattr(span, "instrumentation_scope", None)+ if scope and getattr(scope, "name", None) == _STRANDS_TRACER_SCOPE:+ return True+ attrs = getattr(span, "attributes", None) or {}+ return (+ attrs.get("gen_ai.system") == SemanticConvention.GEN_AI_SYSTEM_STRANDS+ or attrs.get("gen_ai.provider.name")+ == SemanticConvention.GEN_AI_SYSTEM_STRANDS+ )++ # -----------------------------------------------------------------+ # Private helpers+ # -----------------------------------------------------------------++ @staticmethod+ def _set_attr(span, key, value):+ """Safely set an attribute on a ``ReadableSpan`` via ``_attributes``.++ After ``on_end`` the span is read-only; the only way to enrich it+ is to mutate the private ``_attributes`` mapping (a+ ``MappingProxyType``). This is the same pattern used by+ OpenInference and is wrapped in a try/except for safety.+ """+ try:+ raw = getattr(span, "_attributes", None)+ if raw is not None:+ new_attrs = dict(raw)+ new_attrs[key] = value+ span._attributes = types.MappingProxyType(new_attrs)+ except Exception:+ pass++ @staticmethod+ def _set_attrs(span, mapping):+ """Batch version of ``_set_attr``."""+ try:+ raw = getattr(span, "_attributes", None)+ if raw is not None:+ new_attrs = dict(raw)+ new_attrs.update(mapping)+ span._attributes = types.MappingProxyType(new_attrs)+ except Exception:+ pass++ # -----------------------------------------------------------------+ # SpanProcessor API+ # -----------------------------------------------------------------++ def on_start(self, span, parent_context=None):+ """Add static OpenLIT attributes while the span is still writable.++ For ``chat`` spans, sets ``_framework_llm_span_active`` so that+ provider-level instrumentors (OpenAI, Anthropic, ...) skip creating+ their own duplicate chat span.+ """+ if not self._is_strands_span(span):+ return++ try:+ span.set_attribute(TELEMETRY_SDK_NAME, "openlit")+ 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)+ except Exception:+ pass++ if getattr(span, "name", "") == "chat":+ try:+ span._kind = SpanKind.CLIENT+ except Exception:+ pass+ try:+ token = set_framework_llm_active()+ span_id = span.get_span_context().span_id+ with self._fw_tokens_lock:+ self._fw_tokens[span_id] = token+ except Exception:+ pass++ def on_end(self, span):+ """Enrich the finished span with derived attributes and record metrics."""+ if not self._is_strands_span(span):+ return++ span_id = getattr(getattr(span, "context", None), "span_id", None)+ if span_id is not None:+ with self._fw_tokens_lock:+ fw_token = self._fw_tokens.pop(span_id, None)+ if fw_token is not None:+ try:+ reset_framework_llm_active(fw_token)+ except Exception:+ pass++ try:+ self._process_span(span)+ except Exception:+ logger.debug("Error processing Strands span", exc_info=True)++ def shutdown(self):+ """No-op; nothing to clean up."""++ def force_flush(self, timeout_millis=None):+ """No-op."""++ # -----------------------------------------------------------------+ # Core processing+ # -----------------------------------------------------------------++ def _process_span(self, span):+ attrs = span.attributes or {}+ operation = attrs.get("gen_ai.operation.name", "")++ agent_name = attrs.get(SemanticConvention.GEN_AI_AGENT_NAME)+ if agent_name and not attrs.get(SemanticConvention.GEN_AI_AGENT_ID):+ span_id_hex = format(span.context.span_id, "016x")+ self._set_attr(+ span,+ SemanticConvention.GEN_AI_AGENT_ID,+ f"{agent_name}-{span_id_hex}",+ )++ # Normalize gen_ai.system → gen_ai.provider.name (use semconv constant+ # for the framework provider so hyphen/underscore stays consistent)+ gen_ai_system = attrs.get("gen_ai.system", "")+ if gen_ai_system and not attrs.get(SemanticConvention.GEN_AI_PROVIDER_NAME):+ if gen_ai_system in ("strands-agents", "strands_agents"):+ provider = SemanticConvention.GEN_AI_SYSTEM_STRANDS+ else:+ provider = gen_ai_system+ self._set_attr(span, SemanticConvention.GEN_AI_PROVIDER_NAME, provider)++ # Normalize Strands-native cache token keys → OTel standard keys+ _CACHE_KEY_MAP = {+ "gen_ai.usage.cache_read_input_tokens": SemanticConvention.GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS,+ "gen_ai.usage.cache_write_input_tokens": SemanticConvention.GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS,+ }+ for strands_key, otel_key in _CACHE_KEY_MAP.items():+ val = attrs.get(strands_key)+ if val is not None and not attrs.get(otel_key):+ self._set_attr(span, otel_key, val)++ # Remap Strands-native system_prompt → gen_ai.system_instructions+ if operation == "invoke_agent":+ system_prompt = attrs.get("system_prompt")+ if system_prompt and not attrs.get(+ SemanticConvention.GEN_AI_SYSTEM_INSTRUCTIONS+ ):+ self._set_attr(+ span, SemanticConvention.GEN_AI_SYSTEM_INSTRUCTIONS, system_prompt+ )++ # Duration (nanoseconds → seconds)+ duration = 0.0+ if span.end_time and span.start_time:+ duration = (span.end_time - span.start_time) / 1e9+ self._set_attr(+ span, SemanticConvention.GEN_AI_CLIENT_OPERATION_DURATION, duration+ )++ # Server address / port (inferred from model name)+ model_name = attrs.get("gen_ai.request.model", "")+ server_address = attrs.get(SemanticConvention.SERVER_ADDRESS, "")+ server_port = attrs.get(SemanticConvention.SERVER_PORT, 0)+ if not server_address and model_name:+ server_address, server_port = infer_server_address(model_name)+ if server_address:+ self._set_attrs(+ span,+ {+ SemanticConvention.SERVER_ADDRESS: server_address,+ SemanticConvention.SERVER_PORT: server_port,+ },+ )++ # Normalize multi-agent operation names to invoke_workflow+ if operation in ("invoke_swarm", "invoke_graph"):+ workflow_name = attrs.get("gen_ai.agent.name", "")+ self._set_attrs(+ span,+ {+ SemanticConvention.GEN_AI_OPERATION: SemanticConvention.GEN_AI_OPERATION_TYPE_FRAMEWORK,+ SemanticConvention.GEN_AI_WORKFLOW_NAME: workflow_name,+ },+ )+ operation = "invoke_workflow"++ # Output type for agent / workflow spans+ if operation in ("invoke_agent", "invoke_workflow"):+ self._set_attr(+ span,+ SemanticConvention.GEN_AI_OUTPUT_TYPE,+ SemanticConvention.GEN_AI_OUTPUT_TYPE_TEXT,+ )++ # Tool type and tool call id (Strands-native attrs / events)+ if operation == "execute_tool":+ self._set_attr(span, SemanticConvention.GEN_AI_TOOL_TYPE, "function")+ if not attrs.get(SemanticConvention.GEN_AI_TOOL_CALL_ID):+ tid = (+ attrs.get("tool_use_id")+ or attrs.get("toolUseId")+ or attrs.get("gen_ai.tool.call.id")+ )+ if not tid:+ tid = self._extract_tool_call_id_from_span_events(span)+ if tid:+ self._set_attr(+ span, SemanticConvention.GEN_AI_TOOL_CALL_ID, str(tid)+ )++ # OTel-compliant span names (read attrs after normalization / _set_attrs)+ self._set_otel_compliant_span_name(span, operation)++ # Chat span enrichment: match provider span attributes+ if operation == "chat":+ self._enrich_chat_span(span, attrs, model_name)+ self._store_chat_info_for_parent(span, model_name)++ # Propagate recommended attrs from child chat spans to invoke_agent+ if operation == "invoke_agent":+ self._enrich_agent_from_children(span)++ # Content capture: extract from events → span attributes+ if self._capture_message_content:+ self._extract_and_set_content(span, operation)++ # Emit inference log event for chat spans (provider span is+ # suppressed, so this processor is the single source of truth)+ if operation == "chat" and self._event_provider:+ self._emit_chat_inference_event(span, attrs, server_address, server_port)++ # Record OpenLIT metrics (skip spans without a recognized operation)+ if not self._disable_metrics and self._metrics and operation:+ record_strands_metrics(+ self._metrics,+ operation,+ duration,+ self._environment,+ self._application_name,+ model_name,+ server_address,+ server_port,+ )++ if span.status and span.status.status_code == StatusCode.ERROR:+ current_attrs = span.attributes or {}+ if SemanticConvention.ERROR_TYPE not in current_attrs:+ self._set_attr(+ span,+ SemanticConvention.ERROR_TYPE,+ span.status.description or "_OTHER",+ )++ def _set_otel_compliant_span_name(self, span, operation):+ """Rename Strands spans to OTel gen_ai patterns (parity with ``chat {model}``)."""+ if operation not in ("invoke_agent", "execute_tool", "invoke_workflow"):+ return+ try:+ attrs = span.attributes or {}+ if operation == "invoke_agent":+ agent_name = attrs.get(SemanticConvention.GEN_AI_AGENT_NAME, "")+ if agent_name:+ span._name = f"invoke_agent {agent_name}"+ elif operation == "execute_tool":+ tool_name = attrs.get(SemanticConvention.GEN_AI_TOOL_NAME, "")+ if tool_name:+ span._name = f"execute_tool {tool_name}"+ elif operation == "invoke_workflow":+ workflow_name = attrs.get(SemanticConvention.GEN_AI_WORKFLOW_NAME, "")+ if workflow_name:+ span._name = f"invoke_workflow {workflow_name}"+ except Exception:+ pass++ # -----------------------------------------------------------------+ # Chat span enrichment (parity with provider spans)+ # -----------------------------------------------------------------++ def _enrich_chat_span(self, span, attrs, model_name):+ """Add attributes to chat spans that match provider-level chat spans."""+ enrichments = {}++ # Span name: "chat" → "chat {model}" (matching OpenAI pattern)+ if model_name:+ try:+ span._name = f"chat {model_name}"+ except Exception:+ pass++ # Override gen_ai.provider.name with actual provider for chat spans+ provider = infer_provider_name(model_name) if model_name else ""+ if provider:+ enrichments[SemanticConvention.GEN_AI_PROVIDER_NAME] = provider++ # response.model: use existing attr or fall back to request model+ if not attrs.get(SemanticConvention.GEN_AI_RESPONSE_MODEL) and model_name:+ enrichments[SemanticConvention.GEN_AI_RESPONSE_MODEL] = model_name++ # response.id: propagate from existing attrs or extract from events+ if not attrs.get(SemanticConvention.GEN_AI_RESPONSE_ID):+ response_id = self._extract_response_id(span)+ if response_id:+ enrichments[SemanticConvention.GEN_AI_RESPONSE_ID] = response_id++ # Finish reasons from output events+ _, output_msgs, _ = extract_content_from_events(span, "chat")+ if output_msgs:+ finish_reasons = [+ m.get("finish_reason")+ for m in output_msgs+ if isinstance(m, dict) and m.get("finish_reason")+ ]+ if finish_reasons:+ enrichments[SemanticConvention.GEN_AI_RESPONSE_FINISH_REASON] = (+ finish_reasons+ )++ enrichments[SemanticConvention.GEN_AI_OUTPUT_TYPE] = (+ SemanticConvention.GEN_AI_OUTPUT_TYPE_TEXT+ )++ # Token totals and cost+ input_tokens = attrs.get("gen_ai.usage.input_tokens", 0)+ output_tokens = attrs.get("gen_ai.usage.output_tokens", 0)+ if input_tokens or output_tokens:+ enrichments[SemanticConvention.GEN_AI_CLIENT_TOKEN_USAGE] = int(+ input_tokens+ ) + int(output_tokens)+ if self._pricing_info and model_name:+ cost = get_chat_model_cost(+ model_name, self._pricing_info, input_tokens, output_tokens+ )+ enrichments[SemanticConvention.GEN_AI_USAGE_COST] = cost++ if enrichments:+ self._set_attrs(span, enrichments)++ def _store_chat_info_for_parent(self, span, model_name):+ """Store enriched chat span data keyed by parent span ID."""+ try:+ parent_ctx = getattr(span, "parent", None)+ parent_id = getattr(parent_ctx, "span_id", None) if parent_ctx else None+ if parent_id is None:+ return+ final_attrs = span.attributes or {}+ info = {+ "response_model": final_attrs.get(+ SemanticConvention.GEN_AI_RESPONSE_MODEL, model_name+ ),+ "response_id": final_attrs.get(SemanticConvention.GEN_AI_RESPONSE_ID),+ "finish_reasons": final_attrs.get(+ SemanticConvention.GEN_AI_RESPONSE_FINISH_REASON+ ),+ "input_tokens": final_attrs.get("gen_ai.usage.input_tokens", 0),+ "output_tokens": final_attrs.get("gen_ai.usage.output_tokens", 0),+ }+ with self._chat_info_lock:+ self._chat_info[parent_id] = info+ except Exception:+ pass++ def _enrich_agent_from_children(self, span):+ """Propagate recommended attributes from last child chat span."""+ try:+ span_id = getattr(getattr(span, "context", None), "span_id", None)+ if span_id is None:+ return+ with self._chat_info_lock:+ info = self._chat_info.pop(span_id, None)+ if not info:+ return+ enrichments = {}+ current = span.attributes or {}+ if info.get("response_model") and not current.get(+ SemanticConvention.GEN_AI_RESPONSE_MODEL+ ):+ enrichments[SemanticConvention.GEN_AI_RESPONSE_MODEL] = info[+ "response_model"+ ]+ if info.get("response_id") and not current.get(+ SemanticConvention.GEN_AI_RESPONSE_ID+ ):+ enrichments[SemanticConvention.GEN_AI_RESPONSE_ID] = info["response_id"]+ if info.get("finish_reasons") and not current.get(+ SemanticConvention.GEN_AI_RESPONSE_FINISH_REASON+ ):+ enrichments[SemanticConvention.GEN_AI_RESPONSE_FINISH_REASON] = info[+ "finish_reasons"+ ]+ if enrichments:+ self._set_attrs(span, enrichments)+ except Exception:+ pass++ @staticmethod+ def _extract_response_id(span):+ """Try to extract a response ID from span events."""+ for event in span.events or []:+ ea = event.attributes or {}+ rid = ea.get("gen_ai.response.id") or ea.get("response_id")+ if rid:+ return str(rid)+ return ""++ @staticmethod+ def _extract_tool_call_id_from_span_events(span):+ """Best-effort tool call id from Strands span events."""+ for event in span.events or []:+ if event.name == "gen_ai.tool.message":+ ea = event.attributes or {}+ tid = ea.get("id") or ea.get(SemanticConvention.GEN_AI_TOOL_CALL_ID)+ if tid:+ return str(tid)+ for event in span.events or []:+ ea = event.attributes or {}+ tid = (+ ea.get(SemanticConvention.GEN_AI_TOOL_CALL_ID)+ or ea.get("tool_use_id")+ or ea.get("toolUseId")+ or ea.get("gen_ai.tool.call.id")+ )+ if tid:+ return str(tid)+ return None++ # -----------------------------------------------------------------+ # Content extraction → span attributes+ # -----------------------------------------------------------------++ def _extract_and_set_content(self, span, operation):+ """Extract messages from span events and set as span attributes."""+ try:+ input_msgs, output_msgs, system_instr = extract_content_from_events(+ span, operation+ )++ additions = {}++ if operation == "execute_tool":+ # For tool spans: map to tool-specific attributes+ if input_msgs:+ first = (+ input_msgs[0] if isinstance(input_msgs, list) else input_msgs+ )+ parts = first.get("parts", []) if isinstance(first, dict) else []+ if parts:+ arguments = parts[0].get(+ "arguments", parts[0].get("response", "")+ )+ additions[SemanticConvention.GEN_AI_TOOL_CALL_ARGUMENTS] = (+ truncate_content(+ json.dumps(arguments)+ if not isinstance(arguments, str)+ else arguments+ )+ )+ if output_msgs:+ additions[SemanticConvention.GEN_AI_TOOL_CALL_RESULT] = (+ truncate_content(json.dumps(output_msgs))+ )+ else:+ if input_msgs:+ truncate_message_content(input_msgs)+ additions[SemanticConvention.GEN_AI_INPUT_MESSAGES] = json.dumps(+ input_msgs+ )+ if output_msgs:+ truncate_message_content(output_msgs)+ additions[SemanticConvention.GEN_AI_OUTPUT_MESSAGES] = json.dumps(+ output_msgs+ )+ if system_instr:+ additions[SemanticConvention.GEN_AI_SYSTEM_INSTRUCTIONS] = (+ truncate_content(str(system_instr))+ )++ if additions:+ self._set_attrs(span, additions)+ except Exception:+ logger.debug("Error extracting Strands content", exc_info=True)++ # -----------------------------------------------------------------+ # Chat inference log event+ # -----------------------------------------------------------------++ def _emit_chat_inference_event(self, span, attrs, server_address, server_port):+ """Emit ``gen_ai.client.inference.operation.details`` for chat spans."""+ try:+ input_msgs, output_msgs, system_instr = extract_content_from_events(+ span, "chat"+ )++ extra = {}++ input_tokens = attrs.get("gen_ai.usage.input_tokens")+ output_tokens = attrs.get("gen_ai.usage.output_tokens")+ if input_tokens is not None:+ extra["input_tokens"] = input_tokens+ if output_tokens is not None:+ extra["output_tokens"] = output_tokens++ cache_read = attrs.get(+ SemanticConvention.GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS+ ) or attrs.get("gen_ai.usage.cache_read_input_tokens")+ cache_write = attrs.get(+ SemanticConvention.GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS+ ) or attrs.get("gen_ai.usage.cache_write_input_tokens")+ if cache_read is not None:+ extra["cache_read_input_tokens"] = cache_read+ if cache_write is not None:+ extra["cache_creation_input_tokens"] = cache_write++ response_id = attrs.get(+ SemanticConvention.GEN_AI_RESPONSE_ID+ ) or self._extract_response_id(span)+ if response_id:+ extra["response_id"] = response_id++ if system_instr:+ extra["system_instructions"] = system_instr++ # Finish reason from output messages+ if output_msgs:+ finish_reasons = [+ m.get("finish_reason")+ for m in output_msgs+ if isinstance(m, dict) and m.get("finish_reason")+ ]+ if finish_reasons:+ extra["finish_reasons"] = finish_reasons++ emit_strands_inference_event(+ event_provider=self._event_provider,+ operation_name=SemanticConvention.GEN_AI_OPERATION_TYPE_CHAT,+ request_model=attrs.get("gen_ai.request.model"),+ input_messages=input_msgs if self._capture_message_content else None,+ output_messages=output_msgs if self._capture_message_content else None,+ server_address=server_address,+ server_port=server_port,+ **extra,+ )+ except Exception:+ logger.debug("Error emitting Strands inference event", exc_info=True)diff --git a/sdk/python/src/openlit/instrumentation/strands/utils.py b/sdk/python/src/openlit/instrumentation/strands/utils.pynew file mode 100644index 00000000..dc096b83--- /dev/null+++ b/sdk/python/src/openlit/instrumentation/strands/utils.py@@ -0,0 +1,328 @@+"""Strands Agents instrumentation utilities.++Provides model-to-provider mapping, server address inference, content+extraction from Strands native span events, and metrics recording.+"""++import json+import logging++from openlit.__helpers import (+ get_server_address_for_provider,+ otel_event,+)+from openlit.semcov import SemanticConvention++logger = logging.getLogger(__name__)++# -------------------------------------------------------------------------+# Model prefix → provider mapping (used to infer server address / port)+# -------------------------------------------------------------------------+_MODEL_PREFIX_TO_PROVIDER = {+ "anthropic.": "aws.bedrock",+ "amazon.": "aws.bedrock",+ "meta.": "aws.bedrock",+ "us.anthropic.": "aws.bedrock",+ "us.amazon.": "aws.bedrock",+ "us.meta.": "aws.bedrock",+ "eu.anthropic.": "aws.bedrock",+ "eu.amazon.": "aws.bedrock",+ "eu.meta.": "aws.bedrock",+ "gpt-": "openai",+ "o1": "openai",+ "o3": "openai",+ "o4": "openai",+ "claude": "anthropic",+ "gemini": "google",+ "mistral": "mistral_ai",+ "command": "cohere",+ "deepseek": "deepseek",+}+++def infer_server_address(model_name):+ """Return ``(server_address, server_port)`` inferred from *model_name*."""+ if not model_name:+ return "", 0+ lower = str(model_name).lower()+ for prefix, provider in _MODEL_PREFIX_TO_PROVIDER.items():+ if lower.startswith(prefix):+ return get_server_address_for_provider(provider)+ return "", 0+++def infer_provider_name(model_name):+ """Return a provider name (e.g. ``"openai"``) inferred from *model_name*."""+ if not model_name:+ return ""+ lower = str(model_name).lower()+ for prefix, provider in _MODEL_PREFIX_TO_PROVIDER.items():+ if lower.startswith(prefix):+ return provider+ return ""+++# -------------------------------------------------------------------------+# Content extraction from Strands span events+# -------------------------------------------------------------------------+++def _safe_json_loads(value):+ """Parse *value* as JSON if it is a string, otherwise return as-is."""+ if isinstance(value, str):+ try:+ return json.loads(value)+ except (json.JSONDecodeError, TypeError):+ return value+ return value+++def _convert_strands_content_to_parts(content):+ """Convert Strands Bedrock-style content blocks to OTel message parts."""+ blocks = _safe_json_loads(content)+ if not isinstance(blocks, list):+ blocks = [blocks] if blocks else []++ parts = []+ for block in blocks:+ if isinstance(block, dict):+ if "text" in block:+ parts.append({"type": "text", "content": block["text"]})+ elif "toolUse" in block:+ tu = block["toolUse"]+ parts.append(+ {+ "type": "tool_call",+ "id": tu.get("toolUseId", ""),+ "name": tu.get("name", ""),+ "arguments": tu.get("input", {}),+ }+ )+ elif "toolResult" in block:+ tr = block["toolResult"]+ parts.append(+ {+ "type": "tool_call_response",+ "id": tr.get("toolUseId", ""),+ "response": tr.get("content", ""),+ }+ )+ else:+ for key, value in block.items():+ parts.append({"type": key, "content": value})+ elif isinstance(block, str):+ parts.append({"type": "text", "content": block})++ return parts or [{"type": "text", "content": str(content)}]+++def extract_content_from_events(span, operation):+ """Extract message content from Strands span events.++ Handles both *legacy* (named events like ``gen_ai.user.message``) and+ *latest experimental* (``gen_ai.client.inference.operation.details``)+ convention modes.++ Returns:+ tuple: ``(input_messages, output_messages, system_instructions)``+ where each messages list follows the OTel structured format+ and *system_instructions* is a string or ``None``.+ """+ input_msgs = []+ output_msgs = []+ system_instructions = None++ for event in span.events or []:+ event_attrs = event.attributes or {}++ if event.name == "gen_ai.client.inference.operation.details":+ if "gen_ai.input.messages" in event_attrs:+ raw = _safe_json_loads(event_attrs["gen_ai.input.messages"])+ if isinstance(raw, list):+ input_msgs = raw+ else:+ input_msgs = [raw] if raw else []+ if "gen_ai.output.messages" in event_attrs:+ raw = _safe_json_loads(event_attrs["gen_ai.output.messages"])+ if isinstance(raw, list):+ output_msgs = raw+ else:+ output_msgs = [raw] if raw else []+ if "gen_ai.system_instructions" in event_attrs:+ system_instructions = event_attrs["gen_ai.system_instructions"]+ continue++ if event.name == "gen_ai.system.message":+ content = event_attrs.get("content", "")+ system_instructions = content+ elif event.name == "gen_ai.user.message":+ content = event_attrs.get("content", "")+ parts = _convert_strands_content_to_parts(content)+ input_msgs.append({"role": "user", "parts": parts})+ elif event.name == "gen_ai.assistant.message":+ content = event_attrs.get("content", "")+ parts = _convert_strands_content_to_parts(content)+ input_msgs.append({"role": "assistant", "parts": parts})+ elif event.name == "gen_ai.tool.message":+ content = event_attrs.get("content", "")+ tool_id = event_attrs.get("id", "")+ if operation == "execute_tool":+ input_msgs.append(+ {+ "role": "tool",+ "parts": [+ {+ "type": "tool_call",+ "id": tool_id,+ "name": "",+ "arguments": _safe_json_loads(content),+ }+ ],+ }+ )+ else:+ input_msgs.append(+ {+ "role": "tool",+ "parts": [+ {+ "type": "tool_call_response",+ "id": tool_id,+ "response": _safe_json_loads(content),+ }+ ],+ }+ )+ elif event.name == "gen_ai.choice":+ message = event_attrs.get("message", "")+ finish_reason = event_attrs.get("finish_reason", "")+ if operation == "execute_tool":+ output_msgs.append(+ {+ "role": "tool",+ "parts": _convert_strands_content_to_parts(message),+ }+ )+ else:+ parts = _convert_strands_content_to_parts(message)+ entry = {"role": "assistant", "parts": parts}+ if finish_reason:+ entry["finish_reason"] = str(finish_reason)+ output_msgs.append(entry)++ return input_msgs, output_msgs, system_instructions+++# -------------------------------------------------------------------------+# Inference log event emission (matching OpenAI pattern)+# -------------------------------------------------------------------------+++def emit_strands_inference_event(+ event_provider,+ operation_name,+ request_model,+ input_messages=None,+ output_messages=None,+ server_address=None,+ server_port=None,+ **extra_attrs,+):+ """Emit ``gen_ai.client.inference.operation.details`` log event.++ Mirrors :func:`openlit.instrumentation.openai.utils.emit_inference_event`+ so that chat telemetry from Strands is identical to OpenAI in+ observability backends.+ """+ try:+ if not event_provider:+ return++ attributes = {+ SemanticConvention.GEN_AI_OPERATION: operation_name,+ }++ if request_model:+ attributes[SemanticConvention.GEN_AI_REQUEST_MODEL] = request_model++ if server_address:+ attributes[SemanticConvention.SERVER_ADDRESS] = server_address+ if server_port:+ attributes[SemanticConvention.SERVER_PORT] = server_port++ if input_messages is not None:+ attributes[SemanticConvention.GEN_AI_INPUT_MESSAGES] = input_messages+ if output_messages is not None:+ attributes[SemanticConvention.GEN_AI_OUTPUT_MESSAGES] = output_messages++ for key, value in extra_attrs.items():+ if value is None:+ continue+ if key == "response_id":+ attributes[SemanticConvention.GEN_AI_RESPONSE_ID] = value+ elif key == "finish_reasons":+ attributes[SemanticConvention.GEN_AI_RESPONSE_FINISH_REASON] = value+ elif key == "input_tokens":+ attributes[SemanticConvention.GEN_AI_USAGE_INPUT_TOKENS] = value+ elif key == "output_tokens":+ attributes[SemanticConvention.GEN_AI_USAGE_OUTPUT_TOKENS] = value+ elif key == "cache_creation_input_tokens":+ attributes[+ SemanticConvention.GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS+ ] = value+ elif key == "cache_read_input_tokens":+ attributes[SemanticConvention.GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS] = (+ value+ )+ elif key == "system_instructions":+ attributes[SemanticConvention.GEN_AI_SYSTEM_INSTRUCTIONS] = value+ elif key == "tool_definitions":+ attributes[SemanticConvention.GEN_AI_TOOL_DEFINITIONS] = value+ else:+ attributes[key] = value++ event = otel_event(+ name=SemanticConvention.GEN_AI_CLIENT_INFERENCE_OPERATION_DETAILS,+ attributes=attributes,+ body="",+ )+ event_provider.emit(event)++ except Exception as e:+ logger.warning("Failed to emit Strands inference event: %s", e, exc_info=True)+++# -------------------------------------------------------------------------+# Metrics recording+# -------------------------------------------------------------------------+++def record_strands_metrics(+ metrics,+ operation,+ duration,+ environment,+ application_name,+ model,+ server_address,+ server_port,+):+ """Record ``gen_ai.client.operation.duration`` histogram."""+ try:+ attributes = {+ SemanticConvention.GEN_AI_OPERATION: operation,+ SemanticConvention.GEN_AI_PROVIDER_NAME: SemanticConvention.GEN_AI_SYSTEM_STRANDS,+ "service.name": application_name,+ "deployment.environment": environment,+ }+ if model and model != "unknown":+ attributes[SemanticConvention.GEN_AI_REQUEST_MODEL] = model+ if server_address:+ attributes[SemanticConvention.SERVER_ADDRESS] = server_address+ if server_port:+ attributes[SemanticConvention.SERVER_PORT] = server_port++ if "genai_client_operation_duration" in metrics:+ metrics["genai_client_operation_duration"].record(duration, attributes)+ except Exception:+ passdiff --git a/sdk/python/src/openlit/instrumentation/together/async_together.py b/sdk/python/src/openlit/instrumentation/together/async_together.pyindex f5a62026..cdaaea32 100644--- a/sdk/python/src/openlit/instrumentation/together/async_together.py+++ b/sdk/python/src/openlit/instrumentation/together/async_together.py@@ -3,6 +3,7 @@ Module for monitoring Together API calls."""import time+from opentelemetry import trace as trace_api, context as context_apifrom opentelemetry.trace import SpanKindfrom openlit.__helpers import (handle_exception,@@ -123,9 +124,17 @@ def async_completion(span_name = f"{SemanticConvention.GEN_AI_OPERATION_TYPE_CHAT} {request_model}"if streaming:- # Special handling for streaming response to accommodate the nature of data flow- awaited_wrapped = await wrapped(*args, **kwargs)span = tracer.start_span(span_name, kind=SpanKind.CLIENT)+ ctx = trace_api.set_span_in_context(span)+ token = context_api.attach(ctx)+ try:+ awaited_wrapped = await wrapped(*args, **kwargs)+ except Exception as e:+ handle_exception(span, e)+ context_api.detach(token)+ span.end()+ raise+ context_api.detach(token)return TracedAsyncStream(awaited_wrapped, span, span_name, kwargs, server_address, server_port)diff --git a/sdk/python/src/openlit/instrumentation/together/together.py b/sdk/python/src/openlit/instrumentation/together/together.pyindex 2e6c24e2..7ba1a6ba 100644--- a/sdk/python/src/openlit/instrumentation/together/together.py+++ b/sdk/python/src/openlit/instrumentation/together/together.py@@ -3,6 +3,7 @@ Module for monitoring Together API calls."""import time+from opentelemetry import trace as trace_api, context as context_apifrom opentelemetry.trace import SpanKindfrom openlit.__helpers import (handle_exception,@@ -123,9 +124,17 @@ def completion(span_name = f"{SemanticConvention.GEN_AI_OPERATION_TYPE_CHAT} {request_model}"if streaming:- # Special handling for streaming response to accommodate the nature of data flow- awaited_wrapped = wrapped(*args, **kwargs)span = tracer.start_span(span_name, kind=SpanKind.CLIENT)+ ctx = trace_api.set_span_in_context(span)+ token = context_api.attach(ctx)+ try:+ awaited_wrapped = wrapped(*args, **kwargs)+ except Exception as e:+ handle_exception(span, e)+ context_api.detach(token)+ span.end()+ raise+ context_api.detach(token)return TracedSyncStream(awaited_wrapped, span, span_name, kwargs, server_address, server_port)diff --git a/sdk/python/src/openlit/instrumentation/vertexai/async_vertexai.py b/sdk/python/src/openlit/instrumentation/vertexai/async_vertexai.pyindex f3bfad16..370d0c6b 100644--- a/sdk/python/src/openlit/instrumentation/vertexai/async_vertexai.py+++ b/sdk/python/src/openlit/instrumentation/vertexai/async_vertexai.py@@ -4,6 +4,7 @@ Module for monitoring VertexAI API calls.import loggingimport time+from opentelemetry import trace as trace_api, context as context_apifrom opentelemetry.trace import SpanKindfrom openlit.__helpers import (handle_exception,@@ -119,8 +120,17 @@ def async_send_message(span_name = f"{SemanticConvention.GEN_AI_OPERATION_TYPE_CHAT} {request_model}"if streaming:- awaited_wrapped = await wrapped(*args, **kwargs)span = tracer.start_span(span_name, kind=SpanKind.CLIENT)+ ctx = trace_api.set_span_in_context(span)+ token = context_api.attach(ctx)+ try:+ awaited_wrapped = await wrapped(*args, **kwargs)+ except Exception as e:+ handle_exception(span, e)+ context_api.detach(token)+ span.end()+ raise+ context_api.detach(token)return TracedAsyncStream(awaited_wrapped,diff --git a/sdk/python/src/openlit/instrumentation/vertexai/vertexai.py b/sdk/python/src/openlit/instrumentation/vertexai/vertexai.pyindex 9ec97345..93c337ce 100644--- a/sdk/python/src/openlit/instrumentation/vertexai/vertexai.py+++ b/sdk/python/src/openlit/instrumentation/vertexai/vertexai.py@@ -4,6 +4,7 @@ Module for monitoring VertexAI API calls.import loggingimport time+from opentelemetry import trace as trace_api, context as context_apifrom opentelemetry.trace import SpanKindfrom openlit.__helpers import (handle_exception,@@ -119,8 +120,17 @@ def send_message(span_name = f"{SemanticConvention.GEN_AI_OPERATION_TYPE_CHAT} {request_model}"if streaming:- awaited_wrapped = wrapped(*args, **kwargs)span = tracer.start_span(span_name, kind=SpanKind.CLIENT)+ ctx = trace_api.set_span_in_context(span)+ token = context_api.attach(ctx)+ try:+ awaited_wrapped = wrapped(*args, **kwargs)+ except Exception as e:+ handle_exception(span, e)+ context_api.detach(token)+ span.end()+ raise+ context_api.detach(token)return TracedSyncStream(awaited_wrapped,diff --git a/sdk/python/src/openlit/otel/events.py b/sdk/python/src/openlit/otel/events.pyindex 33e432e6..4e4b1043 100644--- a/sdk/python/src/openlit/otel/events.py+++ b/sdk/python/src/openlit/otel/events.py@@ -15,7 +15,7 @@ from opentelemetry.sdk._logs.export import (BatchLogRecordProcessor,SimpleLogRecordProcessor,)-from opentelemetry.sdk._logs import LoggerProvider+from opentelemetry.sdk._logs import LoggerProvider as SDKLoggerProviderfrom opentelemetry.sdk._logs.export import ConsoleLogRecordExporterfrom openlit.__helpers import parse_exporters@@ -61,82 +61,81 @@ def setup_events(try:if not EVENTS_SET:- # Create resource with service and environment information- resource = Resource.create(- attributes={- SERVICE_NAME: application_name,- DEPLOYMENT_ENVIRONMENT: environment,- TELEMETRY_SDK_NAME: "openlit",- }- )-- # Initialize the LoggerProvider with the created resource.- logger_provider = LoggerProvider(resource=resource)-- # Only set environment variables if you have a non-None value.- if otlp_endpoint is not None:- os.environ["OTEL_EXPORTER_OTLP_ENDPOINT"] = otlp_endpoint-- if otlp_headers is not None:- if isinstance(otlp_headers, dict):- headers_str = ",".join(- f"{key}={value}" for key, value in otlp_headers.items()- )- else:- headers_str = otlp_headers-- os.environ["OTEL_EXPORTER_OTLP_HEADERS"] = headers_str-- # Check for OTEL_LOGS_EXPORTER env var for multiple exporters support- exporters_config = parse_exporters("OTEL_LOGS_EXPORTER")- processors_added = False+ existing_provider = _logs.get_logger_provider()- if exporters_config is not None:- # New behavior: use specified exporters from OTEL_LOGS_EXPORTER- for exporter_name in exporters_config:- if exporter_name == "otlp":+ if isinstance(existing_provider, SDKLoggerProvider):+ logger.info("Detected existing LoggerProvider, reusing it")+ else:+ # No SDK provider configured yet -- create one.+ resource = Resource.create(+ attributes={+ SERVICE_NAME: application_name,+ DEPLOYMENT_ENVIRONMENT: environment,+ TELEMETRY_SDK_NAME: "openlit",+ }+ )++ logger_provider = SDKLoggerProvider(resource=resource)++ if otlp_endpoint is not None:+ os.environ["OTEL_EXPORTER_OTLP_ENDPOINT"] = otlp_endpoint++ if otlp_headers is not None:+ if isinstance(otlp_headers, dict):+ headers_str = ",".join(+ f"{key}={value}" for key, value in otlp_headers.items()+ )+ else:+ headers_str = otlp_headers++ os.environ["OTEL_EXPORTER_OTLP_HEADERS"] = headers_str++ exporters_config = parse_exporters("OTEL_LOGS_EXPORTER")+ processors_added = False++ if exporters_config is not None:+ for exporter_name in exporters_config:+ if exporter_name == "otlp":+ event_exporter = OTLPLogExporter()+ log_processor = (+ BatchLogRecordProcessor(event_exporter)+ if not disable_batch+ else SimpleLogRecordProcessor(event_exporter)+ )+ logger_provider.add_log_record_processor(log_processor)+ processors_added = True+ elif exporter_name == "console":+ event_exporter = ConsoleLogRecordExporter()+ log_processor = SimpleLogRecordProcessor(event_exporter)+ logger_provider.add_log_record_processor(log_processor)+ processors_added = True+ elif exporter_name == "none":+ continue+ else:+ logger.warning("Unknown log exporter: %s", exporter_name)++ if not processors_added:+ logger.warning(+ "OTEL_LOGS_EXPORTER is set but no valid exporters "+ "configured. Log export is disabled. "+ "Valid exporters: otlp, console"+ )+ else:+ if os.getenv("OTEL_EXPORTER_OTLP_ENDPOINT"):event_exporter = OTLPLogExporter()+ # pylint: disable=line-too-longlog_processor = (BatchLogRecordProcessor(event_exporter)if not disable_batchelse SimpleLogRecordProcessor(event_exporter))- logger_provider.add_log_record_processor(log_processor)- processors_added = True- elif exporter_name == "console":+ else:event_exporter = ConsoleLogRecordExporter()log_processor = SimpleLogRecordProcessor(event_exporter)- logger_provider.add_log_record_processor(log_processor)- processors_added = True- elif exporter_name == "none":- # "none" means no exporter, skip- continue- else:- logger.warning("Unknown log exporter: %s", exporter_name)-- # Warn if no valid exporters were configured- if not processors_added:- logger.warning(- "OTEL_LOGS_EXPORTER is set but no valid exporters configured. "- "Log export is disabled. Valid exporters: otlp, console"- )- else:- # Default behavior: use OTEL_EXPORTER_OTLP_ENDPOINT check- if os.getenv("OTEL_EXPORTER_OTLP_ENDPOINT"):- event_exporter = OTLPLogExporter()- # pylint: disable=line-too-long- log_processor = (- BatchLogRecordProcessor(event_exporter)- if not disable_batch- else SimpleLogRecordProcessor(event_exporter)- )- else:- event_exporter = ConsoleLogRecordExporter()- log_processor = SimpleLogRecordProcessor(event_exporter)- logger_provider.add_log_record_processor(log_processor)+ logger_provider.add_log_record_processor(log_processor)- _logs.set_logger_provider(logger_provider)+ _logs.set_logger_provider(logger_provider)EVENTS_SET = Truediff --git a/sdk/python/src/openlit/otel/metrics.py b/sdk/python/src/openlit/otel/metrics.pyindex 5bb32906..7f58178b 100644--- a/sdk/python/src/openlit/otel/metrics.py+++ b/sdk/python/src/openlit/otel/metrics.py@@ -159,73 +159,75 @@ def setup_meter(application_name, environment, meter, otlp_endpoint, otlp_headertry:if meter is None and not METER_SET:- # Create a resource with the service name attribute.- resource = Resource.create(- attributes={- SERVICE_NAME: application_name,- DEPLOYMENT_ENVIRONMENT: environment,- TELEMETRY_SDK_NAME: "openlit",- }- )-- # Only set environment variables if you have a non-None value.- if otlp_endpoint is not None:- os.environ["OTEL_EXPORTER_OTLP_ENDPOINT"] = otlp_endpoint-- if otlp_headers is not None:- if isinstance(otlp_headers, dict):- headers_str = ",".join(- f"{key}={value}" for key, value in otlp_headers.items()- )- else:- headers_str = otlp_headers- # Now, we have either converted the dict to a string or used the provided string.- os.environ["OTEL_EXPORTER_OTLP_HEADERS"] = headers_str-- # Check for OTEL_METRICS_EXPORTER env var for multiple exporters support- exporters_config = parse_exporters("OTEL_METRICS_EXPORTER")- metric_readers = []-- if exporters_config is not None:- # New behavior: use specified exporters from OTEL_METRICS_EXPORTER- for exporter_name in exporters_config:- if exporter_name == "otlp":- metric_exporter = OTLPMetricExporter()- metric_readers.append(- PeriodicExportingMetricReader(metric_exporter)+ existing_provider = metrics.get_meter_provider()++ if isinstance(existing_provider, MeterProvider):+ logger.info("Detected existing MeterProvider, reusing it")+ meter = metrics.get_meter(__name__, version="0.1.0")+ else:+ # No SDK provider configured yet -- create one.+ resource = Resource.create(+ attributes={+ SERVICE_NAME: application_name,+ DEPLOYMENT_ENVIRONMENT: environment,+ TELEMETRY_SDK_NAME: "openlit",+ }+ )++ if otlp_endpoint is not None:+ os.environ["OTEL_EXPORTER_OTLP_ENDPOINT"] = otlp_endpoint++ if otlp_headers is not None:+ if isinstance(otlp_headers, dict):+ headers_str = ",".join(+ f"{key}={value}" for key, value in otlp_headers.items())- elif exporter_name == "console":- metric_exporter = ConsoleMetricExporter()- metric_readers.append(- PeriodicExportingMetricReader(metric_exporter)+ else:+ headers_str = otlp_headers+ os.environ["OTEL_EXPORTER_OTLP_HEADERS"] = headers_str++ exporters_config = parse_exporters("OTEL_METRICS_EXPORTER")+ metric_readers = []++ if exporters_config is not None:+ for exporter_name in exporters_config:+ if exporter_name == "otlp":+ metric_exporter = OTLPMetricExporter()+ metric_readers.append(+ PeriodicExportingMetricReader(metric_exporter)+ )+ elif exporter_name == "console":+ metric_exporter = ConsoleMetricExporter()+ metric_readers.append(+ PeriodicExportingMetricReader(metric_exporter)+ )+ elif exporter_name == "none":+ continue+ else:+ logger.warning("Unknown metric exporter: %s", exporter_name)++ if not metric_readers:+ logger.warning(+ "OTEL_METRICS_EXPORTER is set but no valid exporters "+ "configured. Metric export is disabled. "+ "Valid exporters: otlp, console")- elif exporter_name == "none":- # "none" means no exporter, skip- continue+ else:+ if os.getenv("OTEL_EXPORTER_OTLP_ENDPOINT"):+ metric_exporter = OTLPMetricExporter()else:- logger.warning("Unknown metric exporter: %s", exporter_name)-- # Warn if no valid exporters were configured- if not metric_readers:- logger.warning(- "OTEL_METRICS_EXPORTER is set but no valid exporters configured. "- "Metric export is disabled. Valid exporters: otlp, console"+ metric_exporter = ConsoleMetricExporter()+ metric_readers.append(+ PeriodicExportingMetricReader(metric_exporter))- else:- # Default behavior: use OTEL_EXPORTER_OTLP_ENDPOINT check- if os.getenv("OTEL_EXPORTER_OTLP_ENDPOINT"):- metric_exporter = OTLPMetricExporter()- else:- metric_exporter = ConsoleMetricExporter()- metric_readers.append(PeriodicExportingMetricReader(metric_exporter))- meter_provider = MeterProvider(- resource=resource, metric_readers=metric_readers- )+ meter_provider = MeterProvider(+ resource=resource, metric_readers=metric_readers+ )- metrics.set_meter_provider(meter_provider)+ metrics.set_meter_provider(meter_provider)- meter = metrics.get_meter(__name__, version="0.1.0")+ meter = metrics.get_meter(__name__, version="0.1.0")METER_SET = Truediff --git a/sdk/python/src/openlit/otel/tracing.py b/sdk/python/src/openlit/otel/tracing.pyindex f0c91ffb..9ed82c75 100644--- a/sdk/python/src/openlit/otel/tracing.py+++ b/sdk/python/src/openlit/otel/tracing.py@@ -53,80 +53,84 @@ def setup_tracing(os.environ["HAYSTACK_AUTO_TRACE_ENABLED"] = "false"if not TRACER_SET:- # Create a resource with the service name attribute.- resource = Resource.create(- attributes={- SERVICE_NAME: application_name,- DEPLOYMENT_ENVIRONMENT: environment,- TELEMETRY_SDK_NAME: "openlit",- }- )-- # Initialize the TracerProvider with the created resource.- trace.set_tracer_provider(TracerProvider(resource=resource))-- # Only set environment variables if you have a non-None value.- if otlp_endpoint is not None:- os.environ["OTEL_EXPORTER_OTLP_ENDPOINT"] = otlp_endpoint-- if otlp_headers is not None:- if isinstance(otlp_headers, dict):- headers_str = ",".join(- f"{key}={value}" for key, value in otlp_headers.items()- )- else:- headers_str = otlp_headers-- os.environ["OTEL_EXPORTER_OTLP_HEADERS"] = headers_str-- # Check for OTEL_TRACES_EXPORTER env var for multiple exporters support- exporters_config = parse_exporters("OTEL_TRACES_EXPORTER")- processors_added = False+ existing_provider = trace.get_tracer_provider()- if exporters_config is not None:- # New behavior: use specified exporters from OTEL_TRACES_EXPORTER- for exporter_name in exporters_config:- if exporter_name == "otlp":+ if isinstance(existing_provider, TracerProvider):+ logger.info("Detected existing TracerProvider, reusing it")+ else:+ # No SDK provider configured yet -- create one.+ resource = Resource.create(+ attributes={+ SERVICE_NAME: application_name,+ DEPLOYMENT_ENVIRONMENT: environment,+ TELEMETRY_SDK_NAME: "openlit",+ }+ )++ trace.set_tracer_provider(TracerProvider(resource=resource))++ if otlp_endpoint is not None:+ os.environ["OTEL_EXPORTER_OTLP_ENDPOINT"] = otlp_endpoint++ if otlp_headers is not None:+ if isinstance(otlp_headers, dict):+ headers_str = ",".join(+ f"{key}={value}" for key, value in otlp_headers.items()+ )+ else:+ headers_str = otlp_headers++ os.environ["OTEL_EXPORTER_OTLP_HEADERS"] = headers_str++ # Check for OTEL_TRACES_EXPORTER env var for multiple exporters support+ exporters_config = parse_exporters("OTEL_TRACES_EXPORTER")+ processors_added = False++ if exporters_config is not None:+ for exporter_name in exporters_config:+ if exporter_name == "otlp":+ span_exporter = OTLPSpanExporter()+ span_processor = (+ BatchSpanProcessor(span_exporter)+ if not disable_batch+ else SimpleSpanProcessor(span_exporter)+ )+ trace.get_tracer_provider().add_span_processor(+ span_processor+ )+ processors_added = True+ elif exporter_name == "console":+ span_exporter = ConsoleSpanExporter()+ span_processor = SimpleSpanProcessor(span_exporter)+ trace.get_tracer_provider().add_span_processor(+ span_processor+ )+ processors_added = True+ elif exporter_name == "none":+ continue+ else:+ logger.warning("Unknown trace exporter: %s", exporter_name)++ if not processors_added:+ logger.warning(+ "OTEL_TRACES_EXPORTER is set but no valid exporters "+ "configured. Trace export is disabled. "+ "Valid exporters: otlp, console"+ )+ else:+ if os.getenv("OTEL_EXPORTER_OTLP_ENDPOINT"):span_exporter = OTLPSpanExporter()+ # pylint: disable=line-too-longspan_processor = (BatchSpanProcessor(span_exporter)if not disable_batchelse SimpleSpanProcessor(span_exporter))- trace.get_tracer_provider().add_span_processor(span_processor)- processors_added = True- elif exporter_name == "console":+ else:span_exporter = ConsoleSpanExporter()span_processor = SimpleSpanProcessor(span_exporter)- trace.get_tracer_provider().add_span_processor(span_processor)- processors_added = True- elif exporter_name == "none":- # "none" means no exporter, skip- continue- else:- logger.warning("Unknown trace exporter: %s", exporter_name)-- # Warn if no valid exporters were configured- if not processors_added:- logger.warning(- "OTEL_TRACES_EXPORTER is set but no valid exporters configured. "- "Trace export is disabled. Valid exporters: otlp, console"- )- else:- # Default behavior: use OTEL_EXPORTER_OTLP_ENDPOINT check- if os.getenv("OTEL_EXPORTER_OTLP_ENDPOINT"):- span_exporter = OTLPSpanExporter()- # pylint: disable=line-too-long- span_processor = (- BatchSpanProcessor(span_exporter)- if not disable_batch- else SimpleSpanProcessor(span_exporter)- )- else:- span_exporter = ConsoleSpanExporter()- span_processor = SimpleSpanProcessor(span_exporter)- trace.get_tracer_provider().add_span_processor(span_processor)+ trace.get_tracer_provider().add_span_processor(span_processor)TRACER_SET = Truediff --git a/sdk/python/src/openlit/semcov/__init__.py b/sdk/python/src/openlit/semcov/__init__.pyindex 004b4c59..d342b4a5 100644--- a/sdk/python/src/openlit/semcov/__init__.py+++ b/sdk/python/src/openlit/semcov/__init__.py@@ -117,7 +117,7 @@ class SemanticConvention:GEN_AI_USER_MESSAGE = "gen_ai.user.message"GEN_AI_SYSTEM_MESSAGE = "gen_ai.system.message"GEN_AI_ASSISTANT_MESSAGE = "gen_ai.assistant.message"- GEN_AI_TOOL_MESSAGE = "gen_ai.tools.message"+ GEN_AI_TOOL_MESSAGE = "gen_ai.tool.message"GEN_AI_CHOICE = "gen_ai.choice"# GenAI Event Names (OTel Semconv v1.29+)@@ -360,6 +360,8 @@ class SemanticConvention:GEN_AI_SYSTEM_GOOGLE_ADK = "google_adk"GEN_AI_SYSTEM_CLAUDE_AGENT_SDK = "claude_agent_sdk"GEN_AI_SYSTEM_AGENT_FRAMEWORK = "agent_framework"+ GEN_AI_SYSTEM_STRANDS = "strands_agents"+ GEN_AI_SYSTEM_SMOLAGENTS = "smolagents"# Graph Execution Attributes (framework-agnostic, usable across LangGraph, CrewAI, etc.)GEN_AI_GRAPH_NODES = "gen_ai.graph.nodes"@@ -516,11 +518,9 @@ class SemanticConvention:GEN_AI_RESPONSE_IMAGE = "gen_ai.response.image"GEN_AI_TOOL_CALLS = "gen_ai.response.tool_calls"- # GenAI Content+ # GenAI Content (input/output messages defined in Tier 1 above)GEN_AI_CONTENT_PROMPT_EVENT = "gen_ai.content.prompt"- GEN_AI_INPUT_MESSAGES = "gen_ai.input.messages"GEN_AI_CONTENT_COMPLETION_EVENT = "gen_ai.content.completion"- GEN_AI_OUTPUT_MESSAGES = "gen_ai.output.messages"GEN_AI_CONTENT_REVISED_PROMPT = "gen_ai.content.revised_prompt"GEN_AI_CONTENT_REASONING = "gen_ai.content.reasoning"@@ -643,12 +643,11 @@ class SemanticConvention:DB_INDEX_NAME = "db.index.name"DB_COLLECTION_DIMENSION = "db.collection.dimension"DB_INDEX_DIMENSION = "db.index.dimension"- DB_COLLECTION_DIMENSION = "db.collection.dimension"DB_SEARCH_SIMILARITY_METRIC = "db.search.similarity_metric"DB_INDEX_METRIC = "db.create_index.metric"DB_COLLECTION_SPEC = "db.collection.spec"DB_INDEX_SPEC = "db.create_index.spec"- DB_NAMESPACE = "db.query.namespace"+ DB_QUERY_NAMESPACE = "db.query.namespace"DB_UPDATE_METADATA = "db.update.metadata"DB_UPDATE_VALUES = "db.update.values"DB_UPDATE_ID = "db.update.id"@@ -887,7 +886,7 @@ class SemanticConvention:# Browser-Use Agent Specific AttributesGEN_AI_AGENT_MAX_STEPS = "gen_ai.agent.max_steps"- GEN_AI_AGENT_TASK_ID = "gen_ai.agent.task_id"+ GEN_AI_BROWSER_AGENT_TASK_ID = "gen_ai.agent.task_id"GEN_AI_AGENT_SESSION_ID = "gen_ai.agent.session_id"GEN_AI_AGENT_USE_VISION = "gen_ai.agent.use_vision"GEN_AI_AGENT_MAX_FAILURES = "gen_ai.agent.max_failures"@@ -909,7 +908,7 @@ class SemanticConvention:GEN_AI_ACTION_EXTRACTED_CONTENT_LENGTH = "gen_ai.action.extracted_content_length"# Browser-Use Browser Specific Attributes- GEN_AI_BROWSER_PAGE_TITLE = "gen_ai.browser.page_title"+ GEN_AI_BROWSER_CURRENT_PAGE_TITLE = "gen_ai.browser.page_title"GEN_AI_BROWSER_TABS_COUNT = "gen_ai.browser.tabs_count"# Browser-Use Agent Execution Attributes@@ -934,7 +933,6 @@ class SemanticConvention:# Browser-Use Operation AttributesGEN_AI_OPERATION_TYPE = "gen_ai.operation.type"- GEN_AI_CLIENT_OPERATION_DURATION = "gen_ai.client.operation.duration"# Browser-Use Span Name ComponentsGEN_AI_SPAN_INVOKE_MODEL = "invoke_model"@@ -1032,49 +1030,9 @@ class SemanticConvention:GEN_AI_FRAMEWORK_INDEX_NAME = "gen_ai.framework.index.name"GEN_AI_FRAMEWORK_INDEX_TYPE = "gen_ai.framework.index.type"- # === GENERAL FRAMEWORK SEMANTIC CONVENTIONS (reusable across frameworks) ===-- # Framework tracing attributes (general, reusable across frameworks)- GEN_AI_FRAMEWORK_TAGS = "gen_ai.framework.tags"-- # Framework performance tracking (general)- GEN_AI_FRAMEWORK_PERFORMANCE_VS_BASELINE = (- "gen_ai.framework.performance.vs_baseline"- )- GEN_AI_FRAMEWORK_PERFORMANCE_BASELINE_AVG = (- "gen_ai.framework.performance.baseline_avg"- )- GEN_AI_FRAMEWORK_PERFORMANCE_BASELINE_PERCENTILE = (- "gen_ai.framework.performance.baseline_percentile"- )-- # Framework error classification (general)- GEN_AI_FRAMEWORK_ERROR_CLASS = "gen_ai.framework.error.class"- GEN_AI_FRAMEWORK_ERROR_TYPE = "gen_ai.framework.error.type"- GEN_AI_FRAMEWORK_ERROR_MESSAGE = "gen_ai.framework.error.message"-- # Serialized function information (general, reusable)- GEN_AI_SERIALIZED_NAME = "gen_ai.serialized.name"- GEN_AI_SERIALIZED_SIGNATURE = "gen_ai.serialized.signature"- GEN_AI_SERIALIZED_DOC = "gen_ai.serialized.doc"- GEN_AI_SERIALIZED_MODULE = "gen_ai.serialized.module"-- # Provider information (general, reusable)- GEN_AI_REQUEST_PROVIDER = "gen_ai.request.provider"-- # Enhanced token details (general, reusable across providers)- GEN_AI_USAGE_COMPLETION_TOKENS_DETAILS_AUDIO = (- "gen_ai.usage.completion_tokens_details.audio"- )- GEN_AI_USAGE_COMPLETION_TOKENS_DETAILS_REASONING = (- "gen_ai.usage.completion_tokens_details.reasoning"- )- GEN_AI_USAGE_PROMPT_TOKENS_DETAILS_CACHE_READ = (- "gen_ai.usage.prompt_tokens_details.cache_read"- )- GEN_AI_USAGE_PROMPT_TOKENS_DETAILS_CACHE_WRITE = (- "gen_ai.usage.prompt_tokens_details.cache_write"- )+ # === GENERAL FRAMEWORK SEMANTIC CONVENTIONS ===+ # All general framework attrs (tags, errors, serialized, provider, token details)+ # are defined in Tier 2 above. Do not redefine here.# === STANDARD OPENTELEMETRY SEMANTIC CONVENTIONS ===# These are framework-agnostic and reusable across all agent frameworksdiff --git a/sdk/python/tests/test_claude_agent_sdk.py b/sdk/python/tests/test_claude_agent_sdk.pyindex b226ede4..d8d196e0 100644--- a/sdk/python/tests/test_claude_agent_sdk.py+++ b/sdk/python/tests/test_claude_agent_sdk.py@@ -44,6 +44,7 @@ from openlit.instrumentation.claude_agent_sdk.utils import (GEN_AI_SYSTEM_ATTR,GEN_AI_SYSTEM_VALUE,generate_span_name,+ resolve_agent_display_name,get_span_kind,extract_usage,update_root_from_assistant,@@ -247,6 +248,16 @@ class TestSpanNameGeneration:def test_receive_response_span_name(self):assert generate_span_name("receive_response") == "invoke_agent claude_agent_sdk"+ def test_query_span_name_with_model_entity(self):+ assert generate_span_name("query", "claude-opus-4-20250514") == (+ "invoke_agent claude-opus-4-20250514"+ )++ def test_receive_response_span_name_with_model_entity(self):+ assert generate_span_name("receive_response", "claude-sonnet-4") == (+ "invoke_agent claude-sonnet-4"+ )+def test_chat_span_name_with_model(self):assert generate_span_name("chat", "claude-sonnet-4-20250514") == "chat claude-sonnet-4-20250514"@@ -263,6 +274,16 @@ class TestSpanNameGeneration:name = generate_span_name("unknown_op")assert "invoke_agent" in name+ def test_resolve_agent_display_name(self):+ assert resolve_agent_display_name(None) is None+ o = MagicMock()+ o.model = None+ assert resolve_agent_display_name(o) is None+ o.model = " "+ assert resolve_agent_display_name(o) is None+ o.model = "claude-3-haiku"+ assert resolve_agent_display_name(o) == "claude-3-haiku"+class TestGetSpanKind:def test_known_operation_types(self):@@ -712,6 +733,14 @@ class TestSetCreateAgentAttributes:assert attrs[SemanticConvention.SERVER_ADDRESS] == "api.anthropic.com"assert attrs[SemanticConvention.SERVER_PORT] == 443+ def test_custom_agent_name(self):+ span = MagicMock()+ set_create_agent_attributes(+ span, "0.1.0", "test", "test_app", agent_name="claude-sonnet-4-20250514"+ )+ attrs = _get_span_attrs(span)+ assert attrs[SemanticConvention.GEN_AI_AGENT_NAME] == "claude-sonnet-4-20250514"+# ===========================================================================# Root Span (invoke_agent) Attributes@@ -742,9 +771,22 @@ class TestSetInitialSpanAttributes:_, attrs = self._call()assert attrs[GEN_AI_SYSTEM_ATTR] == "anthropic"- def test_agent_name(self):+ def test_agent_name_matches_configured_model(self):_, attrs = self._call()- assert attrs[SemanticConvention.GEN_AI_AGENT_NAME] == "claude_agent_sdk"+ assert attrs[SemanticConvention.GEN_AI_AGENT_NAME] == "claude-sonnet-4-20250514"++ def test_agent_name_falls_back_without_model(self):+ span = MagicMock()+ options = MagicMock()+ options.model = None+ set_initial_span_attributes(+ span, 1000.0, "0.1.0", "test", "test_app",+ options=options, prompt="Hi", capture_message_content=False,+ )+ attrs = _get_span_attrs(span)+ assert attrs[SemanticConvention.GEN_AI_AGENT_NAME] == (+ SemanticConvention.GEN_AI_SYSTEM_CLAUDE_AGENT_SDK+ )def test_request_model(self):_, attrs = self._call(model="claude-sonnet-4-20250514")diff --git a/sdk/python/tests/test_smolagents.py b/sdk/python/tests/test_smolagents.pynew file mode 100644index 00000000..d0f6d827--- /dev/null+++ b/sdk/python/tests/test_smolagents.py@@ -0,0 +1,197 @@+# pylint: disable=duplicate-code, no-member, too-few-public-methods, missing-class-docstring+"""+Tests for smolagents instrumentation using the smolagents Python library.++Tests cover:+- Agent construction (create_agent spans)+- Agent run (invoke_agent spans)+- Tool execution (execute_tool spans)+- Model generate/stream (LLM spans delegated to base SDK instrumentors)+- Streaming output ActionOutput extraction++These tests validate integration with OpenLIT.++Note: These tests require smolagents to be installed.+"""++from dataclasses import dataclass++import pytest++try:+ from smolagents import (+ Tool,+ ToolCallingAgent,+ )+ from smolagents.models import Model+ from smolagents.monitoring import TokenUsage++ SMOLAGENTS_AVAILABLE = True+except ImportError:+ SMOLAGENTS_AVAILABLE = False++import openlit++openlit.init(+ environment="openlit-python-testing",+ application_name="openlit-python-smolagents-test",+)++pytestmark = pytest.mark.skipif(+ not SMOLAGENTS_AVAILABLE, reason="smolagents not installed"+)+++class MockChatMessage:+ """Mock ChatMessage returned by Model.generate()."""++ def __init__(self, content="Hello!", tool_calls=None):+ self.role = "assistant"+ self.content = content+ self.tool_calls = tool_calls or []+ self.raw = None+ self.token_usage = TokenUsage(input_tokens=10, output_tokens=5)+++class DummyModel(Model):+ """A mock model for testing instrumentation without real API calls."""++ def __init__(self):+ super().__init__(model_id="test-model-001")++ def generate(self, messages, **kwargs):+ """Return a canned chat response."""+ return MockChatMessage(content="Test model response")++ def generate_stream(self, messages, **kwargs):+ """Yield two canned streaming chunks."""+ yield MockChatMessage(content="chunk1")+ yield MockChatMessage(content="chunk2")+++class DummyTool(Tool):+ """A simple test tool."""++ name = "dummy_tool"+ description = "A tool for testing purposes"+ inputs = {+ "query": {"type": "string", "description": "The query to process"},+ }+ output_type = "string"++ def forward(self, query: str) -> str:+ """Process the query and return a result string."""+ return f"Processed: {query}"+++class TestSmolAgentsInstrumentation:+ """Tests for smolagents instrumentation."""++ def test_tool_call_instrumentation(self):+ """Tests that Tool.__call__ is instrumented."""+ tool = DummyTool()+ result = tool(query="test query")+ assert "Processed" in str(result)++ def test_model_generate_instrumentation(self):+ """Tests that Model.generate() works (LLM span from base SDK instrumentor)."""+ model = DummyModel()+ messages = [{"role": "user", "content": "Hello"}]+ response = model.generate(messages)+ assert response.content == "Test model response"+ assert response.token_usage.input_tokens == 10+ assert response.token_usage.output_tokens == 5++ def test_model_generate_stream_instrumentation(self):+ """Tests that Model.generate_stream() works (LLM span from base SDK instrumentor)."""+ model = DummyModel()+ messages = [{"role": "user", "content": "Hello streaming"}]+ chunks = list(model.generate_stream(messages))+ assert len(chunks) == 2+ assert chunks[0].content == "chunk1"+ assert chunks[1].content == "chunk2"++ def test_multiple_tool_calls(self):+ """Tests that multiple tool calls are each instrumented."""+ tool = DummyTool()+ r1 = tool(query="first")+ r2 = tool(query="second")+ assert "first" in str(r1)+ assert "second" in str(r2)++ def test_tool_with_exception(self):+ """Tests that tool exceptions are captured in spans."""++ class FailingTool(Tool):+ name = "failing_tool"+ description = "A tool that fails"+ inputs = {"x": {"type": "string", "description": "input"}}+ output_type = "string"++ def forward(self, x: str) -> str:+ """Always raises ValueError for testing."""+ raise ValueError("Tool execution failed")++ tool = FailingTool()+ with pytest.raises(ValueError, match="Tool execution failed"):+ tool(x="test")++ def test_model_with_exception(self):+ """Tests that model exceptions are captured in spans."""++ class FailingModel(Model):+ def __init__(self):+ super().__init__(model_id="fail-model")++ def generate(self, messages, **kwargs):+ """Always raises RuntimeError for testing."""+ raise RuntimeError("Model generation failed")++ model = FailingModel()+ with pytest.raises(RuntimeError, match="Model generation failed"):+ model.generate([{"role": "user", "content": "fail"}])++ def test_create_agent_span(self):+ """Tests that agent construction emits a create_agent span and+ stores the span context on the instance."""+ model = DummyModel()+ tool = DummyTool()+ agent = ToolCallingAgent(+ tools=[tool],+ model=model,+ name="test_create_agent",+ description="Agent for testing create_agent span",+ )+ assert hasattr(agent, "_openlit_creation_context")+ assert agent._openlit_creation_context is not None++ def test_create_agent_span_attributes(self):+ """Tests that create_agent span captures agent metadata."""+ model = DummyModel()+ tool = DummyTool()+ agent = ToolCallingAgent(+ tools=[tool],+ model=model,+ name="attr_test_agent",+ description="Tests attribute capture",+ )+ ctx = agent._openlit_creation_context+ assert ctx is not None+ assert ctx.trace_id != 0+ assert ctx.span_id != 0++ def test_streaming_output_extraction(self):+ """Tests that ActionOutput.output is extracted cleanly, not the repr."""+ from openlit.instrumentation.smolagents.smolagents import (+ _handle_agent_stream,+ )++ @dataclass+ class ActionOutput:+ output: str+ is_final_answer: bool++ event = ActionOutput(output="clean answer", is_final_answer=True)+ extracted = getattr(event, "output", event)+ assert extracted == "clean answer"+ assert "ActionOutput" not in str(extracted)