ISSUE DESCRIPTION Deferred capabilities throw error 400 with Deepseek models Initial…
- User
ISSUE DESCRIPTION
Deferred capabilities throw error 400 with Deepseek models
Initial Checks
- I'm using the latest version of Pydantic AI
- I've searched for my issue in the issue tracker before opening this issue
Description
When running an agent using a DeepSeek reasoning model, using
Capability(..., defer_loading=True)causes aModelHTTPError: status_code: 400during execution loop turns.openai.BadRequestError: Error code: 400 - {'error': {'message': 'The `reasoning_content` in the thinking mode must be passed back to the API.', 'type': 'invalid_request_error', 'param': None, 'code': 'invalid_request_error'}}This is triggered because DeepSeek requires the original
reasoning_contentproduced during the thinking phase to be passed back exactly as-is in the subsequent conversation message history array. Whendefer_loading=True, the graph loop intercepted by PydanticAI's capability runner seems to drop or fail to serialize/propagate thereasoning_contenttoken block back to DeepSeek's chat completions endpoint.Setting
defer_loading=Falsesolves the issue, and the agent executes successfully.Minimal, Reproducible Example
# Remember to export the DEEPSEEK_API_KEY environment variable first, then run this code import random from pydantic_ai import Agent, RunContext from pydantic_ai.capabilities import Capability def roll_dice() -> str: """Roll a six-sided die and return the result.""" return str(random.randint(1, 6)) def get_player_name(ctx: RunContext[str]) -> str: """Get the player's name.""" return ctx.deps agent = Agent( 'deepseek:deepseek-v4-flash', deps_type=str, instructions=( "You're a dice game, you should roll the die and see if the number " "you get back matches the user's guess. If so, tell them they're a winner. " "Use the player's name in the response." ), capabilities=[Capability(id='DICE_ROLL', tools=[get_player_name, roll_dice], defer_loading=True)] # Change this to False and the agent will run successfully. ) dice_result = agent.run_sync('My guess is 4', deps='Anne') print(dice_result.output)Logfire Trace
No response
Python, Pydantic AI & LLM client version
- Assistant
I’ll first inspect the repository structure and search for capability deferral, DeepSeek handling, and reasoning-content serialization. Then I’ll identify the graph-loop mutation and relevant tests before making a focused fix.
- Assistant
rgis unavailable, so I’ll use recursivegrepand narrow the results to source and capability-related tests. - Assistant
The provider profile already enables DeepSeek thinking preservation, suggesting the loss occurs before OpenAI message mapping. I’ll inspect the deferred-capability graph interception and the OpenAI request/response conversion paths, plus existing capability tests that may model multi-turn history.
- Assistant
The displayed mapper was for the Responses API, while DeepSeek uses Chat Completions. I’ll locate the chat mapper’s
ThinkingPartbranch and inspect how deferred capability loading is represented in message history (especially any special load parts that might split or rewrite a model response). - Assistant
I found the Chat Completions mapper around line 1445. I’ll inspect it alongside response processing and the loader toolset to determine whether the reasoning part is absent from history or merely omitted on serialization.
- Assistant
The history confirms capability loading inserts a synthetic tool-search response/request pair before the next model call. DeepSeek’s original model response should still retain its
ThinkingPart; I’ll now inspect the complete Chat mapper logic and the capability auto-reveal hook to see whether adjacent assistant/tool messages are merged, filtered, or transformed in a way that disconnects reasoning from its original tool call. - Assistant
The Chat mapper correctly serializes each stored
ThinkingPartasreasoning_content. The likely protocol violation is subtler: auto-reveal creates a synthetic assistantsearch_toolstool call that never came from DeepSeek, and DeepSeek thinking mode may require every assistant tool-call message—not just its original response—to includereasoning_content. I’ll inspect the synthesis hook and existing DeepSeek/OpenAI mapper tests to establish expected wire payloads and build a local mocked reproduction. - Assistant
The synthesis uses
ToolSearchCallPart, a specialized local bookkeeping exchange. Chat Completions currently treats it as an ordinary assistant function call because it subclassesToolCallPart; this fabricates an assistant turn with no model-produced reasoning. Rather than inventing empty reasoning (which would not be “exactly as-is”), the robust direction is to omit framework-synthetic tool-search bookkeeping from providers that cannot represent native tool-search events, while preserving ordinary model-issuedsearch_toolscalls. I’ll inspect the part metadata/types and other provider mappers to confirm that distinction is intended. - Assistant
The specialized synthetic response has no
provider_name, unlike actual model responses, and is paired with aToolSearchReturnPart. No Chat Completions provider has a native representation for this bookkeeping exchange; sending it as ordinary function traffic is both unnecessary for local discovery and invalid for strict reasoning protocols. I’ll update the Chat mapper to suppress only provider-less synthetic tool-search exchanges and their paired returns, leaving actual model-issuedsearch_toolscalls untouched. - Assistant
The source edit succeeded; only direct
python -m rufffailed because Ruff is managed through the repository environment rather than globally installed. I’ll inspect the diff, run Ruff viauv, and locate the narrow OpenAI test commands/configuration before creating a temporary mocked payload reproduction. - Assistant
Lint passes. I’ll validate the exact failing trajectory without network access by constructing DeepSeek-profile history containing: the original reasoning +
load_capabilitycall, its return, and the synthetic auto-load tool-search exchange. The mapped payload should preserve the exact reasoning on the original assistant message and omit only the fabricated pair. I’ll also compare against a genuine model-issued tool-search call to ensure it remains serialized. - Assistant
The type documentation explicitly says these specialized parts are also synthetic-injection targets on non-native providers, supporting wire-level suppression. I’ll run the temporary mapping script now, with assertions for exact reasoning preservation, absence of
auto_load_*, and preservation of a genuine provider-attributed search call. - Assistant
The mocked reproduction now yields a valid two-message continuation: DeepSeek’s exact
reasoning_contentremains attached to its original assistant tool call, while the synthetic pair is absent; a real model-issuedsearch_toolscall still maps normally. Next I’ll run focused reasoning mapper tests and capability synthetic-exchange tests, then the broader OpenAI model test module if feasible. - Assistant
Focused tests pass. Before broader testing, I’m checking for existing direct Chat-mapper tests that construct provider-less
ToolSearchCallParts. If present, I’ll tighten detection to require a matching synthetic call/return pair rather than relying solely on attribution, avoiding accidental suppression of manually supplied or legacy model calls. - Assistant
There are provider-less typed calls in tool-search tests, so I’ll make the criterion stricter: only suppress a provider-less all-tool-search response when its call IDs are paired in the immediately following request. This captures the framework’s synthetic exchange shape and preserves standalone/provider-less calls.
- Assistant
The stricter logic is correct but pushes the already complex mapper over the lint threshold. I’ll extract pair detection into a small module-level helper, keeping the mapper readable and independently testable without suppressing complexity checks.
- Assistant
I found the existing module-level message-mapping helpers. I’ll place the detector alongside them and replace the inline scan with one call, then rerun lint.
- Assistant
The stricter implementation now passes formatting and lint. I’ll run the full OpenAI model test module to catch any history-mapping regressions, then run static type checking for the changed module if the repository provides Pyright.
- Assistant
All 200 OpenAI tests pass. Pyright found only narrowing issues in the extracted helper because
all(isinstance(...))does not narrow a later comprehension. I’ll make the comprehension’s type check explicit and remove an unnecessaryNonecheck on return IDs, then rerun lint, type checking, and the mocked reproduction. - Assistant
Pyright confirms
ToolSearchCallPart.tool_call_idis always a string as well, so the remainingNoneguard is unnecessary. I’ll remove it and rerun all quality gates. - Assistant
Formatting, lint, and Pyright now all pass. I’ll rerun the exact mocked DeepSeek trajectory after the stricter pairing change, rerun focused capability tests, and inspect the final diff/status for accidental files.
- Assistant
The final mocked reproduction passes, including the edge case that an unpaired provider-less search call remains on the wire. Only the intended source file is modified. I’ll run the full tool-search test module because this change relies on synthetic exchange semantics, then review the checklist and submit if it passes.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.