logfire icon indicating copy to clipboard operation
logfire copied to clipboard

instrument_anthropic: messages given as a generator are consumed before the request is sent

Open armanunix opened this issue 1 month ago • 0 comments

Description

Description

The Anthropic SDK accepts messages as any iterable. When messages is a generator and the client is instrumented with logfire.instrument_anthropic, Logfire reads the messages from the request options (to record them as gen_ai.input.messages) before the SDK serializes the request body. That consumes the generator, so the request is sent with no messages at all. A real API rejects such a request with HTTP 400, so a call that works without Logfire fails with it. The span still shows the messages as input.

Example code

import json, sys
from importlib.metadata import version
import anthropic, logfire
from opentelemetry.sdk.trace import SpanProcessor
try:
    import httpx2 as httpx                       # anthropic >= 1.0
except ImportError:
    import httpx

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])
SENT = []
def reply(request):                              # records what the server receives
    SENT.append(json.loads(request.content))
    return httpx.Response(200, json={"id": "msg_1", "type": "message", "role": "assistant", "model": "claude-x",
                                     "content": [{"type": "text", "text": "Paris."}], "stop_reason": "end_turn",
                                     "stop_sequence": None, "usage": {"input_tokens": 3, "output_tokens": 1}})
def client():
    return anthropic.Anthropic(api_key="x", base_url="http://mock", max_retries=0,
                               http_client=httpx.Client(transport=httpx.MockTransport(reply)))
plain, traced = client(), client()
logfire.instrument_anthropic(traced)
KW = dict(model="claude-x", max_tokens=50)

def as_list():
    return [{"role": "user", "content": "What is the capital of France?"}]
def as_generator():
    yield {"role": "user", "content": "What is the capital of France?"}

for name in ("logfire", "logfire-sdk"):
    try:
        print(f"{name} {version(name)} | anthropic {version('anthropic')} | python {sys.version.split()[0]}"); break
    except Exception:
        pass
for label, c in (("without Logfire", plain), ("with Logfire   ", traced)):
    for form, msgs in (("list     ", as_list), ("generator", as_generator)):
        SENT.clear(); spans.ended.clear()
        answer = c.messages.create(messages=msgs(), **KW).content[0].text
        recorded = next((s.attributes["gen_ai.input.messages"] for s in spans.ended if "gen_ai.input.messages" in s.attributes), None)
        print(f"{label}, messages as a {form}: app got {answer!r}; messages the server received: "
              f"{len(SENT[-1]['messages'])}; span input messages: {recorded}")

Output (logfire 5.2.0 from PyPI; main at ac9722e519 / logfire-sdk 6.0.0b8 prints the same):

logfire 5.2.0 | anthropic 1.15.0 | python 3.13.7
without Logfire, messages as a list     : app got 'Paris.'; messages the server received: 1; span input messages: None
without Logfire, messages as a generator: app got 'Paris.'; messages the server received: 1; span input messages: None
with Logfire   , messages as a list     : app got 'Paris.'; messages the server received: 1; span input messages: [{"role":"user","parts":[{"type":"text","content":"What is the capital of France?"}]}]
with Logfire   , messages as a generator: app got 'Paris.'; messages the server received: 0; span input messages: [{"role":"user","parts":[{"type":"text","content":"What is the capital of France?"}]}]

Expected

The request is the same with and without Logfire: the iterable is turned into a list once and that list is both recorded and sent, or Logfire only reads messages when it is a list.

Python, Logfire & OS Versions, related packages (not required)

- logfire 5.2.0 (PyPI) and logfire `main` at commit ac9722e519 (installed from git; logfire-sdk 6.0.0b8)
- anthropic 1.15.0, opentelemetry-sdk 1.45.1
- Python 3.13.7, macOS; also reproduced on Ubuntu Linux with Python 3.12.3 (logfire 5.1.1, 5.2.0 and main)

armanunix avatar Oct 18 '26 17:10 armanunix