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 to understand the codebase and locate relevant files related to capabilities and model handling.
- Assistant
Let me get a better overview of the repository structure.
- Assistant
Let me explore the structure more, particularly looking for capabilities and model-related code.
- Assistant
Now let me focus on the core source directory and capabilities.
- Assistant
Good, let me look at the capabilities module and the deferred capabilities files.
- Assistant
Let me examine the key files related to this issue.
- Assistant
Let me look at the messages.py to understand how reasoning content is structured, and then the agent graph to see how capabilities interact with the history.
- Assistant
Let me search for "thinking" or "reasoning" related code.
- Assistant
Good! So there's a
ThinkingPartclass. Let me look at it more closely. - Assistant
Let me check how HistoryCompletionPart is defined in messages.py and how thinking parts are stored in the conversation history.
I need to understand the message structure better and how tool calls and returns are handled, especially for deferred capabilities.
Let me open the messages.py file and search for HistoryCompletionPart.
- Assistant
Let me explore the message structure more:
- Assistant
I need to install the package first.
- Assistant
Let me install from the root directory instead which may have a different install setup.
- Assistant
Let me try using the .venv directory:
- Assistant
Good. Now let me understand the issue better. The problem is that when DeepSeek returns reasoning/thinking content, and a capability is loaded (defer_loading=True), the reasoning_content is not preserved in the message history when it's sent back to the API. Let me look at how capabilities are loaded and how messages are processed.
- Assistant
Now let me look at
_deferred_capability_loader.pyin capabilities which is relevant to deferred loading: - Assistant
Let me now look at the toolset for deferred capability loading to understand how it processes messages.
- Assistant
Now I need to understand how the message history is processed. The issue is that when DeepSeek returns a reasoning_content/thinking part, and then a deferred capability is loaded (triggering a tool call to
load_capabilityand return), the reasoning_content needs to be preserved in the history when it's sent back to the API.Let me look at the _agent_graph.py file to see how the execution loop works, and how messages are handled after a model response with thinking.
- Assistant
Let me look at how messages are built and sent back to the API. The issue is about
reasoning_contentfrom DeepSeek. Let me look at the DeepSeek model implementation. - Assistant
Great. Let me look at the DeepSeek provider's
messages.pyfile or the relevant Python file for history serialization. I'll search for "history" or "serialize" in the codebase. - Assistant
Let me look at the pydantic_ai_slim module structure - specifically around how messages are serialized for API calls.
- Assistant
Let me look at the models directory and the OpenAI / DeepSeek model implementations to understand how messages are serialized for the API.
- Assistant
DeepSeek uses the OpenAI API, so let me look at how messages are serialized.
- Assistant
Now let me look more closely at how thinking parts are serialized back to OpenAI.
- Assistant
Let me look for the
_MessageBuilderclass and understand how messages are serialized for OpenAI-compatible models. - Assistant
Let me search the models/openai.py file for how history is sent to the API.
- Assistant
Let me look at the
_MessageBuilderclass more carefully: - Assistant
No builder class found. Let me look for how ModelMessages are converted to OpenAI messages.
- Assistant
Let me look at the _a2a.py file that has the
build_message_historyfunction. - Assistant
Let me search more directly for how history is serialized to OpenAI format.
- Assistant
Let me search for
messages=where OpenAI messages are built: - Assistant
Found it - line 1453 is
_MessageBuilderwhich seems to be around there. Let me look at lines 1270-1500 to understand the message building. - Assistant
Perfect! Now I see how messages are mapped. The
_map_model_responsemethod processesModelResponseand its parts, includingThinkingPart. The issue is likely that when a deferred capability is loaded, the message history might be manipulated in a way that loses the thinking content.Let me look at the
_agent_graph.pyfile to understand how history is managed during the execution loop. I'll search for where messages are added to the history and how they're processed after a model response. - Assistant
Great. Now, I need to look at the
_clean_message_historyfunction, as that might be where the issue occurs. It's at line 2220 in_agent_graph.py. Let me examine that function, and then I need to understand how the history is being processed during deferred capability loading.Let me also look at the
_pending_messages.pyfile in capabilities (which might be related to how messages are deferred). We already looked at that, but let me check it again: - Assistant
Let me continue reading the
_clean_message_historyfunction to understand how model responses are handled: - Assistant
Good, I see that
_clean_message_historydoesn't seem to drop thinking parts, just merges consecutive messages.Let me re-read the error message and try to understand the problem better.
The error is:
Thereasoning_contentin the thinking mode must be passed back to the API.This means that DeepSeek's API is receiving a request that has a history containing an assistant message that should have
reasoning_content, but it's missing.Let me think about the sequence of events:
- Model responds with reasoning_content (thinking) + a tool call to
load_capability - The agent processes the response and adds it to history
- The agent calls the
load_capabilitytool and gets the result - The agent constructs a new request to the model with the history (which should include the assistant response from step 1)
- Model responds with reasoning_content (thinking) + a tool call to
- Assistant
Let me look at the _agent_graph.py main loop and understand how the model is invoked in the graph loop.
- Assistant
Good! Now I need to understand where exactly the
reasoning_contentis lost. Let me look at the Agent class and see how tool calls and returns are processed. Let me search for where ModelResponse is processed for tool calls. - Assistant
Now I need to understand the problem better. Let me think about the flow:
- DeepSeek model responds with a thinking part (contains
reasoning_content) and a tool call toload_capability. - The
LoadCapabilityCallPartis a subclass ofToolCallPartwithtool_kind='capability-load'. - The agent processes the tool call by calling the
load_capabilitytool. - After the tool returns, a new assistant message is sent to the model containing:
- The thinking part (should have
reasoning_content) - The tool call (should have the tool call id, name, arguments) And a new tool message is sent:
- The tool return (with the tool call id and result)
- The thinking part (should have
But when the assistant message is serialized back to DeepSeek API, it might strip the thinking content from the message because:
- The thinking content is stored in
ThinkingPartobjects. - These need to be serialized with
reasoning_contentfield for DeepSeek.
Let me look at how
_append_responseis implemented and see if there's anything that strips thinking content. - DeepSeek model responds with a thinking part (contains
- Assistant
Let me look at the
_append_responsemethod. - Assistant
Let me look at how the DeepSeek provider profile handles reasoning_content:
- Assistant
Great! I can see the key settings:
openai_chat_thinking_field='reasoning_content'openai_chat_send_back_thinking_parts='field'
Now let me look at the profiles/deepseek.py to understand the full profile:
- Assistant
Now let me understand the issue more deeply. Let me look at the agent graph to understand the flow when a model responds with thinking and tool calls.
- Assistant
I see! On line 1197:
elif isinstance(part, _messages.ThinkingPart): passThe thinking part is just skipped/ignored when collecting tool calls. This is fine because the thinking part is already part of the
model_responsewhich gets appended to history. Let me look at what happens when the deferred capability is loaded. The issue seems to be that when the model returns a response with thinking content, and then the tools are called (includingload_capability), the model needs to see the previous assistant message including the thinking content in the history.Let me look at how the deferred tool handler works to understand what happens to the model_response.
- Assistant
I think I need to understand the full flow better. Let me look at
_pending_messages.pyin the capabilities directory to understand how messages are handled during deferred capability loading. - Assistant
Let me trace the issue more carefully. The error indicates that when a ModelResponse with thinking + tool call is sent back to the API, the
reasoning_contentis missing. Let me look at the_MapModelResponseContext._map_response_thinking_partmethod more carefully. - Assistant
Wait, the code in
_map_response_thinking_partlooks correct. It stores the thinking content. But wait, the issue might be different. Let me think about what could be going wrong.When the model returns a
ModelResponsewith ThinkingPart(s) and ToolCallPart(s), the_map_response_thinking_partmethod correctly stores the thinking inself.thinkingswith the keyitem.id(which for DeepSeek would bereasoning_content).But wait, what is
item.idfor DeepSeek? Let me check how ThinkingPart is created from the DeepSeek response. Let me look at the_process_thinkingmethod in the OpenAI model: - Assistant
Good! Now I can see how the thinking part is created:
items.append(ThinkingPart(id=field_name, content=reasoning, provider_name=self.system))So for DeepSeek,
field_namewould bereasoning_content(fromprofile.openai_chat_thinking_field), andself.systemwould be'deepseek'.Now when the thinking part is mapped back to the API call:
elif include_method == 'field': field = profile.openai_chat_thinking_field if field: # pragma: no branch self.thinkings.setdefault(field, []).append(item.content)For DeepSeek,
profile.openai_chat_thinking_fieldis'reasoning_content'andinclude_methodis'field'.So the thinking should be stored in
self.thinkings['reasoning_content'].Now when creating the message:
if self.thinkings: for field_name, contents in self.thinkings.items(): message_param[field_name] = '\n\n'.join(contents) - Assistant
Let me now look at the
after_model_requesthook in the DeferredCapabilityLoader capability to see if it modifies the response. - Assistant
Let me check whether OpenAIChatModel is overridden for DeepSeek.
- Assistant
Let me check how the deepseek model is configured.
- Assistant
Let me look at how messages flow through the
prepare_messagesmethod. - Assistant
Let me search for prepare_messages more broadly:
- Assistant
Let me look at the base
prepare_messagesmethod: - Assistant
Let me trace the issue more carefully. The issue is that DeepSeek requires
reasoning_contentto be passed back. Let me look at how the deferred capability loader intercepts responses. - Assistant
Let me look at
fill_run_metadatato understand what metadata it fills in. - Assistant
Now I need to understand the actual flow of messages. The problem is:
- The agent sends a request to DeepSeek
- DeepSeek responds with thinking (reasoning_content) + a tool call for
load_capability - The
load_capabilitytool is executed and returns - The response needs to be sent back to DeepSeek with the assistant message (thinking + tool call) preserved
The question is: when
defer_loading=True, does the ModelResponse from step 2 get properly preserved with the ThinkingPart? - Assistant
Now let me trace through what actually happens. Let me look at the model response process more carefully. Let me check if there's a
wrap_model_requestor similar in the hooks: - Assistant
Let me look at the actual model request flow when deferred capabilities are used. I need to look at how the model response history is preserved.
- Assistant
Let me now look at the full
map_assistant_messagemethod in the OpenAI model to understand how it handles different part types: - Assistant
- Assistant
Let me look at how
_narrow_tool_call_partsworks: - Assistant
Let me now look at how the loaded capability IDs are refreshed in the agent graph:
- Assistant
Let me look more carefully at the
wrap_model_requesthook in the Instrumentation capability: - Assistant
Now let me take a different approach. Let me look at the existing tests for deferred capabilities to understand how they work, and specifically check if there's a test for deferred capabilities with thinking/reasoning models.
- Assistant
Let me now look at what tests exist for deferred capabilities specifically with thinking/reasoning:
- Assistant
Let me look at the test files more broadly to understand how deferred capabilities are tested.
- Assistant
Let me look more carefully at the test suite for deferred capabilities. Let me search for tests that combine thinking and deferred capabilities:
- Assistant
Let me now look at the
ToolCallPart.narrow_typemethod: - Assistant
Let me now look at the tests for capabilities to understand how deferred loading interacts with thinking:
- Assistant
Let me look at the specific DeepSeek test file and existing thinking tests:
- Assistant
Let me look at the test_capabilities.py file to find a test that tests deferred capabilities with a model:
- Assistant
Let me look at
synthesize_local_tool_search_messagesto see if it could affect thinking parts: - Assistant
Let me actually create a test script to reproduce the issue. First, let me understand the flow by examining how the model serializes messages when there's a thinking part and a tool call:
- Assistant
Let me check how to properly import from the repo
- Assistant
I need to install the package first. Let me check if there's a way to install it from the local repo.
- Assistant
Let me try using the .venv python with proper PYTHONPATH
- Assistant
Let me look at how ToolReturnParts are serialized to OpenAI format:
- Assistant
Let me look at how the ToolReturnPart is serialized in _map_user_message.
- Assistant
Let me take a different approach. Let me write a more comprehensive test script to actually reproduce the issue:
- Assistant
Let me fix the test script.
- Assistant
Let me check the ToolReturnPart constructor:
- Assistant
Let me check the BaseToolReturnPart:
- Assistant
Let me trace the issue more carefully by looking at how a model response from DeepSeek is processed:
- Assistant
Let me look at the
_process_responsemethod: - Assistant
Let me look at how
_prepare_requesthandles the messages: - Assistant
Let me look at
synthesize_local_tool_search_messagesto see if it could affect thinking parts: - Assistant
Let me now approach this differently. Let me write a test using the TestModel or FunctionModel that explicitly tests the serialization of thinking parts when deferred capabilities are loaded. I need to understand if the problem is in the message history or in the serialization.
- Assistant
- Assistant
Now I understand the flow better! I see something very interesting: when the load_capability tool is called and a capability is loaded, the framework automatically generates a synthetic ModelResponse for search_tools. This synthetic ModelResponse doesn't have a ThinkingPart but is present in the message history.
Let me trace where this synthetic search_tools ModelResponse comes from:
- Assistant
Let me look at how the
search_toolstool call is being synthesized and added to the message history. The key is understanding where the syntheticModelResponsewithsearch_toolscomes from: - Assistant
Let me look at the
_tool_search.pycapability file: - Assistant
Found it! I now see the root cause. The
ToolSearch.before_model_requestmethod appends a syntheticModelResponsewithToolSearchCallPartto the message history. This synthetic response has noThinkingPart, so when DeepSeek receives it, it doesn't havereasoning_content- which DeepSeek requires for all assistant messages in the conversation following a thinking response.Let me verify this by looking at the key code:
- Assistant
Now I understand the issue completely! The
ToolSearch.before_model_requestmethod creates a syntheticModelResponsewith only aToolSearchCallPart, but noThinkingPart. When this synthetic response is sent to DeepSeek (which requiresreasoning_contentin all assistant messages following a thinking response), it fails with a 400 error.The fix is: when creating the synthetic
ModelResponse, we should copy anyThinkingParts from the most recentModelResponsein the message history into the synthetic response. This ensures DeepSeek's requirement forreasoning_contentis satisfied.Let me implement the fix:
- Assistant
Let me look at the full before_model_request method more carefully, and also look at how ModelResponse parts are built.
- Assistant
Now I need to implement the fix. The issue is that the synthetic
ModelResponsecreated byToolSearch.before_model_requestdoesn't have anyThinkingPart, which causes DeepSeek's API to reject the request since it requiresreasoning_contentin all assistant messages following a thinking response.The fix: when creating the synthetic
ModelResponse, copy anyThinkingParts from the most recentModelResponsein the message history. - Assistant
Now let me look at the exact lines that need to be modified:
- Assistant
Now let me implement the fix. I need to:
- Import
ThinkingPartfrom the messages module - In the
before_model_requestmethod, when creating the syntheticModelResponse, include anyThinkingParts from the most recentModelResponsein the message history.
- Import
- Assistant
Good, now let me modify the
before_model_requestmethod to include ThinkingParts: - Assistant
Now let me apply the fix. I need to find the thinking parts from the most recent ModelResponse in the history and include them in the synthetic ModelResponse:
- Assistant
Good. Now let me verify the fix by running the test again:
- Assistant
The fix is working! Now in Call 2, Message 3 shows:
ModelResponse ThinkingPart: id='reasoning_content', provider_name='deepseek' ToolCallPart: tool_name='search_tools', tool_kind='tool-search'Previously it was:
ModelResponse ToolCallPart: tool_name='search_tools', tool_kind='tool-search'The synthetic ModelResponse now includes the ThinkingPart from the previous response. Let me verify the fix doesn't break when there are no thinking parts:
- Assistant
The fix works for both thinking and non-thinking models. In the non-thinking case, the synthetic ModelResponse doesn't have ThinkingPart (because there are no ThinkingParts in the history), which is correct.
Now let me run the existing tests to make sure I haven't broken anything:
- Assistant
All 720 tests passed! Let me also run the tool search tests and other related tests:
- Assistant
All tool search tests pass too. Let me run a broader test suite:
- Assistant
Let me run the DeepSeek model tests as well:
- Assistant
Let me run the streaming and agent tests as well:
- Assistant
The only failure is an MCP server test that fails due to a missing
mcpmodule - that's an environment issue, not related to my change. Let me run some more tests to be thorough: - Assistant
All streaming tests pass. Let me run the test_toolsets.py as well.
- Assistant
Again, only the MCP-related test fails (missing
mcpmodule). Let me run a few more tests to confirm: - Assistant
All OpenAI responses tests pass. Let me also run some model-related tests:
- Assistant
All tests pass. Let me now verify the final state of the fix by looking at the complete diff:
- Assistant
Let me fix the missing newline at end of file:
- Assistant
Let me verify the diff again:
- Assistant
Good. The diff looks clean. Let me run the full capabilities and tool search tests one more time to confirm everything passes:
- Assistant
All 1010 tests pass. Let me clean up the temporary test files:
- Assistant
Let me verify the final state of the modified file:
- Assistant
Let me verify the key modified section of the code:
- Assistant
The fix looks clean and correct. Let me now submit 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.