Skip to content

fix: materialize generator messages in instrument_anthropic - #2714

Merged
alexmojaki merged 4 commits into
pydantic:mainfrom
fxia0018:fix/anthropic-generator-messages
Nov 16, 2026
Merged

alexmojaki merged 4 commits into
pydantic:mainfrom
fxia0018:fix/anthropic-generator-messages

Conversation

@fxia0018

@fxia0018 fxia0018 commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #2587

Problem

instrument_anthropic reads messages from the request options to record gen_ai.input.messages before the Anthropic SDK serializes the request body. The SDK accepts messages as 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-list messages iterable into a list and write it back to options.json_data before 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_messages asserting that a generator messages is materialized into a list (written back to options.json_data) and recorded as gen_ai.input.messages correctly.

Signed-off-by: Jace Xia [email protected]

View guided diff

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]>
@fxia0018 fxia0018 changed the title fix: materialize generator in instrument_anthropic fix: materialize generator messages in instrument_anthropic Nov 3, 2026

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

@github-actions

github-actions Bot commented Nov 3, 2026 •

Copy link
Copy Markdown
Contributor

Coverage report

Click to see where and how coverage changed

FileStatementsMissingCoverageCoverage
(new stmts)
Lines missing
  logfire-sdk/logfire/_internal/integrations/llm_providers
  anthropic.py
Project Total  

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 chrikrah left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@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?

@fxia0018

Copy link
Copy Markdown
Contributor Author

Thanks for the detailed review and the repro, @chrikrah! Applied the suggested change in 2481d7a: widened the messages annotation to Iterable[dict[str, Any]]. Locally pyright now reports 0 errors on the file, and tests/otel_integrations/test_anthropic.py passes (55 passed).

@veria-ai

veria-ai Bot commented Nov 13, 2026 •

Copy link
Copy Markdown

Reviews

`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]]`.
@fxia0018
fxia0018 force-pushed the fix/anthropic-generator-messages branch from 2481d7a to 197822d Compare November 13, 2026 08:22
@alexmojaki
alexmojaki added this pull request to the merge queue Nov 16, 2026

@chrikrah chrikrah left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@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.

@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to failed status checks Nov 16, 2026
@alexmojaki
alexmojaki added this pull request to the merge queue Nov 16, 2026
Merged via the queue into pydantic:main with commit 54bf26d Nov 16, 2026
30 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

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

3 participants