DeepSeek 网摘deepseek.wang
EN
📄 查看英文原文

API · 2026-04-25 · 机器翻译,仅供参考

DeepSeek API Function Calling on V4: A Practical Guide

API·April 25, 2026·By DS Guide Editorial
DeepSeek API 函数-calling tutorial card showing the five steps of the V4 tool-call loop: describe 函数s in the tools array using JSON Schema, post the user message to chat completions, inspect tool_calls in the response, run the 函数 in your own code, and send the result back as a tool role message — supported in both non-thinking and thinking mode.

您希望模型获取实时数据、调用您的内部服务或通过自己的代码链式调用步骤——而不是凭空猜测答案。这正是DeepSeek API函数调用的目的,在V4上,它通过您已在其他地方使用的相同OpenAI兼容的`tools`数组工作。行为在2025年底发生了实质性变化,并在2026年4月24日的V4预览中再次变化:工具使用现在可以在思维模式下工作,严格模式在两种模式下都得到支持,而传统的`deepseek-chat`和`deepseek-reasoner` ID正在倒计时。本指南将介绍请求形状、完整的Python循环、严格模式、思维模式工具调用、错误处理以及一个计费的工作示例,以便您无惊喜地交付。

DeepSeek API函数调用实际上是什么

Diagram of DeepSeek API 函数 calling cycle from LLM to tool_call to app to tool_result and back

函数调用——DeepSeek的文档中“工具调用”和“函数调用”可以互换使用——是一种合约:您在JSON Schema中描述一个或多个函数,发送用户消息,然后模型决定是直接回答还是返回结构化的工具调用请求。该功能让模型决定何时请求外部函数而不是直接回答;模型可以生成工具请求,但您的应用程序仍然需要执行该函数并将结果发送回来。您的后端是执行层;模型永远不会自行接触您的API或数据库。

这种分离很重要。模型提出建议;您的代码处理。如果您忘记将工具的输出发送回下一个请求,对话就会停滞。

V4模型ID以及函数调用如何适用

The current generation is DeepSeek V4 (Preview),发布于2026年4月24日。它作为两个具有相同功能集的开源混合专家模型发货: deepseek-v4-pro (1.6T total / 49B active) and deepseek-v4-flash (284B / 13B 活跃). 两者都暴露了对OpenAI兼容的工具调用 POST /chat/completions endpoint at https://api.deepseek.com。DeepSeek API使用与OpenAI/Anthropic兼容的API格式;通过修改配置,您可以使用OpenAI/Anthropic SDK或与OpenAI/Anthropic API兼容的软件来访问DeepSeek API。

旧版ID仍然暂时有效。模型名称deepseek-chat和deepseek-reasoner将于2026年7月24日被弃用;为了兼容性,它们分别对应于DeepSeek-V4 Flash的非思考模式和思考模式。如果您维护的是旧版集成,迁移只需一行代码。 model= swap — 基础URL未变。

Model ID Tier Tool calling 思维模式工具 严格模式
deepseek-v4-pro Frontier Yes Yes 是(Beta)
deepseek-v4-flash Cost-efficient Yes Yes 是(Beta)
deepseek-chat (legacy) Routes to V4-Flash Yes 否(非思维模式) Yes
deepseek-reasoner (legacy) Routes to V4-Flash Yes Yes Yes

两个旧ID的退休: 2026-07-24 15:59 UTC之后,使用它们的请求将失败。相应地制定计划。要查看每个模型的更详细地图,请参阅助手消息中的数组。 DeepSeek V4 概览及 DeepSeek V4-Flash 等级页面。

快速入门:最小工具调用

The wire format matches OpenAI's exactly. Define tools in the 线格式与OpenAI的完全匹配。在以下定义工具: tools 数组,发送请求,检查 消息工具调用, 在您的代码中运行该函数,然后将结果返回作为 tool 角色消息。以下是标准的Python流程,它路由到 deepseek-v4-pro 非思考模式:

from openai import OpenAI

client = OpenAI(
    api_key="<your api key>",
    base_url="https://api.deepseek.com",
)

