AD SPACE AVAILABLE · BRAND PARTNERS WELCOME

Implementing Multi-Turn Function Calling and Strict Tool Schemas with the DeepSeek API

Geraldo Bracamontes Varga · 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

Building autonomous agents, automated database retrieval tools, and multi-step business workflows with large language models inevitably collides with a frustrating engineering reality: parameter drift, invalid JSON syntax, and dropped context across multi-turn tool interactions. When an agent invents non-existent parameters or forgets previous function call outputs mid-conversation, entire backend pipelines fail.

The DeepSeek API solves these reliability issues by supporting standard OpenAI-compatible tool calling while offering a dedicated Strict Mode via its Beta endpoint. By pairing strict: true schemas with an explicit conversational state machine, developers can eliminate parameter hallucinations and maintain deterministic multi-turn loops.

At 365Finds, our operational recommendation is straightforward: always enforce strict tool schemas on any DeepSeek workflow that mutates state, executes SQL, or integrates with third-party webhooks. Given DeepSeek's aggressive pricing model, spending pennies to guarantee schema integrity prevents costly runtime crashes.


1. The Engineering Pain Points in Tool Calling

In production systems, vanilla function calling models frequently suffer from three failure modes:

  1. Schema Drift and Parameter Hallucination: The model includes imaginary parameters, guesses property types, or omits mandatory fields under complex reasoning prompts.
  2. Context Rupture in Multi-Turn Loops: Backend engineers fail to properly round-trip the assistant's previous tool_calls payload along with the matching tool role responses, causing the model to lose the conversational thread or repeat identical calls.
  3. Reasoning State Eviction: When developers run DeepSeek's reasoning models (or models with thinking mode active), omitting the model's generated reasoning_content from subsequent requests causes immediate 400 Bad Request API rejections.

DeepSeek provides structural guarantees against these failures through constrained decoding at the API level, provided your client properly defines schemas and maintains message continuity.


2. Enabling Strict Tool Schemas (strict: true)

DeepSeek's Strict Mode enforces that model-generated function arguments adhere strictly to your JSON Schema definition down to the exact field name and type.

Two Mandatory Configuration Requirements

To activate strict schema enforcement:

  1. Target the Beta Endpoint: Your client must set base_url to https://api.deepseek.com/beta (or /v1/beta depending on your SDK layer).
  2. Flag Functions with "strict": true: Each function definition object inside your tools list must explicitly include "strict": true.

Schema Constraints in Strict Mode

When strict: true is enabled, DeepSeek applies rigid validation rules:

Example: Strict Tool Definition in Python

tools = [
    {
        "type": "function",
        "function": {
            "name": "lookup_customer_order",
            "description": "Fetch order status and shipping history from the relational database.",
            "strict": True,  # Enables DeepSeek strict schema validation
            "parameters": {
                "type": "object",
                "properties": {
                    "customer_id": {
                        "type": "string",
                        "description": "The unique customer UUID, e.g. 'cust_982341'."
                    },
                    "order_status": {
                        "type": "string",
                        "enum": ["pending", "shipped", "delivered", "cancelled", "all"],
                        "description": "The order fulfillment status filter."
                    },
                    "limit": {
                        "type": "integer",
                        "description": "Maximum number of order records to retrieve (1-50)."
                    }
                },
                "required": ["customer_id", "order_status", "limit"],
                "additionalProperties": False
            }
        }
    }
]

If the model attempts to generate an extraneous parameter or returns a string for limit, DeepSeek's constrained decoding catches the violation before token emission, guaranteeing valid JSON parsing on your server.


3. The Multi-Turn Tool Interaction Lifecycle

Function calling does not run external code on DeepSeek's infrastructure. The API acts as an orchestrator: it outputs structured calling instructions, expects your application to execute the business logic, and ingests the results in an unbroken message chain.

[User Query]
      │
      ▼
[DeepSeek API Request] ─── (messages + tools)
      │
      ▼
[Model Returns tool_calls]
      │
      ├── 1. Append Assistant Message (with tool_calls & reasoning_content) to history
      │
      ├── 2. Parse arguments & Execute local function(s)
      │
      ├── 3. Append Tool Response Messages (role="tool", matching tool_call_id)
      │
      ▼
[DeepSeek API Continuation] ─── (accumulated history)
      │
      ├── Model invokes further tools (Return to step 1)
      └── OR Model outputs final user answer (Complete)

Essential Rules for Message Chain Preservation

  1. Keep the Assistant Message Intact: You must append the full assistant message object returned by response.choices[0].message directly to your messages array before adding tool outputs.
  2. One tool Message Per tool_call: If the model invokes multiple functions in parallel, your code must iterate through each item in tool_calls and append a corresponding message with role: "tool", tool_call_id: <tool_call.id>, and the stringified execution output.
  3. Preserve tool_call_id Precision: Mismatched or dropped IDs break the reference graph and result in an API error.

4. The reasoning_content Trap in Thinking Mode

A distinctive feature of DeepSeek models is the reasoning trace. When reasoning is active (such as with deepseek-reasoner or newer unified models operating in thinking mode), the response contains a dedicated reasoning_content field alongside content and tool_calls.

Critical Rule: If an assistant message generated in thinking mode contained reasoning_content, you must pass that exact reasoning_content back to the DeepSeek API in subsequent turns.

