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 a ModelHTTPError: status_code: 400 during execution loop turns.
code
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_content produced during the thinking phase to be passed back exactly as-is in the subsequent conversation message history array. When defer_loading=True, the graph loop intercepted by PydanticAI's capability runner seems to drop or fail to serialize/propagate the reasoning_content token block back to DeepSeek's chat completions endpoint.
Setting defer_loading=False solves the issue, and the agent executes successfully.
Minimal, Reproducible Example
Python
Assistant
Let me start by understanding the issue. The problem is that when using Capability(..., defer_loading=True) with DeepSeek models, the reasoning_content from the thinking phase is not being passed back to the API in subsequent conversation turns, causing a 400 error.
Let me first explore the repository structure to understand how it's organized and find the relevant code.
Assistant
Let me explore the capabilities directory since the issue is related to deferred capabilities and reasoning_content handling.
Assistant
Now let me look at the _pending_messages.py file since it seems related to how messages are handled:
Assistant
Let me look at how messages are handled, especially the reasoning_content part:
Assistant
Let me look at how message history is cleaned and how thinking parts are handled:
Assistant
Let me look at the _clean_message_history function more closely and how ModelResponse messages are handled:
Assistant
Let me look at the ModelResponse class to understand how it handles reasoning_content and thinking parts:
Assistant
Now let me look at the OpenAI model implementation to understand how the reasoning_content is handled when sending messages back:
Assistant
Let me search for how the thinking content/reasoning_content is sent back in assistant messages:
Assistant
Let me look at how the assistant message with thinking parts is built when sending back to the API:
Assistant
Now I need to understand the issue better. Looking at lines 3021-3060, when a ThinkingPart is mapped back, there's a check for item.id and should_send_item_id. Let me look at the should_send_item_id logic and where it comes from:
Assistant
Now let me look at the Chat model (not Responses) since DeepSeek uses the Chat Completions API:
Assistant
Now let me look at the _map_messages method of OpenAIChatModel to understand how ThinkingPart is handled when sending messages back:
Assistant
The key method I need to look at is _map_model_response which maps the ModelResponse back to OpenAI messages. Let me find that method.
Assistant
Let me find the _MapModelResponseContext class:
Assistant
Now I understand how _map_response_thinking_part works. The key is at line 1375-1399. For auto mode (the default), it checks if the ThinkingPart has:
An id that is not 'content'
A provider_name matching the model system
Matches the custom field from the profile
When these conditions are met, the thinking content is stored in self.thinkings dict, and later in _into_message_param (line 1350), the thinkings dict values are set as fields on the message param.
The issue is likely that when defer_loading=True, something is dropping or not properly passing the ThinkingPart through the message history. Let me look at the ModelRequestNode to understand how messages are prepared:
Assistant
Let me look at the _prepare_request method to understand how message history is prepared:
Assistant
Now let me look at the _clean_message_history function more closely. The issue says that when defer_loading=True, the reasoning_content is dropped. Let me look at how ModelResponse messages with ThinkingParts are handled in the _clean_message_history:
Assistant
Let me look at the _append_response method and how responses are handled:
Assistant
Now I need to understand how deferred capabilities load and what happens with the message history during capability loading. Let me look at the _deferred_capabilities.py:
Assistant
Let me look at the _refresh_loaded_capability_ids function and how it handles message history:
Assistant
Let me look at how the CallToolsNode handles the response and what happens after tool execution:
Assistant
Let me continue reading to understand how the next request is formed:
Assistant
Now let me search for tests related to deferred capabilities and thinking/reasoning content to understand the expected behavior:
Assistant
Let me search specifically for tests related to deferred capabilities with thinking:
Assistant
Now let me look at how the ThinkingPart is being handled when the deferred capability loader returns the result of the load_capability tool call. The key insight from the issue is that when using defer_loading=True, the message history between turns might not include the ThinkingPart with the reasoning_content properly.
Let me check the DeepSeek provider profile:
Assistant
Now let me look at the DeepSeek profile to understand how thinking/reasoning content is handled:
Assistant
Now I have a clearer picture. The issue is that when defer_loading=True, during a subsequent turn, the model's ThinkingPart from a previous response is present in message history but when it's mapped back to the API, the reasoning_content might not be getting sent back.
Looking at the DeepSeek provider profile:
openai_chat_thinking_field='reasoning_content' - this means the thinking content is sent back via the reasoning_content field
openai_chat_send_back_thinking_parts='field' - this means thinking parts should be sent back as a field
Let me check the _map_response_thinking_part method more carefully:
Assistant
For include_method == 'field', the thinking content is stored in self.thinkings dict with the field name as key. This is the mode used for DeepSeek since openai_chat_send_back_thinking_parts='field'.
Now let me trace back where the problem might be. When a deferred capability is used, the flow is:
First turn: Model returns a response with ThinkingPart + ToolCallPart (for load_capability)
The load_capability tool is executed and returns the capability instructions
A new ModelRequest is created with the tool result
Second turn: Model receives history including previous ModelResponse (with ThinkingPart)
The issue might be that when the ModelResponse is merged or cleaned, the ThinkingPart is being lost, or the message history sent to the model doesn't include the full response.
Let me check if there's something specific about how deferred capability tool results are handled:
Assistant
The grep command failed because there's no match. Let me look for where LoadCapabilityCallPart and LoadCapabilityReturnPart are handled in the tool execution path.
Assistant
Let me look at the test files that test Deferred capabilities to understand how the flow works:
Assistant
Now let me trace through the issue more carefully. When a thinking model like DeepSeek returns a response with reasoning_content (which is parsed into a ThinkingPart), and then a ToolCallPart for load_capability, the flow is:
Model returns ModelResponse with ThinkingPart + ToolCallPart
The ToolCallPart is executed (load_capability tool)
Tool returns LoadCapabilityReturnPart
A new ModelRequest is created with the ToolReturnPart
The graph goes back to ModelRequestNode
_prepare_request is called, which calls _clean_message_history
The messages sent to the model include the previous ModelResponse with ThinkingPart
_map_messages in OpenAIChatModel is called
The key question is: is the ThinkingPart still present in the message history when the second request is made?
Let me look at a test that simulates the deferred loading flow:
Assistant
Let me continue investigating the issue by looking at the test more carefully.
Assistant
Good, _clean_message_history preserves the ThinkingPart. Let me trace through how it's mapped to the OpenAI format:
Assistant
The ThinkingPart is correctly mapped to reasoning_content. Let me dig deeper into the flow to understand what might be dropping the thinking content in a deferred capability scenario:
Assistant
Let me find the FunctionModel import path and test this properly.
Assistant
Good - the ThinkingPart IS preserved in message history. The issue must be in how the messages are mapped when sent to the API. Let me trace through the OpenAI mapping:
Assistant
Now let me check what happens when mapping these messages through the actual OpenAIChatModel with DeepSeek provider:
Assistant
Interesting! The mapping looks correct - the reasoning_content IS being preserved. Let me now trace through the full agent flow with the actual DeepSeek model to see what's happening:
Assistant
Let me investigate more closely by looking at what happens when there are additional turns with thinking content:
Assistant
Assistant
The previous command failed because I didn't format it correctly. Let me try again with the proper format.
Assistant
Let me examine the prepare_messages method and understand what it does.
Assistant
...
Assistant
...
Assistant
...
Assistant
Let me look at the _split_response function to see if it might be dropping ThinkingPart when splitting a ModelResponse.
Assistant
Let me look at how the model name with provider prefix is handled:
Assistant
Assistant
Let me look at the before_model_request implementations in the capabilities.
Assistant
Let me look at the process_history.py capability since it might be modifying messages.
Assistant
I found an important capability - ProcessHistory. This capability can modify the message history before model requests by replacing request_context.messages entirely. But this is user-provided and not related to the deferred capability loader.
Let me look at the _tool_search.py capability's before_model_request since it might be relevant:
Assistant
Assistant
Let me look at the update method in the profiles module.
Assistant
Assistant
Let me search for the ToolSearchCallPart class to understand its inheritance.
Assistant
The previous command failed. Let me try a different approach to find the ToolSearchCallPart class definition.
Assistant
Good, ToolSearchCallPart extends ToolCallPart. Let me look at how _map_response_tool_call_part handles this:
Assistant
Let me look at the correct section for _map_response_tool_call_part:
Assistant
Assistant
Let me continue investigating by looking at the ToolSearchCallPart class to understand its inheritance and how it relates to NativeToolSearchCallPart.
Assistant
Looking at this issue more carefully, I believe I've found the root cause. When defer_loading=True, the ToolSearchCapability.before_model_request adds synthetic ModelResponse messages with only ToolSearchCallPart (no ThinkingPart). When these are mapped to OpenAI format, they become assistant messages without reasoning_content. DeepSeek's API rejects this because when thinking mode is enabled, all assistant messages must have reasoning_content.
Let me verify my understanding and implement a fix:
Assistant
Now I understand the issue. When ToolSearch.before_model_request adds synthetic ModelResponse messages for tool-search, these synthetic responses don't include ThinkingPart. DeepSeek's API requires that when thinking mode is enabled, the reasoning_content must be passed back. The synthetic assistant message at the end of the message history lacks reasoning_content, causing the 400 error.
The fix should propagate the ThinkingPart from the preceding real ModelResponse into the synthetic one. Let me implement this:
Assistant
The user wants me to open a file. Let me use the correct syntax for the open command.
Assistant
The open command doesn't seem to be working with the FILE parameter format. Let me try a different approach - I'll use the edit command to modify the file directly, or I'll use bash commands to view and edit the file.
Assistant
Now I understand the issue clearly. When ToolSearch.before_model_request creates synthetic ModelResponse messages for deferred capability loading, these synthetic responses don't include ThinkingPart. For DeepSeek reasoning models (and similar models that require reasoning_content to be passed back), this causes a 400 error because the synthetic assistant message doesn't have reasoning_content.
The fix is to propagate the ThinkingPart from the preceding real ModelResponse into the synthetic one. Let me implement this:
Assistant
Let me try a different approach to edit the file using sed:
Assistant
Good, the fix was applied. Let me verify the changes and run tests to make sure everything works correctly.
Assistant
Now let me run some tests to verify the fix works:
Assistant
The test ran successfully. Let me now verify that the ThinkingPart is being propagated to the synthetic message by adding more detailed logging:
Assistant
I see - the test didn't trigger the synthetic ToolSearchCallPart because the capability doesn't have actual tools. Let me create a better test that includes tools in the capability:
Assistant
I see that the synthetic ToolSearchCallPart isn't appearing in the test. Let me investigate why the ToolSearch.before_model_request isn't adding the synthetic messages:
Assistant
The tool search synthetic messages aren't being added because the condition in ToolSearch.before_model_request checks for newly_loaded tools that are NOT already in ctx.discovered_tool_names. Since this is a fresh run, the tools might be considered "already discovered" or the condition isn't being met.
Let me look at the tool_defs_for_loaded_capabilities function to understand what it returns. The issue might be that the tool definitions aren't being properly associated with the capability.
Actually, looking at the output, I can see that roll_dice IS in the function_tools list. So the tools are being loaded. But the synthetic tool-search exchange isn't being added.
Let me check if the issue is with the discovered_tool_names check. The function tool_defs_for_loaded_capabilities returns tools from loaded capabilities, and then we filter out those already in ctx.discovered_tool_names.
I need to debug this more to understand why the synthetic messages aren't being added. Let me add some debug output.
Assistant
I see - the tool_defs_for_loaded_capabilities returns empty because the tools aren't being properly tagged with their capability ID in my test. This is a test setup issue. Let me verify my fix is correct by directly testing the code path where synthetic messages ARE added:
Assistant
The fix is working correctly - the ThinkingPart is being propagated to the synthetic ModelResponse. Now let me run the existing tests to make sure I didn't break anything.
Assistant
All 72 tests related to tool search and deferred capabilities passed. Let me run a broader set of tests to ensure the fix doesn't break anything else.
Assistant
All 720 tests pass. Let me also run some related tests for thinking parts and the agent graph.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
# 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
Python: 3.14
Pydantic AI: 1.106.0
LLM provider SDK: deepseek
Interface
No new interfaces are introduced.
ADDITIONAL ADVICE
Since you are given a git repository, you can use git commands to simplify your work.
For example, if you made a mistake and want to revert your changes, you can use git checkout <file> to restore the file to its original state.
You can also reset all changes in the repository using git reset --hard command.
Additionally, you can use git stash and git stash pop to temporarily save your changes and restore them later.
Finally, you can see the changes that you've made (which will be submitted when you call submit) using git status or git diff commands.
However you don't need to use git add or git commit before submitting your changes. In fact,
submit only submits currently unstaged changes because it uses git diff to get the changes that need to be submitted.
CHECKLIST
Before submitting your solution, please go over the following checklist and make sure you've done everything:
If an error was reported in the issue description, I have successfully reproduced it.
If an error was reported in the issue description, I have confirmed that my fix resolves the error.
I have thought about edge cases and made sure my fix handles them as well.
I have run existing tests in the repository that might have been affected by the change I made and confirmed that they pass.
I want you to list every bullet from this checklist and write your reasoning for why you think you did it or didn't need to.
Repository has been uploaded and your shell is currently at the repository root. Time to solve the issue!
(Current directory: /pydantic-ai, current file: none) bash-$
OK, I see the issue now - the tool call roll_dice is being called repeatedly because the mock model keeps returning a tool call instead of text. But more importantly, I can see that the ThinkingPart IS being preserved in the message history across turns.
The issue reported is about DeepSeek returning a 400 error saying "The reasoning_content in the thinking mode must be passed back to the API." This means the problem is specifically with how the reasoning_content is sent back to the API - not with preserving it in the message history.
Let me look more carefully at what happens when a ModelResponse with ThinkingPart is processed by _map_model_response in the OpenAIChatModel. The key insight from the issue is that when using defer_loading=True, the graph loop "seems to drop or fail to serialize/propagate the reasoning_content token block back to DeepSeek's chat completions endpoint."
Let me trace through what happens:
Model returns response with ThinkingPart(id='reasoning_content', provider_name='deepseek')
This gets stored in message history
On next turn, _map_model_response is called
In _map_response_thinking_part, for include_method='field' (DeepSeek's setting), it should add to self.thinkings
Wait - I need to check if there's an issue with how the ThinkingPart is stored when it comes from a deferred capability tool call response. Let me look at what happens when the load_capability tool is called and returns.
Actually, let me re-read the issue more carefully. The error is:
code
The `reasoning_content` in the thinking mode must be passed back to the API.
This error occurs during "execution loop turns" with deferred capabilities. The key scenario is:
First request: Model returns ThinkingPart + load_capability ToolCallPart
The load_capability tool is executed
Second request: The message history includes the previous ModelResponse with ThinkingPart
Wait - but I already confirmed that the ThinkingPart IS in the message history. And when I tested _map_model_response, it correctly mapped it to reasoning_content.
Let me look at this differently. The issue says this happens specifically with defer_loading=True. What if the problem is in how the ThinkingPart is handled when there are MULTIPLE tool calls?
Actually, let me re-examine the flow. When a deferred capability is loaded:
Turn 1: Model returns ThinkingPart + load_capability call
Tool executes, returns instructions
Turn 2: Model returns ThinkingPart + actual tool call (e.g., roll_dice)
Tool executes, returns result
Turn 3: Model should see the history with both ThinkingParts
The error message says "The reasoning_content in the thinking mode must be passed back to the API." This suggests that DeepSeeek's API requires the EXACT reasoning_content from a previous response to be sent back in subsequent requests.
Let me check if maybe the issue is that when _map_model_response is called, it's not including the reasoning_content because the ThinkingPart doesn't have the right metadata set.
Actually wait - I need to look at what happens when the model's response is processed. When DeepSeek returns a response, the ThinkingPart is created with id='reasoning_content' and provider_name='deepseek'. But what if, during the deferred capability loading flow, the response gets processed differently?
Let me check the _process_thinking method in OpenAIChatModel to see how it creates the ThinkingPart:
python
def _process_thinking(self, message: chat.ChatCompletionMessage) -> list[ThinkingPart] | None:
...
for field_name in (custom_field, 'reasoning', 'reasoning_content'):
...
items.append(ThinkingPart(id=field_name, content=reasoning, provider_name=self.system))
So for DeepSeek, custom_field='reasoning_content' and self.system='deepseek'. This creates:
And when this is mapped back via _map_response_thinking_part with include_method='field':
python
elif include_method == 'field':
field = profile.openai_chat_thinking_field # 'reasoning_content'
if field: # pragma: no branch
self.thinkings.setdefault(field, []).append(item.content)
This should work correctly regardless of whether the ThinkingPart came from a deferred capability or not...
Wait - let me look at the issue again. The user says "When defer_loading=True, the graph loop intercepted by PydanticAI's capability runner seems to drop or fail to serialize/propagate the reasoning_content token block back to DeepSeek's chat completions endpoint."
The key phrase is "the graph loop intercepted by PydanticAI's capability runner". This suggests the issue might be in how the capability hooks process the messages, not in the model mapping itself.
Let me look at the DeferredCapabilityLoaderToolset._load_capability method more carefully. When the load_capability tool is called, it adds the capability ID to ctx.loaded_capability_ids and returns instructions. But does it somehow affect the message history?
Actually, I think I need to look at this from a different angle. Let me check the before_model_request capability hook and see if it modifies the messages in a way that could drop the reasoning_content.
Let me look at the PendingMessageDrainCapability.before_model_request - this drains messages from the queue into the request. Could this be the issue?
Actually, let me look at the _clean_message_history function again. When it merges consecutive ModelRequest messages, it sorts the parts. Could this sorting somehow drop ThinkingParts?
No, _clean_message_history only merges ModelRequest messages, not ModelResponse messages. And ThinkingParts are only in ModelResponse.
Hmm, let me look at what happens during the before_model_request hook more carefully. The PendingMessageDrainCapability drains messages into request_context.messages. But the original message history already has the ThinkingPart. So this shouldn't affect it.
Wait - I need to re-read the _clean_message_history function more carefully. What if the issue is that when a new ModelRequest is created (with the tool result), and it gets merged with a previous one, the intermediate ModelResponse gets affected?
No, that doesn't make sense either. The _clean_message_history function only merges consecutive messages of the same type (ModelRequest with ModelRequest, ModelResponse with ModelResponse).
Let me look at the issue from the API perspective. When DeepSeek returns a response with reasoning_content, the framework stores it as a ThinkingPart. When sending the next request, the framework needs to include this reasoning_content back. If it doesn't, DeepSeek returns a 400 error.
But I've already confirmed that:
The ThinkingPart IS in the message history
_map_model_response correctly maps it to reasoning_content
So what could be different between defer_loading=True and defer_loading=False?
Let me think about the flow differences:
With defer_loading=False:
Turn 1: Model returns ThinkingPart + tool call (e.g., roll_dice)
Tool executes
Turn 2: Model receives history with ThinkingPart, returns final answer
With defer_loading=True:
Turn 1: Model returns ThinkingPart + load_capability call
load_capability tool executes
Turn 2: Model receives history with ThinkingPart, returns ThinkingPart + tool call (e.g., roll_dice)
Tool executes
Turn 3: Model receives history with both ThinkingParts, returns final answer
The error happens in step 3 or 5, when the model is making a subsequent request after the deferred capability was loaded.
Wait - actually, I just realized something. The error message says "The reasoning_content in the thinking mode must be passed back to the API." This could mean that when the model returns reasoning_content on one turn, the NEXT request MUST include that same reasoning_content in the assistant message.
If DeepSeeek v4-flash uses reasoning_content in thinking mode, and the agent makes a tool call, then the next request must include the reasoning_content from the previous assistant message.
But I've confirmed this works correctly...
Unless... there's something different about how the ModelResponse is being processed when it comes from a deferred capability flow.
Wait - let me look at the ModelResponse that's created. When the FunctionModel returns a ModelResponse, what happens to its provider_name?
In my test, I explicitly set provider_name='deepseek' on the ModelResponse. But in a real scenario with DeepSeek provider, the provider_name would be set by the model's _process_response method.
Let me check what provider_name is set to for the DeepSeek model...
Actually, let me look at this from another angle. What if the issue is in how the ThinkingPart is handled in the CallToolsNode? After the model returns a response with ThinkingPart and ToolCallPart, the CallToolsNode processes the tool calls and creates a new ModelRequest. But what happens to the ThinkingPart during this process?
Let me look at _handle_tool_calls in CallToolsNode:
The output_parts are the tool return parts. The ModelResponse (with ThinkingPart) is already in ctx.state.message_history via _append_response. So this should be fine.
Hmm, I'm stuck. Let me look at the existing tests to see if there are any tests for deferred capabilities with thinking/reasoning content.
Actually, I think I should look at the actual error more carefully. The error is:
code
The `reasoning_content` in the thinking mode must be passed back to the API.
This is a 400 error from DeepSeek's API. It means that DeepSeek sent back reasoning_content in its response, and in the NEXT request, Pydantic AI should send that same reasoning_content back in the assistant message.
So the question is: when the deferred capability is loaded, what is the assistant message that gets sent back to DeepSeek?
Let me trace through what happens when there's a tool call response with ThinkingPart:
ModelResponse with ThinkingPart + ToolCallPart is in message history
_map_model_response is called
In _MapModelResponseContext._into_message_param:
python
if self.thinkings:
for field_name, contents in self.thinkings.items():
message_param[field_name] = '\n\n'.join(contents)
This should add reasoning_content to the message param. And I confirmed this works.
Wait - let me look at _into_message_param more carefully:
python
def _into_message_param(self) -> chat.ChatCompletionAssistantMessageParam | None:
if not self.texts and not self.thinkings and not self.tool_calls:
return None
message_param = chat.ChatCompletionAssistantMessageParam(role='assistant')
if self.thinkings:
for field_name, contents in self.thinkings.items():
message_param[field_name] = '\n\n'.join(contents)
if self.texts:
message_param['content'] = '\n\n'.join(self.texts)
else:
message_param['content'] = None
if self.tool_calls:
message_param['tool_calls'] = self.tool_calls
return message_param
OK so this returns a message param with reasoning_content, content=None, and tool_calls.
Now let me check if there's something else going on. What if the issue is specific to how the ModelResponse is serialized/deserialized during the graph execution?
Actually, wait. Let me look at what happens during _clean_message_history. Specifically, what happens when two consecutive ModelResponse messages are merged?
python
if (
last_message
and isinstance(last_message, _messages.ModelResponse)
# Responses can only be merged if they didn't really come from an API
and last_message.provider_response_id is None
and last_message.provider_name is None
and last_message.model_name is None
and message.provider_response_id is None
and message.provider_name is None
and message.model_name is None
):
merged_message = replace(last_message, parts=[*last_message.parts, *message.parts])
clean_messages[-1] = merged_message
This only merges if both messages have provider_name=None. Since DeepSeek responses have provider_name='deepseek', they won't be merged. Good.
OK, I think I need to actually test with the real DeepSeek model to see what's happening. But I don't have a DeepSeek API key. Let me look at the test infrastructure to see if there are any cassette recordings for DeepSeek.
Actually, let me re-read the issue one more time:
When defer_loading=True, the graph loop intercepted by PydanticAI's capability runner seems to drop or fail to serialize/propagate the reasoning_content token block back to DeepSeek's chat completions endpoint.
The key phrase is "the graph loop intercepted by PydanticAI's capability runner". This suggests that something in the capability processing chain is the culprit.
Let me look at how the DeferredCapabilityLoader capability wraps the graph nodes. Maybe there's something in the wrap_model_request or similar hooks that affects how messages are processed.
Actually, I just had another thought. What if the issue is with how the ModelResponse is handled when the capability loader tool returns? Let me look at what _load_capability returns:
python
async def _load_capability(self, tool_args: dict[str, Any], ctx: RunContext[AgentDepsT]) -> LoadCapabilityReturn:
capability_id = tool_args['id']
...
return {'instructions': instructions_text} if instructions_text is not None else {}
This returns a dict, which gets wrapped in a ToolReturnPart. But this shouldn't affect the previous ModelResponse with the ThinkingPart.
Wait - let me look at what happens to the message history between turns. Specifically, after a tool call is executed, what does the message history look like?
This all looks correct. The ThinkingParts are preserved.
Hmm, let me look at this from a different angle. What if the issue is with how _map_model_response handles the ModelResponse when it was returned by the model in a PREVIOUS turn (not the current turn)?
Actually, I think the issue might be in the _into_message_param method. Let me look at it again:
python
def _into_message_param(self) -> chat.ChatCompletionAssistantMessageParam | None:
if not self.texts and not self.thinkings and not self.tool_calls:
return None
...
If a ModelResponse has only ThinkingPart (no text, no tool calls), then self.thinkings would be populated, so it returns a message param with reasoning_content and content=None.
But wait - what if there's a ModelResponse that has only a ThinkingPart (thinking-only response)? Let me check what happens with thinking-only responses in CallToolsNode:
python
is_thinking_only = not is_empty and all(
isinstance(p, _messages.ThinkingPart) for p in self.model_response.parts
)
If the response is thinking-only, the node handles it specially, potentially retrying with a prompt like "Please include your response in a tool call or call a tool or return text."
But this doesn't seem to be the issue in the reported case.
OK, I'm going to take a different approach. Let me look at the git log to see if there have been any recent changes related to deferred capabilities and thinking parts.
Actually, I think I should look at the actual test file for deferred capabilities to see if there are any tests for this scenario.
Let me search for tests that involve both defer_loading=True and ThinkingPart.
Actually, I wonder if the issue is with how the ThinkingPart gets its provider_name set. When the DeepSeek model processes a response, it creates ThinkingPart with provider_name='deepseek'. But what if, during the deferred capability flow, the response goes through some processing that changes or clears the provider_name?
Actually, wait. I just realized something. The _map_response_thinking_part method in _MapModelResponseContext has this code:
python
elif include_method == 'field':
field = profile.openai_chat_thinking_field
if field: # pragma: no branch
self.thinkings.setdefault(field, []).append(item.content)
For DeepSeek, include_method='field' and field='reasoning_content'. This code doesn't check item.provider_name - it always adds the thinking content if include_method='field'.
But for include_method='auto', it does check provider_name:
python
if (
item.id
and item.id != 'content'
and item.provider_name == self._model.system
and matches_custom_field
):
So for DeepSeek, the 'field' mode should always work.
But wait - what if the profile is NOT being picked up correctly? What if, in the deferred capability flow, the model being used has a different profile that uses 'auto' instead of 'field'?
Actually, that doesn't make sense because the model is the same throughout the run.
Let me look at what happens with the _map_model_response method. It creates a new _MapModelResponseContext for each call:
This is called for each ModelResponse in the message history. So each ModelResponse is mapped independently.
Wait... I just had a thought. What if the issue is that the ModelResponse from a deferred capability flow is somehow getting processed by a DIFFERENT model (like FunctionModel in tests)?
No, that doesn't make sense for the real-world scenario with DeepSeek.
OK let me try a completely different approach. Let me look at what the user says works: defer_loading=False. What's different between defer_loading=False and defer_loading=True?
With defer_loading=False:
All tools from the capability are available from the start
The model can call any tool directly
The flow is: request -> response with tool call -> tool execution -> next request
With defer_loading=True:
The load_capability tool is available, but the actual tools are not
The model must first call load_capability to load the capability
The flow is: request -> response with load_capability call -> capability load -> next request -> response with actual tool call -> tool execution -> next request
So the key difference is an extra turn in the conversation. In this extra turn, the model first calls load_capability, then makes a second request with the loaded capability.
What if the issue is that, after the load_capability tool returns, the next request includes the capability's instructions, and these instructions are somehow different from what the model expects?
Actually, wait. Let me re-read the issue one more time:
This is triggered because DeepSeek requires the original reasoning_content produced during the thinking phase to be passed back exactly as-is in the subsequent conversation message history array.
"passed back exactly as-is" - this is the key phrase. DeepSeek requires the reasoning_content to be passed back EXACTLY as-is. What if there's some processing that modifies the content?
In _into_message_param:
python
if self.thinkings:
for field_name, contents in self.thinkings.items():
message_param[field_name] = '\n\n'.join(contents)
This joins multiple thinking contents with \n\n. If there's only one ThinkingPart, it just uses its content. So no modification there.
But wait - what if the issue is with how the ThinkingPart.content is stored? If the DeepSeek API returns reasoning_content with some specific encoding (like Unicode escapes or newlines), and Pydantic AI normalizes it, then it wouldn't be "exactly as-is".
Hmm, but this seems unlikely. The OpenAI SDK should handle the JSON encoding correctly.
Let me take yet another approach. Let me look at the actual error message:
code
The `reasoning_content` in the thinking mode must be passed back to the API.
This error means DeepSeeek's API received a request WITHOUT the reasoning_content from the previous assistant message. So the question is: why would the reasoning_content not be sent?
Possible reasons:
The ThinkingPart is not in the message history
The ThinkingPart is in the history but _map_model_response doesn't map it correctly
The _map_model_response returns None for some reason
The mapped message is filtered out somewhere
Let me check if _map_model_response can return None:
python
def _into_message_param(self) -> chat.ChatCompletionAssistantMessageParam | None:
if not self.texts and not self.thinkings and not self.tool_calls:
return None
This returns None only if there are no texts, thinkings, or tool calls. So a ModelResponse with only ThinkingPart would NOT return None.
But wait - what if the ThinkingPart is being filtered out somewhere before reaching _map_model_response?
Let me look at what happens in _map_messages:
python
async def _map_messages(
self,
messages: Sequence[ModelMessage],
...
) -> list[chat.ChatCompletionMessageParam]:
openai_messages: list[chat.ChatCompletionMessageParam] = []
for message in messages:
if isinstance(message, ModelRequest):
async for item in self._map_user_message(message):
openai_messages.append(item)
elif isinstance(message, ModelResponse):
if (mapped := self._map_model_response(message)) is not None:
openai_messages.append(mapped)
else:
assert_never(message)
So if _map_model_response returns None, the message is skipped. But as I analyzed above, it shouldn't return None for a ModelResponse with ThinkingPart.
Wait... let me look at this more carefully. What happens if _map_model_response is called on a ModelResponse that has NO parts at all? That would return None. But a ModelResponse with ThinkingPart should have parts.
OK, let me think about this from the perspective of what happens when _clean_message_history is called on the message history:
Yes, it's a shallow copy. So the list is new but the elements (messages) are the same objects. This means the ThinkingPart in the ModelResponse is the same object.
OK, I think I need to approach this differently. Let me look at the actual code that handles the response mapping when there's a deferred capability.
Actually, I wonder if the issue is related to how the ModelResponse is created when the model returns a response. Let me check if there's any code that creates a new ModelResponse object during the deferred capability flow.
Wait - I just thought of something. In the deferred capability flow, when the model returns a response with load_capability tool call, the response is appended to message history. Then the tool is executed, and the result is added to message history. Then a new request is made.
But what if, during the tool execution, the message history is somehow modified or replaced? Let me look at _finish_handling in ModelRequestNode:
ctx.state.message_history[:] = messages # Replaces contents of the list
Wait - this replaces the contents of the list! And messages comes from request_context.messages, which is a copy of the original list. So the original message history is replaced with the processed messages.
But the processed messages should still contain the ModelResponse with ThinkingPart, right? Let me trace through more carefully.
messages = request_context.messages (the processed messages)
ctx.state.message_history[:] = messages (replace history with processed messages)
So after step 5, ctx.state.message_history contains the processed messages from request_context.messages. These should be the same as the original messages (plus any drained pending messages).
OK, I really can't find the issue just by reading the code. Let me try to look for any recent changes in the git history that might have introduced this bug.
Actually, let me re-read the issue description once more. The user says:
When defer_loading=True, the graph loop intercepted by PydanticAI's capability runner seems to drop or fail to serialize/propagate the reasoning_content token block back to DeepSeek's chat completions endpoint.
Wait - "the graph loop intercepted by PydanticAI's capability runner". What if the issue is in the capability runner, specifically in how it intercepts and processes the graph loop?
Let me look at the capability wrapper and how it intercepts model requests:
This wraps the model request and calls the handler. The handler makes the actual API call. The wrapper can modify the request before calling the handler and modify the response after.
But the DeferredCapabilityLoader doesn't override wrap_model_request. So it shouldn't affect the model request processing.
Let me look at the DeferredCapabilityLoaderToolset.call_tool method:
This just calls _load_capability for capability-load tool calls. And _load_capability returns the instructions as a dict.
Hmm, I'm stuck. Let me try to reproduce the issue with a simulated DeepSeek API to see what's actually happening.
Actually, I just realized I should look at the _process_response method in OpenAIChatModel. When the model returns a response, it creates a ModelResponse with the ThinkingPart. Let me check if there's any issue with how this is done.
Actually, let me look at the _process_thinking method:
python
def _process_thinking(self, message: chat.ChatCompletionMessage) -> list[ThinkingPart] | None:
profile = OpenAIModelProfile.from_profile(self.profile)
custom_field = profile.openai_chat_thinking_field
items: list[ThinkingPart] = []
for field_name in (custom_field, 'reasoning', 'reasoning_content'):
if not field_name:
continue
reasoning: object = getattr(message, field_name, None)
if not reasoning:
continue
...
items.append(ThinkingPart(id=field_name, content=reasoning, provider_name=self.system))
return items
return items or None
For DeepSeek, custom_field='reasoning_content'. So it checks for message.reasoning_content first. If found, it creates ThinkingPart(id='reasoning_content', content=reasoning, provider_name='deepseek') and returns it.
This looks correct.
OK, I think I need to actually create a test case that simulates the DeepSeek API behavior to see what's happening. Let me create a test script.
Actually, wait. I just realized something. The issue says "the graph loop intercepted by PydanticAI's capability runner seems to drop or fail to serialize/propagate the reasoning_content token block".
What if the issue is that the reasoning_content is being dropped during SERIALIZATION? Specifically, when the message history is serialized and then deserialized (e.g., for resuming a conversation)?
But the issue doesn't mention conversation resumption. It happens during a single run with multiple turns.
Hmm, let me look at the issue from yet another angle. The user says:
Setting defer_loading=False solves the issue, and the agent executes successfully.
With defer_loading=False, the flow is:
Turn 1: Model returns ThinkingPart + tool call (e.g., roll_dice)
Tool executes
Turn 2: Model receives history with ThinkingPart, returns final answer
With defer_loading=True, the flow is:
Turn 1: Model returns ThinkingPart + load_capability call
load_capability tool executes
Turn 2: Model receives history with ThinkingPart, returns ThinkingPart + tool call
Tool executes
Turn 3: Model receives history with both ThinkingParts, returns final answer
Wait - in turn 2 of the defer_loading=True flow, the model receives a request. The history includes:
And the instructions include the loaded capability's instructions.
Now, the model returns a response with ThinkingPart + tool call. But for the 400 error to occur, the model's API must have NOT received the reasoning_content from turn 1.
Wait - actually, re-reading the error:
The reasoning_content in the thinking mode must be passed back to the API.
This error happens when the model sends back reasoning_content in its response, and the NEXT request does NOT include that reasoning_content. So the error happens on turn 2's API call, not turn 3's.
Let me think about what happens in turn 2:
The messages are prepared
_map_messages is called on the messages
For the ModelResponse (from turn 1), _map_model_response is called
_map_response_thinking_part is called for the ThinkingPart
Since include_method='field', it adds the content to self.thinkings
_into_message_param creates the assistant message with reasoning_content
This should work...
Unless... the issue is with how the message history is prepared between turns. Let me look at what happens when the CallToolsNode creates the next request:
Wait! I see something. After CallToolsNode creates the next node, it doesn't add anything to the message history. The response is already added by _append_response in ModelRequestNode._finish_handling. And the new request is added at the start of _prepare_request.
So the message history should be:
ModelRequest (user prompt) - from turn 1
ModelResponse (ThinkingPart + load_capability ToolCallPart) - from turn 1's _finish_handling
ModelRequest (LoadCapabilityReturnPart) - from turn 2's _prepare_request
And this should work correctly.
OK, let me try a completely different approach. Let me look at the git log to see if there have been any recent changes related to this issue.
Actually, I think I should look at the issue from a more practical standpoint. Let me create a test that specifically tests the scenario where a deferred capability is used with a thinking model.
Actually wait, let me re-read the _into_message_param method once more:
python
def _into_message_param(self) -> chat.ChatCompletionAssistantMessageParam | None:
if not self.texts and not self.thinkings and not self.tool_calls:
return None
message_param = chat.ChatCompletionAssistantMessageParam(role='assistant')
if self.thinkings:
for field_name, contents in self.thinkings.items():
message_param[field_name] = '\n\n'.join(contents)
if self.texts:
message_param['content'] = '\n\n'.join(self.texts)
else:
message_param['content'] = None
if self.tool_calls:
message_param['tool_calls'] = self.tool_calls
return message_param
I notice that if there's no texts but there ARE thinkings and tool_calls, it sets message_param['content'] = None. This is correct.
But wait - what about the case where there's NO tool_calls and NO texts but there IS a thinking? The message would have reasoning_content and content=None. This should be valid.
Hmm, let me look at the Chat Completion API spec. For OpenAI, an assistant message with content=None and reasoning_content set should be valid.
Wait - actually, I just noticed something in the condition:
python
if not self.texts and not self.thinkings and not self.tool_calls:
return None
If there's a ThinkingPart but include_method='tags' (or auto falls back to tags), then the thinking content goes into self.texts, not self.thinkings. So self.thinkings would be empty but self.texts would have the content wrapped in tags.
But for DeepSeek, include_method='field', so it should go into self.thinkings.
OK wait, I just realized I might have been looking at the wrong place. Let me look at whether there's any processing that happens to the message history BETWEEN when the ModelResponse is appended and when the next request is made.
In _prepare_request:
python
# This will raise errors for any tool name conflicts.
ctx.deps.tool_manager = await ctx.deps.tool_manager.for_run_step(run_context)
# Fetch instructions now that dynamic toolsets have been resolved by for_run_step.
instruction_parts = await _get_instructions(ctx, run_context)
if instruction_parts:
instruction_parts = _messages.InstructionPart.sorted(instruction_parts) or None
self.request.instructions = _messages.InstructionPart.join(instruction_parts) if instruction_parts else None
The instructions are resolved and set on the request. Then later:
So the message history is replaced with whatever request_context.messages contains after all the capability hooks.
Now, what capability hooks are there that could modify the messages?
PendingMessageDrainCapability.before_model_request - appends pending messages to request_context.messages
That's it. No other capability should modify the messages.
Wait - but there's also the _clean_message_history function that's called:
python
# Run a first pass so `prepare_messages` sees a normalized history.
messages = _clean_message_history(messages)
# Hand off to the model class for any history shapes the active provider can't
# ship on the wire
prepared = model.prepare_messages(messages)
# If `prepare_messages` produced a new list, re-run cleanup
if prepared is not messages:
messages = _clean_message_history(prepared)
else:
messages = prepared
So _clean_message_history is called twice (potentially) before the messages are sent to the model. And model.prepare_messages is also called.
The user is pointing out that my previous function call format was incorrect. I need to look at how ThinkingPart's provider_name is used when determining whether to include it in the output message when using defer_loading=True.
Looking at the issue:
With defer_loading=True, the graph loop "seems to drop or fail to serialize/propagate the reasoning_content token block back to DeepSeek's chat completions endpoint."
The error is: "The reasoning_content in the thinking mode must be passed back to the API."
Let me think about what happens during the flow with defer_loading=True:
First turn: Model returns ThinkingPart + ToolCallPart for load_capability
Tool is executed, returns instructions
Second turn: The graph loops back to ModelRequestNode, which calls _prepare_request
In _prepare_request, _clean_message_history is called
Then the messages are sent to the model via _map_messages
The key question is: what happens to the ThinkingPart between turn 1 and turn 2?
Let me look at _map_response_thinking_part in openai.py more carefully. The issue is that when mapping a ThinkingPart to the response context, the method checks certain conditions:
python
def _map_response_thinking_part(self, item: ThinkingPart) -> None:
profile = OpenAIModelProfile.from_profile(self._model.profile)
include_method = profile.openai_chat_send_back_thinking_parts
if include_method == 'auto':
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
):
self.thinkings.setdefault(item.id, []).append(item.content)
else:
start_tag, end_tag = self._model.profile.thinking_tags
self.texts.append('\n'.join([start_tag, item.content, end_tag]))
elif include_method == 'tags':
start_tag, end_tag = self._model.profile.thinking_tags
self.texts.append('\n'.join([start_tag, item.content, end_tag]))
elif include_method == 'field':
field = profile.openai_chat_thinking_field
if field:
self.thinkings.setdefault(field, []).append(item.content)
For DeepSeek with openai_chat_send_back_thinking_parts='field' and openai_chat_thinking_field='reasoning_content', when include_method == 'field', it should always add the content to self.thinkings[field]. But I need to understand what's different about how ThinkingPart is handled when defer_loading=True vs defer_loading=False.
When defer_loading=True:
Turn 1: Model returns ThinkingPart(id='reasoning_content', provider_name='deepseek', content='...') + ToolCallPart
The ThinkingPart is created by _process_thinking which sets provider_name=self.system (which is 'deepseek')
The response is stored in message history
Turn 2: When _map_messages is called, _map_model_response processes the previous response
_map_response_thinking_part is called with the ThinkingPart
Since include_method='field', it should add to self.thinkings
Wait, but _map_response_thinking_part is called from within _MapModelResponseContext, which is created fresh for each ModelResponse. Let me trace through more carefully...
Actually, I think I need to look at what happens to the ThinkingPart when the deferred capability is being loaded. When the load_capability tool is called, the response includes:
ThinkingPart from the model
ToolCallPart for load_capability
After the tool is executed, the next request is built. The message history at this point should include:
ModelRequest (user prompt)
ModelResponse (ThinkingPart + ToolCallPart)
ModelRequest (ToolReturnPart for load_capability)
When the second turn happens, _map_messages should process message #2 and map the ThinkingPart correctly.
Hmm, but what if the issue is that the ThinkingPart's provider_name is NOT set correctly? Let me check _process_thinking:
For DeepSeek, custom_field='reasoning_content' and self.system='deepseek'. So the ThinkingPart should have id='reasoning_content' and provider_name='deepseek'.
But wait - for the DeepSeek provider, the model is created as:
python
model = OpenAIChatModel('deepseek-v4-flash', provider=DeepSeekProvider(api_key='...'))
And DeepSeekProvider.name returns 'deepseek'. So self.system='deepseek'.
OK, so the ThinkingPart should be created correctly. And _map_response_thinking_part with include_method='field' should add it to self.thinkings.
Let me re-read the issue description more carefully:
When defer_loading=True, the graph loop intercepted by PydanticAI's capability runner seems to drop or fail to serialize/propagate the reasoning_content token block back to DeepSeek's chat completions endpoint.
"The graph loop intercepted by PydanticAI's capability runner" - this suggests the issue is in the capability runner, not in the model's _map_messages.
Wait, let me think about this differently. The issue might be in how MessageHistory is handled between turns. Specifically, when a deferred capability is loaded, there might be some transformation of the message history that drops the ThinkingPart.
Let me look at what happens during the capability loading flow more carefully. When load_capability is called:
DeferredCapabilityLoaderToolset.call_tool is called
_load_capability is called
It returns {'instructions': instructions_text}
This becomes a ToolReturnPart
A new ModelRequest with the ToolReturnPart is created
The graph goes back to ModelRequestNode
But wait - in step 5, what exactly happens? Let me look at CallToolsNode._handle_tool_calls:
So output_parts contains the tool return parts, and a new ModelRequest is created. This is then appended to the message history by _prepare_request:
python
ctx.state.message_history.append(self.request)
So the message history should include:
ModelRequest (user prompt) - from turn 1
ModelResponse (ThinkingPart + ToolCallPart for load_capability) - from turn 1
ModelRequest (ToolReturnPart for load_capability) - from turn 2
Then, when the model is called again, _map_messages processes all three messages. Message #2 should be mapped with the ThinkingPart included.
Wait, but what if the issue is that _map_model_response returns None for some reason? Let me check:
python
def _into_message_param(self) -> chat.ChatCompletionAssistantMessageParam | None:
if not self.texts and not self.thinkings and not self.tool_calls:
return None
If the response has ThinkingPart + ToolCallPart, then:
self.thinkings should have the thinking content
self.tool_calls should have the tool call
So it should NOT return None.
Hmm, I'm struggling to find the bug. Let me try a different approach - let me look at the tests for deferred capabilities to see if there's a specific test that involves thinking/reasoning.
Actually, I wonder if the issue is that when the ModelResponse is created in _process_response, the ThinkingPart's provider_name is set to self.system, but self.system might be different than expected.
Wait, let me check the issue description again. The user says:
This is triggered because DeepSeek requires the original reasoning_content produced during the thinking phase to be passed back exactly as-is in the subsequent conversation message history array.
So the issue is that the reasoning_content is NOT being passed back. Let me think about what could cause this...
Oh wait! I think I might have found it. Let me look at _clean_message_history again:
python
def _clean_message_history(messages: list[_messages.ModelMessage]) -> list[_messages.ModelMessage]:
clean_messages: list[_messages.ModelMessage] = []
for message in messages:
last_message = clean_messages[-1] if len(clean_messages) > 0 else None
if isinstance(message, _messages.ModelRequest):
if (
last_message
and isinstance(last_message, _messages.ModelRequest)
# Requests can only be merged if they have the same instructions
and (
not last_message.instructions
or not message.instructions
or last_message.instructions == message.instructions
)
):
parts = [*last_message.parts, *message.parts]
parts.sort(
# Tool return parts always need to be at the start
key=lambda x: 0 if isinstance(x, _messages.ToolReturnPart | _messages.RetryPromptPart) else 1
)
merged_message = _messages.ModelRequest(
parts=parts,
instructions=last_message.instructions or message.instructions,
timestamp=message.timestamp or last_message.timestamp,
)
clean_messages[-1] = merged_message
else:
clean_messages.append(message)
elif isinstance(message, _messages.ModelResponse): # pragma: no branch
# Interrupted responses are preserved as-is. Stream cancellation can
# leave incomplete tool calls, but filtering or synthesizing tool
# returns is a separate run-resumption semantics decision.
if (
last_message
and isinstance(last_message, _messages.ModelResponse)
# Responses can only be merged if they didn't really come from an API
and last_message.provider_response_id is None
and last_message.provider_name is None
and last_message.model_name is None
and message.provider_response_id is None
and message.provider_name is None
and message.model_name is None
):
merged_message = replace(last_message, parts=[*last_message.parts, *message.parts])
clean_messages[-1] = merged_message
else:
clean_messages.append(message)
return clean_messages
This looks fine - it doesn't drop ThinkingParts.
OK, let me think about this differently. The user reports the error:
code
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 means the OpenAI SDK (or DeepSeek's OpenAI-compatible API) rejected the request because the reasoning_content was not included in the assistant message.
So the question is: what's happening that causes the reasoning_content to NOT be included?
Let me trace through more carefully. In _map_messages for OpenAIChatModel:
python
async def _map_messages(
self,
messages: Sequence[ModelMessage],
model_request_parameters: ModelRequestParameters,
*,
model_settings: ModelSettings | None = None,
) -> list[chat.ChatCompletionMessageParam]:
openai_messages: list[chat.ChatCompletionMessageParam] = []
for message in messages:
if isinstance(message, ModelRequest):
async for item in self._map_user_message(message):
openai_messages.append(item)
elif isinstance(message, ModelResponse):
if (mapped := self._map_model_response(message)) is not None:
openai_messages.append(mapped)
else:
assert_never(message)
So for each ModelResponse, _map_model_response is called. If it returns None, the message is skipped. Otherwise, it's appended.
For a ModelResponse with ThinkingPart + ToolCallPart, _map_model_response should return a message param with reasoning_content set.
Let me check if there's any code that modifies the ModelResponse before it reaches _map_messages...
Actually, I just realized something. Let me look at model.prepare_messages:
python
def prepare_messages(self, messages: list[ModelMessage]) -> list[ModelMessage]:
...
if ToolSearchTool not in self.profile.supported_native_tools:
from .._tool_search import synthesize_local_tool_search_messages
messages = synthesize_local_tool_search_messages(messages)
...
This calls synthesize_local_tool_search_messages which iterates through messages and processes them. If the message is a ModelResponse, it processes each part. Let me check if this could drop the ThinkingPart...
Looking at the code:
python
for msg in messages:
if isinstance(msg, _messages.ModelResponse):
buffer: list[ModelResponsePart] = []
split_emitted = False
changed = False
for part in msg.parts:
if isinstance(part, NativeToolSearchCallPart):
buffer.append(synthesize_local_from_native_call(part))
changed = True
elif isinstance(part, NativeToolSearchReturnPart):
...
else:
buffer.append(part)
if changed:
if buffer:
out.append(_split_response(msg, buffer, first=not split_emitted))
else:
out.append(msg)
If changed is False (no NativeToolSearchCallPart or NativeToolSearchReturnPart), then the original message is appended unchanged. So ThinkingParts should be preserved.
OK, I think I need to look at this from a different angle. Let me check if there's a test that specifically tests deferred capabilities with thinking/reasoning content. If not, I should create one.
Actually, I just realized something. Let me re-read the issue:
When running an agent using a DeepSeek reasoning model, using Capability(..., defer_loading=True) causes a ModelHTTPError: status_code: 400 during execution loop turns.
So the issue is specifically with DeepSeek reasoning models and deferred capabilities. The user says setting defer_loading=False solves the issue.
The difference between defer_loading=True and defer_loading=False is:
With defer_loading=True, the model makes a load_capability call first
With defer_loading=False, the tools are available immediately
In the defer_loading=True case, the flow is:
Turn 1: Model returns ThinkingPart + load_capability ToolCallPart
Tool executed, capability loaded
Turn 2: Model returns ThinkingPart + actual tool ToolCallPart
Tool executed
Turn 3: Model returns ThinkingPart + TextPart (final answer)
The error occurs on one of the subsequent turns. The error message says the reasoning_content must be passed back. This means the assistant message in the request doesn't include the reasoning_content from the previous turn.
Let me think about what happens between turn 1 and turn 2:
Turn 1's response is stored in message history
The load_capability tool is executed
A new ModelRequest is created with the tool return
The graph goes back to ModelRequestNode
_prepare_request is called
Messages are cleaned and prepared
_map_messages is called
In step 7, _map_model_response should be called for the ModelResponse from turn 1. This should include the ThinkingPart.
Wait, but what if the issue is that between turn 1 and turn 2, the ModelResponse is somehow modified? Or what if the messages passed to _map_messages don't include the ModelResponse from turn 1?
Let me look at what messages are passed to _map_messages in _prepare_request:
So messages = request_context.messages, which starts as a copy of ctx.state.message_history. The before_model_request hook can modify this.
Then later:
python
# Merge possible consecutive trailing `ModelRequest`s into one
messages = _clean_message_history(messages)
...
prepared = model.prepare_messages(messages)
...
if prepared is not messages:
messages = _clean_message_history(prepared)
else:
messages = prepared
And then the messages are used to call the model.
So the issue could be in any of:
before_model_request modifying messages
_clean_message_history dropping messages
model.prepare_messages modifying messages
Let me check each of these more carefully...
Actually, I just realized something. Let me look at before_model_request again:
python
async def before_model_request(
self,
ctx: RunContext[Any],
request_context: ModelRequestContext,
) -> ModelRequestContext:
"""Drain `'asap'` messages into the upcoming model request.
...
"""
assert ctx.pending_messages is not None, 'drain runs during an agent run, which always has a queue'
drained = _drain_by_priority(ctx.pending_messages, 'asap')
for message in _stamped_messages(
drained, fallback_run_id=ctx.run_id, fallback_conversation_id=ctx.conversation_id
):
request_context.messages.append(message)
ctx.messages.append(message)
return request_context
This drains pending messages and appends them to request_context.messages. This shouldn't affect existing messages.
Hmm, but what if there's a capability that replaces request_context.messages entirely instead of modifying it in place?
Let me check if there are any other before_model_request implementations in the capabilities...
I found the issue! In the _tool_search.py capability's before_model_request method (lines 212-254), when tools are loaded from a deferred capability, it creates syntheticModelResponse and ModelRequest messages to represent a tool-search exchange.
This ModelResponse has NO ThinkingPart in it. When this synthetic ModelResponse is appended to request_context.messages, it comes AFTER the real ModelResponse that has the ThinkingPart.
But wait, that shouldn't cause an issue - the messages are still in order. Let me think more carefully...
Actually, I think the issue might be different. Let me re-read the code more carefully.
When a deferred capability is loaded:
Turn 1: Model returns ThinkingPart + load_capabilityToolCallPart
Tool executed, capability loaded
Turn 2: before_model_request is called
In turn 2's before_model_request, the ToolSearchCapability.before_model_request is called. If there are newly loaded tools, it creates synthetic messages:
This adds a synthetic ModelResponse with just a ToolSearchCallPart. This synthetic response is appended to the END of the messages.
But wait, this is the issue! The synthetic ModelResponse is added AFTER the real ModelResponse that has the ThinkingPart. When DeepSeek receives this message history, it sees:
ModelResponse (ToolSearchCallPart) <-- synthetic, NO reasoning_content
ModelRequest (ToolSearchReturnPart) <-- synthetic
Now, when the model is called, the API sends these messages. The last assistant message is the synthetic one (#4) which does NOT have reasoning_content. But the previous assistant message (#2) DOES have reasoning_content.
Hmm, but that shouldn't cause an issue either - each assistant message is independent. The error is about NOT passing back the reasoning_content from a PREVIOUS assistant message that had thinking mode enabled.
Wait, let me re-read the error message:
code
The `reasoning_content` in the thinking mode must be passed back to the API.
This means the API expects that when a model is in "thinking mode", the reasoning_content from the model's previous response must be passed back. If the model is in thinking mode and the previous response had reasoning_content, but the current request's assistant message doesn't include it, the API returns a 400 error.
So the issue is: the model's previous response (from turn 1) has reasoning_content, and when making the request for turn 2, the assistant message for turn 1's response should include the reasoning_content. If it doesn't, the API returns 400.
But I've already confirmed that _map_model_response correctly includes the reasoning_content in the assistant message. So why would it not be there?
Wait, let me think about this more carefully. The _map_messages method in OpenAIChatModel processes ALL messages in the history and maps them to OpenAI format. So the messages sent to the API should include:
User message
Assistant message with reasoning_content + tool_calls
Tool message
(synthetic) Assistant message with tool_search_call
(synthetic) Tool message
The assistant message #2 should have reasoning_content. Let me verify this...
Actually, I think I need to trace through what _map_model_response does for the real ModelResponse (turn 1's response). It calls _MapModelResponseContext.map_assistant_message, which iterates over all parts and maps them.
For the ThinkingPart, it calls _map_response_thinking_part. With include_method='field' (DeepSeek's setting), it adds the content to self.thinkings[field].
Then _into_message_param creates the message with reasoning_content set.
So the message should be correct...
Unless... the issue is that when the synthetic messages are added by ToolSearchCapability.before_model_request, they're added to request_context.messages but then _clean_message_history is called, and it might merge or drop messages incorrectly.
Let me look at _clean_message_history again:
python
def _clean_message_history(messages: list[_messages.ModelMessage]) -> list[_messages.ModelMessage]:
clean_messages: list[_messages.ModelMessage] = []
for message in messages:
last_message = clean_messages[-1] if len(clean_messages) > 0 else None
if isinstance(message, _messages.ModelRequest):
if (
last_message
and isinstance(last_message, _messages.ModelRequest)
# Requests can only be merged if they have the same instructions
and (
not last_message.instructions
or not message.instructions
or last_message.instructions == message.instructions
)
):
# Merge requests...
else:
clean_messages.append(message)
elif isinstance(message, _messages.ModelResponse):
# Responses can only be merged if they didn't really come from an API
if (
last_message
and isinstance(last_message, _messages.ModelResponse)
and last_message.provider_response_id is None
and last_message.provider_name is None
and last_message.model_name is None
and message.provider_response_id is None
and message.provider_name is None
and message.model_name is None
):
# Merge responses...
else:
clean_messages.append(message)
return clean_messages
For merging responses, both must have provider_name=None. The real ModelResponse has provider_name='deepseek', so it won't be merged. The synthetic ModelResponse has provider_name=None, so it also won't be merged with the real one.
So the messages should be preserved correctly.
Hmm, I'm still stuck. Let me look at this from yet another angle. What if the issue is that the ToolSearchCapability.before_model_request is adding synthetic messages that somehow interfere with the real messages?
Actually, wait. I just realized something. The ToolSearchCapability.before_model_request adds synthetic messages. But the order matters! Let me look at the message order after this hook:
Assistant message with reasoning_content + tool_calls
Tool message
Assistant message with tool_search_call
Tool message
The assistant message #2 should have reasoning_content. So this should work...
Unless the issue is that DeepSeek's API has a special requirement. Let me re-read the error message:
code
The `reasoning_content` in the thinking mode must be passed back to the API.
This error occurs when the model is in "thinking mode" and the previous response had reasoning_content, but the current request doesn't include it. But I've confirmed that the request DOES include it...
Wait, let me check if there's something special about how the messages are sent to the API. Maybe the issue is not in the message mapping but in how the messages are serialized or sent.
Actually, I think I need to take a step back and consider what "defer_loading" actually does. Let me re-read the issue:
When defer_loading=True, the graph loop intercepted by PydanticAI's capability runner seems to drop or fail to serialize/propagate the reasoning_content token block back to DeepSeek's chat completions endpoint.
"The graph loop intercepted by PydanticAI's capability runner" - this suggests the issue is in the capability runner, specifically in how it intercepts the graph loop.
What if the issue is that when a capability is loaded (via load_capability), the response from that tool call execution somehow affects the message history?
Let me look at what happens when load_capability returns. The _load_capability method returns:
python
return {'instructions': instructions_text} if instructions_text is not None else {}
This becomes a ToolReturnPart. The ToolReturnPart is then added to the message history as part of a new ModelRequest.
But wait, the ToolReturnPart is created with the tool call ID that matches the original ToolCallPart. And the original ToolCallPart was in the ModelResponse with the ThinkingPart.
Let me check if the issue is with how the LoadCapabilityCallPart is handled differently from a regular ToolCallPart...
Actually, let me look at the _deferred_capabilities.py file to see how LoadCapabilityCallPart and LoadCapabilityReturnPart are defined.
I already looked at this file earlier. LoadCapabilityCallPart extends ToolCallPart with tool_kind='capability-load'. And LoadCapabilityReturnPart extends ToolReturnPart with tool_kind='capability-load'.
These are typed subclasses of the base parts. They shouldn't affect the mapping to OpenAI format since _map_model_response iterates over all parts and maps them based on their base type.
Wait, but let me check. In _map_response_tool_call_part:
This maps any ToolCallPart (including LoadCapabilityCallPart) to a tool call. So that should work.
Hmm, I'm still stuck. Let me try a different approach - let me write a test that specifically tests the deferred capability flow with a thinking model and see if I can reproduce the issue.
Actually, I just thought of something. What if the issue is not in the message history but in how the model is configured for the second turn? For example, what if thinking=True is not set for the second turn?
DeepSeek's API might require that when you pass reasoning_content back, you also enable thinking mode (e.g., reasoning_effort or thinking parameter). If the thinking mode is not enabled on the second turn, the API might reject the request.
But that doesn't match the error message. The error says "The reasoning_content in the thinking mode must be passed back to the API." This means the thinking mode IS enabled, but the reasoning_content is NOT being passed back.
OK wait, I just realized something. Let me re-read the code for _clean_message_history:
python
elif isinstance(message, _messages.ModelResponse): # pragma: no branch
if (
last_message
and isinstance(last_message, _messages.ModelResponse)
and last_message.provider_response_id is None
and last_message.provider_name is None
and last_message.model_name is None
and message.provider_response_id is None
and message.provider_name is None
and message.model_name is None
):
merged_message = replace(last_message, parts=[*last_message.parts, *message.parts])
clean_messages[-1] = merged_message
else:
clean_messages.append(message)
Wait, this code only merges consecutive ModelResponse messages if they BOTH have provider_name=None. But what if the synthetic ModelResponse from ToolSearchCapability.before_model_request has provider_name=None, and it comes AFTER the real ModelResponse?
In that case, the synthetic response won't merge with the real one (because the real one has provider_name='deepseek'). So the messages should be preserved correctly.
But wait, what if there's a scenario where TWO synthetic ModelResponse messages are created, and they get merged? That could cause issues if the merged response drops some parts...
Actually no, the synthetic messages are only added once per capability load, and they're added as a pair (ModelResponse + ModelRequest).
Hmm, let me think about this more. The user says the issue happens specifically with defer_loading=True. Let me compare the two flows:
With defer_loading=False:
Turn 1: Model returns ThinkingPart + tool call
Tool executed
Turn 2: Model returns ThinkingPart + final answer
With defer_loading=True:
Turn 1: Model returns ThinkingPart + load_capability call
Assistant message with reasoning_content + tool_calls
Tool message (for load_capability)
Assistant message with tool_search_call
Tool message (for tool_search)
The assistant message #2 has reasoning_content. So the API should be happy...
Unless the issue is that the API checks the LAST assistant message, not the one with reasoning_content. Let me think about this...
Actually, DeepSeek's error message says "The reasoning_content in the thinking mode must be passed back to the API." This could mean that when the model is in thinking mode (which it is for the entire conversation with a reasoning model), the reasoning_content from EVERY assistant message that produced thinking must be passed back.
But wait, the synthetic assistant message (#4) doesn't have reasoning_content because it was created synthetically. It only has a ToolSearchCallPart. This is fine because it's not a real response from the model.
Hmm, but what if DeepSeek's API doesn't distinguish between real and synthetic messages? What if it checks that ALL assistant messages have reasoning_content when the model is in thinking mode?
That doesn't sound right. The API should only care about its own responses, not synthetic ones.
OK, I think I need to approach this differently. Let me look for any code that might be modifying the ThinkingPart or removing it from the message history.
Actually, let me look at the _map_response_thinking_part method one more time. I want to check if there's any condition that could cause the thinking content to be skipped:
python
def _map_response_thinking_part(self, item: ThinkingPart) -> None:
profile = OpenAIModelProfile.from_profile(self._model.profile)
include_method = profile.openai_chat_send_back_thinking_parts
if include_method == 'auto':
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
):
self.thinkings.setdefault(item.id, []).append(item.content)
else:
start_tag, end_tag = self._model.profile.thinking_tags
self.texts.append('\n'.join([start_tag, item.content, end_tag]))
elif include_method == 'tags':
start_tag, end_tag = self._model.profile.thinking_tags
self.texts.append('\n'.join([start_tag, item.content, end_tag]))
elif include_method == 'field':
field = profile.openai_chat_thinking_field
if field: # pragma: no branch
self.thinkings.setdefault(field, []).append(item.content)
For DeepSeek, include_method='field' and field='reasoning_content'. So:
python
elif include_method == 'field':
field = profile.openai_chat_thinking_field # 'reasoning_content'
if field: # True
self.thinkings.setdefault(field, []).append(item.content)
This adds the content to self.thinkings['reasoning_content']. Then in _into_message_param:
python
if self.thinkings:
for field_name, contents in self.thinkings.items():
message_param[field_name] = '\n\n'.join(contents)
So message_param['reasoning_content'] is set to the content. This looks correct.
Wait, I just realized something. The issue might be in how the ThinkingPart is handled when the model response comes from the FunctionModel (used in tests) vs the real DeepSeek model.
When using FunctionModel, the response is returned directly by the user-provided function. The user can set any ThinkingPart attributes. But when using the real DeepSeek model, the ThinkingPart is created by _process_thinking in OpenAIChatModel.
Let me check _process_thinking one more time:
python
def _process_thinking(self, message: chat.ChatCompletionMessage) -> list[ThinkingPart] | None:
profile = OpenAIModelProfile.from_profile(self.profile)
custom_field = profile.openai_chat_thinking_field
items: list[ThinkingPart] = []
for field_name in (custom_field, 'reasoning', 'reasoning_content'):
if not field_name:
continue
reasoning: object = getattr(message, field_name, None)
if not reasoning:
continue
if not isinstance(reasoning, str):
warnings.warn(...)
continue
items.append(ThinkingPart(id=field_name, content=reasoning, provider_name=self.system))
return items
return items or None
For DeepSeek, custom_field='reasoning_content' and self.system='deepseek'. So:
Wait, I just had another thought. What if the issue is that the ThinkingPart is being created correctly, but when the message history is processed through model.prepare_messages, something goes wrong?
Let me check model.prepare_messages again:
python
def prepare_messages(self, messages: list[ModelMessage]) -> list[ModelMessage]:
if ToolSearchTool not in self.profile.supported_native_tools:
from .._tool_search import synthesize_local_tool_search_messages
messages = synthesize_local_tool_search_messages(messages)
...
For DeepSeek, ToolSearchTool is NOT in supported_native_tools (I think). So synthesize_local_tool_search_messages is called.
Let me look at this function again:
python
def synthesize_local_tool_search_messages(messages: list[ModelMessage]) -> list[ModelMessage]:
out: list[ModelMessage] = []
for msg in messages:
if isinstance(msg, _messages.ModelResponse):
buffer: list[ModelResponsePart] = []
split_emitted = False
changed = False
for part in msg.parts:
if isinstance(part, NativeToolSearchCallPart):
buffer.append(synthesize_local_from_native_call(part))
changed = True
elif isinstance(part, NativeToolSearchReturnPart):
...
else:
buffer.append(part)
if changed:
if buffer:
out.append(_split_response(msg, buffer, first=not split_emitted))
else:
out.append(msg)
elif isinstance(msg, _messages.ModelRequest):
...
return out
If changed is False (no NativeToolSearchCallPart or NativeToolSearchReturnPart in the message), the original message is appended unchanged. So ThinkingParts should be preserved.
But wait! There's a subtle issue here. If changed is True but buffer is empty (which could happen if the message only contains NativeToolSearchReturnPart and no other parts), then _split_response is NOT called, and the message is lost!
Let me check:
python
if changed:
if buffer:
out.append(_split_response(msg, buffer, first=not split_emitted))
If changed=True but buffer is empty, the message is not appended to out. But this only happens for ModelResponse messages that contain NativeToolSearchCallPart or NativeToolSearchReturnPart, not regular messages with ThinkingPart.
So this shouldn't be the issue for our case.
OK, I think I need to actually trace through the code more carefully to find the bug. Let me write a test that simulates the exact scenario described in the issue.
Actually, wait. I just realized that I should check if there's a ThinkingPart being added to the message history AFTER the _clean_message_history call but BEFORE the actual API call.
Let me look at _prepare_request one more time:
python
messages = _clean_message_history(messages)
# Hand off to the model class for any history shapes the active provider can't
# ship on the wire
prepared = model.prepare_messages(messages)
# If `prepare_messages` produced a new list, re-run cleanup
if prepared is not messages:
messages = _clean_message_history(prepared)
else:
messages = prepared
And then:
python
return model, model_settings or None, model_request_parameters, messages, run_context
So the messages returned from _prepare_request are what gets sent to the model's request() method.
So openai_messages is what gets sent to the API. This is created by _map_messages.
Now, _map_messages processes each message and calls _map_model_response for ModelResponse messages. For each ModelResponse, it should create an assistant message with reasoning_content.
I've traced through the code multiple times and can't find the bug. Let me try a different approach - let me actually write a test and run it.
Actually, I just had a new thought. What if the issue is related to the order of messages in the message history? Specifically, what if the synthetic tool-search messages (from ToolSearchCapability.before_model_request) are added AFTER the real ModelResponse, but the _map_messages method processes them in a way that affects the real response?
No, that doesn't make sense. _map_messages processes each message independently.
OK let me think about this differently. The user says:
Setting defer_loading=False solves the issue
With defer_loading=False, there's no load_capability tool call, and the tools are available immediately. The flow is:
Turn 1: Model returns ThinkingPart + actual tool ToolCallPart
Tool executed
Turn 2: Model returns ThinkingPart + final answer
In this case, the ToolSearchCapability.before_model_request doesn't add synthetic messages because no new tools are discovered.
But wait, with defer_loading=True, the ToolSearchCapability.before_model_request DOES add synthetic messages. And these synthetic messages are added to the END of the message history.
So the difference is:
With defer_loading=False: Messages end with the real ModelResponse
With defer_loading=True: Messages end with synthetic tool-search messages
What if DeepSeek's API has a bug or special behavior where it checks the LAST assistant message for reasoning_content?
Actually, that sounds unlikely. Let me re-read the error message:
code
The `reasoning_content` in the thinking mode must be passed back to the API.
Hmm, what if the error is about the FIRST assistant message (not the last) not having reasoning_content? But that doesn't make sense either, because the first assistant message (the real one) DOES have reasoning_content.
Wait, I just realized something. Let me check if there's a scenario where the first ModelResponse gets replaced or dropped.
Actually, let me look at _clean_message_history one more time. What if there's a bug where consecutive ModelResponse messages get merged incorrectly?
Actually no, I already checked this. The merge condition requires both messages to have provider_name=None, and the real ModelResponse has provider_name='deepseek'.
OK, I think I need to just write a test and run it to see what's actually happening. Let me create a test script.
Actually, wait. I just thought of something. Let me check if the issue is with how the ThinkingPart is created. The _process_thinking method uses getattr(message, field_name, None) to get the reasoning content from the OpenAI SDK's response object.
What if the DeepSeek API returns reasoning_content but the OpenAI SDK doesn't expose it as an attribute? In that case, getattr(message, 'reasoning_content', None) would return None, and the ThinkingPart would not be created.
But the user says defer_loading=False works, which means the ThinkingPart IS being created correctly. So this can't be the issue.
Hmm, let me think about this from the API perspective. When DeepSeeek receives a request with:
User message
Assistant message with reasoning_content + tool_calls
Tool message
And then returns a response with reasoning_content, the next request must include that reasoning_content back. This is what the user is saying.
So the issue is in the SECOND round trip:
User message
Assistant message with reasoning_content + load_capability tool_calls
Tool message (for load_capability)
(synthetic) Assistant message with tool_search_call
(synthetic) Tool message
Assistant message with reasoning_content + actual tool tool_calls <-- THIS IS THE SECOND RESPONSE
Tool message (for actual tool)
And then the third request should include the reasoning_content from the assistant message #6.
Wait, but the synthetic assistant message #4 doesn't have reasoning_content. Does DeepSeek care about that?
Actually, I think the issue might be that DeepSeek's API sees the synthetic assistant message #4 and expects it to have reasoning_content because the model is in thinking mode. Since it doesn't, the API returns an error.
But wait, the synthetic message is a local fabrication - it's not from the actual DeepSeek model. It represents a tool search exchange. The API shouldn't care about it.
Unless... the issue is that the API sees the synthetic assistant message as the most recent assistant message from the model, and expects it to have reasoning_content because the model is in thinking mode.
Actually, I think this might be it! If DeepSeek's API checks the LAST assistant message for reasoning_content, and the last assistant message is the synthetic one (which doesn't have reasoning_content), the API would return an error.
But wait, the synthetic message is added by ToolSearchCapability.before_model_request. This is called BEFORE the model's request() method. So the messages sent to the API include both the real assistant message (with reasoning_content) AND the synthetic one (without).
Hmm, but the synthetic message is a ModelResponse with only a ToolSearchCallPart. When mapped to OpenAI format, it becomes an assistant message with tool_calls but no reasoning_content.
So the API sees:
User message
Assistant message with reasoning_content + tool_calls (for load_capability)
Tool message (for load_capability)
Assistant message with tool_calls (for tool_search) -- NO reasoning_content!
Tool message (for tool_search)
And then the API might check: "Is this the latest turn? Does the latest assistant message have reasoning_content?" If the API thinks the thinking mode is still active, it might require reasoning_content on the LAST assistant message.
But this doesn't make sense because the synthetic messages are local fabrications, not from the actual model. The API shouldn't care about them.
OK, I think I've been overthinking this. Let me just look for the actual bug.
Actually, I just realized something. Let me re-read the issue description:
When defer_loading=True, the graph loop intercepted by PydanticAI's capability runner seems to drop or fail to serialize/propagate the reasoning_content token block back to DeepSeek's chat completions endpoint.
"the graph loop intercepted by PydanticAI's capability runner" - this is key. The capability runner intercepts the graph loop. What does it intercept?
Let me look at the capability runner... Actually, let me search for "capability runner" in the codebase.
Actually, I think "capability runner" refers to the capability hooks system, specifically the before_model_request and after_model_request hooks.
Let me look at what happens in before_model_request more carefully. There's the ToolSearchCapability.before_model_request which adds synthetic messages. But is there something else?
Actually, let me look at what happens to the messages after _map_messages returns. The openai_messages list is what gets sent to the API. Let me check if there's any processing after _map_messages that could drop the reasoning_content.
So openai_messages is sent directly to the API. There's no further processing.
OK, I think the issue must be in _map_messages. Let me look at it one more time:
python
async def _map_messages(
self,
messages: Sequence[ModelMessage],
model_request_parameters: ModelRequestParameters,
*,
model_settings: ModelSettings | None = None,
) -> list[chat.ChatCompletionMessageParam]:
openai_messages: list[chat.ChatCompletionMessageParam] = []
for message in messages:
if isinstance(message, ModelRequest):
async for item in self._map_user_message(message):
openai_messages.append(item)
elif isinstance(message, ModelResponse):
if (mapped := self._map_model_response(message)) is not None:
openai_messages.append(mapped)
else:
assert_never(message)
For each ModelResponse, _map_model_response is called. If it returns None, the message is skipped. Otherwise, it's appended.
For a ModelResponse with ThinkingPart, _map_model_response should return a message with reasoning_content. Let me verify this by looking at _map_model_response and _MapModelResponseContext:
So for a ModelResponse with ThinkingPart + ToolCallPart:
_map_response_thinking_part is called -> adds to self.thinkings
_map_response_tool_call_part is called -> adds to self.tool_calls
_into_message_param creates the message
In _into_message_param:
python
def _into_message_param(self) -> chat.ChatCompletionAssistantMessageParam | None:
if not self.texts and not self.thinkings and not self.tool_calls:
return None
message_param = chat.ChatCompletionAssistantMessageParam(role='assistant')
if self.thinkings:
for field_name, contents in self.thinkings.items():
message_param[field_name] = '\n\n'.join(contents)
if self.texts:
message_param['content'] = '\n\n'.join(self.texts)
else:
message_param['content'] = None
if self.tool_calls:
message_param['tool_calls'] = self.tool_calls
return message_param
So the message param has:
role='assistant'
reasoning_content=<content from ThinkingPart>
content=None
tool_calls=[tool call from ToolCallPart]
This looks correct!
Wait, but I just realized something. What if the issue is that the ThinkingPart is NOT being added to self.thinkings because include_method is not 'field'?
Let me check the DeepSeek provider's profile again:
The update method only copies non-default values. So openai_chat_send_back_thinking_parts from the DeepSeek profile ('field') should be preserved since the base ModelProfile probably has it as None or some other default.
Let me think about this issue differently. Let me look at the ToolSearchCapability.before_model_request more carefully - it adds synthetic messages to request_context.messages. These synthetic messages include a ModelResponse with a ToolSearchCallPart.
But wait - the ToolSearchCallPart is a NativeToolSearchCallPart, not a regular ToolCallPart. Let me check how this is handled when mapping.
Actually, I wonder if the issue is that when _map_messages processes the synthetic ModelResponse with ToolSearchCallPart, it doesn't handle ToolSearchCallPart (which extends NativeToolSearchCallPart which extends NativeToolCallPart) correctly.
Let me check _map_model_response / _MapModelResponseContext.map_assistant_message:
python
def map_assistant_message(self, message: ModelResponse) -> chat.ChatCompletionAssistantMessageParam | None:
for item in message.parts:
if isinstance(item, TextPart):
self._map_response_text_part(item)
elif isinstance(item, ThinkingPart):
self._map_response_thinking_part(item)
elif isinstance(item, ToolCallPart):
self._map_response_tool_call_part(item)
elif isinstance(item, NativeToolCallPart | NativeToolReturnPart): # pragma: no cover
self._map_response_builtin_part(item)
...
Wait, ToolSearchCallPart extends ToolCallPart (through _deferred_capabilities.py), not NativeToolSearchCallPart. Let me check:
python
@dataclass(repr=False)
class LoadCapabilityCallPart(ToolCallPart):
...
So LoadCapabilityCallPart extends ToolCallPart. That's fine.
But what about ToolSearchCallPart? Let me check...
Actually, looking at the messages module:
python
class ToolSearchCallPart(ToolCallPart):
...
So ToolSearchCallPart extends ToolCallPart. So in map_assistant_message, it would be handled by the isinstance(item, ToolCallPart) branch.
But wait, NativeToolSearchCallPart is different:
python
class NativeToolSearchCallPart(NativeToolCallPart):
...
So NativeToolSearchCallPart extends NativeToolCallPart, not ToolCallPart.
OK so the synthetic message created by ToolSearchCapability.before_model_request uses ToolSearchCallPart, which extends ToolCallPart. So it would be handled correctly.
Hmm, I'm still stuck. Let me try a completely different approach. Let me look for any code that specifically handles reasoning_content or ThinkingPart in the context of deferred capabilities.
Actually, wait. I just realized something. Let me re-read the ToolSearchCapability.before_model_request method:
python
async def before_model_request(
self, ctx: RunContext[AgentDepsT], request_context: ModelRequestContext
) -> ModelRequestContext:
"""Append a synthetic tool-search exchange for tools unlocked by a capability load."""
loaded = tool_defs_for_loaded_capabilities(ctx, request_context.model_request_parameters.function_tools)
newly_loaded = [tool_def for name, tool_def in loaded.items() if name not in ctx.discovered_tool_names]
if not newly_loaded:
return request_context
...
request_context.messages.extend([...])
return request_context
This appends synthetic messages to request_context.messages. But these are just appended to the END of the messages list. They don't replace or modify the existing messages.
So the real ModelResponse with ThinkingPart should still be in the list, at its original position.
Wait, but what if the issue is with how _clean_message_history handles these messages? Let me trace through what happens:
So the assistant message #2 has reasoning_content. The API should be happy.
I'm really confused about what the actual bug is. Let me try to reproduce it with a test.
Actually, wait. Let me re-read the issue one more time. The user says:
This is triggered because DeepSeek requires the original reasoning_content produced during the thinking phase to be passed back exactly as-is in the subsequent conversation message history array.
"the subsequent conversation message history array" - this refers to the message history sent TO the API. So the issue is that when the messages are sent to DeepSeek's API, the reasoning_content is not included.
But I've traced through the code and it seems like reasoning_content SHOULD be included. So either:
I'm missing something in my analysis
The bug is somewhere else
The issue description is misleading
Let me try a different approach. Let me look at what happens when model.prepare_messages is called. Specifically, let me check if synthesize_local_tool_search_messages does anything that could affect the ThinkingPart.
Actually, wait. Let me check if ToolSearchCallPart extends ToolCallPart:
Let me trace through the issue more carefully. I've been going in circles. Let me take a fresh look at this.
The issue is:
With defer_loading=True, when using DeepSeek reasoning models, a 400 error is thrown
The error says: "The reasoning_content in the thinking mode must be passed back to the API."
Setting defer_loading=False fixes the issue
The key insight from the issue description is:
"the graph loop intercepted by PydanticAI's capability runner seems to drop or fail to serialize/propagate the reasoning_content token block back to DeepSeek's chat completions endpoint."
Let me think about what happens step by step when defer_loading=True:
Turn 1: Model returns ThinkingPart (with reasoning_content) + load_capability ToolCallPart
The load_capability tool is executed
The ToolSearchCapability.before_model_request adds synthetic messages
Turn 2: A new request is made with the message history
Wait - I think I need to look at what happens AFTER the tool execution but BEFORE the next model request. Let me look at CallToolsNode._handle_tool_calls:
python
async def _handle_tool_calls(
self,
ctx: GraphRunContext[...],
tool_calls: list[_messages.ToolCallPart],
) -> AsyncIterator[_messages.HandleResponseEvent]:
...
output_parts: list[_messages.ModelRequestPart] = []
...
async for event in process_tool_calls(...):
yield event
...
if output_final_result:
...
else:
# Add user prompt if provided, after all tool return parts
if self.user_prompt is not None:
output_parts.append(_messages.UserPromptPart(self.user_prompt))
self._next_node = ModelRequestNode[DepsT, NodeRunEndT](_messages.ModelRequest(parts=output_parts))
So after tool execution, a new ModelRequest is created with output_parts (the tool return parts). This becomes the next node.
Then in ModelRequestNode._prepare_request:
python
ctx.state.message_history.append(self.request)
The new request is appended to the message history.
The before_model_request hook is called. This is where ToolSearchCapability.before_model_request adds synthetic messages.
Now here's the key question: after before_model_request, what does request_context.messages look like?
It should have:
ModelRequest (user prompt) - from turn 1
ModelResponse (ThinkingPart + load_capability ToolCallPart) - from turn 1
ModelRequest (LoadCapabilityReturnPart) - the new request
ModelResponse (ToolSearchCallPart) - synthetic
ModelRequest (ToolSearchReturnPart) - synthetic
Then _clean_message_history is called. This should preserve all messages.
Then model.prepare_messages is called. For DeepSeek, this calls synthesize_local_tool_search_messages.
Wait! Let me check if synthesize_local_tool_search_messages does anything that could cause issues...
Looking at the code:
python
def synthesize_local_tool_search_messages(messages: list[ModelMessage]) -> list[ModelMessage]:
out: list[ModelMessage] = []
for msg in messages:
if isinstance(msg, _messages.ModelResponse):
buffer: list[ModelResponsePart] = []
split_emitted = False
changed = False
for part in msg.parts:
if isinstance(part, NativeToolSearchCallPart):
buffer.append(synthesize_local_from_native_call(part))
changed = True
elif isinstance(part, NativeToolSearchReturnPart):
...
else:
buffer.append(part)
if changed:
if buffer:
out.append(_split_response(msg, buffer, first=not split_emitted))
else:
out.append(msg)
elif isinstance(msg, _messages.ModelRequest):
...
return out
This function processes ModelResponse messages. For each one, it checks if there are NativeToolSearchCallPart or NativeToolSearchReturnPart parts.
But the synthetic messages use ToolSearchCallPart, NOT NativeToolSearchCallPart. So changed would be False for the synthetic message, and it would be appended unchanged.
Wait, but ToolSearchCallPart extends ToolCallPart, and NativeToolSearchCallPart extends NativeToolCallPart. These are different class hierarchies!
So synthesize_local_tool_search_messages shouldn't affect the synthetic messages at all.
Hmm, I'm still stuck. Let me try to create a minimal reproduction and run it.
Actually, wait. Let me re-read the issue one more time:
This is triggered because DeepSeek requires the original reasoning_content produced during the thinking phase to be passed back exactly as-is in the subsequent conversation message history array.
"passed back exactly as-is" - this is the key phrase. DeepSeek wants the reasoning_content to be passed back EXACTLY as-is.
What if the issue is that when _into_message_param creates the message, it joins multiple thinking contents with \n\n?
python
if self.thinkings:
for field_name, contents in self.thinkings.items():
message_param[field_name] = '\n\n'.join(contents)
If there's only one ThinkingPart, then contents is a list with one element, and '\n\n'.join(contents) just returns that element. So this should be fine.
But what if there's something else going on? Let me think...
Actually, wait. I just realized something. Let me look at the _map_response_thinking_part method again:
python
elif include_method == 'field':
field = profile.openai_chat_thinking_field
if field: # pragma: no branch
self.thinkings.setdefault(field, []).append(item.content)
This adds the content to self.thinkings[field]. For DeepSeek, field='reasoning_content'.
But what if profile.openai_chat_thinking_field is None or empty? In that case, field would be None or empty, and if field: would be False, so the content would NOT be added.
But I checked the DeepSeek provider, and it sets openai_chat_thinking_field='reasoning_content'. So this shouldn't be the issue.
Unless... there's something wrong with how the profile is resolved? Let me check.
Actually, wait. The OpenAIModelProfile.from_profile(self._model.profile) call might be returning a different profile than expected.
Let me look at OpenAIModelProfile.from_profile:
Actually, I realize I should just try to write a test that reproduces the issue. Let me do that.
But first, let me think about what the ACTUAL bug might be. The user says:
defer_loading=True causes the issue
defer_loading=False works fine
The key difference is the load_capability tool call and the subsequent tool-search synthetic messages.
What if the bug is NOT in the message mapping, but in how the messages are PREPARED before being sent to the model?
Actually, I just had a thought. What if the issue is that when ToolSearchCapability.before_model_request adds synthetic messages, those messages are added AFTER the existing messages. But then _clean_message_history is called, and it processes messages in order.
If there's a bug in _clean_message_history that drops the ThinkingPart from the earlier ModelResponse when processing the later synthetic messages, that could explain the issue.
But I've already checked _clean_message_history and it doesn't seem to drop any parts.
OK, I think I need to take a step back and think about this more carefully.
The error message is: "The reasoning_content in the thinking mode must be passed back to the API."
This means the API received a request where:
The model is in "thinking mode"
A previous assistant message had reasoning_content
The current request's corresponding assistant message does NOT have reasoning_content
So the bug is that the assistant message sent to the API doesn't have reasoning_content, even though the corresponding ModelResponse has a ThinkingPart.
Let me think about when this could happen:
_map_model_response returns None for the ModelResponse with ThinkingPart
_map_model_response doesn't include reasoning_content in the returned message
For case 1, _map_model_response returns None only if _into_message_param returns None, which happens when not self.texts and not self.thinkings and not self.tool_calls.
For a ModelResponse with ThinkingPart + ToolCallPart, self.thinkings and self.tool_calls should both be populated, so this shouldn't happen.
For case 2, the issue would be in _map_response_thinking_part not adding to self.thinkings.
With include_method='field', the code is:
python
field = profile.openai_chat_thinking_field
if field:
self.thinkings.setdefault(field, []).append(item.content)
This should work if field is truthy. For DeepSeek, field='reasoning_content', which is truthy.
So both cases seem to work correctly. But the user reports an issue...
Wait! I just had a realization. What if the issue is NOT with the first ModelResponse (the one with ThinkingPart + load_capability call), but with a LATER ModelResponse?
Let me think about the flow again:
Turn 1: Model returns ThinkingPart + load_capability ToolCallPart
Tool executed
Turn 2: Model returns ThinkingPart + actual tool ToolCallPart (e.g., roll_dice)
Tool executed
Turn 3: Model returns ThinkingPart + TextPart (final answer)
Assistant message #2: tool_calls (for tool_search, NO reasoning_content)
The second assistant message doesn't have reasoning_content because it's a synthetic message. Could this be the issue?
Actually, wait. DeepSeek's error says "The reasoning_content in the thinking mode must be passed back to the API." This might mean that when the model is in thinking mode, EVERY assistant message that comes from the model must have reasoning_content. But the synthetic assistant message is NOT from the model - it's a local fabrication.
Unless DeepSeek's API doesn't distinguish between "real" and "synthetic" assistant messages. It just sees a sequence of messages and expects that if thinking mode is enabled, all assistant messages should have reasoning_content.
If that's the case, then the fix would be to NOT add synthetic assistant messages when the model is in thinking mode. Or to add reasoning_content to the synthetic messages.
But wait, that doesn't make sense. The synthetic messages are for tool search, which is a different mechanism. They shouldn't need reasoning_content.
Hmm, actually, I think the issue might be different. Let me re-read the error:
"The reasoning_content in the thinking mode must be passed back to the API."
This could also mean: "When the model previously returned reasoning_content, you must pass that SAME reasoning_content back in the next request."
So the issue might be that the reasoning_content from turn 1's response is not being passed back in turn 2's request.
But I've verified that _map_model_response DOES include reasoning_content for turn 1's response. So the assistant message for turn 1 should have reasoning_content.
Unless... there's a bug in _map_model_response that I'm not seeing.
Actually, let me look at this from a different angle. What if the issue is that the ThinkingPart's content is somehow empty or invalid?
No, that doesn't make sense either. The user says it works with defer_loading=False, which means the ThinkingPart is valid.
OK, I think I need to just create a test and run it to see what's actually happening.
Actually, wait. I just realized I should check if there's an issue with how the ThinkingPart is handled when map_assistant_message is called. Let me trace through more carefully:
For a ModelResponse with ThinkingPart + ToolCallPart:
Since ToolSearchCallPart extends ToolCallPart, if the message has both ThinkingPart and ToolCallPart, both _map_response_thinking_part and _map_response_tool_call_part would be called.
But wait, LoadCapabilityCallPart also extends ToolCallPart. So for turn 1's response (ThinkingPart + LoadCapabilityCallPart), both methods would be called.
This looks correct.
OK, I've been going in circles. Let me just look for any changes to the codebase that might have introduced this bug. Let me check the git log for recent changes related to ThinkingPart or reasoning_content.
Actually, I think the issue might be related to a specific case where the message order or processing causes the ThinkingPart to be lost. Let me create a minimal reproduction.
Let me create a test script that:
Uses a mock model that simulates DeepSeek's behavior
Uses a deferred capability
Verifies that the reasoning_content is passed back correctly
Let me trace through the actual code path one more time, looking for any place where the ThinkingPart could be lost.
Actually, I think I found a potential issue! Let me look at model.prepare_messages again:
python
def prepare_messages(self, messages: list[ModelMessage]) -> list[ModelMessage]:
if ToolSearchTool not in self.profile.supported_native_tools:
from .._tool_search import synthesize_local_tool_search_messages
messages = synthesize_local_tool_search_messages(messages)
For DeepSeek, ToolSearchTool is NOT in supported_native_tools. So synthesize_local_tool_search_messages is called.
This function processes each ModelResponse and checks for NativeToolSearchCallPart or NativeToolSearchReturnPart. If found, it splits the message.
But here's the thing: the synthetic message from ToolSearchCapability.before_model_request uses ToolSearchCallPart, NOT NativeToolSearchCallPart. So the synthetic message would not be processed by this function.
However, what if there's a NativeToolSearchCallPart somewhere else in the message history? In that case, the function would split the message and create new ModelResponse objects.
But wait, for a simple deferred capability scenario, there shouldn't be any NativeToolSearchCallPart in the message history.
Hmm, let me think about this differently. Let me check if there's a scenario where ToolSearchCallPart could be treated as NativeToolSearchCallPart:
python
if isinstance(part, NativeToolSearchCallPart):
buffer.append(synthesize_local_from_native_call(part))
changed = True
This checks specifically for NativeToolSearchCallPart, not ToolSearchCallPart. So ToolSearchCallPart would fall through to the else branch and be added to buffer unchanged.
OK, so synthesize_local_tool_search_messages shouldn't cause issues.
Wait, I just realized something else. Let me look at the _split_response function:
When splitting, it creates a new ModelResponse with only the specified parts. If the original ModelResponse had a ThinkingPart, but it's not included in the parts list, the new ModelResponse would NOT have the ThinkingPart!
But this only happens when changed=True (i.e., when the message contains NativeToolSearchCallPart or NativeToolSearchReturnPart). For a simple deferred capability scenario, there shouldn't be any such parts.
Wait, but what if the ToolSearchCallPart (from the synthetic message) is somehow being treated as NativeToolSearchCallPart?
Let me check:
<tool_call>
<function=bash_terminal>
<parameter=command>
sed -n '241,280p' /pydantic-ai/pydantic_ai_slim/pydantic_ai/_tool_search.py
</tool_call>