Bring 30 `pydantic_ai` leaf-module functions under the cognitive complexity limit of 15

Merged
DS
1mo ago
+1126-820

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

Part of #10983.

Why we make these changes

The cognitive complexity gate from #11117 allows 15 per function. 30 functions in 18 pydantic-ai-slim leaf modules scored over that on main, 723 points in total: the clai chat loop, instrumentation and OTel conversion, provider construction, image and embedding request builders, run-result and usage serialization, and the local workspace's run. This PR brings each of them to 15 or under with no change in behavior. It does not close #10983: the remaining packages and modules are later PRs.

Each function took the fix that agent_docs/complexity.md names for its shape:

  • Dispatch on type or key (infer_provider_class, handle_slash_command, unsupported_file_input, GoogleImageGenerationModel._map_input_image, XaiImageGenerationModel._map_input_images, InstrumentationSettings.messages_to_otel_messages): match, with the cases in the old order. Arms with more than a line got their own method.
  • Passes (_serialize_model_request_parameters, _span_input_messages, _filter_serialized, BedrockJsonSchemaTransformer.transform): one function per pass, such as _redact_mcp_tool_definition and _strict_incompatible_keys.
  • Closure-hosted (UsageBase.__get_pydantic_core_schema__, InstrumentedEmbeddingModel._instrument): the closure bodies became module functions or methods, as _serialize_usage already was.
  • Orchestration (ask_agent, run_chat, LocalWorkspaceBackend.run, model_request_batch): only pure steps moved out. Every yield, cleanup and cancellation path stays in place.
  • The rest: guard clauses, and a private method or module function next to its only caller.

New public surface

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

Verification

  • Existing tests and inline snapshots pass unchanged, over the test files that reach each changed module. No test file, snapshot or cassette changes.
  • Request bodies are byte-identical, main against this branch, for the four request builders this PR touches: 29 requests over 27 test nodes, 0 differences.
  • scripts/check_complexity.py passes. Every function in the 18 changed files scores 15 or under; the 42 new private functions score 0 to 11.
Before and after scores: 723 → 289
FunctionFileBeforeAfter
infer_provider_classproviders/__init__.py422
ask_agent_cli/__init__.py3715
AzureProvider.__init__providers/azure.py347
_serialize_model_request_parameters_instrumentation.py3310
InstrumentationSettings.messages_to_otel_messagesmodels/instrumented.py314
handle_slash_command_cli/__init__.py308
GoogleEmbeddingModel.embedembeddings/google.py296
InstrumentationSettings._span_input_messagesmodels/instrumented.py2910
LocalWorkspaceBackend.runworkspaces/local.py2715
ConversationStore.saveconversation_store.py2610
run_chat_cli/__init__.py2615
UsageBase.__get_pydantic_core_schema__usage.py241
_run_chat_command_cli/__init__.py2415
GoogleImageGenerationModel._map_responseimages/google.py2311
unsupported_file_input_file_input.py2312
CacheHealthDetector.observe_cache_health.py2212
GoogleImageGenerationModel._map_input_imageimages/google.py223
InstrumentedEmbeddingModel._instrumentembeddings/instrumented.py2211
_filter_serializedrun.py2214
model_request_batchdirect.py229
annotate_tool_call_otel_metadata_instrumentation.py2013
_response_provider_detailsimages/google.py1910
BedrockJsonSchemaTransformer.transformproviders/bedrock.py187
resolve_openai_dimensionsimages/_openai_geometry.py188
AgentRunResult._validate_serializedrun.py177
ConversationStore._kept_historyconversation_store.py179
XaiImageGenerationModel._map_input_imagesimages/xai.py1714
_run_batchesdirect.py1710
UsageBase.opentelemetry_attributesusage.py1612
mcp_telemetry_url_tool_names_instrumentation.py169
Total723289
Request-body capture