tools = [
    {
        "type": "函数",
        "函数": {
            "名称": "get_weather",
            "描述": "Get weather of a location, the user should supply a location first.",
            "参数": {
                "type": "object",
                "properties": {
                    "location": {
                        "type": "string",
                        "描述": "The city and state, e.g. San Francisco, CA",
                    }
                },
                "必需": ["location"],
            },
        },
    }
]

def send(messages):
    resp = client.chat.completions.create(
        model="deepseek-v4-pro",
        messages=messages,
        tools=tools,
    )
    return resp.choices[0].message

messages = [{"role": "user", "content": "How's the weather in Hangzhou?"}]
msg = send(messages)
tool = msg.tool_calls[0]
messages.append(msg)
messages.append({"role": "tool", "tool_call_id": tool.id, "content": "24°C"})
final = send(messages)
print(final.content)

The execution flow: the user asks about the weather in Hangzhou, the model returns the 函数 call get_weather({location: ‘Hangzhou’}), your code calls the 函数 and provides the result to the model, and the model returns in natural language, “The current temperature in Hangzhou is 24°C.” If you have not picked up an API key yet, the get a DeepSeek API key 操作演示需要几分钟;更广泛的OpenAI-shaped流程将在 DeepSeek OpenAI SDK compatibility.

请求和响应的形状

三个请求字段驱动行为:

  • tools — 一组函数描述符。每个都有 类型: "函数" and a 函数 object with 名称, 描述,以及一个JSON模式 参数 block.
  • tool_choice — controls invocation. “none” means the model will not call any tool and instead generates a message; “auto” means the model can pick between generating a message or calling one or more tools; “required” means the model must call one or more tools; specifying a particular tool via {“type”: “函数”, “函数”: {“名称”: “my_函数”}} forces the model to call that tool.
  • 严格 — set inside a 函数 descriptor to enforce the schema.

在响应端,当模型想要调用一个工具时,它返回 finish_reason: "tool_calls" and a tool_calls 调用函数的参数以JSON格式返回,由模型生成;请注意,模型并不总是生成有效的JSON,并且可能会产生您函数模式中未定义的参数——在调用函数之前,请在您的代码中验证这些参数。始终使用严格模式。 json.loads(tool.函数.arguments) 在 try/except 中。

严格模式:强制执行模式

严格模式是一个Beta功能,它在服务器上关闭了验证循环。在严格模式下,模型在输出工具调用时严格遵循函数的JSON模式要求,确保模型的输出符合用户的定义;它支持思考模式和非思考模式。服务器将验证用户提供的函数的JSON模式。

要启用它,请将 "严格": true to the 函数 definition and lock the schema down — usually that means setting additionalProperties: false:

{
  "type": "函数",
  "函数": {
    "名称": "get_weather",
    "严格": true,
    "描述": "Get weather of a location.",
    "参数": {
      "type": "object",
      "properties": {
        "location": {"type": "string"}
      },
      "必需": ["location"],
      "additionalProperties": false
    }
  }
}

如果您的模式使用DeepSeek的严格验证器不支持的数据类型,请求将在模型运行之前出错——这很有用,因为它在部署时而不是对话中揭示了模式错误。 DeepSeek API JSON mode 当您需要不带工具调用的纯 JSON 输出时。

思考模式下的函数调用

Editor and terminal showing DeepSeek V4-Pro 函数 calling combined with thinking mode emitting a tool call after reasoning.

思考模式曾经是一个独立的模型。在 V4 中,它是一个请求参数:传递 reasoning_effort="high" (or "max") 加上 extra_body={"thinking": {"type": "enabled"}} 与V4模型配对。从DeepSeek-V3.2开始,API支持在思考模式下使用工具。DeepSeek模型的思考模式支持工具调用;在输出最终答案之前,模型可以进行多次推理和工具调用,以提高响应质量。

一个不明显的规定会让大多数初次集成遇到麻烦:与不涉及工具调用的思维模式中的转折不同,对于执行工具调用的转折,推理内容必须在所有后续请求中完全传递回API;如果您的代码没有正确传递推理内容,API将返回400错误。

这意味着在调用思考模式工具后,你附加回的助手消息必须包含 messages 。模式看起来像这样: reasoning_content alongside the final content. The pattern looks like this:

