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 understanding the issue. The problem is that when using
defer_loading=Truewith DeepSeek models, thereasoning_contentfrom thinking mode is not properly passed back to subsequent API calls, causing a 400 error. Let me explore the repository structure first. - Assistant
Let me explore more to understand the structure, especially around capabilities and deferred loading.
- Assistant
Let me explore the key files to understand the issue better.
- Assistant
Let me first understand the issue better. The problem is:
- When using DeepSeek models with
defer_loading=Truefor capabilities, thereasoning_contentfrom thinking mode is not preserved in subsequent API calls - DeepSeek requires the original
reasoning_contentto be passed back in subsequent conversation messages - Setting
defer_loading=Falseworks fine
Let me explore the repository structure to understand how deferred capabilities work and how messages are handled.
- When using DeepSeek models with
- Assistant
The issue is about
defer_loading=Truecausing an error with DeepSeek models becausereasoning_contentis not preserved when passing messages back. Let me understand the flow:- When
defer_loading=True, capabilities are not loaded initially but are made available as a tool to load later - When DeepSeek models produce
reasoning_content, it needs to be passed back exactly as-is3. During the capability runner's execution loop, it seems like thereasoning_contentis being dropped
Let me look at the execution loop and message handling.
- When
- Assistant
Let me look at how the deferred capability loader toolset works:
- Assistant
Let me look at the toolsets directory to understand the deferred capability loader:
- Assistant
Let me look at the agent graph and how messages are handled:
- Assistant
Let me look at the agent graph to understand the execution loop:
- Assistant
Let me search for how messages are prepared and sent to the model, and how thinking/reasoning content is handled:
- Assistant
I need to make only one tool call at a time. Let me start with exploring the repository structure to understand the codebase.
- Assistant
Let me search for how reasoning_content is handled in the codebase:
- Assistant
Let me look at the OpenAI model to understand how reasoning content is handled:
- Assistant
Now let me look at the messages module to understand how ModelResponse and ThinkingPart are structured:
- Assistant
Let me look at how the OpenAI model translates model response messages back to API format:
- Assistant
Let me look at the _ResponseMessageBuilder more carefully to understand how thinking parts are sent back to the API:
- Assistant
Let me look at how messages are converted back to OpenAI format.
- Assistant
Let me search for how model messages get translated into OpenAI API messages format, focusing on the history conversion.
- Assistant
Let me look at the
_map_model_responseand_map_messagesfunctions: - Assistant
Now I see the key mechanism. The
_MapModelResponseContext._map_response_thinking_parthandles mappingThinkingPartobjects back toreasoning_contentfields when sending messages to the API. Let me now understand what happens during the deferred capability loading flow. Let me look at the agent graph to see how messages are managed during the capability loading loop. - Assistant
Let me look at how the agent graph manages message history around deferred capability loading, particularly the
before_model_requestflow: - Assistant
Now let me look at
CallToolsNodeto understand the tool call handling flow, especially for deferred tools: - Assistant
Let me understand the flow better by looking at how tool calls are processed and how deferred tool results work:
- Assistant
Now I understand the execution flow better. Let me look at
_clean_message_historyto see if it might be stripping reasoning content: - Assistant
Let me look at the
_clean_message_historyfunction: - Assistant
The
_clean_message_historyfunction doesn't seem to strip reasoning content. Let me now look at theprepare_messagesmethod and how it might affect the message history: - Assistant
Let me look at how the OpenAI model processes messages before sending them. The issue is about DeepSeek models specifically. Let me look at the deepseek provider:
- Assistant
Let me look at the deepseek model profile:
- Assistant
Now I understand the key configuration. DeepSeek models have
openai_chat_send_back_thinking_parts='field'which means thinking parts should be sent back as areasoning_contentfield. Let me trace through what happens whendefer_loading=Truecauses aload_capabilitytool call. Let me look at the fullprocess_tool_callsfunction: - Assistant
Now let me look at the
_handle_deferred_tool_resultsmethod and theModelRequestNodemore carefully: - Assistant
Let me look at the
process_historycapability: - Assistant
Let me look at the abstract capability class to understand the hooks:
- Assistant
Let me look at the hooks capability implementation:
- Assistant
Let me look at the combined capability to understand how hooks are chained:
- Assistant
Let me look at the
before_model_requestmethod inCombinedCapability: - Assistant
Let me look at the
before_model_requestmethod inCombinedCapability: - Assistant
Let me look at
_ctx_for_available_capto understand how deferred capabilities are filtered: - Assistant
Let me look at the
_ctx_for_available_capfunction: - Assistant
Now let me look at what hooks
DeferredCapabilityLoaderhas: - Assistant
Let me look at the
Instrumentationcapability and thePendingMessageDrainCapability: - Assistant
Let me look more carefully at how messages are mapped back. Let me look at the
_into_message_parammethod: - Assistant
Now let me understand the full flow more clearly. Let me look at how the ThinkingPart is created from DeepSeek responses:
- Assistant
Now let me understand the key flow. When
defer_loading=Trueis used, the model makes a tool call toload_capability, which returns a result, and then the agent continues with the next model request. The key question is: are the thinking parts preserved correctly?Let me look at the
_prepare_requestmethod more carefully to see how messages flow through before being sent to the model: - Assistant
Let me now search for any tests related to deferred capabilities and thinking/reasoning:
- Assistant
Let me look for tests related to deferred capabilities:
- Assistant
Let me look at the test_capabilities.py file for examples of deferred capabilities:
- Assistant
Let me look at the streaming case and how the OpenAI model handles messages - specifically the
_map_messagesfor the OpenAI model class. Let me look at the full_map_messagesfunction: - Assistant
Let me look at the
prepare_messagesmethod on the model: - Assistant
Let me search in the base model class.
- Assistant
Let me look at the base model class's
prepare_messagesmethod: - Assistant
Let me think about this differently. Let me look at the full flow from the model's perspective. When the agent runs with
defer_loading=True, the flow is:- User prompt → ModelRequestNode → sends to DeepSeek → response with ThinkingPart + ToolCallPart (load_capability)
- CallToolsNode processes tool calls → creates ModelRequest with tool results
- New ModelRequestNode → sends to DeepSeek (with history including the previous response)
- Assistant
Let me look at
_append_response: - Assistant
Let me look at the
ModelRequestNode.runmethod: - Assistant
Let me look at the
ModelRequestNode.runmethod: - Assistant
Let me look at the
_make_requestmethod: - Assistant
Let me look at the
_make_requestmethod: - Assistant
Let me now look at the
wrap_model_requesthook inCombinedCapability: - Assistant
Let me look at the
prepare_messagesmethod in the model: - Assistant
Let me look at the
process_event_streamcapability: - Assistant
Let me look at how instructions are handled in the context of deferred capabilities:
- Assistant
Let me check what
openai_chat_supports_multiple_system_messagesdefaults to for DeepSeek: - Assistant
Let me now focus on the actual error. The error says
reasoning_contentmust be passed back. Let me look at the streaming path for DeepSeek to see how reasoning content is collected: - Assistant
Let me try a different approach. Let me look at the actual test files to understand the flow better:
- Assistant
Let me look for tests that combine deferred loading with thinking:
- Assistant
Let me look at the
Capabilityclass itself: - Assistant
Let me now look at
_get_instructionsto understand how instructions are resolved: - Assistant
Let me now focus on a different approach. Let me write a test script that simulates the issue to understand it better. First, let me check if there are existing tests that demonstrate the deferred capability flow:
- Assistant
Let me look at a specific deferred capability test to understand the flow:
- Assistant
Let me look at how model settings are handled for deferred capabilities:
- Assistant
Let me look at the abstract capability class:
- Assistant
OK let me look at the default implementation:
- Assistant
Let me look at the
_deferred_capabilities.pymodule: - Assistant
Let me now look at
_narrow_tool_call_partsto understand how it might affect things: - Assistant
Let me look at the _narrow_tool_call_parts function:
- Assistant
OK, I need to approach this differently. Let me look at the actual test infrastructure and try to write a test that demonstrates the issue. Let me first understand how the test model works:
- Assistant
Let me now look at how native tools are resolved for DeepSeek's profile:
- Assistant
Let me check what
supports_tool_searchis for DeepSeek: - Assistant
Let me check what the default value of
supported_native_toolsis forOpenAIModelProfile: - Assistant
Let me look at
SUPPORTED_NATIVE_TOOLS: - Assistant
Let me check what's in SUPPORTED_NATIVE_TOOLS:
- Assistant
Let me take a step back and think about this differently. Let me write a script to reproduce the issue:
- Assistant
Let me search for existing tests that use ThinkingPart:
- Assistant
Let me look at how the OpenAI model tests handle thinking parts:
- Assistant
Let me look at the OpenAI model tests to see how reasoning content is tested:
- Assistant
Let me look at the
requestmethod of the OpenAI model to understand how it sends messages: - Assistant
Let me look at the request method:
- Assistant
Let me look at the
_completions_createmethod: - Assistant
Let me look at the
_completions_createmethod: - Assistant
OK let me approach this problem differently. Let me look at the _map_user_message to see how ModelRequest messages are mapped to OpenAI format:
- Assistant
Let me look at the
_map_user_messagemethod: - Assistant
OK, let me take a completely different approach. Let me look at the key flow step by step. When a model request is made with the OpenAI model, what happens to the messages? Let me write a test to simulate this flow:
- Assistant
Let me check how the Python environment is set up:
- Assistant
Let me check the venv:
- Assistant
Let me use the venv python:
- Assistant
Now let me test the actual mapping logic:
- Assistant
The message history looks preserved correctly. Let me now test the actual message mapping to see if the reasoning content is correctly preserved:
- Assistant
Let me test just the thinking part mapping:
- Assistant
OK, the mapping logic is correct -
reasoning_contentIS being preserved in the assistant message. Let me now look at the actual flow more carefully to find where it might be getting dropped. Let me check if there's something in_drop_sampling_params_for_reasoningor_drop_unsupported_paramsthat could affect things: - Assistant
Let me look at these functions:
- Assistant
Let me check if
ToolSearchToolis in the defaultSUPPORTED_NATIVE_TOOLS: - Assistant
Let me check the correct import for ToolSearchTool:
- Assistant
- Assistant
Now let me check how the OpenAI SDK serializes these messages. The
ChatCompletionAssistantMessageParamdoesn't havereasoning_contentin its annotations, but it's a TypedDict (just a dict). Let me check if the SDK strips extra keys: - Assistant
Good - the dict itself preserves
reasoning_content. But let me check if the OpenAI SDK's client strips extra fields during serialization: - Assistant
Let me investigate how the OpenAI SDK handles serialization:
- Assistant
Let me check how the openai SDK serializes messages - whether it strips extra fields like
reasoning_content. - Assistant
Let me check what
async_maybe_transformdoes with messages: - Assistant
Let me focus on the actual issue now. Let me trace through the exact flow by looking at what
_get_instructionsdoes: - Assistant
Now let me check something critical - does the OpenAI SDK strip extra fields like
reasoning_contentfrom the messages when serializing? Let me test this directly: - Assistant
OK, the SDK correctly preserves
reasoning_content. So the mapping logic is correct. Let me think about what could be different in the deferred capability flow specifically.Let me now look at
_get_instruction_partsto see if it's modifying messages: - Assistant
Let me find the
_get_instruction_partsmethod in the base model: - Assistant
Let me look at the
_get_instruction_partsmethod: - Assistant
OK so the mapping and SDK serialization are both correct. The
reasoning_contentis preserved. Let me think about this differently.Wait - I need to reconsider the flow. When
defer_loading=True, what happens is:- First model call: Model sees deferred catalog, calls
load_capability - Tool executes, returns instructions
- Second model call: Model sees the loaded capability tools, uses them
But the issue is about what happens BETWEEN step 1 and step 3. Let me look at the actual flow more carefully.
In step 1, the model responds with
ModelResponse(ThinkingPart + ToolCallPart). This is stored in message history.In step 2, the tool returns and a new
ModelRequestis created.In step 3, when
_prepare_requestis called, it calls_get_instructions(). Now, because the capability was just loaded, the capability's instructions become available. These instructions get set on the ModelRequest (the tool return message).But wait - there's a subtlety here. Let me look at
_merge_leading_system_messages: - First model call: Model sees deferred catalog, calls
- Assistant
- Assistant
OK, Instrumentation doesn't have
after_model_requestorbefore_model_request. So the response should not be modified by any capability.Let me think about this from a completely different angle. Let me re-read the error message:
"The
reasoning_contentin the thinking mode must be passed back to the API."This error means DeepSeek's API is expecting
reasoning_contentbut it's not present.Let me check if there could be an issue with how
content: nullis serialized by the OpenAI SDK. Maybe when content isNone, the SDK sets it toomitor drops the field entirely?Actually, wait. Let me look at the ChatCompletionAssistantMessageParam more carefully. In the OpenAI SDK, TypedDicts might use
NotRequiredfields, and the SDK might stripNonevalues or use omit.Let me check:
- Assistant
Let me now try a completely different approach. Let me look at what happens with the
_map_user_messagewhen processing ModelRequest messages. Specifically, let me check ifToolReturnPartmapping could cause issues: - Assistant
Let me look at
_prepare_request_parametersmore carefully: - Assistant
Let me look at the
_call_toolsfunction to understand how tool results are created: - Assistant
Let me take a completely different approach. Let me write a test script that simulates the exact deferred capability flow with thinking parts to see if the reasoning_content is properly preserved:
- Assistant
Interesting! The ThinkingParts are present in the message history. But this test uses FunctionModel which doesn't go through the OpenAI
_map_messages. Let me now write a test that specifically tests the OpenAI message mapping with the deferred capability flow: - Assistant
Let me fix the test - I should use
OpenAIChatModelnotOpenAIModel: - Assistant
Let me check how OpenAIChatModel is initialized:
- Assistant
Let me look at how OpenAIChatModel is initialized:
- Assistant
Let me look at the init method:
- Assistant
Let me look at how
ToolSearchCallPartandNativeToolCallPartrelate to each other: - Assistant
OK so
ToolSearchCallPartis aToolCallPart, not aNativeToolCallPart. So it would be correctly mapped.Let me now focus on a different angle. Let me check the streaming path since DeepSeek models might use streaming:
- Assistant
Let me check how
synthesize_local_tool_search_messagesworks and whether it could affect thinking content: - Assistant
Let me look at this function:
- Assistant
Let me try to directly test the OpenAI message mapping with DeepSeek-like profile:
- Assistant
OK, I've confirmed that the reasoning_content IS correctly preserved in the message mapping. Let me now focus on understanding what's ACTUALLY different about the deferred loading flow. Let me look more carefully at what
_call_toolsdoes and how tool return parts are created: - Assistant
Let me look at
_call_tool: - Assistant
OK, I've been going deep into the code but let me step back and think about what's actually different. Let me check if there's something specific about how
CombinedCapability.get_instructionshandles loaded deferred capabilities: - Assistant
Now I can see something very interesting! In Call 2, there's a
ModelResponse [ToolSearchCallPart] has_thinking=False- a ModelResponse WITHOUT thinking! This is the key!Let me understand where this
ToolSearchCallPartcomes from and why it doesn't have a ThinkingPart: - Assistant
ToolSearchToolIS inFunctionModel.supported_native_tools(). Sosynthesize_local_tool_search_messagesis NOT called. But then where is theToolSearchCallPartcoming from?Let me check what profile FunctionModel uses:
- Assistant
Let me check how
prepare_messagesworks onFunctionModel: - Assistant
Let me look at how native tools interact with the deferred loading mechanism. The
ToolSearchCallPartseems to be generated by the framework: - Assistant
Let me trace where the
ToolSearchCallPartin the message history comes from. Let me check the_prepare_requestflow more carefully: - Assistant
Let me look at how
_resolve_native_tool_swapworks: - Assistant
Let me add more detailed debugging to trace exactly when the
ToolSearchCallPartappears: - Assistant
Let me fix the import and rerun:
- Assistant
Now I can see the problem clearly! In the final message history, there's a
ModelResponse [ToolSearchCallPart] has_thinking=False- a ModelResponse WITHOUT thinking content! When DeepSeek receives this, it sees an assistant message withoutreasoning_contentand throws the 400 error.Let me find where this
ToolSearchCallPartModelResponse is being created: - Assistant
Let me look at the key file where
ToolSearchCallPartis created: - Assistant
I found the root cause! The
ToolSearch.before_model_requestmethod creates a syntheticModelResponsewith only aToolSearchCallPartand NOThinkingPart:ModelResponse( parts=[ ToolSearchCallPart( args={'queries': capability_ids}, tool_call_id=call_id, ), ] ),When this is sent to DeepSeek, it gets mapped to an assistant message WITHOUT
reasoning_content, causing the 400 error.Now let me implement the fix. The issue is in
_into_message_param- when there are no thinking parts but the model requires sending back thinking as a field, we need to include an emptyreasoning_contentfield: - Assistant
Now let me implement the fix. The issue is in
_into_message_param- when there are no thinking parts but the model requires sending back thinking as a field, we need to include an emptyreasoning_contentfield: - Assistant
Now let me implement the fix:
- Assistant
Now let me verify the fix:
- Assistant
Now let me run the existing tests to make sure the fix doesn't break anything:
- Assistant
Let me run the tests without the timeout argument:
- Assistant
All capability tests pass. Let me also run the OpenAI model tests:
- Assistant
All OpenAI model tests pass. Let me also run the agent tests and tool tests:
- Assistant
The failure is an MCP-related test that requires the
mcpmodule which is not installed - not related to my fix. Let me skip that and run the rest: - Assistant
Let me try skipping MCP tests more explicitly:
- Assistant
Let me check the exact failing test name:
- Assistant
Let me skip all MCP-related tests:
- Assistant
All tests pass except for MCP-related tests which require the
mcpmodule that's not installed. Let me also run the tools tests: - Assistant
Let me also run the tool_search tests:
- Assistant
All tests pass. Let me also run the OpenAI-specific tests related to reasoning:
- Assistant
Let me now verify the fix with a comprehensive end-to-end test:
- Assistant
Let me fix the import and re-run:
- Assistant
Now let me verify that the fix doesn't affect non-DeepSeek models (where
openai_chat_send_back_thinking_partsis not'field'): - Assistant
All test cases pass correctly:
- Non-DeepSeek model without thinking → no
reasoning_content✓ - DeepSeek model with thinking → actual
reasoning_content✓ - DeepSeek model without thinking (synthetic exchange) → empty
reasoning_content✓
Let me check the git diff to see the exact change:
- Non-DeepSeek model without thinking → no
- Assistant
Now let me run a final comprehensive test to verify everything works:
- Assistant
All 1208 tests pass. Let me now do a final verification with the exact scenario from the issue:
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.