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 find the relevant files related to the issue.
Assistant
Let me look at how the deferred capability loader works and how it processes messages, particularly looking for where reasoning_content might be dropped. Let me look at the wrapper.py and the process_history for deferred capabilities.
Assistant
Let me look at how the OpenAI model (which DeepSeek uses) handles reasoning_content and the message serialization.
Assistant
Now let me look at how messages are serialized back to the API. Let me search for the part that converts ModelResponse/ThinkingPart back to API requests.
Assistant
Let me look at the deferred capability loader toolset and pending messages handling.
Assistant
Now let me look at how the deferred capability loading interacts with the message history. The issue says the reasoning_content is dropped when
defer_loading=True. Let me look at the_pending_messages.pyand the process_history for deferred capabilities.Assistant
Let me search for where thinking parts might be dropped or filtered in the message history processing.
Assistant
Let me search for
_clean_message_historyand how the message history is processed before being sent to the model.Assistant
The
_clean_message_historydoesn't seem to drop ThinkingParts. Let me look at the model request context and the message processing more specifically. Let me look at lines around 280-300 and 920-960 of_agent_graph.py.Assistant
Let me look at how
prepare_messagesworks and the tool search synthesis that might split ModelResponse.Assistant
Let me look at how the
load_capabilitytool return is converted into instructions, as this seems to be the key difference.Assistant
Let me look at the
_deferred_capabilities.pyand how the load_capability return part is handled.Assistant
Let me search for where
LoadCapabilityReturnPartinstructions are converted into ModelRequest instructions.Assistant
Let me search for where the load_capability return instructions become InstructionPart on a ModelRequest.
Assistant
Let me look at how tool results are processed and where the load_capability instructions are turned into ModelRequest instructions.
Assistant
Let me look at how the load_capability return is processed. Let me look at process_tool_calls and the part of the graph that handles tool returns and converts instructions.
Assistant
Let me look at how the load_capability instructions become part of a ModelRequest - examining toolsets/abstract.py and the enqueue mechanism.
Assistant
Let me look at how the
load_capabilitytool result is converted into instructions on the next ModelRequest. Let me look at the toolsets/function.py and toolsets/abstract.py for howinstruction_partsare computed and how theload_capabilityreturn value gets turned into instructions.Actually, let me look at the function toolset to see if there's special handling for
capability-loadtool_kind.Assistant
Let me look at the
_enqueue.pyand how the load_capability result is processed into the next ModelRequest instructions.Assistant
Let me look at how the ModelRequestNode._prepare_request extracts instructions from the LoadCapabilityReturnPart.
Assistant
Let me look at the full
_map_messagesof the OpenAI chat model to understand how ThinkingPart is mapped.Assistant
Let me look at the existing tests for deferred capabilities to understand how they're tested and reproduce the issue.
Assistant
Let me look at the DeepSeek provider profile and the
openai_chat_send_back_thinking_partssetting.Assistant
Let me look at
_get_instruction_partsto understand how instructions are extracted.Assistant
Let me look at how the OpenAI tests mock the client to write a reproduction script.
Assistant
Let me find the MockOpenAI and completion_message helpers.
Assistant
Now I have enough info to write a reproduction script. Let me create one that simulates DeepSeek's reasoning_content with a deferred capability.
Assistant
Let me look at how the openai tests create function tool calls. Let me search.
Assistant
Now let me fix the repro script to use the proper Function import.
Assistant
I need to allow model requests. Let me set the env var.
Assistant
The
check_allow_model_requestsreads the module global. But there's a fixture that sets it. Let me look at the conftest. There's aPREFER_APIand the model checks the global. Actually, the issue is that the openai modelrequestcallscheck_allow_model_requests()which checks the global. But the conftest sets it to False during tests. My script setspydantic_ai.models.ALLOW_MODEL_REQUESTS = Truebut the openai model imports it. Let me check howcheck_allow_model_requestsis imported in openai.py.Actually it calls
check_allow_model_requests()function which reads the global in the models module. My settingpydantic_ai.models.ALLOW_MODEL_REQUESTS = Trueshould work since the function reads the module global at call time. But maybe the conftest is auto-loaded and sets it to False after my import. Let me check the conftest.Actually, wait, the issue is that pytest's conftest has a fixture that runs
override_allow_model_requests(False). But I'm running this as a plain script, not pytest. Let me check why ALLOW_MODEL_REQUESTS is False.Actually, let me look at the conftest to understand.
Assistant
The conftest sets
ALLOW_MODEL_REQUESTS = Falseon import. Let me move the override to after all imports.Assistant
I can see the issue now. Look at Request 1: the first assistant message (load_capability call) HAS
reasoning_content, but there's a second synthetic assistant message (search_tools call) with NOreasoning_content. Let me find where this auto-generatedsearch_toolscall comes from.Assistant
I found the root cause. The
ToolSearchToolset.before_model_requestappends a syntheticModelResponsewith aToolSearchCallPartbut NOThinkingPart. Let me look at the full file.Assistant
Let me look at the DeepSeek test cassettes to understand the expected message format with reasoning_content.
Assistant
Let me check how
ToolSearchCallPartis mapped in the OpenAI chat model.Assistant
Let me check the
ToolSearchCallPartclass definition and how it's serialized.Assistant
Let me find the
ToolSearchCallPart(local) class.Assistant
Let me run the repro with
defer_loading=Falseto compare the working case.Assistant
Let me check whether the synthetic search_tools exchange is persisted in the actual message history.
Assistant
The synthetic exchange IS persisted. Let me find where it's added to the persistent history after
before_model_request.Assistant
Let me look at how
message_historyis returned from_prepare_requestand persisted.Assistant
The synthetic exchange is persisted via
ctx.state.message_history[:] = messages(line 916). Now let me understanddiscovered_tool_namesand when the synthetic exchange is added.Assistant
Let me check whether the toolset also has a
before_model_requestthat adds the synthetic exchange.Assistant
Now let me look at the imports in the
_tool_search.pycapability file.Assistant
Let me search for any DeepSeek cassettes with tool calls to understand the expected multi-turn format.
Assistant
Let me look at the
ThinkingPartdefinition.Assistant
Let me look at the tests for the synthetic tool-search exchange to understand when it's added (native vs local).
Assistant
Let me search for existing tests combining deferred capabilities with thinking/reasoning, and look at the cross-provider replay test.
Assistant
Let me check the git history of the
_tool_search.pycapability to understand recent design changes.Assistant
Let me check how Anthropic creates ThinkingParts (whether they have signatures/ids) to refine the filter.
Assistant
Let me check how OpenAI Responses creates ThinkingParts (encrypted reasoning).
Assistant
Now I understand the root cause and the fix. Let me look at the exact
before_model_requestonce more and implement the fix.Assistant
Now let me implement the fix. First, update the imports to include
ThinkingPartandreplace:Assistant
Now let me modify the
before_model_requestto reuse reasoning parts:Assistant
Let me use the
editcommand to apply the fix. First, let me open the file.Assistant
Now let me run my reproduction script to verify the reasoning_content is now propagated to the synthetic message.
Assistant
The synthetic search_tools assistant message now carries
reasoning_content. Let me run the relevant test suites to make sure I haven't broken anything.Assistant
All passing. Let me run a broader set of related tests to be safe.
Assistant
Let me verify the gpt-oss (OpenRouter/Ollama) case is handled correctly by checking the profiles.
Assistant
OpenRouter has its own
_map_response_thinking_partthat handlesreasoning_details. Let me check_from_reasoning_detailand_into_reasoning_detailto understand the ThinkingPart shape for OpenRouter.Assistant
Let me look at
_into_reasoning_detailfor OpenRouter to ensure round-tripping works.Assistant
Let me run the OpenRouter and Ollama tests to ensure the fix doesn't break them.
Assistant
Let me check
synthesize_local_tool_search_messagesto ensure the ThinkingParts in the synthetic message aren't stripped.Assistant
Let me check whether there are existing tests combining reasoning with deferred capabilities that might assert message shapes.
Assistant
Let me run the test_agent.py tests around those ThinkingPart usages to be sure they pass.
Assistant
The 3 failures are due to a missing
mcpmodule (environment issue), not my change. Let me confirm these are pre-existing by stashing my change and re-running.Assistant
The 3 failures are pre-existing (missing
mcpmodule). Now let me verify edge cases. Let me test the thinking-tags case (where reasoning is folded into content withid='content') to ensure it's NOT reused.Assistant
The thinking-tags case correctly leaves the synthetic message unchanged (no stray tags). Let me view the final diff and clean up temp files.
Assistant
Let me check whether the cross-provider VCR/cassette tests actually ran or were skipped (they may need API keys).
Assistant
The cassette test passed, confirming my fix doesn't change the wire for non-reasoning providers. Let me run a few more relevant test files (thinking, profiles) to be thorough.
Assistant
Let me verify the DeepSeek profile for v4 models produces reasoning (to confirm the fix applies to the issue's exact model).
Assistant
The fix is complete. Let me run the most directly affected test files once more to confirm everything passes.
Assistant
Let me verify the module imports cleanly and there are no syntax/lint issues.
Assistant
Let me do a final review of the complete change.
Assistant
Let me check if there are other capabilities that synthesize
ModelResponsemessages (which might also drop reasoning_content).Assistant
Let me also check
_agent_graph.pyand other core files for syntheticModelResponsecreation that might drop reasoning.Assistant
Let me run the full models test directory to catch any regressions (excluding tests requiring live API keys where possible).
Assistant
Let me identify the 2 failures and 6 errors to check if they're pre-existing.
Assistant
The errors are all
UserWarning: Thelocal_dir_use_symlinksargument is deprecatedfrom huggingface_hub. These are environment-related (huggingface_hub version), not caused by my change. Let me confirm by checking the specific test files.Let me get the actual test names that failed/errored.
Assistant
The failures/errors are all in
tests/models/test_outlines.py(huggingface_hub deprecation + llamacpp). Let me confirm these are pre-existing by stashing my change.Assistant
All failures are pre-existing environment issues (huggingface_hub deprecation, llamacpp, missing
mcpmodule), confirmed by stashing. My change introduces no regressions.Let me do a final review of the complete fix and submit.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.