Captured with an httpx request tap, plus an SDK-boundary tap for the two builders that don't use httpx: the kwargs of xAI's image.sample/image.sample_batch (gRPC) and botocore's _make_api_call params (Bedrock). Each capture ran on main and on this branch, and the two were diffed per test node after normalizing random ids.

Request builderTest nodesRequestsDifferences
GoogleEmbeddingModel.embedtest_google_task_prefix (11 cases), TestGoogle::test_query_with_task_type120
GoogleImageGenerationModel._map_input_imagetest_google_image_edit_binary_image_vcr, test_google_cloud_image_generation_forwards_gcs_references, test_google_image_generation_downloads_image_url30
XaiImageGenerationModel._map_input_imagestest_xai_image_generation_sdk_call_and_response_mapping, test_xai_image_generation_forwards_every_reference_image40
BedrockJsonSchemaTransformer.transformtest_bedrock_contains (10 cases, native and tool output)100

The Vertex-credentialed nodes (test_google_task_prefix_vertex, test_google_cloud_image_edit_vcr, test_google_cloud_gcs_image_edit_vcr) skip without credentials and are not in the capture.

What changes for existing users

Nothing.

PR decisions

2026-11-03 · R3 scope re-scored on main 5616c2199 · iter -

  • Decision: All 30 listed functions in scope at their listed scores; no other function in the 18 files scores over 15, and no logic moved out of them
  • Why: dispatch: re-score on current main, drop any under 15, pick up moved logic
  • Source: https://github.com/pydantic/pydantic-ai/issues/10983
  • Session: 3b97af02-4b08-481e-9b8f-47a8ac77dbe0

2026-11-03 · proof W for gRPC and botocore builders · iter -

  • Decision: xAI images (gRPC) and Bedrock (botocore) bypass httpx, so wire_trace.py sees neither; a companion local plugin records xai image.sample/sample_batch kwargs and botocore _make_api_call params in the same JSONL format, and compare_norm2.py diffs both
  • Why: dispatch requires byte-identical request bodies for xAI images and BedrockJsonSchemaTransformer.transform
  • Source: https://github.com/pydantic/pydantic-ai/issues/10983
  • Session: 3b97af02-4b08-481e-9b8f-47a8ac77dbe0

2026-11-03 · warning frames kept on the user's call · iter -

  • Decision: Warnings moved one frame deeper keep their target: Google embedding task warnings use stacklevel=3, and AzureProvider._init_from_arguments passes warning_stacklevel=4 to _get_http_client
  • Why: behavior unchanged: the warning must still point at the caller of embed() / AzureProvider(...)
  • Source: https://github.com/pydantic/pydantic-ai/issues/10983
  • Session: 3b97af02-4b08-481e-9b8f-47a8ac77dbe0

2026-11-03 · embedding span embeddings attribute bug reported, not folded · iter -

  • Decision: InstrumentedEmbeddingModel._instrument writes attributes['embeddings'] after the span opened, so it never reaches the span; the refactor keeps that write as is and the bug goes to the manager
  • Why: dispatch: a bug found along the way goes to the manager with its repro
  • Source: https://github.com/pydantic/pydantic-ai/issues/10983
  • Session: 3b97af02-4b08-481e-9b8f-47a8ac77dbe0

2026-11-03 · command-form check left duplicated in harness backends · iter -

  • Decision: LocalWorkspaceBackend.run's string-vs-argv check moves to a private _check_command_form in workspaces/local.py; the same check in three harness backends stays for R8
  • Why: harness execution backends are R8's scope
  • Source: https://github.com/pydantic/pydantic-ai/issues/10983
  • Session: 3b97af02-4b08-481e-9b8f-47a8ac77dbe0

2026-11-03 · pre-push review 1 of 3 at 2d500a4de79862d0f1b48bbe9a64113c41219ea2 · iter -

2026-11-03 · pre-push review 1 of 3 at 2d500a4de79862d0f1b48bbe9a64113c41219ea2 · iter -

