AD SPACE AVAILABLE · BRAND PARTNERS WELCOME

Configuring DeepSeek API Multi-Turn Function Calling: Preserving reasoning_content and Enforcing Strict JSON Schemas

Lara Jorge Ricart · 365Finds Editorial
Indexed 88,650 Wiki articles

Put 365 Wiki to work with your AI

Copy the prompt below, paste it into the AI you already use, then ask your question.

Download full Skill

Try it with the prompt first. If you use 365 Wiki often, install the full 365Wiki Skill so you do not have to paste it again. No regular AI? Gemini or Microsoft Copilot on the web will work.

365Wiki Skill

When developers connect reasoning models like DeepSeek-R1 to automated agent pipelines, multi-turn function calling routinely fails at two critical choke points: client libraries silently strip the model's chain-of-thought, triggering an immediate HTTP 400 error, and unconstrained schemas produce hallucinated or malformed JSON arguments.

At 365Finds, our operational recommendation is decisive: always target DeepSeek's beta endpoint with strict: true enabled, and write an explicit message serializer that preserves reasoning_content across every tool-execution turn. Relying on vanilla OpenAI SDK abstractions or treating the beta endpoint as unstable experimental territory are common architectural errors that cause pipeline instability.


The Core Problem: Why Multi-Turn Agent Loops Crash

When DeepSeek operates in thinking/reasoning mode and detects that a tool is required, it returns a distinct payload structure:

  1. message.reasoning_content: Contains the chain-of-thought reasoning explaining why and how the tool must be called.
  2. message.tool_calls: Contains the target function name and the JSON string arguments.
  3. message.content: Remains null or an empty string, as the model pauses final output generation until the tool result arrives.

The HTTP 400 Trap

In standard multi-turn chat without tools, DeepSeek's API treats previous reasoning_content as optional and ignores it if echoed back. However, when the tools parameter is present in the request payload, DeepSeek enforces a strict protocol requirement: any preceding assistant message generated in thinking mode must retain its reasoning_content when echoed back into conversation history.

If your client library drops this custom field, DeepSeek’s gateway rejects the next roundtrip:

{
  "error": {
    "message": "The reasoning_content in the thinking mode must be passed back to the API.",
    "type": "invalid_request_error",
    "code": "invalid_request_error"
  }
}

Most generic wrappers—including vanilla LangChain adapters, custom chat memory stores, and standard openai library message serializations—strip unrecognized attributes when reassembling messages. As soon as the backend runs the function and submits the tool role message, the pipeline crashes.


Enforcing Strict JSON Schemas via the Beta Endpoint

Reasoning models excel at complex planning, but free-form JSON generation frequently slips into schema drift: inventing non-existent parameters, dropping mandatory attributes, or enclosing JSON inside Markdown code fences.

DeepSeek provides native Strict Mode (Beta) to force tool outputs to adhere strictly to your JSON Schema.

Configuration Requirements

To enforce strict validation, your integration must satisfy three conditions:

  1. Target the Beta Base URL: Point your client to https://api.deepseek.com/beta instead of the default root.
  2. Flag Functions with "strict": true: Add "strict": true inside each function specification within the tools list.
  3. Comply with Strict Schema Rules:
    • Every object level must set "additionalProperties": false.
    • Every key defined under properties must be listed in required: [...].
    • For optional fields, define union types such as ["string", "null"] with a null default, rather than omitting the property from required.

Production Implementation: Resilient Agent Loop with Pydantic

The following end-to-end Python implementation demonstrates how to use the OpenAI SDK with Pydantic V2 to automatically generate strict schemas, serialize reasoning_content, and handle tool execution with automated error recovery.

import json
import os
from typing import Any, Dict, List, Optional
from openai import OpenAI
from pydantic import BaseModel, Field, ValidationError

# 1. Initialize client targeting DeepSeek's Beta endpoint
client = OpenAI(
    api_key=os.environ.get("DEEPSEEK_API_KEY"),
    base_url="https://api.deepseek.com/beta",
)

# 2. Define business tools using Pydantic models with strict compliance
class DatabaseQueryInput(BaseModel):
    table_name: str = Field(description="Name of the target database table")
    query_filter: str = Field(description="SQL-style WHERE clause string")
    limit: Optional[int] = Field(default=10, description="Maximum number of rows to return")

# 3. Helper to format Pydantic models into DeepSeek-compliant strict tool schemas
def generate_strict_tool_schema(name: str, description: str, model_cls: type[BaseModel]) -> Dict[str, Any]:
    schema = model_cls.model_json_schema()
    
    # Enforce strict requirements: additionalProperties false and all properties required
    properties = schema.get("properties", {})
    required_keys = list(properties.keys())
    
    # Normalize optional fields to allow null if needed
    clean_properties = {}
    for key, val in properties.items():
        prop = val.copy()
        if "anyOf" in prop:
            prop["type"] = [item.get("type") for item in prop.pop("anyOf") if item.get("type")]
        clean_properties[key] = prop

    return {
        "type": "function",
        "function": {
            "name": name,
            "description": description,
            "strict": True,
            "parameters": {
                "type": "object",
                "properties": clean_properties,
                "required": required_keys,
                "additionalProperties": False,
            },
        },
    }

