openllmetry icon indicating copy to clipboard operation
openllmetry copied to clipboard

🐛 Bug Report: penAI instrumentation consumes generator/iterator `messages` and `tools`, so the model receives an empty conversation (default settings)

Open armanunix opened this issue 2 months ago • 3 comments

Which component is this bug for?

OpenAI Instrumentation

📜 Description

The OpenAI SDK accepts messages and tools as any iterable, including generators and map() objects, and sends them correctly. With the OpenAI instrumentation active (default settings), these one-shot iterables are consumed by the instrumentation while recording content, and the SDK then sends an empty list to the API:

  • messages=(m for m in history) → the request contains 0 messages
  • messages=map(...) → 0 messages
  • tools=(t for t in tools) → the request contains 0 tools
  • same for AsyncOpenAI

Meanwhile the span records the full messages and tools, so the trace shows a conversation the model never received.

Impact:

  • Empty messages: the real API rejects the request (400), but only when tracing is on; disabling tracing to debug makes the error disappear.
  • Empty tools: the request is valid, so the model silently answers without access to its tools: no error, changed agent behavior, and the trace still lists the tools.

The consumption happens in the content-recording path: with TRACELOOP_TRACE_CONTENT=false the requests are correct. Since content recording is on by default, the default configuration is affected.

👟 Reproduction steps

Self-contained (mock HTTP transport, no API key):

import json, httpx, openai
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import SimpleSpanProcessor
from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter
from opentelemetry.instrumentation.openai import OpenAIInstrumentor

exporter = InMemorySpanExporter()
provider = TracerProvider(); provider.add_span_processor(SimpleSpanProcessor(exporter))
OpenAIInstrumentor().instrument(tracer_provider=provider)

received = []
def handler(request):
    body = json.loads(request.content)
    received.append({"messages": len(body.get("messages", [])), "tools": len(body.get("tools", []))})
    return httpx.Response(200, json={"id": "c1", "object": "chat.completion", "created": 0, "model": "m",
        "choices": [{"index": 0, "finish_reason": "stop", "message": {"role": "assistant", "content": "ok"}}],
        "usage": {"prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2}})
client = openai.OpenAI(api_key="x", base_url="http://mock/v1",
                       http_client=httpx.Client(transport=httpx.MockTransport(handler)))

MSGS = [{"role": "system", "content": "be brief"}, {"role": "user", "content": "hi"}]
TOOLS = [{"type": "function", "function": {"name": "get_weather", "parameters": {"type": "object"}}}]

client.chat.completions.create(model="m", messages=(m for m in MSGS))
print("messages generator -> server received:", received[-1], "(expected 2 messages)")

client.chat.completions.create(model="m", messages=MSGS, tools=(t for t in TOOLS))
print("tools generator    -> server received:", received[-1], "(expected 1 tool)")

👍 Expected behavior

The request sent to the API is identical with and without instrumentation: 2 messages and 1 tool. The instrumentation should not consume one-shot iterables, e.g. by materializing them once (list(...)) and passing the materialized list on to the wrapped call.

👎 Actual Behavior with Screenshots

Default settings (and TRACELOOP_TRACE_CONTENT=true):

messages generator -> server received: {'messages': 0, 'tools': 0} (expected 2 messages)
tools generator    -> server received: {'messages': 2, 'tools': 0} (expected 1 tool)

With TRACELOOP_TRACE_CONTENT=false:

messages generator -> server received: {'messages': 2, 'tools': 0} (expected 2 messages)
tools generator    -> server received: {'messages': 2, 'tools': 1} (expected 1 tool)

Also reproduced with messages=map(...) and with AsyncOpenAI.

🤖 Python Version

3.12

📃 Provide any additional context for the Bug.

  • opentelemetry-instrumentation-openai 0.62.4 and current main (same result); openai 2.54.0; opentelemetry-sdk 1.45.0; Ubuntu 24.04.
  • OpenInference's OpenAI instrumentation handles the same inputs correctly (the full request is sent).

👀 Have you spent some time to check if this bug has been raised before?

  • [x] I checked and didn't find similar issue

Are you willing to submit PR?

Yes I am willing to submit a PR!

armanunix avatar Oct 01 '26 17:10 armanunix

The Anthropic instrumentation (opentelemetry-instrumentation-anthropic 0.62.4 and current main) has the same behavior with default settings: generator messages and tools are consumed before the request is sent.

Input passed as a generator Without instrumentation With instrumentation
messages (3 messages) 3 sent 0 sent
tools (1 tool) 1 sent 0 sent

Minimal reproduction (anthropic 1.11.0, mock transport, no API key):

import json, anthropic
try:
    import httpx2 as httpx       
except ImportError:
    import httpx
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.instrumentation.anthropic import AnthropicInstrumentor

AnthropicInstrumentor().instrument(tracer_provider=TracerProvider())

received = []
def handler(request):
    b = json.loads(request.content)
    received.append({"messages": len(b.get("messages", [])), "tools": len(b.get("tools", []))})
    return httpx.Response(200, json={"id": "msg_1", "type": "message", "role": "assistant", "model": "m",
        "content": [{"type": "text", "text": "ok"}], "stop_reason": "end_turn", "stop_sequence": None,
        "usage": {"input_tokens": 1, "output_tokens": 1}})
client = anthropic.Anthropic(api_key="x", base_url="http://mock",
                             http_client=httpx.Client(transport=httpx.MockTransport(handler)))
MSGS = [{"role": "user", "content": "hi"}, {"role": "assistant", "content": "hello"},
        {"role": "user", "content": "weather?"}]
TOOLS = [{"name": "get_weather", "input_schema": {"type": "object"}}]

client.messages.create(model="m", max_tokens=10, messages=(m for m in MSGS))
print("messages generator:", received[-1])   # expected 3 messages, got 0
client.messages.create(model="m", max_tokens=10, messages=MSGS, tools=(t for t in TOOLS))
print("tools generator:   ", received[-1])   # expected 1 tool, got 0

The same fix (materialize the iterable once and pass the list on to the wrapped call) would apply to both the OpenAI and Anthropic packages. OpenInference's Anthropic instrumentation sends the full request for the same inputs.

armanunix avatar Oct 01 '26 22:10 armanunix

I've opened PR #4544 fixing this for both the OpenAI and Anthropic packages.

The instrumentation now materializes one-shot iterables (messages, tools, and system where applicable) exactly once and writes the list back into the call kwargs before recording, so the request sent to the API is identical with and without instrumentation. Only true iterators are touched (iter(value) is value — generators, map() objects, iter() results); lists and tuples pass through untouched.

Verified with the issue's mock-transport harness: generator messages/tools now deliver the full 2 messages / 1 tool to the API on both packages, and the span still records them. New regression tests (10 OpenAI + 7 Anthropic) fail on the unpatched code and pass with the fix.

rupak-eng avatar Oct 03 '26 04:10 rupak-eng

The span still records the consumed messages, so the trace looks correct while the request is not. With messages passed as a generator, the span's gen_ai.input.messages contains the user message, but the HTTP request body has "messages": []. Anyone debugging from the trace sees a normal prompt and has no indication that the model received an empty conversation.

armanunix avatar Oct 04 '26 15:10 armanunix