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
Let me start by understanding the issue:
-
When using DeepSeek reasoning models with
Capability(..., defer_loading=True), the agent throws aModelHTTPError: status_code: 400with the error message: "Thereasoning_contentin the thinking mode must be passed back to the API." -
DeepSeek requires the original
reasoning_contentproduced during the thinking phase to be passed back exactly as-is in the subsequent conversation message history. -
When
defer_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.
So the issue is about handling
reasoning_contentin the message history when using deferred capabilities. Let me explore the codebase to understand the structure and find the relevant code.Let me start by exploring the repository structure.
-
Assistant
Let me explore more about the codebase structure, particularly the capabilities module and how deferred loading works.
Assistant
Let me look at the key files related to deferred capabilities and the thinking/reasoning content handling.
Assistant
Let me look at the key files for deferred capability loading and reasoning content handling.
Assistant
Let me use the bash_terminal to read files.
Assistant
Let me now look at the deferred tool handler which is probably where the message history manipulation happens:
Assistant
Let me look at the capability module and process_history, which might be where message history is processed
Assistant
Let me look at the capability.py and the _thinking_part.py for reasoning content handling
Assistant
Now let me understand how
reasoning_contentis handled in the message layer. Let me look at the models and messages:Assistant
The file is very long. Let me search for reasoning_content handling in the OpenAI model code
Assistant
Let me look at the
_thinking_part.pyand the graph-related code that handles message rebuildingAssistant
Let me look at the graph code to understand the message flow
Assistant
Let me look at the agent's internal graph, especially the deferred capability handling:
Assistant
Let me look at the key files - the agent graph and the deferred capabilities handler
Assistant
Let me look at the ModelRequestNode and how messages are built for API calls:
Assistant
Let me look at the ModelRequestNode implementation to understand how messages are built.
Assistant
Let me look at the DeepSeek provider and the OpenAI profile for reasoning
Assistant
Let me look at the profile for DeepSeek and OpenAI's chat handling for reasoning_content:
Assistant
Let me look at the OpenAI profile for relevant settings, and also look at how messages are converted for API calls:
Assistant
Let me see the full OpenAIModelProfile class:
Assistant
Now let me look at the critical part - how thinking parts are sent back in chat completions requests. Let me search for the chat completions message conversion code
Assistant
Let me look at how thinking parts are serialized into chat messages for API requests:
Assistant
Let me look at the deferred capabilities handling in the agent
Assistant
Let me look at the
_refresh_loaded_capability_idsfunction and the_capability_owned.pytoolsets:Assistant
Let me look at these refresh functions:
Assistant
Let me look at the wrapper capability and how messages are wrapped:
Assistant
Let me look at the DeferredCapabilityLoaderToolset:
Assistant
Let me look at the
_build_retry_nodemethod in the agent graph:Assistant
Let me look at the
_build_retry_nodemethod:Assistant
Let me look at the CallToolsNode in detail, especially the part where tool calls are handled and deferred tools vs non-deferred:
Assistant
Let me look at how the OpenAI model's chat completions adapter converts the internal message format to API messages:
Assistant
Let me look at the
_map_messagesmethod for the Chat model:Assistant
Let me look at
_map_model_responseAssistant
Let me see `_map_model_response
Assistant
Let me look at
_append_responseto see how responses are added to the message history:Assistant
Let me look at `_append_response
Assistant
Let me look at how tool returns are mapped in the chat completions API:
Assistant
Let me look at how tool returns are mapped as part of user messages:
Assistant
Let me look at how tool calls are handled in CallToolsNode._run_stream, looking for where ModelRetry is handled:
Assistant
Let me look at the relevant sections:
Assistant
Let me look at how tool calls are processed, particularly around line 1678:
Assistant
Let me look at how thinking parts are created from the API response:
Assistant
Let me look at how ModelRetry from tool execution is handled in CallToolsNode:
Assistant
Let me look at how capabilities are combined and how
before_model_requestis chained:Assistant
Let me look at the existing tests for deepseek to understand the reasoning_content handling:
Assistant
Let me look for where the message history might be modified during the graph's processing that could drop thinking parts. Let me search for message manipulation:
Assistant
Let me look at the UserPromptNode processing where
_clean_message_historyis called:Assistant
Let me look at how output_parts from CallToolsNode become a ModelRequestNode:
Assistant
Let me look at where the CallToolsNode._run_stream builds the next node:
Assistant
Let me look at
_handle_tool_callsand what happens after tool calls are executed:Assistant
Let me look at the Instrumentation capability:
Assistant
The
Instrumentationcapability wrapswrap_model_request, which is called from theModelRequestNode._make_requestmethod. But it doesn't modify the messages.Let me now think about the problem from a higher level. Let me search for any issue related to this in the codebase or look at the git log for recent changes.
Actually, let me try a different approach. Let me write a script that simulates the issue by looking at message mapping. But first, let me look more at the OpenAI model's message mapping to understand what exactly happens when the model returns a response with both thinking parts and tool calls and then that response is resent.
Let me look at if there's any place where the message history might be filtered or cleaned that could drop thinking parts.
Actually, let me search for the specific error message:
Assistant
Let me look at how xAI handles reasoning_content to understand the pattern:
Assistant
Let me look at existing tests for deferred capabilities to understand the expected behavior:
Assistant
Let me look at the test_capabilities.py for deferred loading
Assistant
Let me look at the abstract capability's
before_model_request:Assistant
Let me look at the git history for recent changes related to thinking parts or deferred capabilities
Assistant
I see a very relevant commit:
f9f8b951 feat: On-demand (deferred loading) capabilities. Let me look at what was changed:Assistant
Let me look at the changes in openai.py from this commit, specifically related to deferred capabilities:
Assistant
Let me look at the _agent_graph.py changes from that commit:
Assistant
Let me look at how
ToolReturnPartis serialized:Assistant
Let me look at those methods:
Assistant
Let me look at the test model to understand how to reproduce this:
Assistant
Let me write a script to try to reproduce the issue with a mock model. But first, let me look at how the
TestModelworks to understand the test infrastructureAssistant
Let me check how
_get_instructionsworks and if it could affect message history:Assistant
Let me search for any test that combines thinking with deferred capabilities
Assistant
Let me write a reproduction script using the test utilities. But first, let me look at how the test framework works for the agent graph
Assistant
Let me look at
TestModel._requestAssistant
Let me look at the
_requestmethod:Assistant
Let me look at the
_tool_search.pycapability since it might modify messages:Assistant
Let me check if ToolSearch is auto-injected and how the capability chain is composed:
Assistant
Let me look at how the agent builds its capability chain:
Assistant
Let me find
_inject_auto_capabilities:Assistant
Let me look at
_inject_auto_capabilitiesAssistant
Let me find
_AUTO_INJECT_CAPABILITY_TYPES:Assistant
Let me look at
_AUTO_INJECT_CAPABILITY_TYPES:Assistant
Let me look at
tool_defs_for_loaded_capabilities:Assistant
Let me look at
_pending_messages.py:Assistant
Let me look at how
DeferredCapabilityLoaderis created/injected:Assistant
Let me look at the agent code where
DeferredCapabilityLoaderis injected:Assistant
Let me check if there are any recent changes that might be relevant to this issue:
Assistant
Let me write a script to test the message mapping directly and see if reasoning_content is being dropped
Assistant
Let me use the virtual environment:
Assistant
Good, the basic mapping works. Now let me simulate the ToolSearch synthetic messages scenario
Assistant
Let me check if the narrow-tool-call logic maintains the tool call properly - especially for the subsequent mapping of the LoadCapabilityCallPart back to API format:
Assistant
Let me check if TestModel can return thinking parts:
Assistant
Let me search for where thinking parts could be filtered out in the agent graph
Assistant
Let me look at the test for deferred capabilities to find patterns that might reveal the bug:
Assistant
Let me look at the end-to-end test for deferred capabilities:
Assistant
Let me search for tests that combine thinking parts and tool calls:
Assistant
Let me look at the ModelProfile to see if there's a generic way to check for thinking requirements:
Assistant
Let me try to write a reproduction test using a FunctionModel that returns thinking parts, to verify my hypothesis about the synthetic messages:
Assistant
Now I've confirmed my hypothesis. The synthetic assistant message (Message 3) has no
reasoning_content, which causes DeepSeek to reject the request. Let me implement the fix.The fix should be in
ToolSearch.before_model_request. When the model profile indicates that thinking parts must be sent back as a separate field (like DeepSeek), we should skip the synthetic messages.Let me first look at the exact code I need to modify:
Assistant
Let me see the full
before_model_requestmethod:Assistant
Let me see the rest of the
before_model_requestmethod:Assistant
Let me check the MoonshotAI provider to see if it has similar settings:
Assistant
Now I have a clear understanding of the issue. Let me implement the fix. The problem is in
ToolSearch.before_model_requestwhich creates synthetic messages that include an assistant message withoutreasoning_content. DeepSeek requires all assistant messages to includereasoning_contentwhen thinking mode is active.The fix should:
- Detect when the provider requires thinking parts to be sent as a field (
openai_chat_send_back_thinking_parts == 'field') - Skip the synthetic messages but still mark the tools as discovered
Let me implement this:
- Detect when the provider requires thinking parts to be sent as a field (
Assistant
Let me read the imports and the full
before_model_requestmethodAssistant
Now let me implement the fix. I need to modify the
before_model_requestmethod in_tool_search.py:Assistant
Let me use the
replacecommand insteadAssistant
Let me read the exact content around the method
Assistant
Let me use a Python script to make the edit
Assistant
Let me see the method more carefully with line numbers
Assistant
Let me use Python to make the replacement properly
Assistant
The file was updated. Let me verify the change:
Assistant
Let me see the rest of the new method
Assistant
Good, the edit looks correct. Let me now run the existing tests related to this code to make sure I haven't broken
Assistant
Let me run without the timeout argument:
Assistant
All deferred capability tests pass. Let me also run the tool search tests:
Assistant
Let me also run tests that specifically test synthetic tool search:
Assistant
Let me look at the synthetic test to make sure it still works correctly with my change:
Assistant
Let me verify what profile FunctionModel uses:
Assistant
Let me write a quick test to verify my fix works with the DeepSeek profile:
Assistant
Let me verify the fix doesn't break the normal flow for OpenAI (which doesn't require reasoning_content in all messages):
Assistant
Let me run a broader set of tests to make sure nothing is broken:
Assistant
All 874 tests pass. Let me also run the agent tests and the model tests to make sure nothing is broken:
Assistant
Let me also run the OpenAI model tests:
Assistant
Let me also run the model request parameters tests that may test deferred capabilities:
Assistant
Let me verify the final state of my changes:
Assistant
The diff looks clean and correct. Let me now run a broader set of tests to make sure nothing is broken
Assistant
The 1 failure is due to a missing
mcpmodule, unrelated to my change. Let me verify:Assistant
Let me see the actual failure:
Assistant
The failure is pre-existing (MCP-related), not caused by my change. Let me verify by running only the capability and tool search tests:
Assistant
All 874 tests pass. Let me now submit the fix.
Let me do a final review of the changes
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.