If your backend uses an abstraction layer or client gateway that sanitizes incoming dictionaries by stripping non-standard OpenAI fields, DeepSeek will return:

HTTP 400 Bad Request: The reasoning_content in the thinking mode must be passed back to the API.

365Finds Architectural Recommendation


5. Complete Production Implementation

Below is a complete, runnable Python script using the standard openai SDK pointing to DeepSeek's Beta endpoint. It demonstrates strict schema validation, parallel tool execution, and defensive message preservation across multi-turn loops.

import os
import json
from openai import OpenAI

# 1. Initialize client pointing to DeepSeek Beta endpoint
client = OpenAI(
    api_key=os.environ.get("DEEPSEEK_API_KEY", "your-api-key"),
    base_url="https://api.deepseek.com/beta"
)

# 2. Define mock backend services
def fetch_inventory(sku: str, warehouse: str) -> dict:
    stock_db = {
        ("SKU-990", "us-east"): {"available": 42, "status": "in_stock"},
        ("SKU-990", "eu-central"): {"available": 0, "status": "out_of_stock"}
    }
    return stock_db.get((sku, warehouse), {"available": 0, "status": "unknown_warehouse"})

def check_customer_tier(customer_id: str) -> dict:
    tiers = {"CUST-101": "platinum", "CUST-102": "standard"}
    return {"customer_id": customer_id, "tier": tiers.get(customer_id, "standard")}

# 3. Define strict tool schemas
tools = [
    {
        "type": "function",
        "function": {
            "name": "fetch_inventory",
            "description": "Check stock counts for a specific SKU in a designated regional warehouse.",
            "strict": True,
            "parameters": {
                "type": "object",
                "properties": {
                    "sku": {
                        "type": "string",
                        "description": "Product stock keeping unit, e.g. SKU-990"
                    },
                    "warehouse": {
                        "type": "string",
                        "enum": ["us-east", "eu-central", "ap-southeast"],
                        "description": "Warehouse region code"
                    }
                },
                "required": ["sku", "warehouse"],
                "additionalProperties": False
            }
        }
    },
    {
        "type": "function",
        "function": {
            "name": "check_customer_tier",
            "description": "Retrieve customer loyalty tier to evaluate expedited fulfillment eligibility.",
            "strict": True,
            "parameters": {
                "type": "object",
                "properties": {
                    "customer_id": {
                        "type": "string",
                        "description": "Customer identifier string, e.g. CUST-101"
                    }
                },
                "required": ["customer_id"],
                "additionalProperties": False
            }
        }
    }
]

# Dispatch map for local execution
TOOL_REGISTRY = {
    "fetch_inventory": fetch_inventory,
    "check_customer_tier": check_customer_tier
}

def run_agent_turn(conversation_messages: list, model: str = "deepseek-flash") -> str:
    """
    Executes a multi-turn tool calling loop until the model reaches a terminal response.
    """
    max_steps = 5  # Guardrail against infinite loops
    step = 0

    while step < max_steps:
        step += 1
        
        # Call DeepSeek API
        response = client.chat.completions.create(
            model=model,
            messages=conversation_messages,
            tools=tools,
            tool_choice="auto"
        )
        
        assistant_message = response.choices[0].message
        
        # Step A: Append assistant response (preserving tool_calls and reasoning_content)
        conversation_messages.append(assistant_message)
        
        # Step B: Check if model requests tool execution
        if not assistant_message.tool_calls:
            # Model generated final text output
            return assistant_message.content
        
        # Step C: Handle all requested tool calls (including parallel calls)
        for tool_call in assistant_message.tool_calls:
            func_name = tool_call.function.name
            func_args_str = tool_call.function.arguments
            
            try:
                func_args = json.loads(func_args_str)
                handler = TOOL_REGISTRY.get(func_name)
                
                if handler:
                    execution_result = handler(**func_args)
                else:
                    execution_result = {"error": f"Function {func_name} not implemented"}
            except Exception as e:
                execution_result = {"error": f"Tool execution failed: {str(e)}"}
            
            # Step D: Append tool message matching specific tool_call_id
            conversation_messages.append({
                "role": "tool",
                "tool_call_id": tool_call.id,
                "content": json.dumps(execution_result)
            })

    return "Agent aborted: maximum tool interaction steps reached."

# Execution demonstration
if __name__ == "__main__":
    messages = [
        {
            "role": "user",
            "content": "Can customer CUST-101 get expedited delivery on SKU-990 from both us-east and eu-central warehouses?"
        }
    ]
    
    final_answer = run_agent_turn(messages)
    print("\n--- Final Assistant Response ---")
    print(final_answer)

6. Architectural Comparison & Best Practices

Implementation DimensionStandard DeepSeek Tool CallingStrict Beta Tool Calling (strict: true)
API Endpointhttps://api.deepseek.comhttps://api.deepseek.com/beta
Parameter ConformanceBest-effort; prone to hallucinating optional keysGrammatically enforced; zero unexpected keys
Schema StrictnessStandard JSON Schema; optional keys permittedAll keys mandatory in required; additionalProperties: false
Failure ModeClient-side deserialization or validation errorsModel constrained during generation
Ideal WorkloadRapid prototyping; loose explorationTransactional workflows; database queries; production agents

Operational Checklist for Engineers


References