Bug: failed calls lose their request parameters (OpenAI) or all span attributes and the duration metric (Anthropic)
Component
OpenLIT Python SDK
What happened?
When the provider rejects a request, the span says almost nothing about what was requested:
- OpenAI (HTTP 500): the span keeps the model and
stream, but none of the request parameters the app sent (temperature,top_p,max_tokens,seed,stop). The successful version of the same call records all of them. - Anthropic (HTTP 400): the span has no attributes at all: no model, no provider, no
error.type, no request parameters. In addition, nogen_ai.client.operation.durationpoint is recorded for the failed call (OpenAI records one, witherror.type).
Failed calls are the ones people look up in their traces, and these attributes (which model, which parameters, which error) are exactly what is needed to understand them.
Steps to reproduce
Run this with OpenLIT installed (it uses a local mock transport, no API keys needed):
import json, sys, httpx
from importlib.metadata import version
from opentelemetry import trace, _logs, metrics
from opentelemetry.sdk.trace import TracerProvider, SpanProcessor
from opentelemetry.sdk._logs import LoggerProvider
from opentelemetry.sdk.metrics import MeterProvider
from opentelemetry.sdk.metrics.export import InMemoryMetricReader
class Spans(SpanProcessor):
def __init__(self): self.ended, self.open = [], {}
def on_start(self, span, parent_context=None): self.open[span.context.span_id] = span.name
def on_end(self, span): self.ended.append(span); self.open.pop(span.context.span_id, None)
spans = Spans(); provider = TracerProvider(); provider.add_span_processor(spans)
trace.set_tracer_provider(provider); _logs.set_logger_provider(LoggerProvider())
reader = InMemoryMetricReader(); metrics.set_meter_provider(MeterProvider(metric_readers=[reader]))
import openlit
import openai, anthropic
openlit.init(disable_batch=True) # metrics on: gen_ai.client.operation.duration
def openai_reply(request):
return httpx.Response(500, json={"error": {"message": "server error", "type": "server_error"}})
def anthropic_reply(request):
return httpx.Response(400, json={"type": "error", "error": {"type": "invalid_request_error", "message": "bad request"}})
oa = openai.OpenAI(api_key="x", base_url="http://mock/v1", max_retries=0, http_client=httpx.Client(transport=httpx.MockTransport(openai_reply)))
an = anthropic.Anthropic(api_key="x", base_url="http://mock", max_retries=0, http_client=httpx.Client(transport=httpx.MockTransport(anthropic_reply)))
def duration_points():
data = reader.get_metrics_data()
return sum(dp.count for rm in (data.resource_metrics if data else []) for sm in rm.scope_metrics for m in sm.metrics
if m.name == "gen_ai.client.operation.duration" for dp in m.data.data_points)
print(f"python {sys.version.split()[0]} | openlit {version('openlit')} | openai {version('openai')} | anthropic {version('anthropic')}")
calls = {"openai (HTTP 500)": lambda: oa.chat.completions.create(model="gpt-4o-mini", messages=[{"role": "user", "content": "hi"}],
temperature=0.3, top_p=0.9, max_tokens=50, seed=7, stop=["END"]),
"anthropic (HTTP 400)": lambda: an.messages.create(model="claude-x", max_tokens=50, messages=[{"role": "user", "content": "hi"}],
temperature=0.3, top_p=0.9, top_k=40, stop_sequences=["END"])}
for label, call in calls.items():
spans.ended.clear(); before = duration_points()
try:
call()
except Exception as e:
got = type(e).__name__
s = spans.ended[0]
print(f"{label}: app got {got}; span status {s.status.status_code.name}; duration points recorded: {duration_points() - before}")
print(f" span attributes: {dict(s.attributes)}")
Output:
python 3.12.3 | openlit 1.45.0 | openai 2.54.0 | anthropic 0.125.0
openai (HTTP 500): app got InternalServerError; span status ERROR; duration points recorded: 1
span attributes: {'telemetry.sdk.name': 'openlit', 'gen_ai.operation.name': 'chat', 'gen_ai.provider.name': 'openai', 'server.address': 'mock', 'server.port': 443, 'deployment.environment': 'default', 'service.name': 'default', 'gen_ai.request.stream': False, 'gen_ai.sdk.version': '2.54.0', 'gen_ai.request.model': 'gpt-4o-mini', 'error.type': 'InternalServerError'}
anthropic (HTTP 400): app got BadRequestError; span status ERROR; duration points recorded: 0
span attributes: {}
Expected behavior
A failed call's span carries the same request attributes as a successful one (model, provider, request parameters) plus error.type. gen_ai.client.operation.duration gets a point with error.type for every failed call, as the GenAI semantic conventions describe.
Environment
- OpenLIT
mainat commit 066e2c582c7e0365437f1eeda65ece4c4360ff58 (installed from git; 1.45.0). openlit 1.45.0 from PyPI behaves the same. - Python 3.12.3, Ubuntu Linux
- openai 2.54.0, anthropic 0.125.0, opentelemetry-sdk 1.45.1
Additional context
For comparison, the same OpenAI call when it succeeds records gen_ai.request.temperature, top_p, max_tokens, seed and stop_sequences.
Pre-submission checklist
- [x] I searched existing issues and didn't find a duplicate
Are you willing to submit PR?
None
The same in the Ollama instrumentation (openlit 1.45.0, also on main at 066e2c5; ollama 0.6.3): a failed chat / generate records no gen_ai.client.operation.duration point, while a successful one records one.
import gc, json, httpx, ollama
from opentelemetry import _logs, metrics, trace
from opentelemetry.sdk._logs import LoggerProvider
from opentelemetry.sdk.metrics import MeterProvider
from opentelemetry.sdk.metrics.export import InMemoryMetricReader
from opentelemetry.sdk.trace import SpanProcessor, TracerProvider
class Spans(SpanProcessor):
def __init__(self): self.started, self.ended = {}, {}
def on_start(self, span, parent_context=None): self.started[span.context.span_id] = span
def on_end(self, span): self.ended[span.context.span_id] = span
def open(self): return [s.name for k, s in self.started.items() if k not in self.ended]
spans = Spans()
provider = TracerProvider(); provider.add_span_processor(spans)
trace.set_tracer_provider(provider)
reader = InMemoryMetricReader(); metrics.set_meter_provider(MeterProvider(metric_readers=[reader]))
_logs.set_logger_provider(LoggerProvider())
import openlit
openlit.init(disabled_instrumentors=[n for n in openlit.MODULE_NAME_MAP if n != "ollama"], disable_batch=True)
def points():
data = reader.get_metrics_data()
return sum(p.count for rm in (data.resource_metrics if data else []) for sm in rm.scope_metrics
for m in sm.metrics if m.name == "gen_ai.client.operation.duration" for p in m.data.data_points)
STATUS = [200]
def respond(request):
if STATUS[0] != 200:
return httpx.Response(STATUS[0], json={"error": "mock failure"})
return httpx.Response(200, json={"model": "m", "created_at": "2026-01-01T00:00:00Z", "done": True, "done_reason": "stop",
"message": {"role": "assistant", "content": "Hello"}, "prompt_eval_count": 3, "eval_count": 1})
client = ollama.Client(host="http://mock", transport=httpx.MockTransport(respond))
for status in (200, 500):
STATUS[0] = status; before = points()
try:
client.chat(model="m", messages=[{"role": "user", "content": "hi"}]); outcome = "ok"
except ollama.ResponseError:
outcome = "ResponseError"
print(f"HTTP {status}: {outcome:14s} new duration points: {points() - before}")
HTTP 200: ok new duration points: 1
HTTP 500: ResponseError new duration points: 0
Failed calls miss their gen_ai.client.operation.duration point in three more places (openlit 1.45.0 and main at d1156bd612): Bedrock converse and converse_stream (ThrottlingException), Google GenAI generate_content (HTTP 400), and a streamed OpenAI chat (stream=True, HTTP 500; the same call without streaming records its point). The successful calls record one.
# Failed calls and gen_ai.client.operation.duration: Bedrock (converse, converse_stream), Google GenAI
# (generate_content) and a streamed OpenAI chat record no duration point when the provider rejects the request.
# The successful calls and a non-streamed failed OpenAI call record one (the Anthropic variant is #1705).
import json, sys, httpx
from importlib.metadata import version
from opentelemetry import trace, _logs, metrics
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk._logs import LoggerProvider
from opentelemetry.sdk.metrics import MeterProvider
from opentelemetry.sdk.metrics.export import InMemoryMetricReader
trace.set_tracer_provider(TracerProvider()); _logs.set_logger_provider(LoggerProvider())
reader = InMemoryMetricReader(); metrics.set_meter_provider(MeterProvider(metric_readers=[reader]))
import openlit, boto3, openai
from botocore.awsrequest import AWSResponse
from botocore.config import Config
from google import genai
from google.genai import types
openlit.init(disable_batch=True)
def duration_points():
data = reader.get_metrics_data()
return sum(dp.count for rm in (data.resource_metrics if data else []) for sm in rm.scope_metrics for m in sm.metrics
if m.name == "gen_ai.client.operation.duration" for dp in m.data.data_points)
class Raw:
def __init__(self, body): self.body = body
def stream(self, *a, **k): yield self.body
def read(self, amt=None): return self.body
def close(self): pass
release_conn = close
def bedrock(status):
body = (json.dumps({"output": {"message": {"role": "assistant", "content": [{"text": "Hello"}]}}, "stopReason": "end_turn",
"usage": {"inputTokens": 3, "outputTokens": 1, "totalTokens": 4}, "metrics": {"latencyMs": 1}})
if status == 200 else json.dumps({"message": "Too many requests, please wait before trying again."}))
headers = {"content-type": "application/json", **({} if status == 200 else {"x-amzn-ErrorType": "ThrottlingException"})}
c = boto3.client("bedrock-runtime", region_name="us-east-1", aws_access_key_id="x", aws_secret_access_key="x",
config=Config(retries={"total_max_attempts": 1}))
c.meta.events.register("before-send.bedrock-runtime.*", lambda request, **_: AWSResponse(request.url, status, headers, Raw(body.encode())))
return c
def google(status):
def reply(request):
if status != 200:
return httpx.Response(status, json={"error": {"code": status, "message": "bad request", "status": "INVALID_ARGUMENT"}})
return httpx.Response(200, json={"candidates": [{"content": {"role": "model", "parts": [{"text": "Hello"}]}, "finishReason": "STOP"}],
"usageMetadata": {"promptTokenCount": 3, "candidatesTokenCount": 1, "totalTokenCount": 4}})
return genai.Client(api_key="x", http_options=types.HttpOptions(base_url="http://mock",
httpx_client=httpx.Client(transport=httpx.MockTransport(reply))))
oa = openai.OpenAI(api_key="x", base_url="http://mock/v1", max_retries=0, http_client=httpx.Client(transport=httpx.MockTransport(
lambda request: httpx.Response(500, json={"error": {"message": "server error", "type": "server_error"}}))))
MODEL, BMSGS, MSGS = "anthropic.claude-3-haiku-20240307-v1:0", [{"role": "user", "content": [{"text": "hi"}]}], [{"role": "user", "content": "hi"}]
calls = [
("Bedrock converse, success", lambda: bedrock(200).converse(modelId=MODEL, messages=BMSGS)),
("Bedrock converse, ThrottlingException", lambda: bedrock(429).converse(modelId=MODEL, messages=BMSGS)),
("Bedrock converse_stream, ThrottlingException", lambda: bedrock(429).converse_stream(modelId=MODEL, messages=BMSGS)),
("Google generate_content, success", lambda: google(200).models.generate_content(model="m", contents="hi")),
("Google generate_content, HTTP 400", lambda: google(400).models.generate_content(model="m", contents="hi")),
("OpenAI chat, HTTP 500", lambda: oa.chat.completions.create(model="gpt-4o-mini", messages=MSGS)),
("OpenAI chat stream=True, HTTP 500", lambda: oa.chat.completions.create(model="gpt-4o-mini", messages=MSGS, stream=True)),
]
print(f"python {sys.version.split()[0]} | openlit {version('openlit')} | boto3 {version('boto3')} | "
f"google-genai {version('google-genai')} | openai {version('openai')}")
for label, call in calls:
before = duration_points()
try:
call(); got = "a response"
except Exception as e:
got = type(e).__name__
print(f"{label:46s} app got {got:22s} duration points recorded: {duration_points() - before}")
python 3.13.7 | openlit 1.45.0 | boto3 1.43.114 | google-genai 2.31.0 | openai 2.54.0
Bedrock converse, success app got a response duration points recorded: 1
Bedrock converse, ThrottlingException app got ThrottlingException duration points recorded: 0
Bedrock converse_stream, ThrottlingException app got ThrottlingException duration points recorded: 0
Google generate_content, success app got a response duration points recorded: 1
Google generate_content, HTTP 400 app got ClientError duration points recorded: 0
OpenAI chat, HTTP 500 app got InternalServerError duration points recorded: 1
OpenAI chat stream=True, HTTP 500 app got InternalServerError duration points recorded: 0
The Ollama case in this comment still reproduces at 1ed8bb7 for non-streaming chat and generate, both sync and async. With a mock HTTP 500, each call raises ResponseError and ends its span, but adds no gen_ai.client.operation.duration observation. Successful controls each add one.
I'd like to cover those four Ollama paths in a separate PR, leaving #1716's OpenAI/Anthropic work alone. The change would preserve the provider exception and record the failed-call duration once, with regressions for success, failure and disabled metrics.
Is anyone already working on the Ollama part?
Thanks. I agree on both points.
#1716 covers the OpenAI and Anthropic non-streaming cases, which is the part the issue body reports. It does not touch Ollama.
Note: #1716 says "Fixes #1705", so merging it closes this issue. A new issue for the remaining paths (Ollama chat and generate, Bedrock converse and converse_stream, Google GenAI generate_content, streamed OpenAI chat) gives your PR something to link to and keeps the other cases tracked. A maintainer could also keep this issue open instead. I'd just rather the leftovers don't vanish when it closes.