OpenAI with_streaming_response calls record no response (no output, response id, finish reasons or usage)
Description
With logfire.instrument_openai(), a call made through client.chat.completions.with_streaming_response.create(...) gets a span, but the span records nothing of the response: no gen_ai.output.messages, gen_ai.response.id, gen_ai.response.finish_reasons or gen_ai.usage.*, although the app receives and parses the full answer. The same call through client.chat.completions.create(...) records all of them.
with_streaming_response is the OpenAI SDK's documented way to read response headers or stream the raw body, so these calls show up in the traces with no answer and no token usage (and so no cost).
In the code, on_response unwraps only LegacyAPIResponse (what with_raw_response returns) before reading the response (openai.py#L624-L626). with_streaming_response returns an openai._response.APIResponse, which is not unwrapped, so getattr(response, "id", ...) and the rest find nothing. Since the body of an APIResponse is only read when the app calls parse(), the response would have to be recorded at that point (or when the context manager exits).
Example code
Runs as is, with a local mock transport (no API key needed):
# OpenAI with_streaming_response: the span records nothing of the response; the plain call records it.
import json, sys
from importlib.metadata import version
import httpx, openai, logfire
from opentelemetry.sdk.trace import SpanProcessor
class Spans(SpanProcessor):
def __init__(self): self.ended = []
def on_end(self, span): self.ended.append(span)
spans = Spans()
logfire.configure(send_to_logfire=False, console=False, additional_span_processors=[spans])
def reply(request):
return httpx.Response(200, json={"id": "chatcmpl-1", "object": "chat.completion", "created": 0, "model": "gpt-4o-mini",
"choices": [{"index": 0, "finish_reason": "stop", "message": {"role": "assistant", "content": "Hello there"}}],
"usage": {"prompt_tokens": 11, "completion_tokens": 5, "total_tokens": 16}})
client = openai.OpenAI(api_key="x", base_url="http://mock/v1", http_client=httpx.Client(transport=httpx.MockTransport(reply)))
logfire.instrument_openai(client)
KEYS = ("gen_ai.output.messages", "gen_ai.response.id", "gen_ai.response.finish_reasons", "gen_ai.usage.output_tokens")
MSGS = [{"role": "user", "content": "hi"}]
def plain():
return client.chat.completions.create(model="gpt-4o-mini", messages=MSGS).choices[0].message.content
def streaming_response():
with client.chat.completions.with_streaming_response.create(model="gpt-4o-mini", messages=MSGS) as r:
return r.parse().choices[0].message.content
def v(*names):
for n in names:
try: return f"{n} {version(n)}"
except Exception: pass
print(f"{v('logfire', 'logfire-sdk')} | openai {version('openai')} | python {sys.version.split()[0]}")
for label, fn in (("chat.completions.create", plain), ("chat.completions.with_streaming_response.create", streaming_response)):
spans.ended.clear()
got = fn()
print(f"{label}: app got {got!r}, spans: {len(spans.ended)}")
for k in KEYS:
print(f" {k} = {next((s.attributes[k] for s in spans.ended if k in s.attributes), None)}")
Output:
logfire-sdk 6.0.0b8 | openai 3.27.0 | python 3.12.3
chat.completions.create: app got 'Hello there', spans: 1
gen_ai.output.messages = [{"role":"assistant","parts":[{"type":"text","content":"Hello there"}],"finish_reason":"stop"}]
gen_ai.response.id = chatcmpl-1
gen_ai.response.finish_reasons = ["stop"]
gen_ai.usage.output_tokens = 5
chat.completions.with_streaming_response.create: app got 'Hello there', spans: 1
gen_ai.output.messages = None
gen_ai.response.id = None
gen_ai.response.finish_reasons = None
gen_ai.usage.output_tokens = None
Expected
A call through with_streaming_response records the response like the plain call: output messages, response id, finish reasons and token usage.
Python, Logfire & OS Versions, related packages (not required)
- logfire `main` at commit 01acf9fb274a8ccc72c513b7f1dfc8bfafc041a5 (installed from git; logfire-sdk 6.0.0b8). logfire 5.1.1 from PyPI behaves the same.
- Python 3.12.3, Ubuntu Linux
- openai 3.27.0, opentelemetry-sdk 1.45.1
I'd like to work on this. Reproduced on main. One catch: the request span has already ended when with_streaming_response returns the APIResponse, so it needs to stay open until parse() (or close) to record the response. I'll open a PR with sync and async tests.