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 a ModelHTTPError: status_code: 400 during execution loop turns.
code
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_content produced during the thinking phase to be passed back exactly as-is in the subsequent conversation message history array. When defer_loading=True, the graph loop intercepted by PydanticAI's capability runner seems to drop or fail to serialize/propagate the reasoning_content token block back to DeepSeek's chat completions endpoint.
Setting defer_loading=False solves the issue, and the agent executes successfully.
Minimal, Reproducible Example
Python
Assistant
Now let me look at OpenAIChatModel._map_messages:
Assistant
Now let me check test_deepseek.py and the imports in openai.py:
Assistant
Now implementing. First, the profile flag:
Assistant
Now add the helper function and the prepare_messages override:
Assistant
Let me restructure for clean type narrowing:
Assistant
Now set the flag in the DeepSeek provider:
Assistant
Now add tests to tests/models/test_deepseek.py:
Assistant
The fold works; just the guessed digest differs. Fix the snapshot:
Assistant
All pass. Now run the broader affected suites and typecheck:
Assistant
All covered. Clean up and review the final diff:
Assistant
All checks pass and is clean. Here's a summary of the fix:
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
# 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
Python: 3.14
Pydantic AI: 1.106.0
LLM provider SDK: deepseek
Interface
No new interfaces are introduced.
git diff --check
Root cause
With Capability(..., defer_loading=True), after the model calls load_capability, ToolSearch.before_model_request records the unlocked tools as a synthetic tool-search exchange: a ModelResponse holding only a ToolSearchCallPart (search_tools call with an auto_load_* id), followed by a ModelRequest with the matching return. On the wire, that synthetic response becomes an assistant message with tool_calls but no reasoning_content — and DeepSeek's thinking mode rejects any assistant tool-call message passed back without its reasoning, producing the 400: "The reasoning_content in the thinking mode must be passed back to the API."
Fix (wire-level only; canonical message history is unchanged)
profiles/openai.py — new OpenAIModelProfile.openai_chat_requires_thinking_with_tool_calls flag documenting the provider constraint.
models/openai.py — OpenAIChatModel.prepare_messages() override (the documented hook for history shapes a provider can't ship): when the flag is set, _fold_synthetic_tool_search_responses() folds framework-synthesized tool-search-only responses (never came from a provider API — same criteria as _clean_message_history) into the nearest preceding model response, presenting the search_tools call as a parallel tool call on the model's own reasoning-bearing load_capability turn. The fold is skipped if anything other than tool returns sits in between (which would detach the call from its role: 'tool' result).
providers/deepseek.py — enables the flag for DeepSeek.
Resulting wire shape: assistant(reasoning_content, tool_calls=[load_capability, search_tools]) → tool(load return) → tool(discovered tools) — every assistant tool-call message carries its reasoning.
Tests (tests/models/test_deepseek.py)
Full mocked agent run with a deferred capability on deepseek-reasoner, asserting every wire assistant tool-call message carries reasoning_content, snapshotting the folded payload, and verifying the standalone synthetic exchange is preserved in result.all_messages() (folding is wire-only, so persisted-history semantics and prompt-cache-friendly replay are untouched).
Two edge-case tests via the public prepare_messages seam: no fold across a user prompt, and no fold when there's no preceding response. (Mock-based rather than VCR since the regression lives in the request body, which cassette matchers don't check.)
Verified: 1,616 tests pass across the deepseek, openai, capabilities, tool-search, agent, and subclass-model suites; pyright and ruff clean; new code paths fully covered including branch arcs.