Repository navigation
fix: materialize generator messages in instrument_anthropic - #2714
Conversation
instrument_anthropic reads `messages` from the request options to record `gen_ai.input.messages` before the SDK serializes the request body. When `messages` is a generator (the Anthropic SDK accepts any iterable), that read consumes it, so the request is sent with no messages and the API rejects it with HTTP 400. Materialize a non-list iterable into a list and write it back to `options.json_data` so the SDK serializes the same list instead of the now-consumed generator. Fixes pydantic#2587 Signed-off-by: Jace Xia <[email protected]>
There was a problem hiding this comment.
All reported issues were addressed across 2 files
Reply to a comment to ask cubic a question or push back. It learns from your replies.
View guided diff | Re-trigger cubic
Coverage reportClick to see where and how coverage changed
This report was generated by python-coverage-comment-action |
||||||||||||||||||||||||
Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com>
Add a test asserting that when combined semconv versions (v1 + v2) are used, the filtered json_data copy backing request_data['messages'] also holds the materialized list, matching the json_data write-back added in 5d9a1f6.
chrikrah
left a comment
There was a problem hiding this comment.
@fxia0018 blocking: the red lint and check at 6b28ca3 come from pyright on line 128. messages is annotated list[dict[str, Any]] two lines above, so pyright calls the new isinstance unnecessary. Widening the annotation clears it, and the isinstance has to stay, since it is what materializes the generator.
-from collections.abc import Callable
+from collections.abc import Callable, Iterable
@@
- messages: list[dict[str, Any]] = json_data.get('messages', [])
+ messages: Iterable[dict[str, Any]] = json_data.get('messages', [])# git archive 6b28ca3 (base 0a17b8d), pyright 1.1.414, Python 3.14.7, logfire.__file__ under the tree
$ pyright --pythonpath .venv/bin/python logfire-sdk/logfire/_internal/integrations/llm_providers/anthropic.py
6b28ca3: 128:24 - error: Unnecessary isinstance call; "list[dict[str, Any]]" is always an instance of "list[Unknown]"
1 error, 0 warnings, 0 informations
with the diff: 0 errors, 0 warnings, 0 informations
$ python -m pytest tests/otel_integrations/test_anthropic.py -k materialize
with the diff: 2 passed, 53 deselected
# earlier run, Python 3.12.14, anthropic 2.6.0
anthropic.py from 0a17b8d, tests kept: 2 failed, 53 deselected
# anthropic.Anthropic over an httpx2 MockTransport, instrument_anthropic(client), messages=<one-item generator>
base: body messages sent: []
6b28ca3: body messages sent: [{'role': 'user', 'content': 'Hello'}]
# not run: the rest of tests/, only the anthropic file
With those two lines in, nothing else blocks a merge from my side. Would you like this as an inline suggestion on line 120 so it applies in one click?
`messages` was annotated `list[dict[str, Any]]`, so pyright flagged the `isinstance(messages, list)` check that materializes generators as unnecessary. The Anthropic SDK accepts any iterable there, so annotate it as `Iterable[dict[str, Any]]`.
2481d7a to
197822d
Compare
chrikrah
left a comment
There was a problem hiding this comment.
@fxia0018 197822d clears the pyright error I blocked on, and pyright now reports zero errors on the whole tree. From my perspective this can be merged.
# git archive 197822d (base 0a17b8d), uv sync --frozen, Python 3.12, logfire.__file__ under the export
$ uv run --frozen pyright # pyright 1.1.414, whole tree, as `make typecheck`
0 errors, 0 warnings, 2 informations
$ uv run --frozen ruff check && uv run --frozen ruff format --check # ruff 0.16.10
All checks passed!
294 files already formatted
$ uv run --frozen pytest -q tests/otel_integrations/test_anthropic.py
55 passed
# anthropic.py from 0a17b8d, tests kept, -k materialize
2 failed
# not run: the rest of tests/, Pythons other than 3.12
Thanks for taking the annotation as written.
Fixes #2587
Problem
instrument_anthropicreadsmessagesfrom the request options to recordgen_ai.input.messagesbefore the Anthropic SDK serializes the request body. The SDK acceptsmessagesas any iterable, and when it's a generator, that read consumes it — so the request is then serialized with no messages and the API rejects it with HTTP 400. A call that works without Logfire fails with it.Fix
In
get_endpoint_config, materialize a non-listmessagesiterable into a list and write it back tooptions.json_databefore converting to semconv. The SDK then serializes the same materialized list instead of the now-consumed generator, so recording the input no longer changes the request.Test
Added
test_get_endpoint_config_materializes_generator_messagesasserting that a generatormessagesis materialized into a list (written back tooptions.json_data) and recorded asgen_ai.input.messagescorrectly.Signed-off-by: Jace Xia [email protected]