ISSUE DESCRIPTION Deferred capabilities throw error 400 with Deepseek models Initial…
- User
ISSUE DESCRIPTION
Deferred capabilities throw error 400 with Deepseek models
Initial Checks
- I'm using the latest version of Pydantic AI
- I've searched for my issue in the issue tracker before opening this issue
Description
When running an agent using a DeepSeek reasoning model, using
Capability(..., defer_loading=True)causes aModelHTTPError: status_code: 400during execution loop turns.openai.BadRequestError: Error code: 400 - {'error': {'message': 'The `reasoning_content` in the thinking mode must be passed back to the API.', 'type': 'invalid_request_error', 'param': None, 'code': 'invalid_request_error'}}This is triggered because DeepSeek requires the original
reasoning_contentproduced during the thinking phase to be passed back exactly as-is in the subsequent conversation message history array. Whendefer_loading=True, the graph loop intercepted by PydanticAI's capability runner seems to drop or fail to serialize/propagate thereasoning_contenttoken block back to DeepSeek's chat completions endpoint.Setting
defer_loading=Falsesolves the issue, and the agent executes successfully.Minimal, Reproducible Example
# Remember to export the DEEPSEEK_API_KEY environment variable first, then run this code import random from pydantic_ai import Agent, RunContext from pydantic_ai.capabilities import Capability def roll_dice() -> str: """Roll a six-sided die and return the result.""" return str(random.randint(1, 6)) def get_player_name(ctx: RunContext[str]) -> str: """Get the player's name.""" return ctx.deps agent = Agent( 'deepseek:deepseek-v4-flash', deps_type=str, instructions=( "You're a dice game, you should roll the die and see if the number " "you get back matches the user's guess. If so, tell them they're a winner. " "Use the player's name in the response." ), capabilities=[Capability(id='DICE_ROLL', tools=[get_player_name, roll_dice], defer_loading=True)] # Change this to False and the agent will run successfully. ) dice_result = agent.run_sync('My guess is 4', deps='Anne') print(dice_result.output)Logfire Trace
No response
Python, Pydantic AI & LLM client version
Assistant
Let me start by exploring the repository structure to understand the codebase
Assistant
Now let me understand the issue better. The error is about
reasoning_contentnot being passed back. Let me look at the capability/deferred loading code.Assistant
Now let me search for where the model messages are formatted with
reasoning_content:Assistant
Now let me look at the openai.py to understand how
reasoning_contentis processed when sending it back:Assistant
Now let me understand the deferred loading flow. Let's look at the deferred capability loader toolset:
Assistant
Now let me trace through what happens during the deferred loading flow. The issue seems to be related to the message history not preserving the reasoning content. Let me search for places where messages are processed:
Assistant
Now let me look at the related test files to find what the existing tests cover:
Assistant
Now let me check what test cassettes we have for tool search related tests:
Assistant
Now let me look at the agent graph code and trace what happens with the messages when a deferred capability is loaded:
Assistant
Let me now understand the flow more deeply. The deferred loader provides a system prompt listing available capabilities. When the model calls
load_capability, the loader returns instructions. Now let me look at how the messages are tracked:Assistant
Now let me look at how the
process_historycapability works - this seems important for handling message history for the deferred capability flow:Assistant
Now let me find tests for deferred capability:
Assistant
Let me look at the rest of this test:
Assistant
Now I understand the basic flow. Let me look at the tool search capability:
Assistant
Now let me find the actual place where the issue might be. The issue says the deferred capability might lose or fail to propagate the
reasoning_contentfield. Let me look for where messages are constructed:Assistant
Let me see the OpenAI Chat model's
_map_messageand how messages are formatted:Assistant
Let me look at the
_map_model_response:Assistant
Now let me look more carefully at the deferred loading process and how messages are constructed during execution. Let me look at the
_parts_manager.py:Assistant
Now let me look at the deferred loading flow more carefully. First, let me understand the issue. The error says "The
reasoning_contentin the thinking mode must be passed back to the API."Let me search for places where the messages may be modified or stripped of thinking content:
Assistant
Now let me trace what happens to the tool search and where the deferred capability loader creates new messages. Let me look at the deferred loading flow again:
Assistant
Let me look at the tool_search toolset:
Assistant
Now let me look at the
_tool_search.pywhere the messages are being manipulated:Assistant
Now let me search the existing logic that converts
ThinkingPartto see what fields are used:Assistant
Now let's look at where messages get filtered before sending. The
prepare_requestmethod:Assistant
Now let me search for where the actual issue might be - maybe related to how deferred capabilities affect the flow:
Assistant
Now let me reproduce the issue first to confirm what we're dealing with:
Assistant
Let me write a small reproducer to see what happens with the test:
Assistant
Let me look for the relevant cassette files:
Assistant
Now let me look more carefully at the deepseek provider and the flow. Let me trace the message format. Looking at the issue, it says "The reasoning_content in the thinking mode must be passed back to the API."
This is because DeepSeek requires reasoning_content to be passed back in the message history. Let me look at the openai.py's
_into_message_param:Assistant
Let me look at the
thinkingsfield. Where is the thinking field set:Assistant
Now let me create a reproducer to verify the issue. First, let me create a test using the function model:
Assistant
Now let me write a reproducer. First, I'll look for tests with FunctionModel and deferred loading:
Assistant
Let me write a reproducer script:
Assistant
Now let me see what happens with a real DeepSeek provider via the OpenAI Chat Model. Let me simulate this more precisely. First let me write a script that uses the actual OpenAIChatModel with the DeepSeek provider and see the actual request that goes out:
Assistant
Now let me try the actual scenario by using a mocked DeepSeek API. Let me look at how to do this:
Assistant
Let me now create a more focused test that exposes the actual issue:
Assistant
Now let me build a more proper reproducer that mocks the OpenAI client and shows the actual request:
Assistant
I can see that the agent is in an infinite loop. Let me look at what's happening. The issue is that the model is calling
roll_diceover and over because it's never returning a final answer. But the actual issue is on the assistant message at index [4] - notice that thesearch_toolscall assistant message does NOT havereasoning_content. Let me think about why.Looking at the output, when
search_toolsis called by the model (in the response withtool_calls), the assistant message hascontent: Nonebut noreasoning_content.But notice that there is a deeper issue: the
search_toolsis being added by Pydantic AI as part of the deferred capability flow (it's a tool search call). However, this is being added to the message history as if the model called it, but the model didn't! This is the tool search capability adding synthetic messages.Let me look at this more carefully:
Assistant
Now I understand. The
ToolSearchcapability synthesizes a fakeModelResponse(withToolSearchCallPart) andModelRequest(withToolSearchReturnPart) to record that the tools were discovered. These are appended to the message history.The problem is that when these messages are sent to the model via DeepSeek, the synthetic
ModelResponseshould have a corresponding reasoning_content field if DeepSeek requires reasoning_content in every assistant message.Wait, let me re-read the error message:
'The
reasoning_contentin the thinking mode must be passed back to the API.'This message indicates that the API expects that every assistant message has a
reasoning_contentfield. Let me check if maybe the issue is that the original message has areasoning_contentbut the synthesized message doesn't.Let me first run the same test with
defer_loading=False:Assistant
OK without defer_loading, the messages look correct. Each
assistantmessage has areasoning_contentfield.With defer_loading, the synthesized
ModelResponsefromToolSearchdoesn't have areasoning_content(because it was not created by the model). This is what causes the 400 error from DeepSeek.Now let me check the tool_search return part too - it's also missing reasoning_content.
Now the question is: how should we handle this? The DeepSeek API requires reasoning_content in assistant messages. We need to either:
- Skip the synthesized ToolSearch messages when sending to DeepSeek (only include them locally)
- Add reasoning_content to the synthetic messages (but that would be fake)
Let me first check the actual DeepSeek API documentation/specification by searching the test cassettes:
Assistant
So DeepSeek requires the
reasoning_contentfield on assistant messages that had it. The issue is that the synthesizedToolSearchcalls don't have this field. Let me dig deeper into how this gets serialized:Assistant
Let me look at how
prepare_messagesworks in the openai model:Assistant
Let me look at the synthesize function:
Assistant
Now let me look at how messages flow when the search_tool call is in history. Let me trace what happens:
ToolSearchcapability adds a syntheticModelResponsecontainingToolSearchCallPartand aModelRequestcontainingToolSearchReturnPart.- When this is sent to the model, the
_map_messagesconverts it. - The
ModelResponsebecomes a chat completion assistant message param. - The
ToolSearchCallPartis treated like aToolCallPart.
Let me check how
ToolSearchCallPartis handled when mapped:Assistant
So the
_map_response_tool_call_partmethod handlesToolCallPart(and by inheritance,ToolSearchCallPart). Whenmap_assistant_messageruns, it iterates through parts and handles each part type. So for the synthesized tool search assistant message, the part is aToolSearchCallPart(a subclass ofToolCallPart), and gets handled correctly.Now the issue is: in the actual request to DeepSeek, the assistant message for the synthesized tool search call doesn't have
reasoning_content. Let me check thematch_assistant_messageflow more carefully:Assistant
Now I see. The flow is:
_map_messagesprocesses each message.- For a
ModelResponsewith parts[ToolSearchCallPart(...)], the parts are mapped:ToolSearchCallPartis matched byisinstance(item, ToolCallPart)(since it's a subclass)- It calls
_map_response_tool_call_partwhich appends totool_calls
_into_message_paramreturns{'role': 'assistant', 'tool_calls': [...], 'content': None}(noreasoning_content!)
The fix should probably be in the place where the message is sent. We need to add an empty
reasoning_contentfield if the model requires it. But wait, this is the synthetic message. Let me look at what the issue description says:The
reasoning_contentin the thinking mode must be passed back to the API.The error is from DeepSeek. They want reasoning_content to be passed back. Now, in this case, the assistant message is the synthesized tool search call - it's not a real assistant message, it's a fake one created by Pydantic AI to track which tools are discovered.
Assistant
Now let me look at how
_clean_message_historyhandles this:Wait, I should also check the messages more carefully. Let me look at how
provider_response_idetc is treated when no provider is set:Assistant
Now I see. The synthetic tool search response has no
provider_name,model_name, etc. So it's "framework synthesized" rather than from a real provider. The_clean_message_historymerges consecutive ones, but it doesn't matter for sending back.Let me think about the fix. The key issue is: when the synthesized assistant message is sent to DeepSeek, it doesn't have
reasoning_content. There are a few options:-
Option A: Add an empty
reasoning_contentfield to the synthetic assistant message. But this is technically incorrect - the model never had a reasoning_content. -
Option B: Don't send the synthetic assistant message to the provider. Only keep it locally for state tracking.
-
Option C: Make the model provider know that the synthetic assistant message doesn't need a
reasoning_content.
Looking at DeepSeek's API: they want
reasoning_contentto be passed back exactly as-is. So sending an empty field may not work either. Looking at the DeepSeek docs more carefully:-
Assistant
Let me check the existing tests to see what is expected. Let me look at the existing deepseek tests:
Assistant
Let me run those existing deepseek tests to see if they pass:
Assistant
Assistant
Now let me understand the situation better. The fundamental issue is:
- The
ToolSearchcapability synthesizes an assistant message with aToolSearchCallPart(tosearch_tools). - When this is sent to DeepSeek via OpenAI Chat Completions, it becomes a regular assistant message with a tool call.
- DeepSeek expects a
reasoning_contentfield on every assistant message in "thinking mode".
Looking at this more carefully, I think the actual fix should be:
When the assistant message is synthetic (i.e., it was created by the framework, not by the model), we should NOT include it as an assistant message to the provider. The DeepSeek API doesn't need to know about our internal tool discovery tracking.
- The
Assistant
So moonshotai has the same problem. Now let me look more carefully at the actual code flow. The issue is in the
ToolSearchcapability. Let me look at how it constructs the synthetic message:Assistant
Now let me look at the actual error message format. The user said:
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'}}Let me search if there's a github issue or test that explains this. Let me also check the existing tests around
thinking_partsandreasoning_content:Assistant
Let me look at the actual issue more carefully. The user said:
When running an agent using a DeepSeek reasoning model, using
Capability(..., defer_loading=True)causes aModelHTTPError: status_code: 400during execution loop turns.Let me see if there are any patterns that indicate what fix is expected. Looking at the issue title and description again:
This is triggered because DeepSeek requires the original
reasoning_contentproduced during the thinking phase to be passed back exactly as-is in the subsequent conversation message history array.OK so DeepSeek is strict about passing back the exact reasoning_content. If a message doesn't have reasoning_content (which is the case for the synthetic ToolSearch message), the API rejects it.
Let me look at the issue tracker for similar issues or PRs:
Assistant
Now let me look at the existing tests around deferred capabilities with deepseek:
Assistant
Now let me look at the actual flow to figure out where to add the fix. The synthetic message is created by
ToolSearch.before_model_request. Let me trace this more:Assistant
Now I can clearly see the issue. In request 2:
[2] role=assistanthasreasoning_content(from real model)[4] role=assistantdoes NOT have (synthetic from tool search)
Assistant
Assistant
Assistant
Let me look at the recent commits to understand the latest state:
Assistant
Let me look at the full PR description and tests:
Assistant
Let me check the test_openai.py file for the deferred capability test cases:
Assistant
Now let me think about this problem from a different angle. The ToolSearch capability has an
_enabledcheck based on whether the model supports native tool search. Let me check:Assistant
Let me look at how the deepseek profile handles supported_native_tools. Looking at the deepseek.py profile:
Assistant
So DeepSeek doesn't override
supported_native_tools. By default, all native tools are supported. Let me check what happens withToolSearchTool:Assistant
Now let me think about the fix more carefully. Looking at this in the broader context:
The ToolSearch capability works in two modes:
- Native mode (provider supports tool search): uses native tool search (Anthropic, OpenAI Responses).
- Local mode: uses
search_toolsfunction tool.
When in local mode, the capability creates a
ToolSearchCallPartandToolSearchReturnPartfor tracking. These get serialized as regular messages.Now for the Chat Completions API with DeepSeek:
- DeepSeek doesn't support native tool search.
- The ToolSearch capability uses local mode.
- The synthesized messages become regular assistant/tool messages.
- DeepSeek requires
reasoning_contenton every assistant message.
The issue is the synthetic assistant message doesn't have a thinking part. So DeepSeek rejects it.
Now the fix: The ToolSearch capability should add a synthetic ThinkingPart to its synthesized ModelResponse. This would make the message include when sent to DeepSeek (assuming empty reasoning_content is acceptable).
Assistant
Now let me think about the right fix. The cleanest solution is to make the synthetic ToolSearch message have an empty ThinkingPart so that when it's mapped,
reasoning_contentis added (even if empty).Wait, let me check what happens with the openai chat completions API when reasoning_content is empty:
Assistant
Now I understand. Looking at the streaming data, the first chunk has
reasoning_content: ""andcontent: null. So when starting a thinking response, the model sendsreasoning_content="". This means empty reasoning_content is valid.Let me look at the test for streaming:
The first chunk in the stream has
reasoning_content: ""andcontent: null. This shows that DeepSeek accepts an assistant message with an empty reasoning_content.So my plan is:
Fix: In the
ToolSearchcapability, add an emptyThinkingPartto the syntheticModelResponseso that when the message is sent to DeepSeek, it includesreasoning_content=''.Assistant
The fix works. Adding an empty
ThinkingPart(content='', id='reasoning_content', provider_name='deepseek')results in the message havingreasoning_content: ''when sent to DeepSeek.But wait, this assumes the provider name is always going to match. Let me think about edge cases:
- The user might use a custom provider name.
- The provider name might not match the thinking field.
Actually, the better approach is to NOT hardcode the provider name. Instead, we should use the profile's
openai_chat_thinking_fieldand the model's system name.Looking at the flow:
- The model knows its system name ().
Assistant
So OpenRouter uses
reasoningfield.Now I need a more general solution. The synthetic ToolSearch message should add an empty
ThinkingPartthat uses whatever field name is configured for the model's profile.Let me check if the model class knows its profile's thinking field:
Assistant
OK so the capability doesn't know about the model's profile. The fix has to be in the model code (or capability with model info).
Actually, let me look at this from another angle. The issue is that the
_map_messagesdoesn't handle the synthetic messages specially. Let me look at where the messages are mapped:Assistant
Now let me think about this. There are two main approaches:
Approach 1: Modify the ToolSearch capability to add an empty ThinkingPart. This would only work if we know the model's profile.
Approach 2: Modify the
_map_messages(or_map_model_response) to handle synthetic messages specially. We could detect them byprovider_name is None and model_name is None.Approach 3: When the synthetic message lacks a ThinkingPart, automatically add an empty one when the model profile requires
reasoning_content.Let me look at how to identify a synthetic message. Looking at the
_clean_message_history:elif isinstance(message, _messages.ModelResponse): 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])Assistant
Now let me think about the cleanest approach. I think the best is to fix the ToolSearch capability to add the empty ThinkingPart. Let me look at how to do this properly.
Actually wait, let me check if there's a way the OpenAI Responses API handles this case (since it works with synthetic messages there). Looking at the OpenAI Responses model:
Assistant
Right, OpenAI Responses uses a special
tool_search_calltype for these messages. For Chat Completions, we don't have that option.Now let me look at the actual fix. Let me look at the code flow and figure out the cleanest approach:
Assistant
Let me look at the parts we add:
ModelResponse( parts=[ ToolSearchCallPart( args={'queries': capability_ids}, tool_call_id=call_id, ), ] ), ModelRequest( parts=[ ToolSearchReturnPart( content={ 'discovered_tools': [ {'name': td.name, 'description': td.description} for td in newly_loaded ] }, tool_call_id=call_id, ), ] ),Now I need to add a
ThinkingPartto theModelResponse. But the issue is that the capability doesn't know what provider name or thinking field to use.Let me think about this. Maybe the fix should be in the model adapter. When a synthetic ModelResponse is sent to a model that requires thinking fields, we should automatically add an empty ThinkingPart.
Let me look at how to detect if a message is synthetic:
Assistant
Assistant
So we have access to the model in
before_model_request. Let me modify the ToolSearch capability:Assistant
Now let me think about this more carefully. There's also the case where a model uses native tool search (Anthropic, OpenAI Responses). In that case, the synthetic message should NOT be added because the provider handles it natively. Let me check:
Actually wait, looking at the flow:
ToolSearch.before_model_requestadds the synthetic messages.Model.prepare_messagesis called which callssynthesize_local_tool_search_messages.
If the provider supports native tool search,
synthesize_local_tool_search_messagesis NOT called (becauseToolSearchTool in self.profile.supported_native_tools).So if a provider supports native tool search, the synthetic messages are sent as-is. But the adapter knows how to handle them (Anthropic uses tool_reference blocks, OpenAI Responses uses tool_search_call type).
For DeepSeek (Chat Completions), the synthetic messages are sent as regular messages, which causes the issue.
OK let me approach this differently. Let me think about the fix at the model adapter level. When the OpenAI Chat model maps the synthetic messages, it should add an empty reasoning_content field if the model requires it.
Assistant
Assistant
OK so my plan is:
- In
map_assistant_message, detect if the message is synthetic (provider_name is None and model_name is None). - If yes, check the profile to see if thinking content is required in field mode.
- If yes, inject an empty ThinkingPart to ensure the field is included.
Let me also check what happens with the ToolSearchCallPart being a subclass of ToolCallPart:
Looking at the iteration:
isinstance(item, ToolCallPart)would match bothToolCallPartandToolSearchCallPart. Good.Now let me implement the fix. Let me first verify that the OpenAI Chat model is the right place. Yes, because DeepSeek uses
OpenAIChatModel.Let me also check what happens with MoonshotAI (which has the same issue):
- In
Assistant
Now let me check the actual tests to make sure I don't break anything:
Assistant
Let me also look at how
test_openai_auto_mode_reasoning_field_different_provider_uses_tagstests:Assistant
OK so the auto mode test confirms my understanding. Let me also check the existing test for thinking_part round trip:
Assistant
Now let me understand the structure better. Let me look at the full flow when
_map_model_responseis called for a synthetic message. The current code:def map_assistant_message(self, message: ModelResponse) -> chat.ChatCompletionAssistantMessageParam | None: for item in message.parts: if isinstance(item, TextPart): ... elif isinstance(item, ThinkingPart): ... elif isinstance(item, ToolCallPart): self._map_response_tool_call_part(item) ...For the synthetic message with just
ToolSearchCallPart, the loop only processes the tool call. We need to inject aThinkingPartbefore the tool call gets processed.Let me write the fix:
Assistant
Now let me think about my approach more. There are several approaches:
-
Approach A: Modify
_MapModelResponseContext.map_assistant_messageto inject an emptyThinkingPartwhen the message is synthetic. -
Approach B: Modify the ToolSearch capability to add the empty
ThinkingPartto the synthetic message.
Approach A is more general because it handles any synthetic assistant message, not just the ToolSearch case. But it might be overreach.
Let me check what other places might create synthetic ModelResponse messages. Let me look at the synthesizer:
-
Assistant
Good - the ToolSearch capability is the only one that creates a synthetic
ModelResponse. So Approach B would work for this specific case.Let me look at the ToolSearch capability code again:
Assistant
OK so the issue is clear. Now let me think about which approach to take.
I think Approach A (modifying the model adapter) is better because:
- It's more general - it handles any synthetic message that lacks thinking content.
- It centralizes the fix in the OpenAI Chat model.
- It's a defensive fix - we don't have to worry about every place that might create a synthetic message.
However, Approach A requires:
- Detecting synthetic messages (provider_name is None and model_name is None).
- Knowing the field name and provider name.
Let me think about whether the fix should be:
- Always inject an empty ThinkingPart (for synthetic messages on providers that use 'field' mode).
- Conditionally inject (only when needed).
I think conditionally is better. Let me implement this.
Actually, let me reconsider. The simpler fix might be Approach B - just modify the ToolSearch capability to add an empty ThinkingPart. The challenge is that the capability doesn't have access to the model's profile.
But wait, the capability does have access to the model via
request_context.model. And the model hasmodel.profileandmodel.system.Let me check:
Assistant
Now let me think about Approach B in more detail. The capability needs to:
- Check if the model is an OpenAI Chat model.
- Check if the model's profile requires thinking content in field mode.
- If yes, add an empty ThinkingPart.
This is too tightly coupled. The capability shouldn't know about specific model implementations.
Let me go with Approach A. Modify the OpenAI Chat model's
_map_model_responseto detect synthetic messages and inject empty ThinkingParts when needed.Actually, I realize there's an even simpler approach. Let me just modify the ToolSearch capability to add an empty
ThinkingPart. The ThinkingPart can have generic fields that work across providers.Wait, no. The
_map_response_thinking_partrequiresitem.idto match the profile'sopenai_chat_thinking_fieldAND to match the model's system. So a generic ThinkingPart won't work for all cases.Assistant
Assistant
OK so
model.profileis a cached property. Let me also see how to access provider_name:Assistant
OK so
model.systemreturns the provider name. Good. Now let me think about my approach.Let me go with Approach A. The fix is in the OpenAI Chat model's
_map_model_response. When the ModelResponse is synthetic (provider_name and model_name are None) and the profile requires thinking content in field mode, inject an empty ThinkingPart.Actually, I realize there's a simpler way. Let me look at how
map_assistant_messageworks:def map_assistant_message(self, message: ModelResponse) -> chat.ChatCompletionAssistantMessageParam | None: for item in message.parts: ... return self._into_message_param()Assistant
Let me check the related tests:
Assistant
Now let me think about Approach A more carefully. Actually, looking at this, I think there's an even simpler fix.
What if instead of fixing the model adapter or capability, we just check if the message has
provider_name=None and model_name=Noneand skip the synthetic assistant message entirely?Wait but that would break the tool call -> tool return pairing.
Let me look at this from another angle. What if we keep the synthetic message but ensure that when it's sent to the model, the
reasoning_contentfield is always included?Actually, I think the cleanest fix is to modify the ToolSearch capability. Let me look at the model access from the capability:
Assistant
OK so
request_context.modelis accessible. Let me check how to access the profile and system name from the model:Assistant
Now let me think about which approach is best. I'll go with Approach A - modifying the OpenAI Chat model's
_map_model_response. This is the cleanest because:- It's centralized in one place.
- It works for any synthetic message, not just the ToolSearch case.
- It uses the model's own profile/system name.
Let me now write the fix:
Assistant
Hmm wait, I realize there may be a complication. The OpenAI Chat model uses
_map_model_responsefor both:- Mapping synthetic messages from the message history.
- Mapping real model responses (used in tests like
test_openai_custom_reasoning_field_*).
So if I modify
_map_model_response, it would affect both cases.For case 2, if we have a real model response with no ThinkingPart (e.g., a model that doesn't support thinking but profile says 'field' mode), we shouldn't add an empty ThinkingPart. So my fix needs to be conditional on synthetic messages.
Let me think about this more carefully. The fix should:
- Detect if the message is synthetic (no provider_name, no model_name).
- If yes, check the profile and inject empty ThinkingPart if needed.
Let me write the fix:
Assistant
Now let me think about this more. I realize that the simpler approach might be to NOT change the model adapter at all, but instead change how the synthetic messages are constructed.
Actually wait, let me re-read the issue more carefully. The user mentions that the issue happens "during execution loop turns". The reproduction is in Python code with a real DeepSeek API call (which requires DEEPSEEK_API_KEY).
Let me re-look at the actual message structure. The problem is:
[4] role=assistant content: None tool_calls: [...]Assistant
Let me now think about this fix from another angle. Let me also check what's in the messages module for the ModelResponse, maybe there's already a mechanism to mark synthetic messages:
Actually, looking at this, I think the simplest approach is to just check if the message is "framework-emitted" and handle it in the OpenAI Chat model. Let me look at the existing tests to see if there's any framework-emitted marker:
Assistant
OK so the existing convention for "synthetic" messages is
provider_name is None and model_name is None and provider_response_id is None. This is what the_clean_message_historyuses to decide if messages can be merged.Now let me think about the fix. I think the best approach is to:
Modify the OpenAI Chat model's
_map_model_response(specificallymap_assistant_message) to detect synthetic messages and inject an empty ThinkingPart when the profile requires thinking content in field mode.Let me now implement this. Let me write the actual code change:
Assistant
Assistant
Now let me think about an alternative approach: what if we modify the ToolSearch capability to add the ThinkingPart? The advantage is that we don't need to detect synthetic messages (because only this one place creates them). The disadvantage is that we need to know the model's profile at runtime.
Let me look at how the capability gets the model:
Assistant
The capability has access to
request_context.model. Let me check the model.profile:Assistant
Let me look at the model interface:
Assistant
OK so
model.profileexists. And the profile hasopenai_chat_thinking_fieldandopenai_chat_send_back_thinking_parts. But this is an OpenAI-specific profile.Hmm, the capability doesn't know if the model is OpenAI-based. Let me think.
OK let me just go with Approach A. Modify the
_map_model_responseto inject empty ThinkingPart for synthetic messages.Wait, let me first think about whether this is really the right fix. Let me look at the message flow once more:
- Real assistant message with thinking + tool call.
- Tool return.
- Synthetic assistant message with tool call (from ToolSearch).
- Tool return (from ToolSearch).
Assistant
OK so the synthetic messages are created to track the discovery state across turns. The model adapter (especially for OpenAI Responses) replays these as native tool search calls.
For Chat Completions, this replay isn't possible. So the synthetic messages are sent as-is.
OK let me proceed with Approach A. Let me write the fix:
Assistant
Let me now implement the fix. I'll modify
map_assistant_messageto inject an emptyThinkingPartfor synthetic messages when needed:Assistant
Good, ThinkingPart is already imported. Now let me make the change:
Assistant
I see there's a duplicate
def map_assistant_messageline. Let me fix that:Assistant
Let me fix the duplicate line:
Assistant
Now I removed the wrong thing. Let me restore the function definition:
Assistant
Let me also fix the indentation of the function definition - it needs 8 spaces not 8 (it's inside a class):
Assistant
The indentation looks fine. The class is inside
OpenAIChatModelclass which is inside an outer class, so it's at this level. Let me verify by checking the surrounding context:Assistant
Looking at it, the
_model,texts, etc. fields are at 8 spaces. The functionmap_assistant_messageshould be at 8 spaces too. But in my edit, I have it at 8 spaces. Let me verify by counting spaces:Assistant
Both are at 8 spaces. Good. Now let me run my reproducer:
Assistant
Now
[4] role=assistanthasreasoning_content(empty string). The fix works.Let me also verify by checking what the actual reasoning_content value is:
Assistant
The fix works as expected:
- DeepSeek profile (field mode + reasoning_content): Adds
reasoning_content: '' - Auto mode + reasoning_content: Adds
reasoning_content: '' - Tags mode: No reasoning_content added (no field name needed)
- False mode: No reasoning_content added
The "field mode without thinking_field" case is an error (can't be configured), so we don't need to worry about it.
Now let me also verify that real responses are NOT modified:
- DeepSeek profile (field mode + reasoning_content): Adds
Assistant
Real responses are NOT modified. Only synthetic messages get the empty reasoning_content injected.
Now let me run the existing tests to make sure I didn't break anything:
Assistant
All OpenAI tests pass. Now let me also run the capability tests:
Assistant
All 720 capability tests pass. Let me run more tests:
Assistant
All 154 tool search tests pass. Let me also run more model tests:
Assistant
One test failed. Let me investigate:
Assistant
This is an outlines test failure unrelated to our changes. Let me verify by checking the test:
Assistant
This test is unrelated to my change. Let me verify by checking what happened:
Assistant
This is an unrelated test failure caused by a deprecation warning in
huggingface_hub. Let me verify by skipping this test:Assistant
All 2047 tests pass. Now let me also check that the test_outlines.py failure is pre-existing (not caused by my change):
Assistant
Yes, the test_outlines.py failure is pre-existing. Let me restore my changes:
Assistant
Now let me also run the broader tests:
Assistant
All 1087 relevant tests pass. Now let me also think about edge cases:
- What if
message.provider_nameis set to something different from the model's system? E.g., user resumes an agent run with messages from a different provider.
Let me check:
- What if
Assistant
The edge cases work correctly:
- Case 1: Synthetic message gets
reasoning_content: ''added ✓ - Case 2: Real response without thinking - NOT modified ✓
- Case 1: Synthetic message gets
Assistant
All edge cases handled correctly. The fix:
- Injects
reasoning_content: ''for synthetic messages (all three: provider_name, model_name, provider_response_id are None). - Does NOT inject for real responses or partial responses.
Let me also look at the case where the message has thinking part but is synthetic (Case 4 from before):
- Injects
Assistant
Excellent! The fix is working correctly. Now let me also think about whether the fix handles the OpenAI Responses case. Since I'm only modifying the OpenAI Chat model (
map_assistant_messagein_MapModelResponseContextwhich is a nested class inOpenAIChatModel), the OpenAI Responses model is unaffected. Good.Let me also check that I'm not breaking any existing tests by running the full openai test suite again:
Assistant
All 200 openai tests pass. Now let me also look at the moonshotai tests:
Assistant
All moonshotai tests pass.
Now let me also run my reproducer with the actual issue scenario:
Assistant
The synthetic message at [4] now has
reasoning_contentfield. The fix is working.Let me also verify the fix handles the case where the user runs the same scenario with a FunctionModel instead of OpenAI Chat model:
Assistant
The FunctionModel reproducer also works correctly.
Let me also think about the additional use case - what about when the messages have a
provider_response_idset? Let me see:Assistant
OK so the synthetic detection uses 3 fields: provider_name, model_name, provider_response_id. Let me verify my fix matches:
Assistant
Good. The fix correctly uses the same detection logic.
Now let me also think about whether I should add the check that the message has a tool call. Currently, the fix injects thinking content for ANY synthetic message that has no thinking part. But the issue specifically happens with tool call messages. Let me think about whether text-only synthetic messages would also have this issue.
Actually, looking at the ToolSearch code, the synthetic message only has a tool call (
ToolSearchCallPart). There's no other place that creates synthetic messages. So I could make the check more specific (only inject for messages with tool calls), but the current check is more defensive.Let me think about edge cases:
- Synthetic message with only text: Not really possible with the current code. But if it were, the empty reasoning_content wouldn't hurt.
- Synthetic message with only tool calls: This is the issue case. We inject empty reasoning_content. ✓
- Synthetic message with both text and tool calls: Would inject empty reasoning_content even though it has text. The text might be enough for DeepSeek, but injecting reasoning_content wouldn't hurt.
I think the current fix is correct. Let me now also think about whether to also fix the OpenAI Responses model. Looking at the OpenAI Responses model:
Assistant
The OpenAI Responses model uses
tool_search_calltype natively, so it doesn't have the issue. My fix is only for the OpenAI Chat model.Now let me look at the actual fix once more:
Assistant
Let me also restore the blank line for cleanliness:
Assistant
Hmm, the edit lost the first line of the comment. Let me fix this:
Assistant
Now the comment is incomplete. The first line was lost. Let me restore the full comment:
Assistant
Now let me verify the file compiles:
Assistant
Let me also re-run the reproducer to make sure the fix still works:
Assistant
The synthetic message at [4] now has
reasoning_content.Let me also test the case when defer_loading=False (no synthetic messages, so the fix should not change anything):
Assistant
Without defer_loading, no synthetic messages, so the fix doesn't affect anything.
Now let me also check the original v4-flash scenario mentioned in the issue:
Assistant
The fix also works for
deepseek-v4-flash. The issue mentions this model specifically.Now let me also think about additional edge cases:
- What if the synthetic message is created by a different mechanism in the future?
- What if the user uses a custom profile that doesn't fit the standard?
For case 1, my fix handles any synthetic message with no thinking part. So it's general.
For case 2, my fix only triggers when
thinking_fieldis set andsend_back_thinking_partsis 'field' or 'auto'. So it only affects providers that use these settings.Let me also check what happens for moonshotai (which uses 'reasoning_content' field):
Assistant
MoonshotAI also gets
reasoning_content: ''injected.Now let me also think about the openrouter case (which uses 'reasoning' field):
Assistant
OpenRouter also gets the correct field name.
Now let me also verify that the fix doesn't accidentally break the OpenAI Responses model. Let me check that the fix is only in the OpenAI Chat model's
_MapModelResponseContext, not the OpenAI Responses model:Assistant
The fix is in
_MapModelResponseContextwhich is insideOpenAIChatModel. TheOpenAIResponsesModelhas its own logic and is unaffected.Let me also run the full OpenAI test suite once more to make sure:
Assistant
All 200 tests pass.
Now let me also look at the moonshotai tests to make sure:
Assistant
All relevant provider tests pass.
Now let me also think about whether I should also consider edge cases with streaming. The streaming case is handled differently (it goes through
_process_thinkingand parts manager). Let me check:Assistant
The streaming case is different - it processes incoming chunks, not outgoing messages. The fix is only for outgoing messages. Good.
Now let me also think about whether the fix could affect test cases. Let me look at the snapshot tests for test_capabilities.py to see if any tests use synthetic messages:
Assistant
These tests use
FunctionModelwhich doesn't go through the OpenAI Chat model's_map_model_response. So they're unaffected.Let me also check the openai tests for any test that might be affected:
Assistant
No tests in test_openai.py use synthetic messages. So the fix doesn't affect any existing tests.
Let me also look at the test_tool_search.py for any tests that might use the OpenAI Chat model:
Assistant
No tests in test_tool_search.py use OpenAI Chat model either.
Let me also check if there's a test for the specific scenario in the issue (deferred capability + deepseek):
Assistant
No specific test. Let me also think about whether to add a test. Looking at the task description:
UNDER NO CIRCUMSTANCES should you modify existing tests or add new tests to the repository.
So I should NOT add tests. Let me just make sure my fix is complete.
Let me also look at one more edge case - what happens when the synthetic message is a "real" ToolCallPart (not ToolSearchCallPart)?
Assistant
Interesting case: an empty synthetic message also gets
reasoning_content: ''injected. This might not be desired because an empty message wouldn't normally need a reasoning_content field. But since the framework's existing logic would skip it (the message is empty), this is just a minor issue.Wait, let me check the existing behavior for empty ModelResponse:
Assistant
The check is
if not self.texts and not self.thinkings and not self.tool_calls. Ifthinkingsis populated (even with empty content), the message is not None. This might cause an issue with empty messages.Hmm, let me think. An empty
ModelResponseshouldn't normally occur because the framework doesn't create them. But if it did, my fix would now make it pass through instead of returning None. Let me think about whether this is a problem.Actually, looking at the output:
Empty synthetic: {'role': 'assistant', 'reasoning_content': '', 'content': None}This returns a message with
content: None(no tool_calls). This is what the framework wants to avoid (it would be rejected by the API). So this might be a regression.Assistant
Let me think about this. The condition is:
thinking_field is setsend_back_thinking_parts in ('field', 'auto')message.provider_name is Nonemessage.model_name is Nonemessage.provider_response_id is Nonenot any ThinkingPart in message.parts
I should add:
message.partsis not empty (since otherwise the synthetic check is meaningless).But wait, an empty synthetic message is still "synthetic" in the framework sense. Let me think.
Actually, the safer condition is: only inject if there's a
ToolCallPartin the message. This makes more sense because:- The issue happens when there's a tool call without thinking.
- If there are no tool calls, the message probably has text content.
Let me update:
Assistant
There's a duplicate
)at line 1336. Let me fix it:Assistant
Now there's a duplicate
for item in message.parts:. Let me fix:Assistant
The file now looks correct. Let me verify by running the tests:
Assistant
Now empty synthetic message returns
None(correct behavior preserved). Let me run the original reproducer to make sure:Assistant
The fix still works for the DeepSeek case.
Let me also run the OpenAI tests again to make sure:
Assistant
All 200 openai tests pass.
Let me also run the capability tests:
Assistant
All tests pass.
Let me also verify the fix is in the correct location by looking at the diff:
Assistant
The diff looks clean and correct.
Now let me also think about a potential alternative approach. What if instead of injecting at the model adapter level, I should look at whether the user expects
ToolCallPartmessages to have aThinkingPart?Let me check if there are other places where this issue might manifest. Let me look at the moonshotai tests:
Assistant
Good, all the existing tests pass.
Now let me also run the test cases that specifically use OpenRouter (which also uses thinking field):
Assistant
Let me check the openrouter tests for thinking/streaming:
Assistant
All 48 openrouter tests pass.
Now let me also think about whether my fix should consider the "auto" mode more carefully. Let me re-read the auto mode logic:
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]))For auto mode:
item.idmust be set
Assistant
The diff looks clean. Now let me also test with my reproducer scripts:
Assistant
The fix works.
Now let me also run the test_capabilities tests one more time to make sure they all pass:
Assistant
All 1076 relevant tests pass.
Let me also test with my reproducer once more and confirm the original behavior:
Assistant
I see - my first reproducer hit the request limit because the model kept calling
roll_dicewithout ending. This is because the model doesn't ever return a final response in my mock. But this is a mock issue, not a fix issue.Let me look at what message 4 (the synthetic one) now contains:
Assistant
The synthetic message at [4] now has
reasoning_content:(empty). The fix works for the original issue.Now let me also think about whether the fix handles all the edge cases mentioned in the issue:
This is triggered because DeepSeek requires the original
reasoning_contentproduced during the thinking phase to be passed back exactly as-is in the subsequent conversation message history array.The issue says "passed back exactly as-is". So empty reasoning_content might not satisfy this requirement. Let me check this.
Actually, looking at the streaming test data, the first chunk has
reasoning_content: "". So empty reasoning_content IS what DeepSeek sends when starting a thinking response. So passing back empty reasoning_content should be acceptable.Let me verify by looking at what happens if we send an empty reasoning_content to DeepSeek:
Assistant
The first chunk has
reasoning_content: "". So DeepSeek accepts an empty reasoning_content when starting a thinking response. My fix uses empty reasoning_content, which should be acceptable.Now let me also check if there's any issue with my fix for OpenAI's own chat completion API. Let me look at what OpenAI's API does with reasoning_content field:
Assistant
No openai tests use
reasoning_content. The OpenAI Chat API doesn't use this field, so the fix doesn't affect OpenAI Chat API.Now let me also consider whether I should add a check for the
provider_namemore carefully. Let me look at the issue description again:This is triggered because DeepSeek requires the original
reasoning_contentproduced during the thinking phase to be passed back exactly as-is in the subsequent conversation message history array.So DeepSeek wants the EXACT reasoning_content passed back. If the synthetic message is followed by a tool call to
search_tools, the model wouldn't have produced a reasoning_content for this tool call. So we should pass an empty reasoning_content (which is what DeepSeek uses as a starting state).Now let me also think about whether my fix should propagate the previous message's reasoning_content. For example, if the previous real assistant message had reasoning_content "I need to think", and the next synthetic message has empty reasoning_content, should we propagate the previous?
Assistant
The fix looks clean. Let me also verify by running the existing tests:
Assistant
All 1155 relevant tests pass.
Now let me also think about whether the fix could cause issues for any other tests:
Assistant
All 585 tests pass for other model providers.
Now let me also clean up by removing the temporary reproducer files:
Assistant
Let me now also double check by looking at the test that I want to ensure passes. Let me verify with the existing test:
Assistant
Both DeepSeek tests pass.
Now let me check if there's a CHANGELOG or anything I should update. Actually let me first check the agent docs:
Assistant
Only my fix is changed. Let me make sure the diff is correct:
Assistant
The fix is clean and minimal.
Now let me also think about whether I need to handle the OpenAI Responses model similarly. Let me check:
Assistant
The OpenAI Responses model uses different mechanics (reasoning items, tool_search_call type). It doesn't have the issue we're fixing.
Now let me also look at the structure of my fix and see if there are any other improvements I should make. Let me re-read the comment:
# Synthetic assistant messages (e.g. the framework-emitted `ToolSearchCallPart` # exchange produced by the `ToolSearch` capability when a deferred capability loads) # carry no `ThinkingPart`, but providers like DeepSeek require every assistant # message in thinking mode to include the configured thinking field. Inject an # empty `ThinkingPart` so the field is populated on the wire. Real responses # carry their own `ThinkingPart` and don't need this; detection uses the # "framework-emitted" convention (`provider_name`/`model_name`/`provider_response_id` # all `None`) also used by `_clean_message_history`.This is a good comment that explains:
- What the issue is (synthetic messages without ThinkingPart).
- Why we need to fix it (DeepSeek requires thinking_content on every assistant message).
- How we detect synthetic messages (the convention used by
_clean_message_history).
Now let me also verify the fix is complete by running my reproducer one final time:
Assistant
The fix works correctly. The synthetic message at position [4] now has
reasoning_content(empty), satisfying DeepSeek's requirement.Now let me also think about whether the issue might also occur with other providers (not just DeepSeek) that use thinking fields. Let me check MoonshotAI again:
The moonshotai provider also has
openai_chat_thinking_field='reasoning_content'andopenai_chat_send_back_thinking_parts='field'. So the fix would also work for MoonshotAI.For OpenRouter, the provider has
openai_chat_thinking_field='reasoning'andopenai_chat_send_back_thinking_parts='field'. So the fix would also work for OpenRouter.Let me clean up:
Assistant
Now let me think about whether there are any other issues that could cause the same problem. Let me also check the message flow once more:
Looking at the issue, the synthetic message is created by
ToolSearch.before_model_request. Let me verify this is the only place:Assistant
The only place that creates a synthetic
ModelResponse(with no provider_name/model_name) for the message history ispydantic_ai_slim/pydantic_ai/capabilities/_tool_search.py:234. Other ModelResponse creations are for direct testing or real responses.Now let me also check if there's any related test in the test file:
Assistant
OK, my understanding is correct. The "framework-emitted" pattern is used elsewhere in the codebase.
Now let me also think about whether the fix should also handle messages where the response was interrupted (state='incomplete'). Let me check:
Assistant
The
statefield indicates whether a response is complete, incomplete, or interrupted. For incomplete responses, the thinking content might be missing. But that's the model's responsibility to handle, not the framework's. The fix focuses on framework-emitted synthetic messages.Now let me also think about a potential issue. What if the provider has a different system name than what we expect? Let me look at this:
Assistant
Interesting - the custom provider doesn't get the reasoning_content. This is because the custom provider doesn't inherit the DeepSeek profile. Let me check:
Assistant
Custom providers with custom profiles also work correctly.
Assistant
Let me also run one more comprehensive test:
Assistant
All 1393 tests pass.
Now let me also do a final review of the code:
Assistant
Assistant
All 1841 relevant tests pass.
Let me also see if there are tests I missed by running just the specific area for thinking:
Assistant
All 142 thinking tests pass.
Let me also look at my final diff one more time:
Assistant
The fix is minimal, well-documented, and only affects the OpenAI Chat model's
_MapModelResponseContext.map_assistant_messagemethod.Let me also check that I haven't introduced any syntax errors:
Assistant
This error is unrelated to my fix - it's about missing API key. Let me test with a mock:
Assistant
The model instantiates correctly. Let me also run a quick test to make sure my fix is syntactically correct:
Assistant
Syntax is correct.
Now let me also think about whether to add a test. The instructions say:
UNDER NO CIRCUMSTANCES should you modify existing tests or add new tests to the repository. This will lead to an error in the system that evaluates your performance. Instead, you can just create a temporary script, use it to test changes and remove it before submitting.
So I should NOT add tests. Let me just remove the temp files and submit.
Let me do a final check:
Assistant
Only the openai.py file is modified. Let me also check there are no leftover files:
Assistant
No leftover files. Good.
Let me also do a final verification that my fix correctly handles the issue:
Assistant
The fix is verified to work correctly.
Assistant
Summary
The issue was that when using
Capability(..., defer_loading=True)with DeepSeek reasoning models, the framework emitted a syntheticModelResponsemessage containing aToolSearchCallPart(from theToolSearchcapability that tracks tool discovery). This synthetic message had noThinkingPart, but DeepSeek requires every assistant message in thinking mode to include thereasoning_contentfield, resulting in a 400 error.Fix
I modified to detect synthetic framework-emitted assistant messages and inject an empty so the configured thinking field (e.g., for DeepSeek) is populated on the wire.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.