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 trace how deferred capabilities rewrite model messages, compare that with DeepSeek/OpenAI reasoning-part serialization, and identify where reasoning metadata is lost. Then I’ll add the smallest source fix and run the relevant capability/model tests (using an offline reproduction if API credentials are unavailable).
- Assistant
rgis unavailable in this environment, so I’ll use recursivegrepto locate the implementations and tests. - Assistant
The likely interaction point is
_agent_graph.py, where capability loading causes an extra model turn. I’ll inspect that loop and OpenAI chat mapping around assistant thinking parts to determine whether the graph mutates the prior response or the serializer rejects thinking parts associated with local tool calls. - Assistant
The excerpt was partly the Responses API path, while DeepSeek uses Chat Completions. I’ll isolate the Chat mapper and response parser, then inspect the typed
LoadCapabilityparts because subclassing or conversion may cause the mapper’s tool-call grouping to omit the adjacent thinking part. - Assistant
The parser correctly creates
ThinkingPart(id='reasoning_content', ...). The decisive code is the Chat mapper at line 1445; I’ll read its complete response-message assembly and the deferred part classes. - Assistant
DeepSeek’s profile explicitly requests thinking replay via a custom field, so this should work. I’ll inspect
_MapModelResponseContext; the bug is likely that it only emits reasoning when text is present, whereas a capability-loading response consists solely of reasoning plus a tool call. - Assistant
At first glance the current serializer would preserve reasoning, suggesting either a recently added profile fix is incomplete for this model or the capability machinery modifies stored responses after parsing. I’ll inspect DeepSeek tests/history, current working-tree state, and every place that reconstructs or replaces response parts during tool execution.
- Assistant
The current DeepSeek profile appears intentionally configured for this requirement, but the provider tests only verify a single turn. I’ll inspect graph normalization around lines 400 and 2100 and build an offline mock-client reproduction of the exact deferred-capability sequence so we can observe the second request payload directly.
- Assistant
The key difference is now clear: after
load_capability, local tool search inserts a synthetic assistantsearch_toolscall with no provider reasoning, followed by its synthetic tool return. DeepSeek validates assistant tool-call messages as thinking-mode outputs, so replaying that internal assistant message triggers the 400 even though the real capability-load response retained its reasoning. I’ll inspect how synthetic search is marked and how other adapters suppress or translate it, then implement Chat-specific filtering that preserves valid message/tool-call pairing. - Assistant
There are three possible wire strategies: fabricate empty reasoning (unsafe), duplicate reasoning (violates “exactly as-is”), or omit the internal auto-discovery exchange. The last is valid:
load_capability’s real tool result remains in history and the newly loaded tool definitions are included in the next request; the synthetic pair is only framework bookkeeping. I’ll check profile conventions and then add an explicit compatibility flag rather than applying DeepSeek behavior to every OpenAI-compatible provider. - Assistant
I’ll add
openai_chat_requires_thinking_part_for_tool_callsto the OpenAI profile, enable it for DeepSeek, and have Chat mapping remove only framework-generatedauto_load_*tool-search call/return parts. User/model-originatedsearch_toolsexchanges remain untouched, mixed messages retain their other parts, and internal history remains unchanged for persistence/discovery. - Assistant
The profile wiring is in place. I’ll now update
_map_messagesto identify the reserved synthetic call IDs and filter both sides of each pair only when the compatibility flag is enabled, using dataclass copies so stored history is never mutated. - Assistant
I can’t call DeepSeek without credentials, but I can reproduce the malformed second-request payload offline: with the compatibility behavior disabled it contains a synthetic assistant
search_toolstool call lackingreasoning_content. I’ll run a temporary script against the actual mapper and verify the DeepSeek profile now emits the real reasoning-bearing capability call and its tool result while excluding only the synthetic pair. - Assistant
The offline reproduction confirms the corrected wire payload: the original reasoning is preserved exactly, the real
load_capabilitycall/return remains, and the reasonless synthetic exchange is absent. I’ll run the DeepSeek/OpenAI thinking tests and the deferred-capability end-to-end tests, then run formatting/type-oriented checks on the edited files. - Assistant
Targeted tests and lint pass. I’ll also run the recorded DeepSeek model suite, which exercises profile construction and response parsing without requiring a live request under the repository’s VCR setup, and inspect the final diff for unintended changes.
- Assistant
The recorded DeepSeek suite passes and the diff is clean. One edge case is covered by the implementation: if synthetic parts are combined with other parts by a processor, only the matching synthetic call/return is removed and the rest of the message is retained. I’ll run the project’s static type checker on the modified package paths if available, then submit.
- Assistant
Pyright found one unnecessary null check because
ToolSearchCallPart.tool_call_idis statically guaranteed to bestr. I’ll remove that redundant condition and rerun all final checks.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.