2026-11-03 · pre-push review 2 of 3 at 242920212e1d79a31452aac8fa682815b97f7234 · iter -

2026-11-03 · pre-push review 2 of 3 at 242920212e1d79a31452aac8fa682815b97f7234 · iter -

2026-11-03 · exempt delta: merge of main 78372f8a7 at ef0c101320675d9a6e6970f1eff1176ab14902fe · iter -

  • Decision: pushed without another review; chains from reviewed 242920212
  • Why: target-branch merge with no conflict resolution: git diff main...242920212 and main...HEAD carry identical change lines (only blob ids and hunk offsets differ); gate, scores and pyright re-run clean; main's new embeddings and run-result tests pass
  • Source: https://github.com/pydantic/pydantic-ai/tree/slim-leaf-complexity
  • Session: 3b97af02-4b08-481e-9b8f-47a8ac77dbe0

2026-11-03 · douwebot optional comment: keep case _: pass in unsupported_file_input · iter -

  • Decision: Refuted with evidence and resolved: dropping the arm fails strict pyright reportMatchNotExhaustive (BinaryContent unmatched); case BinaryContent() instead would leave a never-taken 'no case matched' branch for the coverage gate. A clean approval needs a new head; take it from the next merge of main (exempt delta) and re-apply douwebot
  • Why: pr-review-gates counts any inline douwebot comment on the head, optional or resolved; no code change is net-positive here
  • Source: https://github.com/pydantic/pydantic-ai/pull/12375#discussion_r4460271726
  • Session: 3b97af02-4b08-481e-9b8f-47a8ac77dbe0

2026-11-03 · exempt delta: merge of main e2d290bea at 9b89d2ae16374c3ae9acecd1a87c5e238159a340 · iter -

  • Decision: pushed without another review; chains from reviewed 242920212 via exempt merge ef0c10132
  • Why: target-branch merge with no conflict resolution, touching only .github workflow files outside this PR: branch change lines identical to ef0c10132's; gives douwebot a fresh head after the refuted optional comment
  • Source: https://github.com/pydantic/pydantic-ai/pull/12375
  • Session: 3b97af02-4b08-481e-9b8f-47a8ac77dbe0

2026-11-03 · clean douwebot approval on 9b89d2ae1; gate status misattributes the old comment · iter -

2026-11-03 · final metadata check · iter -

  • Decision: Added topic labels cli, OpenTelemetry, embeddings, workspaces, serialization, usage, caching, message-history, azure, bedrock, xai, google-gemini, media; kept chore despite the checker's removal correction
  • Why: topic rule: every subject the diff materially covers; chore is the category the bots.yml classifier assigns to refactoring (its set is bug/feature/docs/chore/dependency), refactor is not one of them
  • Source: https://github.com/pydantic/pydantic-ai/pull/12375
  • Session: 3b97af02-4b08-481e-9b8f-47a8ac77dbe0

2026-11-03 · merge bar met; enqueued on 9b89d2ae1 · iter -

  • Decision: David: merge bar met; the red 'Gate: clean douwebot approval' status is the gate bug and only check is required; a maintainer enqueued #12375 on 9b89d2ae1
  • Why: douwebot APPROVE on the head with no comments in that review; CI green
  • Source: https://github.com/pydantic/pydantic-ai/pull/12375
  • Session: 3b97af02-4b08-481e-9b8f-47a8ac77dbe0

2026-11-03 · second-opinion review surface: none · iter -

2026-11-03 · out-of-scope bugs routed, no issues filed here · iter -

  • Decision: Embedding span attribute bug is #8293, fixed by the adopted pydanty PR #8295 under another worker; the douwebot gate bug gets a mini PR from another worker. Do not file issues for either
  • Why: David's routing via manager
  • Source: https://github.com/pydantic/pydantic-ai/issues/8293
  • Session: 3b97af02-4b08-481e-9b8f-47a8ac77dbe0

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.