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 and then find the relevant files related to the issue.
Assistant
Let me explore the repository structure first.
Assistant
Let me explore the structure further.
Assistant
Let me explore the deferred capabilities files and understand how they work.
Assistant
Let me look at the process_history and process_event_stream capabilities, and the deferred_tool_handler. The issue is about
reasoning_contentbeing dropped when defer_loading=True. Let me look at how the message history is processed.Assistant
Let me look at the
_pending_messages.pyandprepare_tools.pyfiles, and the toolset_deferred_capability_loader.pyto understand how messages are processed.Assistant
Let me look at the toolset
_deferred_capability_loader.pyto understand how deferred capabilities work.Assistant
Now let me look at the
_agent_graph.pyto understand the graph loop and where messages are processed.Assistant
Let me look at the openai.py model around the reasoning_content handling.
Assistant
Let me look at how the ThinkingPart is serialized back in the chat completions request.
Assistant
Let me look at the chat completions
_map_messagesat line 1445.Assistant
Now let me look at the
_map_model_responsefunction which maps a ModelResponse to a chat completion message.Assistant
So the OpenAI chat completions
_map_model_responsedoes handle the ThinkingPart correctly, sending thereasoning_contentback. So the serialization to DeepSeek API works.The issue says when
defer_loading=True, the reasoning_content is dropped. This means the ThinkingPart is being dropped somewhere in the deferred capability loading path. Let me look at the_pending_messages.py- no, that's the pending message drain.Let me look at the capabilities process_event_stream, thread_executor and how deferred capabilities might intercept. Actually, the key phrase in the issue is "the graph loop intercepted by PydanticAI's capability runner seems to drop or fail to serialize/propagate the reasoning_content token block back to DeepSeek's chat completions endpoint."
Let me look at the
process_event_stream.pyand how deferred capabilities process the event stream / history.Assistant
Let me look at the abstract capability and how the capability runner works in the agent graph. Let me search for "capability" in the
_agent_graph.py.Assistant
Let me look at the
_clean_message_historyfunction and the area around line 2220.Assistant
Let me look at the area around line 858-1010 where the capability hooks are dispatched during the model request.
Assistant
Let me look at
model.prepare_messagesfor the OpenAIChatModel.Assistant
Let me look at the tests for deferred capabilities to understand the flow better.
Assistant
Let me look at the CallToolsNode and how it processes tool calls, particularly around line 1100-1200.
Assistant
Let me look at
reinject_system_prompt.pyand how the load_capability return is processed.Assistant
Let me look at the
_tool_search.pyin capabilities and thesynthesize_local_tool_search_messages.Assistant
Let me look at the DeepSeek provider profile.
Assistant
Let me check the
ToolSearchCallPartandToolSearchReturnPartclasses in messages.py.Assistant
Let me write a reproduction script to understand the message serialization. First, let me check the test setup.
Assistant
Let me try using uv to set up the environment.
Assistant
Now let me write a reproduction script that simulates the DeepSeek flow with deferred capabilities and captures the serialized request to check whether reasoning_content is sent back.
Assistant
The mock needs proper response objects. Let me take a more targeted approach - directly test the
_map_messagesserialization with a constructed message history that mimics the deferred capability loading flow.Assistant
My manual test shows
reasoning_contentIS sent back correctly. So the serialization logic works. The issue must be that the ThinkingPart is dropped from the message history before reaching_map_messages. Let me run the full agent flow with a proper mock using real openai types. Let me look at how tests mock the openai client.Assistant
Let me look at the
MockOpenAI.create_mockandcompletion_messagehelpers.Assistant
Now I have the mock infrastructure. Let me write a reproduction that uses MockOpenAI with DeepSeek provider and reasoning_content, and uses deferred capabilities. I need to make the mock return a sequence of completions, each with reasoning_content and tool calls.
The issue is that
ChatCompletionMessagemay not supportreasoning_contentas a constructor arg. Let me check the mock_xai.py to see how reasoning_content is set.Assistant
Let me check how the openai model tests set reasoning_content for chat completions.
Assistant
Let me look at the test around line 4480 to understand the reasoning_content send-back test with tool calls.
Assistant
Now let me write a full reproduction with a mock that returns a sequence of completions using the DeepSeek provider.
Assistant
Let me create a self-contained mock in the repro script instead of relying on test imports.
Assistant
In my reproduction, the reasoning_content IS being sent back correctly. So my repro doesn't reproduce the bug with this exact flow. Let me look more closely at
synthesize_local_tool_search_messagesand how the synthetic exchange interacts with the history.Assistant
My reproduction preserves reasoning_content. Let me look more carefully at the actual node run flow to understand when messages get appended to history. Let me look at the ModelRequestNode and UserPromptNode run methods.
Assistant
Let me look at the
_make_requestmethod around lines 780-860.Assistant
My reproduction preserves reasoning_content. Let me check the git log for recent changes in this area to understand the current state.
Assistant
Let me look at
tool_defs_for_loaded_capabilitiesto understand when the synthetic exchange is added.Assistant
Let me look at the git history of the
ToolSearch.before_model_requestto understand its purpose.Assistant
Let me look at
_refresh_discovered_tool_namesand howdiscovered_tool_namesis used.Assistant
Let me look at
parse_discovered_toolsto understand what populatesdiscovered_tool_names.Assistant
Let me search for how
discovered_tool_namesis used across the codebase.Assistant
Let me look at the
_run_context.pyto understanddiscovered_tool_namesandavailable_tool_names.Assistant
Let me look at the
ToolSearchToolset.get_toolsto understand howdiscovered_tool_namesandloaded_capability_tool_namesinteract.Assistant
Let me look at the tests for the synthetic search_tools exchange behavior.
Assistant
Let me search for tests that test the synthetic exchange for capability loads.
Assistant
Let me look at the cross-provider capability replay test to understand when the synthetic exchange is needed.
Assistant
Let me look at the parametrization of the cross-provider capability replay test.
Assistant
Let me look at the test around line 3605 that uses
_NoNativeToolSearchModel.Assistant
Let me look at the docs for on-demand capabilities to understand the intended behavior of the synthetic exchange.
Assistant
Let me look at the actual docs file to understand the design intent.
Assistant
Let me look at the
test_two_deferred_capabilities_loaded_sequentiallytest which uses_NoNativeToolSearchModel.Assistant
Let me check FunctionModel's
supported_native_toolsto understand if it supports native tool search.Assistant
Let me check whether any test using
_NoNativeToolSearchModel(local path) asserts the synthetic search_tools exchange in the message history.Assistant
Let me look at the commit that added the synthetic exchange to understand its exact purpose.
Assistant
Let me examine how the synthetic search_tools exchange is serialized for native providers by looking at a cassette.
Assistant
Let me check the OpenAI Chat model profile's
supported_native_toolsand how it's determined.Assistant
Let me check which provider pairs are in
_FIRST_TURN_EXPECTED.Assistant
Let me look at the Google first-turn expected trace to see if it includes the synthetic search_tools exchange.
Assistant
Let me look at the
_narrow_tool_call_partsfunction to see if it affects ThinkingPart.Assistant
Let me write a more faithful reproduction where the mock validates like DeepSeek-reasoner would (raising 400 if an assistant message with tool_calls lacks reasoning_content).
Assistant
I've reproduced the exact error. The synthetic
[assistant] search_toolsmessage (no reasoning_content) triggers DeepSeek-reasoner's validation. Let me check Google'ssupported_native_toolsto understand the local path.Assistant
Let me check the Google cassette to see if the synthetic search_tools exchange is in the request sent to Google.
Assistant
Let me look at
build_run_contextand howRunContext.messagesrelates toctx.state.message_history.Assistant
Let me look at the resume turn expected trace for google→openai-responses.
Assistant
Let me look at the
OpenAIModelProfileto understand theopenai_chat_send_back_thinking_partsfield and its defaults.Assistant
Let me check the Moonshot and gpt-oss profiles to understand the thinking field setup.
Assistant
Let me check which models subclass OpenAIChatModel and whether they override
prepare_messages.Assistant
Let me search for any OpenAI Chat (non-Responses) tests or cassettes that involve the synthetic search_tools exchange.
Assistant
Let me look at the test that uses the openai-chat tool search eval cassette.
Assistant
The
test_tool_search_evaltest usesopenai-chat:gpt-5.4-mini. This test uses REAL search_tools calls (the model calls search_tools to discover tools). It does NOT use deferred capabilities (load_capability). So the synthetic search_tools exchange is NOT involved here (no capability loading).Let me verify by checking the openai-chat eval cassette for auto_load (synthetic) vs search_tools (real).
Assistant
The
test_tool_search_evaltest uses REAL search_tools calls (0auto_load, 14search_tools), not the synthetic exchange. So omitting the synthetic exchange for reasoning models won't affect it. Let me look at the imports in openai.py to implement the fix.Assistant
Let me check whether
OpenAIChatModel.count_tokenscalls_map_messages.Assistant
Let me look at the OpenAIChatModel
requestmethod around line 899-990.Assistant
Let me search for any test that uses OpenAI Chat with
load_capabilityor deferred capabilities.Assistant
Let me check if OpenAIChatModel has a
count_tokensmethod.Assistant
Let me check the imports in openai.py for
replaceandModelRequest.Assistant
replace,ModelRequest,ModelResponse,ToolSearchCallPart,ToolSearchReturnPartare all imported. Now let me view the exact start of_map_messagesto add the strip.Assistant
Let me view the full
_map_messagesto see whereprofileis computed.Assistant
Now let me implement the fix. First, let me view the lines just before
_map_messagesto find a good place for the helper method.Assistant
Now let me implement the fix. Let me open the file at the relevant line.
Assistant
Now let me implement the fix. I'll add a helper method and modify
_map_messagesto strip the synthetic tool-search exchange for reasoning models.Assistant
Now I need to remove the duplicate
profile = OpenAIModelProfile.from_profile(self.profile)that was later in_map_messages. Let me find it.Assistant
The edit looks good. Now let me verify the fix works with my reproduction script.
Assistant
The fix works. Let me verify that the synthetic exchange is stripped from the request but kept in the message history.
Assistant
The fix works perfectly:
- The captured requests no longer have the synthetic
search_toolsassistant message. - Real model messages retain their
reasoning_content. - The synthetic exchange is KEPT in the message history (for cross-provider replay).
Now let me test edge cases: a non-reasoning model should NOT strip, and a real (model-emitted) search_tools call should NOT be stripped.
- The captured requests no longer have the synthetic
Assistant
For non-reasoning models (gpt-4o), the synthetic exchange is NOT stripped (preserving existing behavior). Now let me verify a REAL (model-emitted) search_tools call is NOT stripped, while the synthetic one IS. Let me write a unit test for the helper.
Assistant
All edge cases pass. The fix correctly distinguishes synthetic (no provider info) from real (with provider info) search_tools exchanges. Now let me run the existing tests to make sure I didn't break anything.
Assistant
All tests pass. Let me also run tests for models that subclass OpenAIChatModel (Groq, OpenRouter, Ollama, Cerebras, Moonshot).
Assistant
All tests pass. Let me check whether the xAI model (which uses reasoning_content) subclasses OpenAIChatModel and whether my fix affects it.
Assistant
The XaiModel has its own
_map_messages(doesn't subclass OpenAIChatModel), so it's unaffected — and the issue is specifically about DeepSeek. My fix covers OpenAIChatModel and all its subclasses (DeepSeek, Moonshot, Groq, OpenRouter, Ollama, Cerebras). Let me run a broader set of tests.Assistant
All tests pass. Let me also verify the streaming path works with the fix.
Assistant
The streaming mock needs async context manager support. Let me fix it.
Assistant
The streaming path also works correctly. Let me clean up the temp files and run a final broad test to ensure nothing is broken.
Assistant
All tests pass. Let me review my final changes to ensure they're clean and correct.
Assistant
The diff is clean. Let me verify
_get_instruction_partsdoesn't depend on the synthetic exchange (since it's called with the stripped messages).Assistant
The fix is safe —
_get_instruction_partsusesmodel_request_parameters.instruction_partsin the normal agent flow (not the messages). Let me check whether the XaiModel (Grok, which also usesreasoning_content) would have the same issue, since it has its own_map_messages.Assistant
XaiModel (Grok) also doesn't support native tool search and is a reasoning model, so it could have the same issue. Let me look at its
_map_response_partsto confirm.Assistant
XaiModel (Grok) has its own adapter and could have a similar issue, but the issue is specifically about DeepSeek (which uses
OpenAIChatModel). My fix coversOpenAIChatModeland all its subclasses (DeepSeek, Moonshot, Groq, OpenRouter, Ollama, Cerebras). Let me run a few more relevant tests to be thorough.Assistant
All tests pass. Let me do a final review of the complete diff.
Assistant
The diff is clean. Let me do a final verification recreating the exact issue scenario to confirm the fix resolves it.
Assistant
The fix resolves the issue. Let me verify no temp files remain and submit.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.