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 and understanding how deferred capabilities and DeepSeek reasoning content are handled.
- Assistant
Let me search for deferred loading and reasoning_content handling in the codebase.
- Assistant
rg is not available, let me use grep instead.
- Assistant
Let me examine how DeepSeek handles reasoning content and the deferred capability loader.
- Assistant
I'll inspect the deferred capability loader and how thinking parts get mapped when history is sent back.
- Assistant
Let me look at how DeepSeek model profile handles thinking and how messages are mapped when tool responses follow assistant messages with reasoning.
- Assistant
Let me examine the OpenAI message mapping for thinking parts and search for related deferred capability history behavior.
- Assistant
Let me dig into how load_capability interacts with message history and look for related tests or recent fixes.
- Assistant
I'll look at deferred loading tests and how capability load events modify the message stream.
- Assistant
Let me check recent thinking-related commits and how messages get mapped for load_capability turns.
- Assistant
I need to inspect how tool/load-capability call parts are mapped for OpenAI chat, and whether thinking parts can get lost.
- Assistant
I'll inspect capacity loading history handling and message transformations more carefully.
- Assistant
I'll inspect OpenAI message mapping and the DeepSeek model profile next.
- Assistant
Let me check how the DeepSeek model is constructed and what system name is used for ThinkingParts.
- Assistant
Let me try to reproduce the issue with a mock model and inspect how history is sent back.
- Assistant
I'll inspect the DeepSeek tests and how thinking content is handled during multi-turn tool calls.
- Assistant
Let me examine how loaded capability instructions are injected into the conversation.
- Assistant
Let me search for code that might strip or filter ThinkingParts around capabilities.
- Assistant
I'll look for tests combining tools + thinking and check how message history is cleaned.
- Assistant
I'll check the changelog and deferred-tools docs for clues about this regression.
- Assistant
I'll look for DeepSeek-specific thinking mode configuration and how requests are built.
- Assistant
Let me check cassettes and DeepSeek V4-related code/docs for how thinking is transmitted.
- Assistant
I'll write a reproduction script that mocks the DeepSeek API and captures the messages sent during deferred capability loading.
- Assistant
I'll find where tool call parts get narrowed to LoadCapabilityCallPart and whether that might drop thinking.
- Assistant
Let me look at models/init.py around line 729 for how narrowing happens.
- Assistant
I'll create a mock-based reproduction to inspect whether reasoning_content is included in subsequent API calls.
- Assistant
I'll fix the import and rerun the reproduction script.
- Assistant
I'll enable model requests and rerun the reproduction.
- Assistant
Found the issue: an auto-injected
search_toolsassistant message has noreasoning_content. I'll locate that injection path. - Assistant
I'll open the deferred tool-search auto-load implementation next.
- Assistant
I'll scroll to the auto-load section of the tool search capability.
- Assistant
I'll inspect how OpenAI Responses replaces or wipes synthetic tool-search exchanges, and check related tests.
- Assistant
I'll look for tests around auto-loaded capability tools and any provider-side special casing.
- Assistant
I'll inspect the capability tests covering the synthetic tool-search exchange.
- Assistant
I'll check how conversation-level thinking presence is detected, and whether empty reasoning_content is already handled.
- Assistant
Another approach: inject ThinkingPart into the synthetic ModelResponse when the model is in thinking mode. But
before_model_requesthas access torequest_contextandctx.model. I think the core issue is that DeepSeek's chat completions endpoint is strict about thereasoning_contenttoken block—it must be echoed back exactly in the message history for subsequent turns, but Pydantic AI's capability runner (whendefer_loading=True) drops or fails to serialize thatThinkingPartduring the graph loop. Settingdefer_loading=Falseworks because the full thinking flow stays in the model response path.The
before_model_requesthook looks promising for injectingThinkingParton-the-fly, but it would couple us to OpenAI-specific profiles (likeopenai_chat_thinking_field), which isn't ideal. Instead, the cleanest fix is at the OpenAI message mapping layer in_map_messages, where we can detect when aModelResponsehas tool calls but lacks thereasoning_contentfield after a thinking turn has already occurred. - Assistant
I'll inspect how discovered tool names are parsed from history; that determines how tightly we couple to the synthetic exchange.
- Assistant
I've confirmed the root cause: auto-injected
search_toolsmessages after deferred capability loads lackreasoning_content. I'll fix mapping so thinking-field providers get that padding once thinking has started. - Assistant
I'll check imports at the top of openai.py, then apply the fix.
- Assistant
I'll apply the message-mapping fix next.
- Assistant
I'll remove the duplicate profile assignment left over from the edit.
- Assistant
I'll remove the duplicate
else:that broke the control flow. - Assistant
I'll re-run the reproduction to verify the synthetic search_tools message now includes reasoning_content.
- Assistant
I'll run the relevant OpenAI thinking/DeepSeek tests to check for regressions.
- Assistant
I'll run DeepSeek and deferred capability tests next.
- Assistant
I'll add a temporary unit test covering the padding behavior and edge cases.
- Assistant
I'll fix the temporary test script and toggle again.
- Assistant
I'll review the final diff and run a broader smoke test on the OpenAI model suite.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.