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 analyze this issue. The problem is that when using
Capability(..., defer_loading=True)with DeepSeek reasoning models, thereasoning_contentfrom the thinking phase is not being passed back correctly in subsequent conversation turns, causing a 400 error.Let me start by exploring the repository structure to understand how it's organized and find the relevant code.
Assistant
Good, I can see the repository structure. The key files seem to be related to capabilities. Let me explore the structure more.
Assistant
Let me look at the key files related to the deferred capability loading and how reasoning_content is handled:
Assistant
Let me look at the
_pending_messages.pyfile since it's related to how messages are handled, and also the capability-related files:Assistant
Let me look at the main capability file and how messages are being processed:
Assistant
Now let me look at the
_thinking_part.pyfile and the messages module since the issue is aboutreasoning_contentnot being passed back:Assistant
Let me look at the DeepSeek provider and how it handles reasoning_content:
Assistant
Let me look at the OpenAI model implementation and how it handles thinking parts:
Assistant
The file is very long. Let me search for the specific handling of thinking parts and reasoning_content in the OpenAI model file. The issue is about how thinking/reasoning content is sent back to the model in subsequent requests.
Let me search for the relevant code that builds the request messages.
Assistant
Let me look at the
_map_response_thinking_partfunction around line 1365 and related code:Assistant
Now I understand how thinking parts are mapped back to the model. The key is in
_map_response_thinking_part. Let me look at the profiles to understand how DeepSeek's settings are configured:Assistant
Now let me look at the DeepSeek profile:
Assistant
Let me look at the deferred capability loader toolset:
Assistant
I need to look at the deferred capability loader toolset to understand how it handles the message history when a capability is loaded. Let me focus on the
_deferred_capability_loader.pyfile in the toolsets directory.Assistant
Now let me look at the
_agent_graph.pyfile to understand how messages flow through the agent, especially when a capability is loaded and the conversation continues:Assistant
Now let me understand how the model request is prepared, especially how messages are built. Let me look at the
ModelRequestNodeclass:Assistant
Now let me look at the tests related to deferred capabilities and DeepSeek to better understand the issue:
Assistant
Let me look at the test_capabilities.py file for deferred capability tests:
Assistant
Let me look at the test around line 3021 to see how deferred capabilities work:
Assistant
Let me continue reading this test to see more context:
Assistant
Now let me look at how the message history flows from one turn to another, specifically when thinking parts are involved. Let me look at how the model request is built and specifically how
_map_model_responsehandles messages:Assistant
Let me look at the
_map_messagesmethod which builds the messages for the API request:Assistant
Now I understand the flow better. When a
ModelResponseis mapped to a chat completion message, the_MapModelResponseContext.map_assistant_messagemethod handlesThinkingPartinstances via_map_response_thinking_part. This method checks theopenai_chat_send_back_thinking_partsprofile setting.Looking at the DeepSeek provider configuration, it sets
openai_chat_send_back_thinking_parts='field'andopenai_chat_thinking_field='reasoning_content', which means thinking parts should be sent back as thereasoning_contentfield.Let me check the
_process_thinkingmethod that processes thinking parts when receiving a response, and look at howThinkingPartis created:Assistant
Let me look at how tool search is handled when capabilities are loaded, since the test shows tool search parts are synthesized:
Assistant
Assistant
Let me search for ThinkingPart references in the capabilities directory.
Assistant
The grep command failed with exit code 1, which typically means no matches were found. Let me try a different search approach.
Assistant
Let me look at the wrapper capability which might affect how messages flow:
Assistant
Let me look at how messages are processed in the agent graph when capabilities are loaded:
Assistant
Let me look at the
_clean_message_historyfunction since it processes messages before they're sent to the model:Assistant
I need to look at the
_clean_message_historyfunction to understand how messages are cleaned. Let me look at that function definition.Assistant
Assistant
The previous grep command found the
updatemethod at line 151 of the profiles__init__.pyfile. I need to look at the ModelProfile class definition to understand how profiles work, particularly theupdatemethod and how capabilities/deferred loading might affect the profile resolution.Let me look at the ModelProfile class and its update method to see if there's something that could cause the profile to be different when deferred capabilities are involved.
Assistant
Looking at the
updatemethod, it merges non-default values from another profile. The DeepSeek profile should preserveopenai_chat_send_back_thinking_parts='field'. Let me check how ToolSearchReturnPart is handled in message mapping - maybe the issue is specific to how tool search parts are processed.Assistant
My previous grep command failed because I assumed the messages module was in a
messages/__init__.pyfile, but that path doesn't exist. Let me find where the messages module is actually located in the codebase so I can examine how ToolSearchReturnPart is defined and handled.Assistant
I found that messages are defined in
/pydantic-ai/pydantic_ai_slim/pydantic_ai/messages.py. Let me look at how ToolSearchReturnPart and ToolSearchCallPart are defined and handled.Assistant
My previous command failed with exit code 1, which typically means grep found no matches. Let me search for these classes differently.
Assistant
Now I found the ToolSearchCallPart and ToolSearchReturnPart classes. Let me look at how they're defined and how they might be involved in the issue with reasoning_content not being passed back.
Assistant
Now let me look at how
_deferred_capabilitieshandles parsing loaded capabilities from the message history:Assistant
Let me look at the
parse_loaded_capabilitiesfunction and understand how it processes the message history. The issue might be related to how the message history is parsed when determining which capabilities are loaded. But more importantly, I need to understand where thereasoning_contentmight be getting lost.Let me look at the
parse_loaded_capabilitiesfunction and then trace back to where the issue might be occurring.Assistant
Let me look at the
prepare_messagesmethod in the model class. The issue might be in how messages are prepared before being sent to the API. Theprepare_messagesmethod might be dropping or transforming theThinkingPartwhen there are synthetic tool-search messages in the history.Let me also check if there's something specific about how the model's
prepare_messagesmethod handles the message history.Assistant
Let me search for the prepare_messages method in the OpenAI model file more carefully.
Assistant
The grep command failed with exit code 1, which means no matches were found. Let me search for prepare_messages in the models directory to understand how messages are prepared before being sent to the API.
Assistant
Let me look at the
prepare_messagesmethod in the models__init__.pyfile to understand the default behavior:Assistant
Let me look at the
_refresh_loaded_capability_idsfunction more closely since it modifies the loaded capability state during execution:Assistant
Let me look at the
before_model_requestmethod inToolSearchand trace through how it adds synthetic messages to understand the issue better. The key insight from the issue description is that whendefer_loading=True, thereasoning_contentis not being passed back to DeepSeek.Assistant
Assistant
Let me look at the
_completions_createmethod to see how the API request is built and sent:Assistant
Assistant
My previous grep command failed because I didn't properly invoke it. Let me search for SUPPORTED_NATIVE_TOOLS and ToolSearchTool in the profiles module.
Assistant
OK,
SUPPORTED_NATIVE_TOOLSis imported fromnative_tools. Let me check ifToolSearchToolis in that set.Assistant
Let me look at the native_tools init file to understand how ToolSearchTool is handled and whether it's supported for DeepSeek:
Assistant
I've been investigating this issue. The problem is that when using
defer_loading=Truewith DeepSeek reasoning models, theToolSearch.before_model_requesthook adds syntheticModelResponsemessages containingToolSearchCallPart. These synthetic messages don't have aThinkingPart, so when they're mapped to OpenAI format, they don't include thereasoning_contentfield.DeepSee's API requires that when thinking mode is enabled, ALL assistant messages in the conversation must include the
reasoning_contentfield. The synthetic assistant message withoutreasoning_contentcauses the API to reject the request with a 400 error.Let me implement the fix by ensuring that when
openai_chat_send_back_thinking_parts='field', the thinking field is always included in assistant messages, even if it's empty.Assistant
Now I can see the
_into_message_parammethod. The issue is that whenopenai_chat_send_back_thinking_parts='field'is set (as it is for DeepSeek), the thinking field (reasoning_content) should always be present in assistant messages, even when there's no thinking content (like for synthetic messages). Currently, the code only adds the field whenself.thinkingshas content.Let me implement the fix:
Assistant
I need to properly edit the
_into_message_parammethod to always include the thinking field whenopenai_chat_send_back_thinking_parts='field'. Let me first open the file and then make the fix.Assistant
The tool call arguments need to use the correct parameter names. Let me check the usage again - it should be just
filenotFILE, andlinenotLINE_NUMBER.Assistant
I need to make an edit to the
_into_message_parammethod. The issue is that whenopenai_chat_send_back_thinking_parts='field'is set (like for DeepSeek), the thinking field should always be included in assistant messages, even when there's no thinking content. Let me use the edit command properly.Assistant
I need to open the file first before editing it. Let me use the bash command to open the file.
Assistant
I need to edit the
_into_message_parammethod to always include the thinking field whenopenai_chat_send_back_thinking_parts='field'is set. The issue is on lines 1346-1348. I need to add anelifbranch to include an empty string for the thinking field when there's no thinking content but the profile requires it.Let me use sed to make the edit.
Assistant
Let me verify the edit was applied correctly:
Assistant
The edit was applied successfully. Now let me verify the fix is syntactically correct by checking the code and running the relevant tests.
Assistant
Let me check how to properly run the code in this repository.
Assistant
I need to verify my fix is correct. Let me try to use the existing virtual environment or find another way to test the code.
Assistant
The import was successful. Now let me verify my fix is logically correct and write a test to confirm it works as expected.
Assistant
The model_name is a property. Let me create a simpler test that directly tests the
_into_message_parammethod:Assistant
Good, the profile settings work as expected. Now let me run the existing tests to make sure my fix doesn't break anything:
Assistant
The test failed because
profileis not defined in the_into_message_parammethod scope. I need to access the profile throughself._model.profilelike other methods do in this class. Let me fix this:Assistant
I see the issue. I need to access the profile through
self._model.profilelike other methods in this class do. Let me fix this:Assistant
I need to run the tests to see if my fix broke anything. Let me execute the test command.
Assistant
All 5 thinking-related tests passed. Now let me run more comprehensive tests to make sure I didn't break anything else:
Assistant
I see the issue. The test
test_openai_custom_reasoning_field_sending_back_as_fieldis failing because my fix is settingreasoning_contentto an empty string when there's no thinking content, but in this test case, the profile hasopenai_chat_send_back_thinking_parts='tags', not'field'.Wait, looking at the failure more carefully:
- Expected:
{'role': 'assistant', 'reasoning_content': 'reasoning', 'content': 'response'} - Got:
{'content': 'response', 'reasoning_content': '', 'role': 'assistant'}
The test has a response with
reasoning_content='reasoning'but my code is producing an empty string instead. This is because the test usesopenai_chat_send_back_thinking_parts='tags', which means the thinking content should be converted to tags in the content, NOT in thereasoning_contentfield.But my fix is being applied even when the thinking part is converted to tags mode. The issue is that in
tagsmode, the thinking content is stored inself.texts(as tagged content), NOT inself.thinkings. So my branch is being triggered because is empty.- Expected:
Assistant
Assistant
My previous command failed because I didn't properly invoke the bash tool. Let me run the command to check the test at line 4398.
Assistant
I see the bug now! My fix has a separate
ifstatement that runs AFTER theif self.thinkings:block, which means it overwrites the thinking content with an empty string even when there IS thinking content. I need to make it anelifso it only runs when there's NO thinking content.Assistant
I see the bug! My fix has a separate
ifstatement that runs AFTER theif self.thinkings:block. This means even when there IS thinking content, my code runs and overwrites thereasoning_contentfield with an empty string!I need to change the
ifon line 1350 toelifso it only runs when there's NO thinking content.Assistant
The
elifis now on a separate line from theifblock, which will cause a syntax error. I need to fix this properly - theprofilevariable needs to be defined before theif/elifchain, or I need to restructure the code.Let me fix this properly:
Assistant
Good, the fix now looks correct. The
profilevariable is defined first, then there's anif/elifchain where:- If there's thinking content (
self.thinkings), it adds the thinking content to the message - Otherwise, if the profile requires field mode for thinking parts, it adds an empty string for the thinking field
Let me verify this fix by running the tests again:
- If there's thinking content (
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.