[complexity] Bring 17 Anthropic adapter functions under the cognitive complexity limit of 15

Merged
DS
1mo ago
+850-748

This pull request was posted by Claude Code using claude-opus-5-5 on behalf of David.

Why we make these changes

The cognitive complexity gate from #11117 allows 15 per function. 17 functions in the Anthropic adapter package scored over that on main, 594 points in total: its stream, its response parser, its native-tool, tool_choice, beta-header and container resolvers, its user-prompt and model-response mappers, its request-turn and cache-control placement, its message-creation retry, the unpaired-native-call pass, the fetched-page scan, the usage mappers and the error mapper. This PR brings each to 15 or under with no change in behavior. It is part of #10983, which it does not close.

Each function took the fix agent_docs/complexity.md names for its shape, and stays in the module it lives in:

  • Stream: _get_event_iterator forwards a sync _map_event match once. Each event type maps in its own method, the server and MCP tool-use block starts in their own arms, and a tool-call delta is yield from over handle_tool_call_delta_events. The current block, ignored server-tool indices, pending citations, fetched pages and native tool calls kept across events move to field(init=False) fields.
  • Part-ladders: _process_response, _map_model_response and _map_user_prompt match on the block, part or content type. Text maps in _map_text_block and _map_text_part; an UploadedFile maps in _map_uploaded_file, which the tool-return mapper now shares.
  • Vocab translators: _add_native_tools and _tool_choice_declarations match over the native tool and resolved tool_choice. The tool search, memory and MCP server variants build in _map_tool_search_tool, with_native_memory_tool and map_mcp_server_tool, beside the existing map_advisor_tool.
  • Response metadata: the non-streamed provider_details build in response_provider_details, and the refusal keys in refusal_details, which the stream's message_delta shares. extract_usage_details totals iterations in iteration_usage_details, with one iteration_totals for compaction and advisor; map_usage builds the genai-prices view in usage_to_extract.
  • Request setup: _get_betas_and_extra_headers reads the history's betas in _message_betas, and _request_parts replaces four copies of the same two-level scan. _messages_create's create closure becomes _create_message. _get_container matches the anthropic_container setting. _apply_message_cache_control finds Bedrock's breakpoint candidates in lasting_messages.
  • Passes and checks: drop_unpaired_native_tool_calls indexes results in returned_tool_call_ids and moves a dropped call's cache boundary in keep_cache_boundary_before. api_error classifies the body in error_category and returns early for a stream error event. fetched_pages_from_history and _append_model_request_turns take guard clauses only.

No # complexipy: ignore is added. The # noqa: C901 on _get_event_iterator and _add_native_tools go; _process_response keeps its own and the new _map_content_block_start gets one, since ruff's C901 counts each case (complexipy scores them 11 and 3). Open PRs #11039, #11210, #11211, #11781 and #11871 edit some of these functions and rebase on this one.

New public surface

None. Every new function, method and field is private.

Verification

  • Existing tests and inline snapshots pass unchanged: the 28 Anthropic test files, and the Anthropic cases (-k "anthropic or claude") of 126 cross-provider test files (listed below). No test file, snapshot or cassette changes.
  • Requests and stream events are identical, main against this branch, with tests/refactor_capture.py, over the same selection: 1,128 nodes on each side, with 2,885 Anthropic requests from 994 nodes and 1,446 Anthropic streams carrying 27,328 events from 425 nodes. A second capture over every node of the cross-provider files adds 5,076 nodes. Every differing record is content that changes between runs, not an Anthropic stream or request (details below).
  • scripts/check_complexity.py passes. Every function in the changed files scores 15 or under, and the 26 new private functions and methods score 0 to 11.

What changes for existing users

Nothing.

Test files, capture nodes and results

