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 exploring the repository structure to understand what we're working with.
Assistant
Now let's look at how messages are converted back to the API request, focusing on the openai model:
Assistant
Let's look at the
_map_model_responsefunction that converts a ModelResponse back to a chat completion message:Assistant
Now let me find the
map_assistant_messageand the actual thinking part mapping:Assistant
Now let me understand the issue. Looking at the code:
_process_thinkingbuilds aThinkingPart(id=field_name, content=reasoning, provider_name=self.system)from the response_map_response_thinking_partchecksitem.provider_name == self._model.systemto determine whether to send back to the API
Let me see how the deferred capability loading flow works. The key thing is that the model runs through a sub-loop when there's a
load_capabilitytool call, which means the messages from previous iterations need to be passed back.Let me look at how the graph loop handles deferred loading:
Assistant
Now let me look at how the
Capabilitywithdefer_loading=Trueworks at runtime. First, let me look at the test for this to understand the flow:Assistant
Now let me look at where the deferred loading flow handles reasoning messages. Let me check where model responses are processed:
Assistant
Now let me find the test for deferred capability loading to understand the flow better:
Assistant
Let me now look at where the messages get processed. The issue is that when
defer_loading=True, the model response from a reasoning model contains aThinkingPart. When thisThinkingPartis sent back as part of the conversation history, theidandprovider_namemight be getting dropped or altered in a way that breaks DeepSeek's requirement.Let me look at the
_map_response_thinking_partagain closely:Assistant
Now let me check what
self.systemis for the deepseek model and look at the deepseek provider:Assistant
Now let me look at how
systemandprovider_nameare set. The DeepSeek system isdeepseek. Let me find the model's system:Assistant
So
self.systemreturns the provider name. For DeepSeek, this isdeepseek. The_process_thinkingsetsprovider_name=self.systemto'deepseek'.Now let me understand the issue: When using
defer_loading=True, the model first needs to callload_capabilityto get access to tools. The model returns aModelResponsewith aToolCallParttoload_capabilityalong with theThinkingPart.When this model response is being sent back to the model on the next turn, the
ThinkingPartshould be mapped back as a field. Looking at_map_response_thinking_part:if include_method == 'auto': # Check if thinking came from a custom field from the same provider custom_field = profile.openai_chat_thinking_field matches_custom_field = (not custom_field) or (item.id == custom_field) if ( item.id and item.id != 'content' and item.provider_name == self._model.system and matches_custom_field ):For DeepSeek with
openai_chat_send_back_thinking_parts='field', this is'field'not'auto'. Let me check the full flow more carefully:Assistant
OK, so when
include_method == 'field', it storesself.thinkings[field]and the field isreasoning_content. This should work, unless...Let me check how the conversation history passes through. The key insight is: when
defer_loading=Trueis used, the agent goes through a tool search /load_capabilityflow. The thinking part from the first response is sent back, but there might be something different in how the message gets sent.Let me look at the agent loop and how messages are propagated:
Assistant
Let me now look at how the model response is processed when streaming vs non-streaming. There's something about the response processing at line 1108:
Assistant
Now I see. The first turn would call the model and get a response with
reasoning_content. The model response is stored in the history. Then the next turn comes and the message is sent back. In the mapping_map_response_thinking_partwithinclude_method == 'field', the field isreasoning_content. The result isself.thinkings.setdefault('reasoning_content', []).append(item.content).Then in
_into_message_param:if self.thinkings: for field_name, contents in self.thinkings.items(): message_param[field_name] = '\n\n'.join(contents)This should produce
message_param['reasoning_content'] = .... So the field is being sent back.Let me check the existing tests for thinking parts in OpenAI:
Assistant
Now let me trace what happens during
defer_loading=True. The first model call: the model returns aModelResponsewith bothreasoning_content(becomingThinkingPart) and aToolCallPartforload_capability. The response is saved in the message history. Then the tool call gets executed (loading the capability), and the next model request includes the previous model response in the messages.Let me look at how the response gets created. Let me also search for where reasoning parts get attached to messages:
Assistant
Now let me look at where messages are sent to the model and how the streaming response is processed. Let me first try to reproduce the issue:
Assistant
Good, pydantic_ai is installed. Now let me reproduce the issue locally without actually calling DeepSeek. Let me use TestModel or FunctionModel to verify the issue:
Assistant
Let me look at the xai tests to understand how the ThinkingPart conversion works:
Assistant
Now let me look at the related issue in messages sent for DeepSeek-like models with tool calling. Let me search for how the messages get sent during a tool call:
Assistant
Let me look at the streaming case carefully to find any difference between streaming and non-streaming for thinking parts:
Assistant
OK, so the thinking part handling looks correct. Now let me understand the actual issue better. The user reports:
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.Let me write a test to reproduce the issue. We can mock the openai provider:
Assistant
Now let me write a test that uses TestModel with custom output to simulate the flow:
Assistant
Hmm, the TestModel doesn't know about the defer loading flow. Let me look at how the deferred capability flow works in tests:
Assistant
Now let me look for tests that test thinking with deferred capabilities:
Assistant
Now I want to write a test case to actually simulate the issue. Let me try creating a real test scenario using mocked DeepSeek responses:
Assistant
Now let me write a reproduction script that uses MockOpenAI with DeepSeek-like responses:
Assistant
Let me write the test in a different way - use the conftest approach:
Assistant
Let me look at the conftest to understand the conftest imports:
Assistant
Let me look at how the existing test_openai.py imports work:
Assistant
Let me create the test script as a proper pytest test file:
Assistant
The MockOpenAI uses
from ..conftestso it needs to be in the test package context. Let me just inline the MockOpenAI:Assistant
Wait - I see
search_tools! Let me look at what's happening here:Assistant
Let me look at the full output without truncation:
Assistant
Let me check how the ToolSearchCallPart is being mapped when sending back to the API. Let me look at how the response gets mapped:
Assistant
Let me look at the chat completions mapping (the chat completions path), not the responses path:
Assistant
Let me look at how ToolSearchCallPart/ToolSearchReturnPart are handled in the chat completion
_map_model_response:Assistant
Now let me look at where the synthetic tool-search exchange is added to the messages. The reproduction showed that there's a synthetic
search_toolsassistant message in the conversation. Let me check whether this synthetic message includesreasoning_content. Looking at the code in_tool_search.py:Assistant
I see! The synthetic
ToolSearchCallPartexchange is added to the message history. This syntheticModelResponsedoesn't have aThinkingPart. Let me confirm this is the issue by examining the flow:Assistant
Let me trace through the issue. The synthetic message that's added in
before_model_requestdoesn't includereasoning_content. Let me verify with a focused test:Assistant
Let me check how the chat completions model handles
search_toolssynthetic messages:Assistant
Let me look at how the chat completions model handles the ToolSearchCallPart in
_map_model_response:Assistant
Let me check how Anthropic handles the synthetic message:
Assistant
Let me see how the actual mapping of ToolSearchCallPart happens in the response message for Anthropic:
Assistant
Let me see how Anthropic maps messages back:
Assistant
Let me look at where
before_model_requestadds the synthetic messages:Assistant
Let me find where the openai model handles the request_context:
Assistant
Now let me find where the messages from
request_context.messagesget sent to the model:Assistant
Let me verify that the synthetic messages aren't persisted in history:
Assistant
Let me check how the synthetic messages end up in the persisted history:
Assistant
Let me look at where the synthetic vs real ToolSearch calls might be distinguished:
Assistant
Let me trace through what happens when the model itself generates a search_tools call:
Assistant
Let me look at the chat completions API request building:
Assistant
Now let me look at the test for tool search:
Assistant
Now let me understand the actual API request being sent to the model with reasoning_content. Let me check the issue more carefully. Let me re-read the bug:
Assistant
Let me look at the existing tests for the tool search replay in OpenAI Responses API to understand the pattern:
Assistant
Now I understand the pattern better. The Responses API promotes local-shape
ToolSearch*Partto nativetool_search_call/tool_search_outputitems. For chat completions API, we don't have this option.Let me look at where the OpenAI Chat Completions API handles tool_search (if it does):
Assistant
Assistant
Now let me look at the actual
_map_model_responsefor chat completions to plan the fix:Assistant
Now let me think about the best fix. Looking at the issue:
- The chat completions API doesn't support native
tool_search - Sending
ToolSearchCallPartas a regulartool_callcauses DeepSeek to reject (because DeepSeek expectsreasoning_contentfor thinking mode)
The fix is to skip
ToolSearchCallPartandToolSearchReturnPartwhen mapping to chat completions API.Let me look at the test file for tests on this:
- The chat completions API doesn't support native
Assistant
Let me see what tests exist for the chat completions API with tool search:
Assistant
Let me also look at what happens when we test the chat completions path with the synthetic search_tools:
Assistant
Let me look at how the test file is structured:
Assistant
Now let me write the fix. First, let me understand the structure of the code I need to modify:
Assistant
Good.
ToolSearchCallPartandToolSearchReturnPartare already imported. Now let me implement the fix. The simplest fix is to skip these parts in the chat completions mapping:Assistant
Now let me check the full set of imports and types:
Assistant
Good. Now let me look at the fix more carefully. I need to be careful about a few things:
- The synthetic
ToolSearchCallPartis justToolSearchCallPart(the typed subclass) - The synthetic
ToolSearchReturnPartis justToolSearchReturnPart
These are both subclasses of
ToolCallPart/ToolReturnPart, so we need to check for them BEFORE the general check.Let me make the fix:
- The synthetic
Assistant
Now let me make the fix. First, modify
map_assistant_messageto handleToolSearchCallPart:Assistant
Now let me make the fix:
Assistant
I need to invoke a tool call. Let me make the actual edit.
Assistant
Now I'll make the fix. I need to handle
ToolSearchCallPartandToolSearchReturnPartin the chat completions mapping. Let me first verify whatToolSearchCallPartlooks like and how to skip it cleanly:Assistant
Now I have a clear picture. Let me look at the current
_into_message_parammore carefully to understand the issue:Assistant
Now let me make the fix:
Assistant
Let me use the proper format:
Assistant
Let me try a simpler approach using sed:
Assistant
Now let me apply the second part of the fix for
_map_user_message:Assistant
Now let me verify the changes:
Assistant
Now let me run the reproduction script to verify the fix:
Assistant
Let me verify the fix more carefully by checking what messages are actually in the history when sent:
Assistant
The fix works. Now let me run the existing tests to make sure I didn't break anything:
Assistant
All tests pass. Now let me check that the fix handles edge cases. Let me think about edge cases:
Assistant
That failure is unrelated to my fix (it's a HuggingFace hub deprecation warning). Let me run more targeted tests:
Assistant
All the relevant tests pass. Let me also verify the fix doesn't break anything when the model isn't using thinking:
Assistant
Let me also verify the edge case where the model itself calls
search_tools(not synthetic):Assistant
Let me also test the edge case where there's both
tool_callandsearch_toolsin the same assistant message:Assistant
Let me check whether NativeToolSearchCallPart/ReturnPart also need to be handled:
Assistant
Let me check the
_map_response_builtin_partmethod:Assistant
Now let me also look at whether there's a related test for
NativeToolSearchCallPartthat needs to be aware of this:Assistant
The Temporal test passes in isolation - it's a test ordering issue, not related to my change. Let me make sure the test failure isn't related to my change:
Assistant
Let me also verify the original repro case still works (without my change):
Assistant
All tests pass. Now let me look at one more thing - I want to understand the original error better. Let me check the test that the user described and verify our fix handles the actual reported scenario:
Assistant
Let me look at what happens if a
ModelRequestonly has aToolSearchReturnPart:Assistant
Let me re-verify the fix is correct by looking at the changes:
Assistant
Let me verify the imports:
Assistant
Good. The imports are already there.
Now let me think about whether there are any other places where this could cause issues. Let me look at the Anthropic model to see if it has similar handling:
Assistant
Anthropic handles
ToolSearchCallPart/ToolSearchReturnPartdifferently (they're converted to native format). Let me also check Google:Assistant
Google has a
tool_searchmode too. Let me look at how Google handlesToolSearchCallPart/ToolSearchReturnPart:Assistant
Let me run a more comprehensive test to verify my fix doesn't break anything:
Assistant
All tests pass. Now let me also verify by running a few more related tests:
Assistant
The temporal test failure is unrelated (passes in isolation). Let me verify my fix one more time and check more relevant tests:
Assistant
Now let me also verify the test that uses message_history with a synthetic search_tools call would still work correctly (for cross-provider replay):
Assistant
Let me also check the
_into_message_paramto verify the skip behavior is correct:Assistant
Let me also verify the fix doesn't break the openai-specific tests:
Assistant
Let me also run a comprehensive test focused on the key files I touched:
Assistant
All 1770 tests pass. Let me also make sure I run the test_messages.py:
Assistant
All tests pass. Now let me also clean up my temp files:
Assistant
Let me check the code style guidelines to make sure my fix follows them:
Assistant
Let me also look at how other "skip" patterns are done in the codebase:
Assistant
Now let me also double-check my changes by looking at the modified file:
Assistant
Both changes look good. Let me also re-run the test once more to confirm:
Assistant
The fix works. Let me also clean up temp files:
Assistant
Let me run all relevant tests one more time to confirm everything works:
Assistant
Assistant
Now let me submit my fix:
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.