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 map the capability/deferred-loading flow and DeepSeek/OpenAI message serialization, then identify where reasoning parts are lost. I’ll reproduce the behavior with local model fixtures if available, implement the narrowest fix, and run the relevant test suites plus a focused reproduction.
- Assistant
rgis unavailable, so I’ll use recursivegrepand inspect the matching implementation and tests. - Assistant
The provider profile already opts DeepSeek V4 into thinking-part replay, so the likely fault is not initial parsing but graph history mutation during capability loading. I’ll inspect the deferred loader’s graph interception and the OpenAI request-message mapper side by side.
- Assistant
Capability loading is represented as an ordinary tool-call/return turn, which should preserve the preceding
ModelResponse. I’ll now inspect exactly how response parts become a chat assistant message and how profile merging might override the DeepSeek replay setting. - Assistant
Non-streamed mapping appears correct. The reported
run_syncpath is non-streamed, but capability loading may cause the graph to prune “thinking-only” parts when normalizing tool calls. I’ll trace every mutation/replacement ofModelResponse.parts, especially around tool execution. - Assistant
The deferred path additionally synthesizes a local
search_toolscall/return after loading. The key suspicious code is the graph’s response normalization around lines 941 and 1104; I’ll inspect that and the synthetic search injection to see whether it splits a DeepSeek assistant response in a way that detaches reasoning from its tool call. - Assistant
The failure is now reproducible structurally: after a valid DeepSeek assistant message containing
reasoning_contentandload_capability, Pydantic AI injects a second synthetic assistantsearch_toolscall with no reasoning. In thinking mode, DeepSeek rejects that fabricated assistant turn because no original reasoning exists to replay for it. I’ll inspect message preparation/profile hooks to implement provider-compatible filtering without losing internal discovery state. - Assistant
The synthetic exchange is needed in stored history to mark capability tools discovered, but it is not needed on DeepSeek’s wire because DeepSeek has no native tool-search protocol and loaded tools are already emitted as normal function definitions. The safe fix is therefore to omit only framework-generated auto-load search pairs from the outbound DeepSeek chat history while retaining them internally; user/model-generated search exchanges must remain untouched. I’ll locate the OpenAI model preparation override and profile capability flags to place this narrowly.
- Assistant
There is no existing preparation override, so I’ll implement the filtering in Chat Completions message mapping behind a new explicit profile flag enabled only by the DeepSeek provider. This avoids changing OpenAI, Moonshot, OpenRouter, or genuine search history. I’ll inspect the mapper loop and message part APIs before editing.
- Assistant
Filtering during
_map_messagesmust remove both halves of the synthetic exchange, otherwise the API would see orphaned tool results. I’ll identify synthetic exchanges by the reservedauto_load_call-id plus typedToolSearchCallPart/ToolSearchReturnPart, preserving any unrelated parts if messages were merged. Then I’ll add the profile setting and focused local client reproduction. - Assistant
I’ll now edit three source locations: add a documented OpenAI-chat profile flag, enable it for DeepSeek, and sanitize only synthetic auto-load tool-search parts in the outbound mapper. The stored message list remains unchanged, so capability discovery and replay persistence continue to work.
- Assistant
The profile edit succeeded, but the scripted provider anchor did not match the exact comment ordering, so later edits were intentionally not applied. I’ll inspect the exact block and apply the remaining two changes with corrected anchors.
- Assistant
I’ll apply the corrected edits and compile immediately to catch import/type-name issues.
- Assistant
Compilation passes. I’ll first run the existing OpenAI thinking replay and deferred-capability tests. Then I’ll create a temporary (outside-repository) focused mapper reproduction containing: a real DeepSeek reasoning/tool call, a synthetic auto-load pair, and a normal follow-up request; the assertion will verify exact reasoning replay and complete removal of only the synthetic pair.
- Assistant
Relevant existing tests pass, though the selection matched one test in each file. I’ll now run the focused mapper reproduction directly, using a dummy DeepSeek key and no network request. This reproduces the exact malformed outbound history that caused the HTTP 400 and confirms the corrected wire shape.
- Assistant
The focused reproduction confirms the pre-error shape is corrected: the original assistant turn retains
reasoning_contentexactly, while the fabricated assistant/tool pair is absent and internal history is unmodified. I’ll now run formatting/lint/type checks on changed files and the full OpenAI model/provider tests most likely to expose profile or serialization regressions. - Assistant
All 211 OpenAI/DeepSeek provider tests pass, and changed files pass Ruff formatting/lint. I’ll review the final diff for scope and then run the complete capabilities suite plus the repository’s configured static type checker on the package if practical.
- Assistant
The full 720-test capabilities suite passes. The diff is narrow and preserves normal/user-generated tool search. I’ll run the configured type checker for the three modules, check repository status for accidental files, and then submit if clean.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.