tools = [
    generate_strict_tool_schema(
        name="query_database",
        description="Query the internal analytics database with strict filtering.",
        model_cls=DatabaseQueryInput,
    )
]

# Mock backend execution
def execute_database_query(arguments: DatabaseQueryInput) -> str:
    return json.dumps({
        "status": "success",
        "rows": [
            {"id": 101, "name": "Enterprise Cluster Alpha", "status": "active"},
            {"id": 102, "name": "Staging Node Beta", "status": "idle"},
        ][:arguments.limit]
    })

# 4. Explicit DeepSeek message serializer to prevent dropped reasoning_content
def append_assistant_message(messages: List[Dict[str, Any]], assistant_message: Any) -> None:
    serialized = {
        "role": "assistant",
        "content": assistant_message.content or "",
    }
    
    # Critical: Preserve reasoning_content whenever present
    if hasattr(assistant_message, "reasoning_content") and assistant_message.reasoning_content:
        serialized["reasoning_content"] = assistant_message.reasoning_content
        
    if assistant_message.tool_calls:
        serialized["tool_calls"] = [
            {
                "id": tc.id,
                "type": tc.type,
                "function": {
                    "name": tc.function.name,
                    "arguments": tc.function.arguments,
                },
            }
            for tc in assistant_message.tool_calls
        ]
        
    messages.append(serialized)

# 5. Multi-turn execution loop
def run_agent_loop(prompt: str) -> str:
    messages: List[Dict[str, Any]] = [
        {"role": "user", "content": prompt}
    ]

    max_turns = 5
    for turn in range(max_turns):
        response = client.chat.completions.create(
            model="deepseek-reasoner",
            messages=messages,
            tools=tools,
            tool_choice="auto",
        )
        choice = response.choices[0]
        assistant_msg = choice.message

        # Append assistant response ensuring reasoning_content is preserved
        append_assistant_message(messages, assistant_msg)

        # If no tools invoked, return final answer
        if not assistant_msg.tool_calls:
            return assistant_msg.content or "Task completed without text response."

        # Execute each requested tool call
        for tool_call in assistant_msg.tool_calls:
            tool_id = tool_call.id
            func_name = tool_call.function.name
            raw_args = tool_call.function.arguments

            # Resilient Pydantic parsing with automated error feedback
            if func_name == "query_database":
                try:
                    parsed_args = DatabaseQueryInput.model_validate_json(raw_args)
                    tool_output = execute_database_query(parsed_args)
                except ValidationError as val_err:
                    # Feed validation errors back to model for self-correction
                    tool_output = json.dumps({
                        "status": "error",
                        "validation_error": val_err.errors(),
                        "hint": "Ensure arguments strictly match required types."
                    })
                except Exception as exc:
                    tool_output = json.dumps({"status": "error", "error": str(exc)})
            else:
                tool_output = json.dumps({"status": "error", "message": f"Unknown tool: {func_name}"})

            # Append tool result to context
            messages.append({
                "role": "tool",
                "tool_call_id": tool_id,
                "content": tool_output,
            })

    return "Agent loop exceeded maximum iterations."

if __name__ == "__main__":
    prompt = "Look up active enterprise clusters in our internal analytics database."
    print("Agent Result:", run_agent_loop(prompt))

365Finds Institutional Judgments & Trade-offs

Engineering ChoiceDefault / Common Practice365Finds RecommendationStrategic Rationale
API Base URLDefault https://api.deepseek.comhttps://api.deepseek.com/betaThe beta endpoint introduces strict schema parsing; non-strict execution burns 2-3x more tokens on re-prompts when schemas drift.
Message SerializationGeneric model_dump() or ORM storeCustom serialization preserving reasoning_contentStandard client libraries drop vendor-specific keys, causing unavoidable HTTP 400 gateway rejections in multi-turn tool loops.
Reasoning ScopeRetain all CoT across unlimited turnsPrune older reasoning once tool executions resolvePreserving intermediate thinking is mandatory during active tool turns, but storing 10+ turns of CoT rapidly saturates token budgets.
Thinking Mode UsageKept enabled for all agent callsDisable thinking for simple deterministic routingIf a tool call involves direct 1:1 parameter mapping, disable thinking mode (thinking: {"type": "disabled"}) to cut latency by up to 70%.

Operational Trade-off: Context Budgets vs. Prompt Caching

Feeding reasoning_content back into the context window increases the total token count of the request. However, DeepSeek's architecture utilizes aggressive prompt caching. Because message history prefixes remain consistent across multi-turn tool invocations, cached tokens receive substantial cost discounts (up to 90% off standard input token rates).

The primary bottleneck is not financial cost, but context window exhaustion. In complex workflows spanning more than 5 tool turns, intermediate thinking processes can generate 15,000 to 30,000 tokens of reasoning. If your pipeline hits context constraints, 365Finds recommends pruning reasoning_content from completed earlier steps while strictly preserving it on the immediate predecessor turn of the current active tool exchange.

References