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 trace capability deferred-loading execution and the OpenAI/DeepSeek message serialization path, then add the smallest fix that preserves reasoning blocks through capability loop turns. I’ll inspect repository conventions and relevant tests first, reproduce with a focused mock if possible, run affected tests, and review the final diff.
- Assistant
rgis unavailable in this environment, so I’ll usegrep/findand continue locating the implementation. - Assistant
The failure mechanism is in
ToolSearch.before_model_request: deferred capability loading inserts a synthetic assistant tool-search response after the model’s thinking response. OpenAI Chat serialization maps that synthetic assistant message withoutreasoning_content, which DeepSeek rejects. I’ll preserve the latest model response’s thinking parts on the synthetic response only when they exist; this leaves normal histories and existing snapshots unchanged while satisfying DeepSeek’s exact-field requirement. - Assistant
The source change is in place. The first test command failed before collection because the repository’s package path is not installed in the system interpreter; I’ll rerun with
PYTHONPATH=pydantic_ai_slim(and use the project virtual environment if needed), then inspect formatting and focused behavior. - Assistant
The focused capability and DeepSeek test suites pass (
722 passed), andgit diff --checkis clean. The fix is narrowly scoped: synthetic capability-load assistant messages now retain only the preceding model response’sThinkingParts, so no duplicate text/tool calls are introduced and behavior without reasoning is unchanged. I’ll submit the verified change now.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.