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.codeopenai.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
Python - Assistant
I'll start by exploring the repository structure and understanding how deferred capabilities and reasoning content are handled.
- Assistant
Let me search for deferred capability loading and reasoning_content handling.
- Assistant
rg is not available, let me use grep instead.
- Assistant
Let me search more specifically in the pydantic_ai source code.
- Assistant
There's deferred capability handling and thinking-related code — let me dig into those.
- Assistant
Let me examine the deferred capability loader and DeepSeek reasoning_content handling.
- Assistant
Let me look at the process_history and deferred_tool_handler and also how messages with thinking are handled when deferred capabilities load.
- Assistant
Let me look at openAI reasoning_content mapping and DeepSeek profile.
- Assistant
I need to understand how deferred loading intercepts the execution loop and what happens to message history.
- Assistant
Let me look at the openai model's
_map_response_thinking_partand how thinking parts get sent back. Also look at related tests and recent commits about this issue. - Assistant
Let me look at the DeepSeek tests and capability-related tests around messaging.
- Assistant
Let me inspect message history cleaning and how ModelMessage history is handled.
- Assistant
Let me look at models/init.py around
_clean_message_historyand also at how ToolReturnParts for load_capability work. Also look for issues with merged adjacent responses that might drop thinking... - Assistant
Let me look at
_clean_message_historycarefully. - Assistant
Let me search for related issues and recent thinking handling changes, and also look for where reasoning content might be dropped.
- Assistant
Let me examine how load_capability tool returns inject instructions.
- Assistant
There's a relevant comment near line 1433 in the agent graph — let me inspect that area.
- Assistant
Let me look at tests that verify reasoning_content is sent back on subsequent requests.
- Assistant
Let me thoroughly inspect the mapping of messages including thinking parts.
- Assistant
Let me check AGENTS.md and search for related known issues or TODOs.
- Assistant
Let me search for places where ThinkingPart might be stripped from message history.
- Assistant
Let me inspect how thinking mode is enabled and how DeepSeek v4 isconfigured.
- Assistant
Let me inspect the full
_map_messagesmethod. - Assistant
Let me look at ThinkingPart's content field - could content be None? And when content is empty string? Also, maybe ThinkingPart content can be omitted somehow if item.content is None.
- Assistant
Let me look at
_prepare_requestmore carefully. - Assistant
Let me look at CallToolsNode and the narrowing of tool_call parts.
- Assistant
Let me look at the ThinkingPart dataclass and also related filter/narrowing.
- Assistant
Let me look at how tool returns are mapped.
- Assistant
Let me look at recent capability-related commits and any related TODOs基礎 or bugs.
- Assistant
Let me scann the wrap_model_request hooks that might intercept deferred capability loading.
- Assistant
Let me look at deferred_loading toolset and tool search.
- Assistant
Let me look at how capability-owned tools and deferred tools interact.
- Assistant
Let me look at how function tools are filtered for the model request, especially deferred ones.
- Assistant
I'll write a script that mocks DeepSeek and captures the messages sent after a deferred capability load, to see if reasoning_content is dropped.
- Assistant
Let me fix the reproduction script with a proper DeepSeek-like provider profile.
- Assistant
Found it — a synthetic
search_toolsassistant message withoutreasoning_contentis injected afterload_capability. Let me locate where that's built. - Assistant
Found it in
_tool_search.py— let’s read the auto-load path. - Assistant
The synthetic
search_toolsresponse lacks thinking. Let me check tests and how DeepSeek treats empty reasoning_content. - Assistant
Let me understand how discovery from history works and whether we can avoid a synthetic assistant message.
- Assistant
Let me read how ToolSearchToolset surfaces loaded-capability tools.
- Assistant
Let me read the tests around the synthetic tool-search exchange to understand why it exists.
- Assistant
Let me checkDeepSeek API docs for the exact requirement.
- Assistant
Let me extract the relevant documentation content.
- Assistant
Let me check how Anthropic handles ToolSearchCallPart and whether synthetic messages are filtered on the wire.
- Assistant
Let me check whether the mapping of ToolSearchCallPart goes through as a regular ToolCallPart, and whether there's a special case to add thinking.
- Assistant
Let me look at available_tool_names and whether discovered is required for loaded capability tools.
- Assistant
Let me look at OpenAI Responses and Anthropic handling of tool search after load_capability, and whether synthesizing is required for native.
- Assistant
Let me check Anthropic's handling of local ToolSearchCallPart.
- Assistant
I'll fix OpenAI chat mapping so tool-call assistant messages always include
reasoning_contentwhen the profile requires it. - Assistant
Implementing the fix: ensure
reasoning_contentis always set on tool-call assistant messages when the profile requires field-mode thinking send-back. - Assistant
Let me check FunctionModel and OpenAI chat profile support for ToolSearchTool.
- Assistant
Let me check tests that use
_NoNativeToolSearchModelwith deferred capabilities. - Assistant
Let me verify the mapping fix via the reproduction script.
- Assistant
Let me look at the singleton synthetic disk test and the no-native path.
- Assistant
Let me check what native tools DeepSeek profile reports.
- Assistant
Let me check OpenAIModelProfile.from_profile behavior.
- Assistant
Let me get the order of prepare_request vs before_model_request.
- Assistant
I need to find where
model.prepare_requestis called - that's where native swap happens. - Assistant
Let me inspect when prepare_request is called relative to map_messages.
- Assistant
Looking at therequestmethod:
- Assistant
prepare_requestis called inside each model'srequestmethod AFTER before_model_request. So at before_model_request time, nativos_tools may still include ToolSearchTool as optional before theswap... - Assistant
A cleaner fix: only inject the synthetic tool-search exchange when the model supports native tool search (where it's needed for replay).
- Assistant
I'll update the before_model_request to skip synthetic when ToolSearchTool isn't in the model profile. And keep the mapping thereafter safeguard.
- Assistant
Need to navigate to that line first or use open/file with the full content.
- Assistant
Now I can do the replace.
- Assistant
Re-running the reproduction to verify the synthetic pair is no longer injected.
- Assistant
No more synthetic search_tools without reasoning. Let me run the deferred-capability related tests.
- Assistant
Related tests passed. Let me also run OpenAI thinking tests and tool-search tests.
- Assistant
There's a cross-provider test failing — the synthetic needs to remain in history. Let me inspect it.
- Assistant
I'll revert the inject-skip and instead strip auto_load pairs only when mapping wire messages for field-thinking providers — that keeps history for cross-provider replay.
- Assistant
I'll strip auto_load pairs when mapping to chat completions for field-thinking profiles.
- Assistant
I'll implement wire-level stripping of auto_load pairs for field-thinking profiles.
- Assistant
ToolSearchCallPart and ToolSearchReturnPart are already imported. I'll update
_map_messagesto filter out auto_load pairs when field thinking is required. - Assistant
Now I'll add the helper function near other utility functions at the bottom of the file.
- Assistant
I'll add the helper near the tool search related helpers around line 4398.
- Assistant
I'll add the helper before
_has_tool_search. Also need to import replace if anusing it for filtered messages.replacefrom dataclasses is likely already imported. - Assistant
I need to check if ModelResponsePart and ModelRequestPart are imported.
- Assistant
ModelRequestPart is not imported. Sequence is used - is it imported? Looking atl ine 7 collections.abc.
- Assistant
I need to import ModelRequestPart.
- Assistant
Re-running the reproduction script.
- Assistant
The wire looks correct. Running related tests next.
- Assistant
All related tests passed. Let me review the full diff before submitting.
- Assistant
Let me confirm Moonshot uses the same field mode, and simplify the omit helper if needed.
- Assistant
Good - Moonshot is also covered. Running a broader set of openai model tests.
- Assistant
Checking that agent history still contains the synthetic pair while the wire omits it.
- Assistant
History keeps auto_load while the wire omits it. Cleaning up and submitting.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.