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
Now let's find
_map_model_responsemethod to see its exact structure:Assistant
Now let's implement the fix in
_map_messages:Assistant
Now let's add the
_backfill_missing_reasoning_contentstatic method right before_map_messages:Assistant
Now let's run the reproduction script again against
_map_messagesto confirm the fix:Assistant
The
search_toolssynthetic assistant message now carriesreasoning_content: "". Now let's run the full end-to-end reproduction usingFunctionModelto make sure the whole agent loop runs fine, and check existing test suites don't break.Assistant
Now let's run existing test suites related to this area to make sure nothing broke:
Assistant
All tests pass. Let's run the full test suite for models/openai chat related tests plus a broader sanity check, and also test with the OpenAI-compatible providers (openrouter, groq etc. using OpenAIChatModel) to ensure no regression:
Assistant
Let's now also run a broader test to be safe (full test suite for models + agent + capabilities), and check thinking-related tests too:
Assistant
All pass. Now let's run the full test suite to be thorough (may take a while):
Assistant
This failure is unrelated to our change (environment/network issue with
outlines/llama_cppdownloading a model). Let's skip that test file and continue running the rest of the suite:Assistant
Progressing well with no failures so far. Let's keep waiting.
Assistant
Confirmed - this failure is pre-existing/unrelated to our change (fails even without our patch, likely a sqlite/dbos environment issue when run standalone in this sandbox). Let's restore our changes.
Assistant
Good, our change is restored. All the dbos/temporal failures are pre-existing environment issues unrelated to our fix. Let's now view the final diff to review:
Assistant
Good — all standard TypedDict keys are covered in
_known_keys. Now let's check pyright/lint compliance for this file:Assistant
Let's remove the unnecessary pyright ignore comment:
Assistant
Clean. Let's also run ruff/lint check and re-run the relevant tests once more after this tweak:
Assistant
Now let's re-run our end-to-end reproduction one more time to confirm final state, and also test the streaming path (
_map_messagesis also used by streaming request path presumably):Assistant
Both scenarios behave correctly. Let's clean up any leftover background job / temp files and do a final review of the diff.
Assistant
This looks good. Let's do one final full targeted re-run to be sure everything's consistent:
Assistant
All good. Let's do the checklist review now.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.