Existing tests, at 0b1166e460 (ea6673c0b9 after it changes only the annotation of iteration_totals's kind):

  • uv run pytest -p no:randomly -q <Anthropic files> over tests/models/anthropic/test_automatic_caching_clients.py, tests/models/anthropic/test_bedrock_api_version.py, tests/models/anthropic/test_binary_content_retries.py, tests/models/anthropic/test_cache_diagnostics.py, tests/models/anthropic/test_carried_thinking.py, tests/models/anthropic/test_code_execution_clients.py, tests/models/anthropic/test_code_execution_files.py, tests/models/anthropic/test_compact_messages.py, tests/models/anthropic/test_context_size.py, tests/models/anthropic/test_count_tokens_clients.py, tests/models/anthropic/test_implicit_stream.py, tests/models/anthropic/test_max_tokens.py, tests/models/anthropic/test_native_tool_filtering.py, tests/models/anthropic/test_output.py, tests/models/anthropic/test_stream_parity.py, tests/models/anthropic/test_strict_schema_limits.py, tests/models/anthropic/test_thinking_block_binding_wire.py, tests/models/anthropic/test_thinking_block_binding.py, tests/models/anthropic/test_thinking_tag_mimicry.py, tests/models/anthropic/test_tool_search.py, tests/models/anthropic/test_unpaired_native_tool_calls.py, tests/models/anthropic/test_web_tools.py, tests/models/test_anthropic_batch_vcr.py, tests/models/test_anthropic_batch.py, tests/models/test_anthropic_bedrock_count_tokens.py, tests/models/test_anthropic_loaded_capability_instructions.py, tests/models/test_anthropic_mid_conversation_system.py, tests/models/test_anthropic.py: 999 passed.
  • uv run pytest -p no:randomly -q -k "anthropic or claude" <cross-provider files> over tests/clai2/test_accounts.py, tests/clai2/test_auth_profiles.py, tests/clai2/test_claude_glm_settings.py, tests/clai2/test_effort_command.py, tests/clai2/test_imported_sessions.py, tests/clai2/test_model_chains.py, tests/clai2/test_model_configuration.py, tests/clai2/test_model_defaults.py, tests/clai2/test_model_menu.py, tests/clai2/test_plugin_error_reporting.py, tests/clai2/test_plugin_model_providers.py, tests/clai2/test_retry_after.py, tests/clai2/test_run_model_layers.py, tests/clai2/test_startup_imports.py, tests/clai2/test_status.py, tests/clai2/test_stock_agent.py, tests/clai2/test_task_catalog.py, tests/clai2/test_web_models.py, tests/durable_exec/temporal/test_model_and_serialization.py, tests/harness/advisor/test_advisor.py, tests/harness/advisor/test_output.py, tests/harness/compaction/test_capability_loads.py, tests/harness/compaction/test_compaction.py, tests/harness/compaction/test_context_budget.py, tests/harness/compaction/test_tool_discoveries.py, tests/harness/gh_aw/test_engine_definition.py, tests/harness/logfire_mcp/test_capability.py, tests/harness/memory/test_memory.py, tests/harness/planning/test_planning.py, tests/harness/spend/test_spend.py, tests/harness/subagents/test_subagents_models.py, tests/harness/system_reminders/test_system_reminders.py, tests/harness/test_capability_combine.py, tests/harness/test_docs_examples.py, tests/harness/trajectory_judge/test_trajectory_judge.py, tests/harness/warn_on_cache_busts/test_warn_on_cache_busts.py, tests/models/bedrock/test_cache.py, tests/models/bedrock/test_native_output.py, tests/models/bedrock/test_stream_parity.py, tests/models/bedrock/test_strict_tool_calls.py, tests/models/google/test_code_execution.py, tests/models/google/test_media.py, tests/models/openrouter/test_cache.py, tests/models/test_batch_runs.py, tests/models/test_bedrock.py, tests/models/test_citations.py, tests/models/test_deepseek.py, tests/models/test_error_categories.py, tests/models/test_fallback.py, tests/models/test_github_copilot.py, tests/models/test_google.py, tests/models/test_groq.py, tests/models/test_huggingface.py, tests/models/test_instrumented.py, tests/models/test_mistral.py, tests/models/test_model_names.py, tests/models/test_model_settings_delta.py, tests/models/test_model_settings_support.py, tests/models/test_model.py, tests/models/test_multimodal_tool_returns.py, tests/models/test_native_tool_settings_support.py, tests/models/test_openai_prompt_cache.py, tests/models/test_openai_responses.py, tests/models/test_openai.py, tests/models/test_openrouter.py, tests/models/test_prompt_cache_retention.py, tests/models/test_request_scoped_system_prompts.py, tests/models/test_streamed_continuation.py, tests/models/test_tool_choice_matrix.py, tests/models/test_tool_choice_unit.py, tests/models/test_unattributed_compaction.py, tests/models/test_xai.py, tests/profiles/test_prompt_cache_outlook.py, tests/profiles/test_resolution_matrix.py, tests/providers/test_anthropic.py, tests/providers/test_bedrock.py, tests/providers/test_gateway_cost.py, tests/providers/test_gateway.py, tests/providers/test_litellm.py, tests/providers/test_provider_names.py, tests/test_ag_ui.py, tests/test_agent.py, tests/test_builtin_tools.py, tests/test_cache_prefix_stability.py, tests/test_cache_setting.py, tests/test_canonical_system_live.py, tests/test_canonical_system.py, tests/test_capability_file_understanding.py, tests/test_capability_hooks.py, tests/test_capability_model_fallback.py, tests/test_capability_pending_messages.py, tests/test_capability_spec.py, tests/test_choices.py, tests/test_cli.py, tests/test_code_execution_files_vcr.py, tests/test_exceptions.py, tests/test_function_model_prefix.py, tests/test_gateway_model_name_suggestions.py, tests/test_history_append_only.py, tests/test_history_invariants.py, tests/test_history_properties.py, tests/test_httpx2_sdk_readiness.py, tests/test_images.py, tests/test_instruction_updates.py, tests/test_loaded_capability_instructions.py, tests/test_messages.py, tests/test_model_name_suggestions.py, tests/test_ref_sibling_wire_contract.py, tests/test_retry_feedback.py, tests/test_server_state.py, tests/test_settings.py, tests/test_streaming_errors.py, tests/test_sync_stream_loop_affinity.py, tests/test_system_prompt_part_metadata.py, tests/test_thinking_max_effort.py, tests/test_thinking_native_tools.py, tests/test_thinking_placement.py, tests/test_thinking.py, tests/test_tool_availability_portability.py, tests/test_tool_availability.py, tests/test_tool_failed_wire.py, tests/test_tool_population_diff.py, tests/test_tool_search.py, tests/test_transcript_repair.py, tests/test_unreadable_tool_files.py, tests/test_vercel_ai.py: 828 passed, 7 skipped, 5 xfailed.

Requests and stream events. uv run python -m tests.refactor_capture 425167ad1d -p no:randomly -q -k "anthropic or claude" <both lists>, at 0b1166e460. Pytest -k also matches module and package names, so every node in the Anthropic files runs.

Result: 1,128 nodes and 4,950 records on each side; only in main 0, only in branch 0, differing 1. Stream module pydantic_ai.models.anthropic._streaming reached by 425 nodes, with 1,446 streams and 27,328 events, none differing. Anthropic requests: 2,885 from 994 nodes, all identical: 2,175 Messages API requests on the Claude API, Bedrock, Vertex, Foundry and proxy endpoints, 500 MockAnthropic.messages_create calls, 43 count_tokens calls and 167 batch requests.

The differing node is capture noise, not this change: tests/test_builtin_tools.py::test_builtin_tools_not_supported_file_search_stream[anthropic] differs only in the order of the Supported: [...] list in the unsupported-native-tool UserError, which models/__init__.py (unchanged here) builds from a frozenset of classes. A capture of this branch against itself on that node differs the same way in 3 of 3 runs.

A second capture, at ea6673c0b9, ran every node of the 126 cross-provider files, without -k, so it covers each Anthropic stream test in them whatever its name: 5,076 nodes and 14,933 records on each side; only in main 0, only in branch 0, differing 38. Anthropic streams: 741 streams and 5,561 events from 217 nodes; Anthropic requests: 1,056 from 375 nodes; none of them differs. The 38 differing records are FunctionModel, TestModel, continuation and MCP records whose content changes between runs (process ids, environment output, local-time timestamps, concurrent request order, and the frozenset order above). A capture of this branch against itself over the 38 nodes differs on 35 and records 2 on one side only; the last, tests/test_cli.py::test_mcp_config[False], differs only in the local time clai's instructions render.

At c9c2b0a3e4, which moves _request_parts onto AnthropicModel, a third capture over the 28 Anthropic files and the Anthropic cases of test_request_scoped_system_prompts.py, test_model_settings_delta.py, test_citations.py and test_tool_choice_matrix.py: 1,048 passed on each side, 740 nodes and 3,050 records on each side, none differing.

Nodes that reach each changed request mapper, picked from the request bodies they recorded, all identical on both sides (paths under tests/models/):

  • _add_native_tools, _map_tool_search_tool: anthropic/test_web_tools.py::test_anthropic_web_tools_allowed_callers[setting-direct-previous-versions], test_anthropic.py::test_anthropic_named_native_tool_search_withholds_capability_tool, anthropic/test_count_tokens_clients.py::test_count_tokens_server_tools_by_client[api]
  • with_native_memory_tool: anthropic/test_count_tokens_clients.py::test_count_tokens_server_tools_by_client[mantle]
  • map_mcp_server_tool: anthropic/test_unpaired_native_tool_calls.py::test_in_flight_mcp_call_history_is_accepted, test_anthropic.py::test_cache_point_after_replayed_mcp_tool_result
  • _add_native_tools (advisor): test_anthropic.py::test_anthropic_advisor_result_variants[plaintext]
  • _tool_choice_declarations: test_tool_choice_matrix.py::test_tool_choice_matrix[none-anthropic], test_tool_choice_matrix.py::test_tool_choice_matrix[list_single-anthropic], anthropic/test_output.py::test_no_tools_basemodel_output
  • _get_betas_and_extra_headers, _message_betas, _messages_use_anthropic_uploaded_file, _request_parts: test_anthropic.py::test_files_api_beta_added_only_for_anthropic_uploaded_file[image]
  • _get_betas_and_extra_headers, _message_betas, _request_parts: test_anthropic_mid_conversation_system.py::test_native_tool_availability_delta[claude-opus-5-5], test_request_scoped_system_prompts.py::test_anthropic_request_scoped_reminders_keep_thinking_and_cache[claude-opus-5-5], test_model_settings_delta.py::test_anthropic_effort_change_keeps_the_cache
  • _get_betas_and_extra_headers: test_anthropic.py::test_anthropic_speed_setting[fast], test_anthropic.py::test_anthropic_task_budget_adds_output_config_and_beta
  • _get_container: test_anthropic.py::test_anthropic_container_setting_id_only_dict_unwrapped_to_string, test_anthropic.py::test_anthropic_container_setting_dict_with_skills_passed_through, test_anthropic.py::test_anthropic_container_setting_false_ignores_history, anthropic/test_context_size.py::test_pause_turn_reads_context_from_last_segment
  • _get_container, _messages_create, _create_message: anthropic/test_code_execution_files.py::test_anthropic_code_execution_files_500_with_uploads_drops_history_container[500-retried]
  • _messages_create, _create_message: anthropic/test_code_execution_files.py::test_anthropic_code_execution_files_500_then_stale_thinking_block_still_retries, anthropic/test_max_tokens.py::test_default_max_tokens[custom-timeout]
  • _map_user_prompt, _map_uploaded_file: test_anthropic.py::test_uploaded_file_image
  • _map_user_prompt: test_anthropic.py::test_document_binary_content_input
  • _map_tool_return_part, _map_uploaded_file: test_anthropic.py::test_anthropic_citations_tool_return_documents[on]
  • _map_model_response, _map_text_part: test_citations.py::test_native_citation_replay_after_persisted_history[anthropic-messages]
  • _map_model_response: test_anthropic.py::test_anthropic_model_thinking_part_redacted, anthropic/test_compact_messages.py::test_compact_messages_replay[claude-sonnet-4-6]
  • _append_model_request_turns: test_anthropic_mid_conversation_system.py::test_mid_conversation_system_prompt_takes_cache_breakpoint, test_anthropic_mid_conversation_system.py::test_an_enqueued_instruction_is_inside_the_cache_point_that_follows_it
  • _apply_message_cache_control, lasting_messages: anthropic/test_automatic_caching_clients.py::test_automatic_caching_by_client[bedrock-sonnet-4-5-anthropic_cache]
  • drop_unpaired_native_tool_calls, returned_tool_call_ids: anthropic/test_unpaired_native_tool_calls.py::test_in_flight_mcp_call_history_is_accepted

Two branches reach no recorded request; the existing tests that call the mappers directly cover them: keep_cache_boundary_before (anthropic/test_unpaired_native_tool_calls.py::test_dropped_call_keeps_the_cache_boundary, test_dropped_call_skips_a_block_that_cannot_carry_the_boundary, test_dropped_call_hands_the_boundary_back_a_message_when_its_turn_cannot_carry_it, test_dropped_call_that_opens_the_payload_gives_up_its_boundary, test_dropped_call_hands_its_boundary_across_a_turn_that_cannot_carry_it, through _map_message), and the previous-request breakpoint lasting_messages places on Bedrock (test_anthropic.py::test_anthropic_cache_messages_marks_previous_request_after_wide_turn[bedrock], test_request_scoped_system_prompts.py::test_anthropic_bedrock_lookback_breakpoint_skips_the_request_scoped_entry, through _apply_message_cache_control).

Before and after scores: 594 → 189

Scored with complexipy 8.3.0 on main at 425167ad1d and on this branch.

FunctionFilemainafter
AnthropicStreamedResponse._get_event_iterator_streaming.py1533
drop_unpaired_native_tool_calls_message_passes.py4914
AnthropicModel._process_response__init__.py4111
AnthropicModel._add_native_tools__init__.py4112
AnthropicModel._messages_use_anthropic_uploaded_file__init__.py319
extract_usage_details_response.py3010
AnthropicModel._tool_choice_declarations__init__.py2915
AnthropicModel._map_user_prompt__init__.py2712
AnthropicModel._map_model_response__init__.py259
AnthropicModel._get_betas_and_extra_headers__init__.py2413
AnthropicModel._messages_create__init__.py239
api_error_errors.py2212
fetched_pages_from_history_citations.py2115
AnthropicModel._get_container__init__.py2111
AnthropicModel._apply_message_cache_control__init__.py2110
map_usage_response.py209
AnthropicModel._append_model_request_turns__init__.py1615
Total594189

All files are under pydantic_ai_slim/pydantic_ai/models/anthropic/. The 26 new private functions and methods score 0 to 11.

PR decisions

2026-11-08 · R13 scope re-scored on main 425167ad1d · iter -

  • Decision: 17 functions in scope, same set as the plan; _add_native_tools now 41 (plan 49), _get_container 21 (plan 18), fetched_pages_from_history 21, the rest unchanged; no other models/anthropic/ function over 15
  • Why: manager dispatch: re-score on current main first
  • Source: https://github.com/pydantic/pydantic-ai/tree/425167ad1d
  • Session: 03832d48-e4e7-4975-ab28-9151fef0b7cd

2026-11-08 · implement directly, no plan-only PR · iter -

  • Decision: initialize-worktree complexity question skipped: implement + PR
  • Why: manager dispatch fixes scope, shapes and decisions (D1, D2, D6, D7); a [relaying for david] session cannot take AskUserQuestion
  • Source: https://github.com/pydantic/pydantic-ai/issues/10983
  • Session: 03832d48-e4e7-4975-ab28-9151fef0b7cd

2026-11-08 · Stream: per-event methods on field(init=False) state · iter -

  • Decision: _get_event_iterator forwards a sync _map_event match once; one method per event type, server and MCP tool-use block starts in their own arms; current block, ignored indices, pending citations, fetched pages and builtin calls move to field(init=False); fetched pages seeded from _history_fetched_pages at iterator start, as the old local was
  • Why: this session's call, per agent_docs/complexity.md stream-state-machine and the R11/R12 shape
  • Source: https://github.com/pydantic/pydantic-ai/issues/10983
  • Session: 03832d48-e4e7-4975-ab28-9151fef0b7cd

2026-11-08 · noqa C901 kept on two match dispatchers · iter -

  • Decision: _map_content_block_start gets # noqa: C901 and _process_response keeps its own; _get_event_iterator and _add_native_tools lose theirs
  • Why: this session's call: ruff C901 counts each case (17 and 18), complexipy scores them 3 and 11; agent_docs/complexity.md#dispatch-on-type says a large dispatcher can need the noqa
  • Source: https://github.com/pydantic/pydantic-ai/issues/10983
  • Session: 03832d48-e4e7-4975-ab28-9151fef0b7cd

2026-11-08 · Shared helpers with several callers · iter -

  • Decision: _request_parts (4 history scans), _map_uploaded_file (user prompt and tool return), iteration_totals (compaction and advisor), refusal_details (stream and _process_response) each replace duplicated code
  • Why: this session's call: dedup that also cuts the in-scope functions; not single-use, so D1 is not needed for them
  • Source: https://github.com/pydantic/pydantic-ai/issues/10983
  • Session: 03832d48-e4e7-4975-ab28-9151fef0b7cd

2026-11-08 · D1 single-use extractions · iter -

  • Decision: error_category, iteration_usage_details, usage_to_extract, returned_tool_call_ids, keep_cache_boundary_before, _message_betas, lasting_messages, response_provider_details, with_native_memory_tool, map_mcp_server_tool, _map_tool_search_tool, _map_text_block, _map_text_part, _create_message
  • Why: D1 (David, 2026-11-01): allowed when guard clauses, match and arms cannot reach 15; the last five are arms of a match dispatch, _create_message hoists the existing create closure (closure-hosted case); api_error measured 18 with guards alone
  • Source: https://github.com/pydantic/pydantic-ai/issues/10983
  • Session: 03832d48-e4e7-4975-ab28-9151fef0b7cd

2026-11-08 · fetched_pages_from_history: guards only · iter -

  • Decision: continue guards bring it to exactly 15, so no helper is extracted
  • Why: D1 precondition: a single-use helper only when guards, match and arms cannot reach 15
  • Source: https://github.com/pydantic/pydantic-ai/issues/10983
  • Session: 03832d48-e4e7-4975-ab28-9151fef0b7cd

2026-11-08 · _messages_create binds _create_message with functools.partial · iter -

  • Decision: the create closure becomes the method _create_message; partial binds client, messages, settings, prepared and stream so the four retry call sites keep their argument lists; send and open_stream stay closures inside it
  • Why: this session's call: hoisting all three would repeat a nine-argument list at every send; the hoisted method scores 9
  • Source: https://github.com/pydantic/pydantic-ai/issues/10983
  • Session: 03832d48-e4e7-4975-ab28-9151fef0b7cd

2026-11-08 · pre-push review 1 of 3 at 0b1166e46074de4311e03fe65f952046ad7b7e34 · iter -

2026-11-08 · pre-push review 2 of 3 at ea6673c0b9347741edfb9674015adf8c3ca70c69 · iter -

2026-11-08 · No split proposed · iter -

  • Decision: R13 ships as one PR: 8 files, +851 -749, size: XL, below R11 #12816 (+973 -828, XL) and R10 #12764 (+1157 -997, XL), both merged as one PR
  • Why: dispatch: propose a split only if the diff grows past one reviewer sitting; this one is smaller than the two merged XL adapter PRs
  • Source: https://github.com/pydantic/pydantic-ai/pull/12833
  • Session: 03832d48-e4e7-4975-ab28-9151fef0b7cd

2026-11-08 · pre-push review 3 of 3 at c9c2b0a3e49ea9e2d68147f1ebbe665b8356f159 · iter -

2026-11-08 · douwebot: _request_parts scoped to AnthropicModel · iter -

  • Decision: _request_parts becomes a @staticmethod on AnthropicModel; scores unchanged
  • Why: douwebot finding, valid: agent_docs/index.md scopes helpers called more than once from one class to that class; models/anthropic/AGENTS.md keeps module-level helpers out of init.py
  • Source: https://github.com/pydantic/pydantic-ai/pull/12833#discussion_r4504744047
  • Session: 03832d48-e4e7-4975-ab28-9151fef0b7cd

Checklist

  • No breaking changes in accordance with the version policy.
  • Any permitted compatibility impact has a label, warning, migration and release note, and an exact API-check waiver if the gate reports it.
  • PR title is fit for the release changelog.