大模型网摘deepseek.wang

Tutorials · 2026-10-25

DeepSeek Function Calling in Python: Teaching V4-Pro to Call Your Functions

Function calling is what turns an LLM from a chat box into an agent that acts: the model decides when to call and with what arguments, your code actually executes. This walkthrough uses the DeepSeek API (OpenAI-compatible) with deepseek-v4-pro to build a minimal working loop. For pricing and channel selection see our V4-Pro-0813 access guide; if you are setting up a key for the first time, start with the Python quickstart.

Setup

Install the OpenAI SDK and configure your key (the DeepSeek API speaks the OpenAI wire format):

pip install openai
export DEEPSEEK_API_KEY="your-key"

Step 1: define and declare a tool

Tools are described with JSON Schema — name, purpose and parameters. Here is a weather lookup:

import json
import os
from openai import OpenAI

client = OpenAI(
    api_key=os.environ["DEEPSEEK_API_KEY"],
    base_url="https://api.deepseek.com",
)

tools = [{
    "type": "function",
    "function": {
        "name": "get_weather",
        "description": "Get current weather for a city",
        "parameters": {
            "type": "object",
            "properties": {
                "city": {"type": "string", "description": "City name, e.g. Beijing"},
            },
            "required": ["city"],
        },
    },
}]

def get_weather(city: str) -> str:
    # Swap in your real data source; sample returns fixed values
    return json.dumps({"city": city, "temp_c": 22, "cond": "cloudy"})

Step 2: handle the tool_calls loop

When the model returns tool_calls, run the function and feed results back as role=tool messages until it answers in plain language:

messages = [{"role": "user", "content": "What's the weather in Beijing? What should I wear?"}]

while True:
    resp = client.chat.completions.create(
        model="deepseek-v4-pro",
        messages=messages,
        tools=tools,
        temperature=0,
    )
    msg = resp.choices[0].message
    messages.append(msg)
    if not msg.tool_calls:
        print(msg.content)
        break
    for tc in msg.tool_calls:
        args = json.loads(tc.function.arguments)
        result = get_weather(args["city"])
        messages.append({
            "role": "tool",
            "tool_call_id": tc.id,
            "content": result,
        })

Three common pitfalls

Arguments are strings, not objects — function.arguments comes back as a JSON string, so always json.loads it. Always return tool results — if you re-request without feeding results back, the model will simply call the tool again. Descriptions drive accuracy — the more specific your description fields, the lower the odds of wrong-tool picks or malformed arguments; include value examples when in doubt.

Where to go next

Once a single tool works, try parallel multi-tool calls, wire tools to real data sources, or combine with live retrieval for a real-time QA agent — we previously built a lightweight web-QA agent with the Search and Fetch APIs, and the two compose into a full RAG-plus-tools stack. For image inputs, see the vision tutorial.