[complexity] Bring 14 Bedrock adapter functions under the cognitive complexity limit of 15
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. 14 functions in the Bedrock adapter scored over that on main, 691 points in total: its message, user-prompt and file mappers, its stream, its response parser, its thinking, top_k and tool_choice translators, its error mapper, its request builder and its cache-point helpers. 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, laid out as agent_docs/provider-adapters.md asks:
- Part-ladder:
_map_messagesbuilds a data-only_MapMessagesContextand dispatches each message to_map_model_requestor_map_model_response. The response dispatch is amatchover parts ending inassert_never, with_map_thinking_part,_map_native_tool_calland_map_native_tool_return. The request dispatch keeps itsisinstancechain because_UnpreparedPartis a union alias, as in #12764. Tool returns map in_map_tool_return,_map_tool_return_contentand_map_tool_return_file. The passes after the loop move to_merge_consecutive_user_messages,_add_instruction_cache_points,_add_message_cache_pointsand_check_citations_tool_choice, and the nestedflush_deferred_mediabecomes a module function. - User prompt and files:
_map_user_promptmatches over content. ItsUploadedFilearm and the tool-return one share_map_uploaded_file, and itsCachePointarm is_map_cache_point. - Stream:
_get_event_iteratorforwards a sync_map_chunkonce. Content block start, delta and stop are_map_content_block_*methods, reasoning deltas are_map_reasoning_delta, and the tool ids, native tool returns and citations kept across events move tofield(init=False)fields. - Response:
_process_responsemaps each content block kind in a_map_*_blockmethod. - Vocabulary translators:
_tool_choice_declarationsmatches on the resolved choice. The thinking variants move to_add_thinking_fields, amatchending inassert_never, andtop_kto_add_top_k_field. - Error mapper: the
ClientErrorarm moves to_map_client_error, as_map_status_errordoes inmodels/openai.py. - Single-use steps, as the guide allows:
_add_settings_params,_check_output_mode,_unified_thinking_type,_openai_responses_reasoning_effort,_tool_result_cannot_share_turn._insert_cache_point_before_trailing_documents,_add_anthropic_thinking_fields,_limit_cache_pointsand_map_file_to_content_blocktake guard clauses instead.
No # complexipy: ignore is added, and the three # noqa: C901 markers go. Open PRs #4622, #6570, #7919, #9774, #10368, #11054, #11084, #11131, #11491 and #11781 edit some of these functions and rebase on this one.
This PR changes only bedrock.py, with no test-file change. Bedrock requests go through botocore, which tests/refactor_capture.py doesn't record, so the request proof below ran with a hook on botocore's Endpoint.make_request applied locally. That hook lands in a separate tooling PR.
New public surface
None. Every new function, method and field is private.
Verification
- Existing tests and inline snapshots pass unchanged over the 39 test files that reach
bedrock.py(listed below). No test file, snapshot or cassette changes. - Requests and stream events are identical,
mainagainst this branch, withtests/refactor_capture.pyand the botocore hook applied locally, over 350 tests: 1,198 records on each side, 827 requests, and 151 tests with Bedrock streams carrying 7,392 events. The two differing tests differ between two runs of the same commit too (details below). scripts/check_complexity.pypasses. Every function inbedrock.pyscores 15 or under, and the 32 new private functions and methods score 1 to 13.
What changes for existing users
Nothing.
Test files, capture nodes and results
Existing tests. uv run pytest -p no:randomly <files> over tests/models/anthropic/test_carried_thinking.py, tests/models/bedrock/test_cache.py, tests/models/bedrock/test_contains.py, tests/models/bedrock/test_native_output.py, tests/models/bedrock/test_stream_parity.py, tests/models/bedrock/test_strict_schema_limits.py, tests/models/bedrock/test_strict_tool_calls.py, tests/models/test_bedrock_thread_cancellation.py, tests/models/test_bedrock.py, tests/models/test_citations.py, tests/models/test_model_names.py, tests/models/test_model_settings_support.py, tests/models/test_model.py, tests/models/test_multimodal_tool_returns.py, tests/models/test_prompt_cache_retention.py, tests/models/test_request_scoped_system_prompts.py, tests/models/test_system_voice_fallback.py, tests/models/test_tool_choice_matrix.py, tests/models/test_tool_choice_unit.py, tests/models/test_unattributed_compaction.py, tests/providers/test_bedrock_mantle.py, tests/providers/test_bedrock.py, tests/providers/test_gateway_cost.py, tests/providers/test_gateway.py, tests/test_cache_setting.py, tests/test_canonical_system_live.py, tests/test_canonical_system.py, tests/test_embeddings.py, tests/test_exceptions.py, tests/test_gateway_model_name_suggestions.py, tests/test_history_properties.py, tests/test_missing_usage.py, tests/test_model_name_suggestions.py, tests/test_retry_feedback.py, tests/test_streaming_errors.py, tests/test_thinking_placement.py, tests/test_thinking.py, tests/test_tool_failed_wire.py, tests/test_unreadable_tool_files.py: 2,556 passed, 90 skipped, 18 xfailed, at d8b037cbae. The later commit 5a0f5a1880 changes only _add_thinking_fields's fallback arm, a docstring and a default factory.
Requests and stream events. uv run python -m tests.refactor_capture d2992bc461 -p no:randomly -k bedrock <the same files>, at this PR's head 84e5876eee, with the botocore request hook (reverted here; it lands in the tooling PR) applied locally. An earlier run at 5a0f5a1880 gave the same result, plus the third noise node below. -k bedrock selects every test in the Bedrock test files and the Bedrock cases of the cross-provider ones, so it covers every Bedrock stream test.
Result: 350 nodes and 1,198 records on each side; only in main 0, only in branch 0, differing 2. Stream module pydantic_ai.models.bedrock reached by 151 nodes with 7,392 events, none differing. Requests reached 82 targets, 56 of them Bedrock Converse, ConverseStream and CountTokens endpoints across Nova, Claude, gpt-oss, GPT-5.6 and GPT-6, Qwen, Grok, Llama, Mistral, Writer, DeepSeek and other families.
The differing nodes are capture noise, not this change:
tests/models/test_model_settings_support.py::test_max_retries_keeps_the_bedrock_client_aws_profileandtest_max_retries_sets_how_many_attempts_the_sdk_makes[AnthropicModel[bedrock]]differ only in thex-amz-dateheader thatAnthropicModel's Bedrock client signs over httpx, outsidebedrock.py. A capture of this branch against itself over the same selection gives the same two differences.- In the run at
5a0f5a1880only,tests/models/test_bedrock.py::test_bedrock_streaming_erroralso differed, only in the key order of the replayed response'sHTTPHeadersinside the error it records. This branch has produced different orders in different runs.
Nodes that reach each changed request mapper, picked from the request bodies they recorded, all identical on both sides:
_map_model_request,_map_tool_return:test_bedrock.py::test_bedrock_model_retry,test_bedrock.py::test_bedrock_moonshotai_tool_call; withoutstatus:test_bedrock.py::test_bedrock_writer_tool_result_followed_by_text_accepted_map_tool_return_file:test_multimodal_tool_returns.py::test_mixed_content_ordering[bedrock_claude],test_bedrock.py::test_bedrock_mistral_tool_return_image_accepted_merge_consecutive_user_messages:test_bedrock.py::test_bedrock_llama_tool_result_followed_by_text_accepted,test_bedrock.py::test_bedrock_mistral_two_tool_returns_images_accepted- leading user turn:
test_bedrock.py::test_bedrock_model_with_instructions_only[nova-micro],test_bedrock.py::test_bedrock_model_instructions_only_then_message_history[nova-micro] _map_model_response,_map_thinking_part:test_bedrock.py::test_bedrock_model_thinking_part_anthropic,test_bedrock.py::test_bedrock_model_thinking_part_redacted; carried thinking:test_bedrock.py::test_bedrock_model_structured_output_map_native_tool_call,_map_native_tool_return:test_bedrock.py::test_bedrock_model_with_code_execution_tool,test_bedrock.py::test_bedrock_model_code_execution_tool_sandbox_timeout_add_instruction_cache_points,_add_message_cache_points,_limit_cache_points:test_bedrock.py::test_bedrock_cache_write_and_read,test_bedrock.py::test_unified_cache_reads_history_after_wide_turn_real_api_map_cache_point,_insert_cache_point_before_trailing_documents:test_bedrock.py::test_bedrock_cache_messages_trailing_text_document_after_cache_point,test_bedrock.py::test_bedrock_cache_write_and_read_check_citations_tool_choicepath, cited documents:test_citations.py::test_document_citations[bedrock-pdf],test_citations.py::test_bedrock_tool_return_document_citations_map_user_prompt,_map_file_to_content_block:test_bedrock.py::test_image_as_binary_content_input,test_bedrock.py::test_video_url_input,test_bedrock.py::test_document_url_input_map_uploaded_file:test_multimodal_tool_returns.py::test_multimodal_tool_return_matrix[tool_return_content-uploaded_file-image-bedrock_claude]_build_additional_model_request_fields,_add_thinking_fields,_add_anthropic_thinking_fields:test_bedrock.py::test_bedrock_anthropic_unified_max_effort,test_bedrock.py::test_bedrock_model_thinking_part_anthropic_adaptive_effort,test_bedrock.py::test_bedrock_thinking_high_openai_variant,test_bedrock.py::test_bedrock_thinking_false_openai_responses_variant_always_on,test_bedrock.py::test_bedrock_thinking_high_qwen_variant;top_k:test_bedrock.py::test_bedrock_top_k_nova_variant,test_bedrock.py::test_bedrock_top_k_anthropic_variant; nativetool_choicenone:test_bedrock.py::test_bedrock_tool_choice_none_after_tool_call_claude_tool_choice_declarations,_effective_thinking_type:test_bedrock.py::test_bedrock_specific_tool_choice_with_adaptive_thinking_runs,test_tool_choice_matrix.py::test_tool_choice_matrix[list_single-bedrock],test_bedrock.py::test_bedrock_model_structured_output_messages_create,_add_settings_params:test_bedrock.py::test_bedrock_model_other_parameters,test_bedrock.py::test_bedrock_model_service_tierprepare_request,_check_output_mode:test_bedrock.py::test_bedrock_zai_native_output,bedrock/test_native_output.py::test_bedrock_native_output_qwen- count tokens:
test_bedrock.py::test_bedrock_count_tokens_tool_config
Paths are under tests/models/. No Bedrock test sends a json-format tool result or a user-prompt UploadedFile over botocore; their arms are reached by the existing tests that call the mappers directly, and _map_uploaded_file by the tool-return node above.
Before and after scores: 691 → 151
All in pydantic_ai_slim/pydantic_ai/models/bedrock.py, scored with complexipy on main at d2992bc461 and on this branch.
| Function | main | after |
|---|---|---|
BedrockConverseModel._map_messages | 282 | 14 |
BedrockStreamedResponse._get_event_iterator | 92 | 4 |
BedrockConverseModel._map_user_prompt | 54 | 12 |
BedrockConverseModel._process_response | 40 | 13 |
BedrockConverseModel._build_additional_model_request_fields | 34 | 6 |
BedrockConverseModel._tool_choice_declarations | 28 | 9 |
BedrockConverseModel._messages_create | 26 | 12 |
_effective_thinking_type | 24 | 15 |
_map_api_errors | 22 | 4 |
_add_anthropic_thinking_fields | 19 | 13 |
BedrockConverseModel._map_file_to_content_block | 19 | 14 |
_insert_cache_point_before_trailing_documents | 18 | 11 |
BedrockConverseModel._limit_cache_points | 17 | 14 |
BedrockConverseModel.prepare_request | 16 | 10 |
| Total | 691 | 151 |
PR decisions
2026-11-07 · R11 scope re-scored on main 7e72d571ce · iter -
- Decision: 14 functions in scope, same set and scores as the plan (691 points); no other bedrock.py function over 15
- Why: manager dispatch: re-score on current main first
- Source: https://github.com/pydantic/pydantic-ai/tree/7e72d571ce
- Session: 8b577650-4849-4dc3-9cc0-36b9318d5272
2026-11-07 · 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); a [relaying for david] session cannot take AskUserQuestion
- Source: https://github.com/pydantic/pydantic-ai/issues/10983
- Session: 8b577650-4849-4dc3-9cc0-36b9318d5272
2026-11-07 · Proof W hook: botocore Endpoint.make_request · iter -
- Decision: Proof W records Bedrock requests by wrapping botocore.endpoint.Endpoint.make_request in tests/refactor_capture.py, applied locally uncommitted for R11's proofs; where it lands is still open (manager asking David)
- Why: Managing session's call, on this session's probe: it carries the extra headers and the body bytes, without SigV4 noise
- Source: https://github.com/pydantic/pydantic-ai/issues/10983
- Session: 8b577650-4849-4dc3-9cc0-36b9318d5272
2026-11-07 · Proof W tooling lands inside R11 as its own commit · iter -
- Decision: The Endpoint.make_request hook in tests/refactor_capture.py (plus the matching tests/AGENTS.md capture-section update) is committed inside R11, as a commit separate from the refactor commits; it is the one test-file change R11 allows
- Why: David's decision, relayed by the managing session
- Source: https://github.com/pydantic/pydantic-ai/issues/10983
- Session: 8b577650-4849-4dc3-9cc0-36b9318d5272
- Supersedes: Proof W hook: botocore Endpoint.make_request (landing place only)
2026-11-07 · pre-push review 1 of 3 at d8b037cbae78e6315b47f8a6dfe5598ce0be66f3 · iter -
- Decision: reserved; outcome pending
- Why: tree 3bf1772da17b6038561d326b7801afe62614be4a; scope d2992bc461036747488e4961cb176f5d161d8283..d8b037cbae78e6315b47f8a6dfe5598ce0be66f3 (full branch); policy base 58b007e6c33b48b739035a56dc0f1f3849debb50; first review; light tier (haiku) via claude -p in a detached policy-base worktree, read-only tools, no fan-out
- Source: https://github.com/pydantic/pydantic-ai/tree/bedrock-complexity
- Session: 8b577650-4849-4dc3-9cc0-36b9318d5272
2026-11-07 · pre-push review 1 of 3 at d8b037cbae78e6315b47f8a6dfe5598ce0be66f3 · iter -
- Decision: remediated: _add_thinking_fields falls through for an unknown or missing variant as main does (case _ no-op, not assert_never); _check_output_mode docstring names both guards; _citations default_factory is dict[int, list['CitationsDeltaTypeDef']] like its sibling fields (string forward ref, the TypeDef is TYPE_CHECKING-only)
- Why: reviewed tree 3bf1772da17b6038561d326b7801afe62614be4a; scope d2992bc461..d8b037cbae (full branch); haiku, read-only tools, no fan-out, detached policy-base worktree at 58b007e6c3; first launch failed on CLI args and second on the usage limit before reviewing, neither reached a verdict
- Source: https://github.com/pydantic/pydantic-ai/tree/bedrock-complexity
- Session: 8b577650-4849-4dc3-9cc0-36b9318d5272
- Supersedes: pre-push review 1 of 3 at d8b037cbae78e6315b47f8a6dfe5598ce0be66f3 (reserved)
2026-11-07 · response-part dispatch ends in assert_never · iter -
- Decision: _map_model_response matches every ModelResponsePart and ends in case _: assert_never(part), where main ended its isinstance chain with assert isinstance(item, ToolCallPart)
- Why: this session's call: models/AGENTS.md asks for exhaustive matching with assert_never; both raise AssertionError for an object outside the part union, only the message differs; the part union is the type of ModelResponse.parts, unlike the profile-supplied thinking variant
- Source: https://github.com/pydantic/pydantic-ai/tree/bedrock-complexity
- Session: 8b577650-4849-4dc3-9cc0-36b9318d5272
2026-11-07 · pre-push review 2 of 3 at 5a0f5a1880576d0d9a9a62cbdf978daad20acd39 · iter -
- Decision: reserved; outcome pending
- Why: tree 0109e06419ffc8c332f8eb58571feed787c774cd; scope d8b037cbae..5a0f5a1880576d0d9a9a62cbdf978daad20acd39 (remediation of review 1), full branch as context; policy base 6cd17b80f92b59d7edbdfbab30e54fce80fc7324; light tier (haiku) via claude -p in a detached policy-base worktree, read-only tools, no fan-out
- Source: https://github.com/pydantic/pydantic-ai/tree/bedrock-complexity
- Session: 8b577650-4849-4dc3-9cc0-36b9318d5272
2026-11-07 · _add_thinking_fields falls through for an unknown variant · iter -
- Decision: match on bedrock_thinking_variant ends in case _: pass (no fields, as on main), not case _: assert_never(variant)
- Why: this session's call: the dispatch requires behavior unchanged, and the variant comes from a profile a user can set through profile=, where main silently adds no thinking fields; cost: a Literal value added later without an arm is not caught by pyright; a maintainer may prefer assert_never
- Source: https://github.com/pydantic/pydantic-ai/tree/bedrock-complexity
- Session: 8b577650-4849-4dc3-9cc0-36b9318d5272
2026-11-07 · pre-push review 2 of 3 at 5a0f5a1880576d0d9a9a62cbdf978daad20acd39 · iter -
- Decision: no code change: the three review-1 findings verified fixed; its one finding (fall-through loses exhaustiveness) handled by recording the deliberate choice above, the reviewer's first option
- Why: reviewed tree 0109e06419ffc8c332f8eb58571feed787c774cd; scope d8b037cbae..5a0f5a1880, full branch as context; haiku, read-only tools, no fan-out, policy base 6cd17b80f9
- Source: https://github.com/pydantic/pydantic-ai/tree/bedrock-complexity
- Session: 8b577650-4849-4dc3-9cc0-36b9318d5272
- Supersedes: pre-push review 2 of 3 at 5a0f5a1880576d0d9a9a62cbdf978daad20acd39 (reserved)
2026-11-07 · thinking-variant fallback kept: case _: pass · iter -
- Decision: _add_thinking_fields keeps case _: pass for an unknown or missing bedrock_thinking_variant (no fields, as on main), not assert_never
- Why: the managing session's call: R11's hard constraint is behavior unchanged, and a user can set the variant through profile=; cost as stated in the entry it supersedes
- Source: https://github.com/pydantic/pydantic-ai/pull/12816
- Session: 8b577650-4849-4dc3-9cc0-36b9318d5272
- Supersedes: _add_thinking_fields falls through for an unknown variant
2026-11-07 · tooling placement re-opened; douwebot and pushes on hold · iter -
- Decision: where the botocore capture commit lands is re-asked of David; until the managing session answers: apply no douwebot label and push nothing; CI may run on the current head; the capture-noise fixes (x-amz-date normalization, HTTPHeaders order) wait for the same answer
- Why: the managing session's call: its question to David cited only the original D7, not the 2026-11-03 amendments that gave each capture its own PR (David picked 'Own PR, parallel' then)
- Source: https://github.com/pydantic/pydantic-ai/pull/12816
- Session: 8b577650-4849-4dc3-9cc0-36b9318d5272
2026-11-07 · capture hook split out of R11 · iter -
- Decision: revert b31e36a2f7 (botocore capture hook) with a new commit; R11 changes only bedrock.py; the hook lands in a separate tooling PR built by another worker from b31e36a2f7 plus the two capture-noise fixes; Proof W ran with the hook applied locally
- Why: David's decision, relayed by the managing session, matching his amended D7 ('Own PR, parallel'); the 'inside R11' decision rested on a citation of the original D7 only
- Source: https://github.com/pydantic/pydantic-ai/pull/12816
- Session: 8b577650-4849-4dc3-9cc0-36b9318d5272
- Supersedes: Proof W tooling lands inside R11 as its own commit
2026-11-07 · pre-push review 3 of 3 at 84e5876eee4a9a17e503d6f2c9db3dc4e6edfc77 · iter -
- Decision: reserved; outcome pending
- Why: tree a990476fd7b1cff216749f358e2b904225bb9a75; scope 5a0f5a1880..84e5876eee4a9a17e503d6f2c9db3dc4e6edfc77 (douwebot remediation 1755f031cf and the revert of the capture hook 84e5876eee), full branch as context; policy base 52357f8faa9ca075d397fcda841763a4907dc033; light tier (haiku) via claude -p in a detached policy-base worktree, read-only tools, no fan-out
- Source: https://github.com/pydantic/pydantic-ai/pull/12816
- Session: 8b577650-4849-4dc3-9cc0-36b9318d5272
2026-11-07 · pre-push review 3 of 3 at 84e5876eee4a9a17e503d6f2c9db3dc4e6edfc77 · iter -
- Decision: no findings: current at 84e5876eee4a9a17e503d6f2c9db3dc4e6edfc77
- Why: reviewed tree a990476fd7b1cff216749f358e2b904225bb9a75; scope 5a0f5a1880..84e5876eee (douwebot remediation and the capture-hook revert), full branch as context; haiku, read-only tools, no fan-out, policy base 52357f8faa; review budget now spent
- Source: https://github.com/pydantic/pydantic-ai/pull/12816
- Session: 8b577650-4849-4dc3-9cc0-36b9318d5272
- Supersedes: pre-push review 3 of 3 at 84e5876eee4a9a17e503d6f2c9db3dc4e6edfc77 (reserved)
2026-11-07 · no additional review surface; enqueue after the metadata check · iter -
- Decision: no second opinion beyond the required CI and douwebot reviews; #12816 is enqueued after the final metadata check, by the managing session (this worker never enqueues)
- Why: David's call, relayed by the managing session; options framed by this session: none (recommended), pydanty:review-branch, pydanty:review-lite, douwebot again, local pre-push review
- Source: https://github.com/pydantic/pydantic-ai/pull/12816
- Session: 8b577650-4849-4dc3-9cc0-36b9318d5272
2026-11-07 · enqueued at 2026-11-07T20:47:54Z · iter -
- Decision: #12816 added to the merge queue at head 84e5876eee by the managing session; this worker stays in monitor mode and never enqueues or re-enqueues
- Why: David's call, relayed by the managing session, after the final metadata check
- Source: https://github.com/pydantic/pydantic-ai/pull/12816
- Session: 8b577650-4849-4dc3-9cc0-36b9318d5272
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.
Summary by cubic
Refactors 14 Bedrock adapter functions in bedrock.py to bring each under the 15-point cognitive complexity limit, with no user-visible behavior change.
Refactor
- Maps messages through a data-only context with one method per message kind and part type; the context's wire lists now use default factories, so the constructor call passes only the facts each part is mapped against.
- Moves thinking,
top_k, andtool_choicetranslation intomatchstatements with private helper methods. - Extracts error mapping, settings building, and cache-point handling into private functions.
- Adds no public surface and no
complexipyignores; all existing tests and inline snapshots pass unchanged.