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.codeopenai.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
Python Assistant
Let me start by understanding the issue:
- When using DeepSeek reasoning models with
Capability(..., defer_loading=True), it causes a 400 error because DeepSeek requires thereasoning_contentto be passed back to the API in subsequent messages. - The issue is that when
defer_loading=True, the graph loop doesn't properly serialize/propagate thereasoning_contenttoken block back to DeepSeek's chat completions endpoint.
Let me explore the repository structure first to understand the codebase.
- When using DeepSeek reasoning models with
Assistant
Let me explore the relevant source files. The issue is about capabilities with defer_loading=True and DeepSeek models. Let me look at the capabilities module and the agent graph/runner.
Assistant
Let me explore the key files related to this
Assistant
Let me look at the capability wrapper and the pending messages to understand how they handle message history.
Assistant
Let me now look at the process_history and process_event_stream capabilities, which are likely involved in how messages are handled between turns:
Assistant
Let me look at the deferred tool handler and the process_event_stream:
Assistant
Let me now look at the process_event_stream capability, as it's likely where the message processing for deferred capabilities happens.
Assistant
Let me look at the agent's graph and the toolsets for deferred capability
Assistant
Let me find the agent's graph module and understand how messages are constructed for model requests.
Assistant
Let me look at the OpenAI model and the messages modules to understand how messages are constructed:
Assistant
Let me look at the key sections around these lines to understand how reasoning_content is handled.
Assistant
Let me open the file at line 1140.
Assistant
Let me look at how messages with thinking parts are serialized back to the API. Let me search for where
ThinkingPartis used when constructing requestsAssistant
Let me look at how thinking parts are serialized back to the API for requests. Let me look at the critical section around line 2735 and 3021 in openai.py
Assistant
Let me open at line 2730.
Assistant
Let me scroll down to see the rest of the _map_messages method:
Assistant
Let me scroll down further to see where ThinkingPart is handled:
Assistant
Let me find the chat completions
_map_messagesmethod. Let me look for a different _map_messages in openai.py:Assistant
Let me look at the chat completions
_map_messagesat line 1445Assistant
Let me open at line 1445 only
Assistant
Let me look at the
_map_model_responsemethod and the_MapModelResponseContextclassAssistant
Let me look at the
_MapModelResponseContextclass and_map_model_responsemethod:Assistant
Let me open at line 1293.
Assistant
Let me scroll down to see the rest of `_map_response_thinking_part
Assistant
Now let me look at the DeepSeek profile:
Assistant
Let me look at the ModelProfile class to understand the defaults for
openai_chat_thinking_fieldandopenai_chat_send_back_thinking_partsAssistant
The
openai_chat_thinking_fieldandopenai_chat_send_back_thinking_partsmust be in the OpenAI-specific profile. Let me findAssistant
Now let me look at the deepseek provider to see how it configures the profile
Assistant
Now let me look at the agent graph/run to understand how messages flow in the execution loop, especially with deferred capabilities
Assistant
Let me look at the
_pending_messagescapability, which likely handles deferred message managementAssistant
Let me look at the agent graph to understand the message history flow
Assistant
Let me look at the agent graph
Assistant
Let me look at the ModelRequestNode in the agent graph to see how messages flow
Assistant
Let me look at the ModelRequestNode run method at line 593
Assistant
Let me open at line 581
Assistant
Let me scroll down to see more
Assistant
Let me scroll down to see
_prepare_requestand_make_requestAssistant
Let me scroll down to see the rest of _prepare_request
Assistant
Let me look at the CallToolsNode and how tool results are handled
Assistant
Let me look at CallToolsNode
Assistant
Let me scroll further
Assistant
Let me look at
_handle_tool_callsAssistant
Let me look at
_handle_tool_callsat line 1260Assistant
Let me look at
process_tool_callsfunction:Assistant
Let me look at
process_tool_callsAssistant
Let me search for where
_process_thinkingis calledAssistant
Let me look at line 1090-1120:
Assistant
Let me look at the tool manager and how capability loading works
Assistant
Let me look at ToolManager.for_run_step:
Assistant
Let me open at 120
Assistant
Let me look at how the OpenAI library handles extra fields like
reasoning_contentin the typesAssistant
Let me look for the openai types
Assistant
Let me check the ChatCompletionAssistantMessageParam
Assistant
Let me search for how
reasoning_contentis set on outgoingAssistant
Let me look at
_refresh_loaded_capability_idsAssistant
Let me look at these functions:
Assistant
Let me look at
parse_loaded_capabilities:Assistant
Let me look at `_deferred_capabilities.py
Assistant
Let me look at the
prepare_toolscapability:Assistant
Let me look at how
_map_user_messagehandles ToolReturnPartAssistant
Let me open at 1526
Assistant
Let me check the git log for recent changes related to thinking or reasoning
Assistant
Let me look at how the model class is determined for Deep
Assistant
Let me look at how DeepSeek models are created
Assistant
Let me look at how deepseek models are registered
Assistant
Let me search for the model resolution logic
Assistant
Let me look at the model resolution:
Assistant
Let me open at 109
Assistant
Let me look at how profile is set on OpenAIChatModel
Assistant
Let me look at the constructor for OpenAIChatModel
Assistant
Let me open at 758
Assistant
Let me look at the base Model class:
Assistant
Let me look at Model class:
Assistant
Let me open at 216
Assistant
Let me search for the
profileproperty in the Model classAssistant
Let me look at the profile property:
Assistant
Let me open at 629.
Assistant
Let me check if
OpenAIChatModelhas its ownprofilepropertyAssistant
Let me look at the profile property of OpenAIChatModel
Assistant
Let me open at 860
Assistant
Let me look at the abstract capability's wrap methods:
Assistant
Let me look at the streamed response handling - how ThinkingPart is handled in streaming:
Assistant
Let me look at the streaming thinking delta mapping
Assistant
Let me open at 3310
Assistant
Let me look at
_process_responseto see how the non-streaming pathAssistant
Let me look at
_process_responseat line 1056:Assistant
Let me open at 1056
Assistant
Let me look at
_ChatCompletionclass definition to see if it strips `reasoning_contentAssistant
Let me look at
_ChatCompletion:Assistant
Let me open at 282
Assistant
Let me check the OpenAI ChatCompletion model
Assistant
Let me check the ChatCompletion model
Assistant
Let me look at the ChatCompletion model config
Assistant
Let me check the OpenAI BaseModel for extra field handling
Assistant
Let me search for BaseModel class in the OpenAI module:
Assistant
Let me look at BaseModel class:
Assistant
Let me look at how the messages are used in the API
Assistant
Let me look at
_completions_create:Assistant
Let me open at 962
Assistant
Let me check how OpenAI client serializes messages
Assistant
Let me search for relevant tests
Assistant
Let me look at the DeepSeek test and deferred capabilities test
Assistant
Let me look at the DeepSeek test
Assistant
Let me look at the full deepseek test
Assistant
Let me open the deepseek test
Assistant
Now let me look at test_capabilities.py for deferred capability tests
Assistant
Let me look at the deferred capabilities tests to understand the flow
Assistant
Let me look at handle_thinking_delta
Assistant
Let me look at `_parts_manager.py
Assistant
Let me look at the Capability class
Assistant
Let me search for any related issues or recent commits about this
Assistant
Let me look at the deepseek v4 support
Assistant
Let me look at the diff for the deepseek provider:
Assistant
Now let me look at the longer-term series of changes. Let me focus on the
_map_response_thinking_partmethod more carefully. I think I may have found the issue:When
defer_loading=True, the model first calls . The response includes:Assistant
Let me check how the OpenAI client handles message
Assistant
Let me check how messages are serialized in the OpenAI client
Assistant
Let me look at how completions.create serializes messages
Assistant
Let me look at the implementation of completions.create:
Assistant
Let me find the actual implementation of create
Assistant
Let me look at maybe_transform
Assistant
Let me look at `_transform_typeddict
Assistant
Let me open at 263
Assistant
Let me look at the git log for any recent changes to how reasoning_content is sent back in message serial
Assistant
Let me look at commit 4e91659f that skips empty ModelResponse and the deferred capabilities commit
Assistant
Let me see that commit diff:
Assistant
Let me look at the test for deferred capabilities with model interactions:
Assistant
Let me look at the e2e test for deferred capabilities:
Assistant
Let me open at 3021
Assistant
Let me look at how model name is parsed for DeepSeek
Assistant
Let me look at infer_model at 1051:
Assistant
Let me open at 1051
Assistant
Let me search for reasoning_content in the test files to understand expected
Assistant
Let me look at these tests around line 4350
Assistant
Let me open at 4350
Assistant
Let me look at
_append_responseand_finish_handlingAssistant
Let me look at these methods
Assistant
Let me open at
Assistant
Let me create a test script to reproduce the issue:
Assistant
Let me check the Python environment and run the test properly:
Assistant
Let me test the full _map_messages flow:
Assistant
Let me test with a thinking-only response:
Assistant
Let me look at the Instrumentation capability:
Assistant
Let me check the ToolKind type and how capability-load tool calls are processed
Assistant
Let me look at how tool calls are categorized by kind in process_tool_calls:
Assistant
Let me check the ToolKind definition
Assistant
Let me look at ToolDefinition:
Assistant
Let me look at ToolD
Assistant
Let me open at 687
Assistant
Let me verify this potential bug - let me check if
tool_kindis valid for ToolDefinitionAssistant
Let me check the full ToolDefinition definition
Assistant
Let me look at how function tools are processed in process_tool_calls:
Assistant
Let me try to create a comprehensive test to see if the issue is reproducible:
Assistant
Let me fix the test:
Assistant
Let me check if the OpenAI SDK properly serializes
reasoning_content:Assistant
Let me look at how
GraphAgentDeps.capabilitiesis populated:Assistant
Let me look at
_build_run_capabilitiesAssistant
Let me open at 29
Assistant
Let me search for any related issues:
Assistant
Let me look at the deferred loading capabilities commit to understand what changes it made
Assistant
Let me check the changes to openai.py in that commit:
Assistant
Let me check if OpenAIModel overrides _map_messages:
Assistant
Let me verify the profile used for DeepSeek:
Assistant
Let me verify the full JSON serialization including reasoning_content:
Assistant
Let me check what type the profile is at mapping time:
Assistant
Let me look at the OpenAIModelProfile definition:
Assistant
Let me write a comprehensive test using the full agent flow:
Assistant
Let me fix the script:
Assistant
This is very revealing! The test shows that when using
defer_loading=True, there's an EXTRA tool search step that creates additional messages. Let me look at the tool search capability:Assistant
Let me check how ToolSearch is auto-injected:
Assistant
Let me search for where ToolSearch is auto-injected
Assistant
Let me look at where ToolSearch is auto-added:
Assistant
Let me look at the auto-injection of ToolSearch:
Assistant
Let me open at 2910
Assistant
Now I understand the issue! The
ToolSearch.before_model_requestadds syntheticModelResponse+ModelRequestmessages for tool search when a capability is loaded. These synthetic messages don't includeThinkingPart, which breaks thereasoning_contentchain required by DeepSeek. Let me implement the fix:Assistant
Let me open the tool_search file at the relevant section:
Assistant
Now I understand the bug. The
ToolSearch.before_model_requestmethod adds syntheticModelResponse+ModelRequestmessages for tool search when a deferred capability is loaded. These synthetic messages lackThinkingPart, which breaks thereasoning_contentchain required by DeepSeek.Let me implement the fix in the
_tool_search.pyfileAssistant
Let me use replace to add the import for ThinkingPart
Assistant
Now let me modify the
before_model_requestmethod to include aThinkingPart:Assistant
Let me verify the changes:
Assistant
Let me run the test again to verify the fix:
Assistant
Good, the fix works. The synthetic
ModelResponsenow includes aThinkingPartthat preserves thereasoning_contentchain. Let me run the existing tests to make sure nothing is broken:Assistant
Let me run the tests properly:
Assistant
Let me also run tool search related tests:
Assistant
Let me run the thinking-related tests:
Assistant
Let me also run the broader test suite for capabilities:
Assistant
Let me run the agent tests:
Assistant
I should also preserve the
idfield from the original ThinkingPart. Let me update the fix:Assistant
Let me re-run the tests:
Assistant
Let me re-run the e2e test to confirm the fix produces the right output:
Assistant
The fix is working correctly. Let me run the full capabilities test suite one more time to be sure:
Assistant
Let me also run the model and agent tests:
Assistant
Let me verify the final state of my change:
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.