messages.append({
    "role": "assistant",
    "content": resp.choices[0].message.content,
    "reasoning_content": resp.choices[0].message.reasoning_content,
    "tool_calls": resp.choices[0].消息工具调用,
})

在思维模式中还有两件事需要了解:思维模式不支持温度、top_p、存在惩罚或频率惩罚参数——为了与现有软件兼容,设置这些参数不会触发错误,但也不会产生任何效果。如果您需要温度控制(DeepSeek建议代码为0.0,数据分析为1.0,一般聊天为1.3,创意写作为1.5),请保持非思维模式。如果 DeepSeek prompt engineering 指南深入探讨温度默认值。

多工具、多轮循环

真实的工作流程串联工具。模型可能会调用 get_date,获取答案,然后调用 get_weather 并传入该日期。每次往返都是一个单独的请求,因为 API是无状态的 ——DeepSeek不会记住之前的回合;你每次都必须重新发送完整的 messages 数组。Web聊天会为你保存历史记录;API不会。一个健壮循环的形状:

  1. 发送消息和工具。
  2. If finish_reason == "tool_calls": parse arguments, run each 函数, append tool results, loop.
  3. If finish_reason == "stop": 返回 content 给用户。
  4. 将循环限制在5-10次迭代以内,以防止调用失控。

关于一个带有重试和日志记录的工作流程的端到端循环,请参阅 DeepSeek API code examples;对于更复杂的编排故事,教程通过LangChain的工具节点连接了相同的模式。 DeepSeek with LangChain 在生产中出现了三种故障模式:

Error handling patterns

无效的JSON参数。

  • 包装 。在失败时,发送一个包含错误字符串的消息,并让模型重试。 json.loads on tool.函数.arguments幻觉参数或未知工具名称。 tool 在调度之前,验证
  • Hallucinated 参数 or unknown tool 名称s. 是否与您的注册表匹配。 tool.函数.名称 against your registry before dispatching.
  • 思维模式下400 在工具调用之后。几乎总是缺失 reasoning_content 在附加的助手消息上。

其他状态码遵循在以下文档中记录的标准模式 DeepSeek API error codes。速率限制——当大规模循环工具时相关——在 DeepSeek API rate limits reference.

工具调用工作负载的成本

工具调用会倍增请求,因为每个工具往返都是全新的 POST /chat/completions。在三个令牌桶中分摊成本 在提交预算之前,查看页面缓存输入、非缓存输入、输出。跳过非缓存行是最常见的算术错误。

工作示例, deepseek-v4-flash一个代理进行了1,000,000次调用。每次调用都有一个2,000个token的系统+工具模式前缀(第一次命中后缓存),一个200个token的用户/工具消息(对该前缀的非缓存未命中),以及一个300个token的响应。

  • Cached input: 2,000 × 1,000,000 = 2.0B tokens × $0.0028/M = $5.60
  • Uncached input: 200 × 1,000,000 = 200M tokens × $0.14/M = $28.00
  • Output: 300 × 1,000,000 = 300M tokens × $0.28/M = $84.00
  • Total: $117.60

The same workload on deepseek-v4-pro at the 75% promo through 2026-05-31 costs $7.25 + $87.00 + $261.00 = $355.25 (列表价格:$29.00 + $348.00 + $1,044.00 = $1,421.00)——在促销期间大约是Flash的3倍,在列表价格上是10倍。当编码或代理工作的基准提升足以证明支出合理时使用Pro;否则默认使用Flash。思维模式是最大的成本杠杆:非思维模式完全跳过推理跟踪,并以大约V3.2的速度返回token;思维模式启用一个额外的token成本推理块,但可以提高代码和数学的准确性;思维模式最大值产生DeepSeek头版表中的分数,也消耗最多的token,并且是唯一需要384K+上下文预算的模式。价格截至2026年4月——请在上 DeepSeek API pricing 。 DeepSeek context caching 文档解释了缓存命中率是如何自动应用的。

流式工具调用

Set stream=true SDK产生delta数据块。工具调用参数逐个到达,作为 delta.tool_calls[*].函数.arguments ——将它们累积成一个字符串,并在工具调用完成后解析。当处于思维模式时,推理跟踪会单独流式传输;delta.reasoning_content字段携带它们,您可以在UI中显示它们或丢弃它们。 DeepSeek API streaming 引用具有完整的delta累加器。

