ISSUE DESCRIPTION Deferred capabilities throw error 400 with Deepseek models Initial…
- User
ISSUE DESCRIPTION
Deferred capabilities throw error 400 with Deepseek models
Initial Checks
- I'm using the latest version of Pydantic AI
- I've searched for my issue in the issue tracker before opening this issue
Description
When running an agent using a DeepSeek reasoning model, using
Capability(..., defer_loading=True)causes aModelHTTPError: status_code: 400during execution loop turns.openai.BadRequestError: Error code: 400 - {'error': {'message': 'The `reasoning_content` in the thinking mode must be passed back to the API.', 'type': 'invalid_request_error', 'param': None, 'code': 'invalid_request_error'}}This is triggered because DeepSeek requires the original
reasoning_contentproduced during the thinking phase to be passed back exactly as-is in the subsequent conversation message history array. Whendefer_loading=True, the graph loop intercepted by PydanticAI's capability runner seems to drop or fail to serialize/propagate thereasoning_contenttoken block back to DeepSeek's chat completions endpoint.Setting
defer_loading=Falsesolves the issue, and the agent executes successfully.Minimal, Reproducible Example
# Remember to export the DEEPSEEK_API_KEY environment variable first, then run this code import random from pydantic_ai import Agent, RunContext from pydantic_ai.capabilities import Capability def roll_dice() -> str: """Roll a six-sided die and return the result.""" return str(random.randint(1, 6)) def get_player_name(ctx: RunContext[str]) -> str: """Get the player's name.""" return ctx.deps agent = Agent( 'deepseek:deepseek-v4-flash', deps_type=str, instructions=( "You're a dice game, you should roll the die and see if the number " "you get back matches the user's guess. If so, tell them they're a winner. " "Use the player's name in the response." ), capabilities=[Capability(id='DICE_ROLL', tools=[get_player_name, roll_dice], defer_loading=True)] # Change this to False and the agent will run successfully. ) dice_result = agent.run_sync('My guess is 4', deps='Anne') print(dice_result.output)Logfire Trace
No response
Python, Pydantic AI & LLM client version
- Assistant
I'll start by exploring the repository to understand its structure and locate the relevant files. First, let's check the current directory and see what's there.
- Assistant
Let me explore the structure more to understand the codebase. The issue is about
Capabilitywithdefer_loading=Truecausing an error with DeepSeek models becausereasoning_contentis not being passed back. Let me look at the relevant source code. - Assistant
Let me look at the relevant files: capabilities, deferred loading, and model-related code.
- Assistant
Let me explore the key files related to this issue. The issue is about
reasoning_contentnot being passed back when using deferred capabilities with DeepSeek models. Let me look at:- The capability system and how deferred loading works
- How the model history is serialized/passed back to the API
- The DeepSeek model implementation
- Assistant
Let me look at the key files to understand how deferred capabilities work and how messages/history are managed.
- Assistant
Let me look at the key files: the capability abstract, the deferred capability loader, the openai model (since DeepSeek uses OpenAI-compatible API), and the profiles/openai.py to understand how reasoning_content is handled.
- Assistant
Let me make one call at a time.
- Assistant
Let me look at the deferred capability loader and how messages are handled.
- Assistant
Let me look at the OpenAI model and the DeepSeek provider to understand how reasoning_content is handled.
- Assistant
So DeepSeek requires
reasoning_contentto be passed back in subsequent messages. Let me look at the OpenAI model to understand how this is handled, particularly theopenai_chat_send_back_thinking_partssetting. - Assistant
Now let me look at the OpenAI model implementation to understand how messages are serialized and sent, especially around
reasoning_content: - Assistant
Let me search for the specific parts of the OpenAI model that handle sending back thinking content:
- Assistant
Let me look at how thinking parts are sent back, especially the
_map_response_thinking_partmethod and related logic: - Assistant
Now let me understand how the response context builds messages and where
thinkingsare used. Let me look at the_into_message_parammethod. - Assistant
Let me look at the
_into_message_parammethod and surrounding code to understand how messages are constructed for sending back to the API: - Assistant
Now I need to understand how the message history is built up for subsequent API calls. Let me look at the
_map_historyor equivalent method that convertsModelMessageback to OpenAI format: - Assistant
Let me find the _ResponseContext class and understand how the message history is built:
- Assistant
Let me look at the
_MapModelResponseContextclass in detail: - Assistant
Now I need to understand how deferred capabilities work in the agent graph. Let me look at how they intercept and modify messages:
- Assistant
Let me now look at the
_pending_messages.pycapability and the agent graph to understand how deferred capability loading works: - Assistant
Now let me look at the agent graph to understand how messages are managed during the execution loop:
- Assistant
Let me look at the toolsets directory to find the DeferredCapabilityLoaderToolset:
- Assistant
Let me now look at how the message history is mapped to API format in
_map_messages: - Assistant
Now let me understand the key issue. Let me look at the
_map_model_responsemethod: - Assistant
Let me look at the
_map_model_responsemethod: - Assistant
Now let me search for any message history cleaning or truncation logic that might affect thinking content:
- Assistant
Let me look at the agent graph to understand how messages flow during the execution loop:
- Assistant
Let me look at how
ThinkingPartis created withprovider_nameand how_map_model_responseprocesses it: - Assistant
Now let me understand the message flow better. Let me look at
_clean_message_history: - Assistant
Let me look at the
_clean_message_historyfunction: - Assistant
Let me check what
self.systemis for theOpenAIChatModelwhen used with DeepSeek: - Assistant
Let me look at the
systemproperty: - Assistant
Let me now check how the
load_capabilityresult flows through the agent graph: - Assistant
Let me look at the test file for DeepSeek:
- Assistant
Let me look at the CallToolsNode to understand how tool returns are processed and how the next model request is made:
- Assistant
Let me look at the
CallToolsNode.runmethod, specifically how tool results are turned into messages and how the model request is sent: - Assistant
Let me look at the
_prepare_requestmethod inModelRequestNode: - Assistant
Let me look at the
_prepare_requestmethod: - Assistant
Let me look at
_refresh_loaded_capability_idsand related functions: - Assistant
Let me look at the
_refresh_loaded_capability_idsfunction: - Assistant
Let me check the
prepare_messagesmethod: - Assistant
Let me search more broadly for prepare_messages
- Assistant
Now let me understand the issue better. The problem is that when
defer_loading=Trueis used with DeepSeek, thereasoning_contentfield from assistant messages needs to be preserved in the message history when it's sent back. Let me trace through the message flow more carefully.Let me look at the
_process_responsemethod and then trace what happens when the capability is loaded, and then the agent makes a subsequent request. - Assistant
Let me now look at the key issue. The problem is that when
defer_loading=True, an extra conversation turn happens where the model callsload_capability. The DeepSeek API requires thatreasoning_contentfrom assistant messages be passed back. Let me trace exactly what happens during this flow. - Assistant
Let me look for test cases related to deferred capabilities and thinking:
- Assistant
Let me look at the test for deferred capabilities to understand the expected flow:
- Assistant
Let me look at specific test for deferred loading to understand how tool calls interact:
- Assistant
Let me look at how the model request is made after the tool execution to understand the message flow:
- Assistant
Let me trace the exact issue. The problem is about how messages are being mapped back to OpenAI API format when
defer_loading=True. Let me look at theprocess_tool_callsfunction: - Assistant
Let me look at the
process_tool_callsfunction: - Assistant
Let me look at the combined capability to understand how hooks are chained:
- Assistant
Now let me focus on understanding the exact flow that could cause
reasoning_contentto be dropped. Let me look at howload_capabilitytool results are handled and what happens to the message history: - Assistant
Let me look at the actual flow more carefully by examining how the model request is made with the message history. The key issue is that DeepSeek requires
reasoning_contentto be sent back in subsequent requests. Let me check howModelResponseis being converted: - Assistant
Let me now look at how the
ModelRequestNodeprocesses and adds the model response to history: - Assistant
Let me look at
_make_requestmethod to understand how the response is stored: - Assistant
Let me look at
_finish_handlingand_append_response: - Assistant
Let me look at
_finish_handlingand_append_response: - Assistant
Now let me understand the actual problem. Let me write a script to reproduce the issue by looking at the Capability class and the test model:
- Assistant
Now I need to understand what happens when the
ModelResponsewithThinkingPartis mapped back to OpenAI format for subsequent requests. Let me check thesynthesize_local_tool_search_messagesfunction since it's called inprepare_messages: - Assistant
Let me look more carefully at the
_get_instruction_partsmethod: - Assistant
Let me check the
_get_instruction_partsmethod in the parent Model class: - Assistant
Let me now focus on understanding the specific issue. Let me create a reproduction script to trace the exact problem:
- Assistant
Now let me create a test to reproduce the exact issue. Let me look at the mock model to understand how to simulate DeepSeek's behavior:
- Assistant
Let me look at the TestModel to understand how tests simulate model responses:
- Assistant
Let me look at the TestModel to understand how it handles thinking parts:
- Assistant
Let me find the TestModel class:
- Assistant
Let me look at the DeepSeek profile to understand the full configuration:
- Assistant
Now I understand the problem. Let me create a reproduction script to trace the exact issue:
- Assistant
I need to set up the environment properly. Let me check if there's a virtual environment or if I need to install the package.
- Assistant
Let me use the venv python.
- Assistant
Let me write a script to reproduce the issue. The key thing I want to test is how message history is mapped when using defer_loading with a model that has reasoning_content (like DeepSeek).
The problem likely occurs in
_map_model_response/_MapModelResponseContext. When the model responds withThinkingPart+ToolCallPart(for load_capability), this gets stored in message_history. Then on the next turn, when message_history is sent back to the API, theThinkingPartneeds to be converted back to thereasoning_contentfield.Let me write a test to trace what happens.
- Assistant
Let me understand how the profile is loaded and used in the mapping process:
- Assistant
Let me look at the
from_profilemethod to understand how it works: - Assistant
Let me now look at the existing DeepSeek tests and see if there's something we can learn:
- Assistant
Let me write a more targeted test that simulates the DeepSeek OpenAI model path:
- Assistant
- Assistant
Now let me understand why the mapping works correctly but the actual execution might fail. Let me look at the
prepare_messagesmethod and how it handles the streaming path: - Assistant
The mapping works correctly. Let me now trace through what happens in the
_prepare_requestmethod with the_clean_message_historyfunction, as that's the key path: - Assistant
Good, the mapping and cleaning both work. Let me now look at the streaming path since that's the default for
agent.run(). The streaming response processing might handle things differently: - Assistant
Let me look at the streaming response handling to understand how reasoning_content is accumulated:
- Assistant
Let me look at the streaming response class:
- Assistant
Let me look at the OpenAIStreamedResponse class and how it handles reasoning_content:
- Assistant
OK, the mapping is correct. Let me now look at the actual issue from a different angle. Let me check if the
openai_chat_send_back_thinking_parts='field'profile is being correctly used during streaming when the model also needs to handle tool search: - Assistant
Interesting! I can see that message [3] (the
ToolSearchCallPartresponse) is missingreasoning_content. This is a synthetic response generated by the tool search capability, not by DeepSeek. Let me check where this comes from: - Assistant
Let me look at the
_tool_search.pyto see how the tool search generates a ModelResponse: - Assistant
Found it! The
_tool_search.pybefore_model_requestmethod injects syntheticModelResponse(parts=[ToolSearchCallPart(...)])into the message history. These synthetic messages don't haveThinkingPart, so when they're mapped back to OpenAI format, they produce an assistant message withoutreasoning_content, which DeepSeek rejects.The fix should be in
_map_messages- when sending messages back to a model that usesopenai_chat_send_back_thinking_parts='field', we need to propagatereasoning_contentfrom the previous assistant message to any assistant message that lacks aThinkingPart. - Assistant
Now I understand the root cause. The
_tool_search.pybefore_model_requestinjects a syntheticModelResponse(parts=[ToolSearchCallPart(...)])into the message history. This synthetic message has noThinkingPart, so when mapped back to OpenAI format it produces an assistant message withoutreasoning_content. DeepSeek requiresreasoning_contenton all assistant messages when the model is in thinking mode.The fix should be in
_map_messages- after mapping all messages, propagatereasoning_contentfrom the last assistant message that had it to any subsequent assistant message that doesn't. Let me implement this: - Assistant
Now I've confirmed the exact issue. The fix should propagate
reasoning_contentto assistant messages that lack it when the model requires it. Let me implement this in_map_messages: - Assistant
Now let me implement the fix. I need to add post-processing in
_map_messagesto propagatereasoning_contentto assistant messages that lack it: - Assistant
Now let me implement the fix. I'll add a post-processing step in
_map_messagesto propagatereasoning_content: - Assistant
Now let me verify the fix works:
- Assistant
The fix works. Let me verify the exact change:
- Assistant
Good. Now let me run the existing tests to make sure the fix doesn't break anything:
- Assistant
All 200 OpenAI tests pass. Let me run the DeepSeek tests:
- Assistant
Let me also run the capability tests:
- Assistant
Let me also run the tool search and profile tests:
- Assistant
Let me also run the thinking-related tests:
- Assistant
All thinking tests pass. Let me now run the full test suite for the models:
- Assistant
Let me check what the failure is:
- Assistant
The failure is a pre-existing issue with HuggingFace Hub deprecation warnings, not related to my change. Let me verify:
- Assistant
The failure is from a HuggingFace test, not related to my change. Let me restore my fix:
- Assistant
Let me run the model tests excluding the pre-existing HuggingFace failure:
- Assistant
Let me check which test file contains the failing test:
- Assistant
Let me run the most relevant tests separately:
- Assistant
All 1108 relevant tests pass. Let me also run the core agent tests:
- Assistant
Let me check if this test failure is pre-existing:
- Assistant
Let me check the exact test name:
- Assistant
This is a pre-existing MCP module issue. Let me run the core tests excluding MCP:
- Assistant
Let me also skip the MCP-related tests:
- Assistant
All relevant tests pass. Let me verify the fix handles edge cases correctly by running a comprehensive test:
- Assistant
The fix handles all edge cases correctly. Let me also run the thinking wire contract tests:
- Assistant
All tests pass. Let me now verify the final diff:
- Assistant
Let me clean up the temp files and do a final comprehensive test:
- Assistant
Let me run a final comprehensive test suite:
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.