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 structure to understand the codebase and then find the relevant files related to capabilities and deferred loading.
Assistant
Let me explore the capabilities module to understand the structure.
Assistant
Let me look at the deferred capability loader toolset and how it processes messages during the execution loop.
Assistant
Now let me look at the thread executor and how the graph loop works, since the issue is about the graph loop dropping
reasoning_content:Assistant
Let me look at the abstract capability, especially the
wrap_runmethod:Assistant
Let me look at the
_pending_messages.pyandwrapper.pycapabilities:Assistant
Let me look at the agent graph to understand the execution loop:
Assistant
Let me look at the
_deferred_capabilities.pyandparse_loaded_capabilities:Assistant
Now let me look at the OpenAI model adapter, since DeepSeek uses the OpenAI-compatible API:
Assistant
Now let me look at the
MapModelResponseContext.map_assistant_messageand how ThinkingPart is mapped back:Assistant
Let me look at the ModelRequestNode and CallToolsNode in the agent graph:
Assistant
Let me look at the CallToolsNode.run method:
Assistant
Let me search for where load_capability / capability-load is handled in the message processing:
Assistant
Let me look at how the model response is built from the API response, including the thinking/reasoning content:
Assistant
Let me search for places that might filter or manipulate ThinkingPart in relation to capabilities or tool calls:
Assistant
Let me look at how the
process_tool_callsfunction works and whether it strips ThinkingPart from the model response. Let me look at the tool_manager.Actually, let me step back and think about this issue from the perspective of what happens when
defer_loading=True. The deferred capability loader wraps the toolset. When the model callsload_capability, this is a tool call. The tool returns instructions. Then a new request is made.The crucial thing: the model response that contains the
load_capabilitytool call ALSO containsreasoning_content(ThinkingPart). This response is in the message history. When the next request is made, this assistant message should be mapped back with thereasoning_contentfield.So why would it be dropped? Let me look at whether there's something that reconstructs or replaces the model response when a
load_capabilitycall happens.Let me look at the
_handle_tool_calls->process_tool_callsflow and how theload_capabilitytool is treated. Specifically, theLoadCapabilityCallPartis a typed subclass ofToolCallPart. Let me check whether there's special handling that reconstructs the model response.Assistant
Let me look at the
process_tool_callsfunction:Assistant
Let me look at the instrumentation capability, since it wraps the DeferredCapabilityLoader:
Assistant
Let me look at how the tool search synthesizes messages, since there might be a similar mechanism for capability-load:
Assistant
Let me look at the
_split_responsefunction and check git history for recent changes related to thinking/reasoning and deferred capabilities:Assistant
Let me look at the tests for deferred capabilities and the OpenAI model with reasoning/thinking:
Assistant
Let me look at how DeepSeek is configured and reproduce the issue. Let me check the DeepSeek provider:
Assistant
Let me look at the test mock setup for OpenAI:
Assistant
Let me look at the MockOpenAI and completion_message helpers:
Assistant
Now I have enough understanding. Let me write a reproduction script using a mock OpenAI client with a DeepSeek-like profile:
Assistant
Let me create the reproduction as a proper test file in the tests directory so imports work:
Assistant
Interesting! The reproduction reveals a
search_toolsauto-load mechanism. Let me see the full output:Assistant
I can now see the issue. When
load_capabilityis called, the framework synthesizes an auto-loadsearch_toolsassistant message that has NOreasoning_content. Let me find where this auto-load mechanism is:Assistant
Let me look at the ToolSearchToolset and how discovered tools are tracked:
Assistant
Let me look at the tests for this synthetic search exchange to understand its purpose:
Assistant
Let me look at the tests around the synthetic exchange to understand its purpose and constraints:
Assistant
Let me check the git history for the synthetic exchange and look at the test at line 3602:
Assistant
Let me check how
discovered_tool_namesis used beyond tool visibility:Assistant
Let me read the on-demand capabilities design doc to understand the intent:
Assistant
Let me check how the Anthropic model handles the synthetic ToolSearchCallPart to see if there's special handling:
Assistant
Let me check the git history of the synthetic exchange code:
Assistant
Let me check if OpenAIChatModel overrides prepare_messages and how it handles tool search:
Assistant
Let me look at how the OpenAI Responses model maps ToolSearchCallPart, to understand the native handling:
Assistant
Let me look at
_refresh_discovered_tool_namesand how loaded capabilities relate to discovered tools:Assistant
Let me search for existing tests that combine reasoning/thinking with deferred capabilities or tool search:
Assistant
Let me check if there are OpenAI Chat wire tests that check the synthetic search exchange on the wire:
Assistant
Let me look at the OpenAIModelProfile defaults for the thinking send-back settings:
Assistant
Let me read the full OpenAI Chat
_map_messagesmethod:Assistant
Let me look at
_map_user_messageto understand how tool returns are mapped:Assistant
Let me check usages of
_map_user_messageand the_guard_tool_call_idsignature:Assistant
Let me check the streaming path to ensure
_map_messagescovers it:Assistant
Let me confirm the imports and view the exact lines to modify:
Assistant
Let me check which providers set
openai_chat_send_back_thinking_parts='field':Assistant
Now I understand the issue well. Let me first restore my test file to a clean version, then implement the fix:
Assistant
Now let me implement the fix. First, let me find a good location for the helper functions:
Assistant
Let me add helper functions after
_merge_leading_system_messages. Let me open the file:Assistant
Now let me add the helper functions after
_merge_leading_system_messages:Assistant
I accidentally removed a blank line. Let me fix that and add the helper functions properly:
Assistant
Let me fix the missing blank line between thefunctions:
Assistant
Now let me modify
_map_messages. Let me find its current location:Assistant
My edit broke the function signature. Let me fix it by replacing the broken section:
Assistant
Now let me modify
_map_user_messageto accept and use theomit_tool_call_idsparameter:Assistant
There are leftover duplicate lines (1609-1618). Let me remove them:
Assistant
There's a duplicate
if file_content:line. Let me fix it:Assistant
Now let me verify
AbstractSetis imported:Assistant
I need to add
AbstractSetto the imports:Assistant
Now let me verify the file compiles and run my reproduction test:
Assistant
AbstractSetis incollections.abc? Let me check. Actually,collections.abc.AbstractSetshould exist. Let me verify. In Python 3.13,collections.abc.AbstractSetexists. Wait, the error says it can't import. Hmm. Let me check.Actually,
AbstractSetis exported fromcollections.abc. Let me double check.Actually wait — maybe it's a name issue. In
collections.abc, the class isSet(AbstractSet is an alias). Let me check:collections.abc.Setexists. Andcollections.abc.AbstractSet? Let me verify. Actually,collections.abchas bothSetandAbstractSet? Let me check.Assistant
AbstractSetisn't incollections.abc. Let me revert that import and usefrozenset[str]instead:Assistant
Now let me change the param type to
frozenset[str]:Assistant
Now let me verify the file imports correctly and run my reproduction test:
Assistant
The helper is called with
ModelMessagewhich could be aModelRequest. Let me add an isinstance check:Assistant
Now let me add the
isinstance(message, ModelResponse)check in the helper body:Assistant
Now let me run my reproduction test again:
Assistant
The fix works. Let me verify the wire no longer has the synthetic message while history still retains it:
Assistant
Let me put the verification inside the test file instead:
Assistant
Both tests pass. Now let me run the existing test suites to ensure I haven't broken anything:
Assistant
All existing tests pass. Let me clean up my temporary test file and run a few more relevant test suites:
Assistant
The 3 failures are due to a missing
mcppackage (environment issue), unrelated to my change. Let me confirm:Assistant
The test name resolution failed; the failures were from collection. Let me just confirm the 3 failing tests are MCP-related (collection errors due to missing
mcp), not related to my change. The error wasModuleNotFoundError: No module named 'mcp'fromtests/mcp_server.py. These are environment issues unrelated to my change.Let me verify by running the specific failing tests with the mcp module check. Actually, the failures were
test_explicit_mcp_server,test_implicit_mcp_server,test_parallel_mcp_servers— all MCP tests that need themcppackage. These fail at collection becausetests/mcp_server.pyimportsmcp.Let me confirm
mcpisn't installed and that this is pre-existing by running just those tests.Assistant
The MCP failures are pre-existing environment issues (missing
mcppackage), unrelated to my change. Let me verify DeepSeek usesOpenAIChatModel(so my fix applies):Assistant
Confirmed:
deepseek:resolves toOpenAIChatModel, so my fix applies. Let me run a few more relevant test suites:Assistant
Let me review the final diff to ensure it's clean:
Assistant
Let me check if
count_tokensor other paths call_map_messagesor_map_user_message:Assistant
The fix is correctly scoped to
OpenAIChatModel. Let me run a few more model test files related to message mapping to be thorough:Assistant
Let me reconsider the comment — I referenced a made-up issue number. Let me make it accurate without a specific issue URL:
Assistant
Let me remove the made-up issue URL reference since I can't verify the number:
Assistant
Let me re-create the repro test temporarily to confirm the fix still works after edits, then remove it:
Assistant
Both tests pass — confirming the fix is targeted (drops the synthetic exchange only for field-mode providers like DeepSeek, preserving behavior for other models). Let me clean up the temporary test file:
Assistant
Let me run the OpenAI model tests once more to confirm everything is green after all edits:
Assistant
All 1074 tests pass. Let me do a final lint/compile check:
Assistant
Let me do a final review of the complete diff:
Assistant
The diff is clean and complete. Let me run one final comprehensive check on the most relevant test suites to be certain nothing is broken:
Assistant
All 1307 tests pass. Let me verify there are no leftover temporary files:
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.