Anthropic兼容的替代方案

IDE showing Python tool definitions and a DeepSeek API call with a tools list for 函数 calling

DeepSeek还提供了一个与Anthropic兼容的接口,针对相同的基URL——如果你的代码库已经支持Anthropic,这将非常有用。在该接口中调用的工具使用Anthropic的 输入模式 形状,而不是OpenAI的 参数。每个服务选择一个接口并保持一致性;在生态系统中,OpenAI的接口支持更广泛。

何时使用工具调用

当答案依赖于模型无法获取的数据时,调用工具才能发挥其价值:实时价格、客户的订单、今天的日历、必须精确的计算。如果你只需要结构化输出,则过度使用。当你需要跨多个步骤进行真正的决策和规划时,这是错误的选择;这时,思考模式工具调用加上受限的工具注册表才能发挥作用。

对于更广泛的API模式和规范,该 DeepSeek API docs and guides 中心索引从认证到webhooks的所有内容。

DeepSeek AI Guide is an independent resource and is not affiliated with DeepSeek or its parent company. Model IDs, pricing and API behaviour change; check the official DeepSeek documentation and pricing page before committing to a production decision.

DeepSeek API函数调用是如何工作的?

您发送一个 tools JSON Schema描述你的函数的数组。模型决定是直接回答还是返回一个包含函数名和JSON参数的 tool_calls 数组。你的代码执行该函数,并将结果附加为 角色:"工具" 发送消息,并重新发送完整对话。API是无状态的,因此历史记录必须包含在每次请求中。请参阅 DeepSeek API documentation 以获取完整的模式。

DeepSeek工具调用中的严格模式是什么?

严格模式是一个Beta标志,它强制模型的工具调用输出完全符合您的函数JSON模式。设置 "严格": true 在函数定义中,服务器预先验证模式。它支持思考和未思考模式。当不规范的参数会破坏下游代码时使用它。如果助手消息在下一个请求中返回,或者API返回400错误,则非工具思考会静默地丢弃跟踪。请参阅V4思考模式指南 DeepSeek API best practices 指南涵盖了模式设计。

DeepSeek能否在思考模式下调用工具?

是的,在V4模型上。设置 reasoning_effort="high" with extra_body={"thinking": {"type": "enabled"}}. 关键规则:当一个思考环节产生一个工具调用时,你必须回显 reasoning_content 以强制调用;函数描述过于模糊,模型无法将意图映射到模式;或者您正在使用已弃用的路由。请检查 DeepSeek V4-Pro page.

为什么我的函数调用返回空的tool_calls?

三种常见原因: tool_choice 是隐含的 "自动" 并且模型决定文本已足够——设置 "必需" 和OpenAI Python或Node SDK,它们可以在不更改代码的情况下与DeepSeek一起工作。官方OpenAI SDK通过基础URL覆盖使用;包括LangChain、LlamaIndex和DSPy在内的所有现有OpenAI兼容包装器也都可以使用。完整的兼容性说明位于 DeepSeek API error codes 状态码模式的参考。

函数调用是否与OpenAI SDK兼容?

是的——设置 base_url="https://api.deepseek.com" and the OpenAI Python or Node SDK works against DeepSeek without code changes. The official openai SDK works with a base-URL override; every existing OpenAI-compatible wrapper, including LangChain, LlamaIndex, and DSPy, also works. Full compatibility notes live in the DeepSeek OpenAI SDK compatibility guide.

来源s & Methodology

Last source check: April 30, 2026

Primary sources

Technical references

Methodology

价格数据已与官方DeepSeek定价页面核对,并使用样本令牌使用场景进行标准化,估算每月成本。实际成本可能因缓存、输入/输出比率、区域可用性和提供商更新而有所不同。

Data confidence

High — figures checked directly against the official pricing page on the review date.

Editorial note

DeepSeek偶尔会推出促销折扣,这些折扣并不总是反映在首页标题中。本站上的定价数据集每月自动刷新;本文反映了上述日期所示的数据集。