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 start by exploring the repository structure and understanding how deferred capabilities and reasoning content are handled.
- Assistant
Let me examine the deferred capability and thinking/reasoning content handling.
- Assistant
Let me search for how reasoning_content is handled with DeepSeek models.
- Assistant
rg is not available, let me use grep.
- Assistant
Let me inspect the OpenAI model reasoning handling and deferred capability flow more carefully.
- Assistant
Let me inspect deferred tool loading and message processing around capabilities.
- Assistant
Let me look at how message history is processed when tools are loaded,and examine
_map_response_thinking_partmore carefully. Also look at deferred capability related message rewriting. - Assistant
Let me look at thinking-related code and related tests for deferred capabilities.
- Assistant
Let me look at the combined capabilities and history processing paths.
- Assistant
Let me read the full thinking part mapping and how messages are cleaned before being sent.
- Assistant
Let me examine message mapping and history cleaning closely.
- Assistant
Let me look at
_clean_message_historyand how ModelResponse validation or message serialization might drop fields. Also check if there's something special about instruction parts returning from load... - Assistant
Let me search git history and docs related to this issue.
- Assistant
Let me look at how InstructionPart is handled and search for known issues around tools without reasoning.
- Assistant
Let me look at the deepseek tests carefully.
- Assistant
I don't have DeepSeek API key, so I may need to reproduce the issue by unit testing how messages are mapped. Let me write a test that simulates the message flow with deferred capabilities and checkif ...I understand the issue you're describing with DeepSeek models and deferred capabilities. The error you're seeing is exactly the kind of thing that happens when the
reasoning_contentisn't properly propagated back in the message history.Let me think through this systematically.
- Assistant
Let me dig into how capability-owned tools are gated until loaded.
- Assistant
Let me check how deferred tools are filtered from model requests when tool search isn't configured.
- Assistant
Let me look closely at lines 440-510 which describe how deferred tools are filtered.
- Assistant
Hmm interesting. For deferred capability tools without ToolSearch:
- Assistant
Let me check if ToolSearch gets auto-installed for deferred capabilities and look at how messages change.
- Assistant
Looking at how OpenAI maps deferred tools and how DomainsAPIs handle prepare_request.
- Assistant
Let me look at tests about deferred capability without tool search - how tools are hidden/shown.
- Assistant
Looking at line comments around 3216:
- Assistant
Let me examine how load_capability returns map and how model history looks on subsequent turns.
- Assistant
Found it—after load_capability, ToolSearch synthesizes intermediate messages. Let me check how those are mapped for OpenAI/DeepSeek.
- Assistant
This is critical — let me read ToolSearch.before_model_request that synthesizes those messages.
- Assistant
Synthetic messages may get dropped after mapping: let's trace how ToolSearch parts map for chat completions.
- Assistant
Checking how ToolSearchParts get rewritten for models without native tool search.
- Assistant
ToolSearchCallPart inherits from ToolCallPart! Look:
- Assistant
Found the likely root cause — synthetic ToolSearch messages lack reasoning_content. Let me clarify how discovered tools are tracked.
- Assistant
Let me look at DeepSeek docs references and any existing test covering multi-turn tool use with reasoning.
- Assistant
Let me read DeepSeek thinking guide docs from API and also check if OpenAIResponses model has special handling for synthetic auto_load messages.
- Assistant
I'll write a unit test to confirm synthetic tool-search messages strip reasoning_content on the OpenAI wire.
- Assistant
Confirmed the bug. Let me see how synthetic messages reach permanent history and how other models handle them.
- Assistant
Let me look at how messages from request_context get merged back into state.
- Assistant
Let me check why the synthetic tool-search exchange was introduced.
- Assistant
Let me look at that PR's description or why before_model_request injects.
- Assistant
Let me check docs about on-demand capacities regarding the synthetic exchange.
- Assistant
Synthetic messages may be required for some providers — checking AnthropicTool-search wire handling.
- Assistant
Interesting — on Anthropic with client-side tool search, the synthetic ToolSearchCallPart/ReturnPart get mapped as tool_use + tool_result with tool_references. That tells Anthrop...
- Assistant
Filtering synthetic auto_load pairs from the OpenAI Chat wire seems right. Checking Responses API mapping too.
- Assistant
Checking ModelResponse for a metadata field we can use to mark synthetic messages.
- Assistant
Checking how discovered tools are parsed from history.
- Assistant
Implementing the fix: skip auto_load synthetic tool-search exchanges in OpenAI Chat Completions message mapping.
- Assistant
I'll implement filtering of synthetic auto_load exchanges in OpenAI Chat Completions mapping.
- Assistant
Need to navigate to the right line first.
- Assistant
Need to check if
replaceis imported. - Assistant
Good, replace is imported. Now apply the edit.
- Assistant
Now update
_map_user_messageto accept and use skip_tool_call_ids. - Assistant
Need to go to line 1547 first.
- Assistant
Now apply the edit to
_map_user_message. - Assistant
Adding the helper function near other module-level helpers.
- Assistant
I'll add a shared constant for the auto_load prefix to avoid drift.
- Assistant
Adding the helper near other private helpers in openai.py.
- Assistant
Need to open the openai file first.
- Assistant
I'll add the helper just before
_merge_leading_system_messages. - Assistant
Need to check if Sequence is imported.
- Assistant
Verifying the fix with the reproduction script.
- Assistant
The fix works. Running related existing tests to ensure nothing broke.
- Assistant
Good — capability tests pass. Running thinking-related OpenAI tests next.
- Assistant
Checking how the trailing request interacts with synthetic injection:
- Assistant
Checking for syntax issues and running a broader test slice:
- Assistant
All tests passed. Cleaning up and reviewing the final diff.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.