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

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

使用DeepSeek API SDK:OpenAI和Anthropic客户端

API·April 25, 2026·By DS Guide Editorial
DeepSeek API SDK tutorial card showing the five-step setup: there is no first-party DeepSeek SDK, install the official openai client or the official anthropic client, point base_url and api_key at the DeepSeek endpoint, and the same wrappers your codebase already uses — LangChain, LlamaIndex, the Vercel AI SDK — work without code changes.

您想从自己的代码中调用DeepSeek V4,并想知道您是否需要一个定制的客户端库,或者您已经信任的SDK是否可以使用。简答:没有第一方的“DeepSeek SDK”。DeepSeek API SDK的故事是DeepSeek故意镜像了两种现有的线格式——OpenAI的Chat Completions和Anthropic的Messages——因此官方的`openai`和`anthropic`包,以及大多数第三方包装(LangChain、LlamaIndex、Vercel AI SDK),只需更改`base_url`和`api_key`即可工作。本指南将介绍两个兼容的表面,截至2026年4月应使用的V4模型ID,一个工作的Python快速入门,重要的参数,两个计费的工作示例,以及在生产中会咬你一口的错误模式。

“DeepSeek API SDK”究竟是什么意思

Diagram of OpenAI软件开发工具包 and Anthropic SDK clients both pointing at the DeepSeek API via base_url config

DeepSeek不发布带有自己包名的品牌SDK。相反,该平台公开了两个与开发者已使用的格式相匹配的HTTP表面: OpenAI聊天完成 and Anthropic消息DeepSeek API使用与OpenAI/Anthropic兼容的API格式,通过修改配置,您可以使用OpenAI/Anthropic SDK或与OpenAI/Anthropic API兼容的软件来访问DeepSeek API。这意味着您安装的“SDK”仅仅是来自OpenAI或Anthropic的上游客户端,指向DeepSeek的基础URL,并使用DeepSeek API密钥。

两个实际后果:

  • 如果您的代码库已经调用OpenAI或Anthropic,切换到DeepSeek只需两行代码更改—— base_url and api_key.
  • 基于这些SDK构建的工具——LangChain、LlamaIndex、DSPy、Vercel AI SDK、评估工具如Promptfoo和Inspect——无需代码更改即可工作。官方的openai SDK可以通过base-URL覆盖使用,以及所有现有的OpenAI兼容包装,包括LangChain、LlamaIndex和DSPy,也都适用。

The current generation is DeepSeek V4,于2026年4月24日发布,以MIT许可证下两个开放权重的专家混合模型的形式发货: DeepSeek V4-Pro (1.6T total / 49B active parameters, frontier tier) and DeepSeek V4-Flash (284B / 13B 活跃,成本效益高)。两者均提供默认输出,并支持最多 1,000,000-token context window 的输出。 384,000 tokens 思考模式是一个请求参数,而不是一个独立的模型ID。

两个基本URL以及需要安装哪个SDK

两个端点,两种请求形状——选择与您已使用的SDK生态系统相匹配的一种。

Surface 基础URL 要安装的SDK 端点路径
兼容OpenAI https://api.deepseek.com (or /v1) pip install openai / npm install openai POST /chat/completions
兼容Anthropic https://api.deepseek.com/anthropic pip安装anthropic POST /v1/messages
测试版(FIM,前缀补全) https://api.deepseek.com/beta OpenAI软件开发工具包 POST /chat/completions

Chat requests hit POST /chat/completions, 兼容OpenAI的端点。DeepSeek增加了对Anthropic API格式的支持,基本URL为https://api.deepseek.com/anthropic。两个端点都接受相同的API密钥。使用与现有代码匹配的任一端点;除非有特定的便携性原因,否则不要编写同时击中两个端点的包装层。

快速入门:使用OpenAI软件开发工具包的Python

针对最小可行调用 deepseek-v4-flash 在非思考模式下。将您的密钥保存为 DEEPSEEK_API_KEY,然后运行以下Python代码片段:

from openai import OpenAI
import os

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

resp = client.chat.completions.create(
    model="deepseek-v4-flash",
    messages=[
        {"role": "system", "content": "You are a concise technical assistant."},
        {"role": "user", "content": "Summarise the OSI model in three bullets."},
    ],
    temperature=1.0,
    max_tokens=400,
    extra_body={"thinking": {"type": "disabled"}},  # V4 enables thinking by default; disable for the minimum viable non-thinking call
)
print(resp.choices[0].message.content)

要在V4模型上启用思考模式,添加 reasoning_effort="high" and the thinking 标志。当启用思考模式时,API返回 DeepSeek API documentation 将thinking-max描述为最密集的设置;它需要384K个token的输出预算。thinking_mode是最大的成本杠杆:非思考模式完全跳过推理跟踪,并以大约V3.2的速度返回token,思考模式启用一个额外的token成本但能提高代码和数学的准确性的推理块,而thinking_max在DeepSeek的标题表中生成分数——它也消耗最多的token,并且是唯一需要384K+上下文预算的模式。

resp = client.chat.completions.create(
    model="deepseek-v4-pro",
    messages=[{"role": "user", "content": "Plan a 5-step migration from V3.2 to V4."}],
    reasoning_effort="high",
    extra_body={"thinking": {"type": "enabled"}},
)
print(resp.choices[0].message.reasoning_content)  # the reasoning trace
print(resp.choices[0].message.content)            # the final answer

When thinking is enabled the API returns reasoning_content alongside the final content在V4上,往返 reasoning_content 对于任何助手产生的 tool_calls 条目——省略它将触发400错误。对于纯思考操作而不调用工具,V4不需要往返;旧版 deepseek-reasoner 拒绝 reasoning_content 输入,因此只有在针对该旧ID时才去除它。

在curl中的相同调用

curl https://api.deepseek.com/chat/completions 
  -H "Content-Type: application/json" 
  -H "Authorization: Bearer ${DEEPSEEK_API_KEY}" 
  -d '{
    "model": "deepseek-v4-pro",
    "messages": [
      {"role": "system", "content": "You are a helpful assistant."},
      {"role": "user", "content": "Hello!"}
    ],
    "thinking": {"type": "enabled"},
    "reasoning_effort": "high",
    "stream": false
  }'

快速入门:使用Anthropic SDK的Python

如果您的代码库已经使用Anthropic的 messages.create 形状,安装 anthropic 包和覆盖两个环境变量。配置ANTHROPIC_BASE_URL=https://api.deepseek.com/anthropic和ANTHROPIC_API_KEY,然后调用client.messages.create并设置model="deepseek-v4-pro"。

import anthropic

client = anthropic.Anthropic(
    base_url="https://api.deepseek.com/anthropic",
    api_key="...your DeepSeek key...",
)

message = client.messages.create(
    model="deepseek-v4-pro",
    max_tokens=1024,
    system="You are a helpful assistant.",
    messages=[{"role": "user", "content": "Hi, how are you?"}],
)
print(message.content)

两个特定于Anthropic表面的注意事项。首先,对等性不是1:1:DeepSeek表示端点忽略anthropic-beta和anthropic-version,忽略container、mcp_servers、metadata、service_tier、top_k和几个cache_control字段,支持思考但忽略budget_tokens,并忽略tool_choice中的disable_parallel_tool_use。其次,当你向DeepSeek的Anthropic API传递不受支持的模型名称时,API后端将自动将其映射到deepseek-v4-flash模型。如果你想要V4-Pro,请明确设置模型ID。

Legacy IDs and the migration window

旧代码中硬编码 deepseek-chat or deepseek-reasoner 仍然运行,但受时钟控制。DeepSeek API现在通过OpenAI ChatCompletions接口和Anthropic接口支持V4-Pro和V4-Flash;要访问它们,基本URL保持不变,模型参数应设置为deepseek-v4-pro或deepseek-v4-flash。两个旧版API模型名称deepseek-chat和deepseek-reasoner将于2026-07-24停止使用,在此期间它们分别指向deepseek-v4-flash的非思考和思考模式。硬切换时间是 2026-07-24 at 15:59 UTC; 之后,使用旧ID的请求将失败。

迁移是一行 model= 变更。基本URL不会移动。如果您维护的示例、仪表板或定价计算器仍然引用旧ID,请现在替换它们——参见 DeepSeek API documentation 用于规范映射。

关键参数

DeepSeek API SDK — parameters that matter

OpenAI界面接受您已知的参数。以下是对您最常设置的参数的简要介绍:

  • temperature —— 0为确定性,2为变化最大。DeepSeek推荐的默认值:代码和数学为0.0,数据分析为1.0,一般对话和翻译为1.3,创意写作为1.5。
  • top_p — 核心采样。设置此选项。 or temperature, not both.
  • max_tokens — 输出容量。V4支持高达384,000。在JSON模式下使用时,始终明确设置。
  • reasoning_effort — 仅V4支持;接受 "high" or "max". 与 extra_body={"thinking": {"type": "enabled"}}.
  • stream 配对。 true,您将接收到服务器发送的事件。启用思考功能后, reasoning_content 将与最终答案一起流式传输。请参阅 DeepSeek API streaming 了解块处理。
  • response_format — {"type": "json_object"} 打开JSON模式(下文将介绍)。
  • tools — 以OpenAI格式声明的函数。在思考和非思考模式下均受支持。

The DeepSeek API function calling 指南包含完整的模式;有关缓存键行为和前缀检测规则,请参阅 DeepSeek context caching.

JSON模式——设计而非保证

Set response_format={"type": "json_object"} 模型是 designed 返回有效的JSON。每个生产调用者都必须处理的三个注意事项:

  1. API有时会返回空内容。使用略有变化的提示重试。
  2. 提示本身必须包含字面词“json”和一个小示例模式。
  3. Set max_tokens 足够高,以至于模型不能在对象中间截断。

“保证有效的JSON”不是正确的心理模型。将响应视为需要 json.loads 在try/except内部。更长的处理方法在 DeepSeek API JSON mode.

无状态——最常见的惊喜

上。chat.deepseek.com的网页聊天会保留您的对话历史;API不会。 POST /chat/completions 是无状态的——服务器不会记住之前的回合。您的客户端必须重新发送完整的 messages 数组以维护多轮对话。从聊天应用思维模式过来的新开发者会因此浪费数小时。如果您需要持久性,请在您的侧边构建(以对话ID为键的数据库即可)。

工作示例:每百万次调用的成本

两种场景,一个2,000个token的系统提示在调用间缓存,一个200个token的用户消息每次都作为缓存未命中,一个300个token的响应。价格截至2026年4月——请与 DeepSeek API pricing page before committing budget.

示例 A — deepseek-v4-flash

Bucket Tokens Rate (per 1M) Cost
Input, cache hit 2,000,000,000 $0.0028 $5.60
Input, cache miss 200,000,000 $0.140 $28.00
Output 300,000,000 $0.280 $84.00
Total $117.60

示例 B — deepseek-v4-pro

Bucket Tokens Rate (per 1M) Cost
Input, cache hit 2,000,000,000 $0.003625 promo (list $0.0145) 7.25 美元(列表价 29.00 美元)
Input, cache miss 200,000,000 0.435 美元优惠(列表价 1.740 美元) 87.00 美元(列表价 348.00 美元)
Output 300,000,000 0.87 美元优惠(列表价 3.480 美元) 261.00 美元(列表价 1,044.00 美元)
Total $355.25 优惠至 2026-05-31(列表价 1,421.00 美元)

Pro在V4-Pro 75%促销期间(至2026年5月31日)大约是Flash的3倍(列表价为12倍)。用户消息在每次调用时都是缓存未命中,即使系统提示命中也不要从您的电子表格中省略该行。对于交互式估计,请使用 DeepSeek pricing calculator.

Error handling patterns

The OpenAI软件开发工具包 raises typed exceptions you can catch. The codes you will see in production:

Status Meaning Action
401 无效的API密钥 验证密钥、作用域以及您是否访问了正确的基本URL
402 Insufficient balance 充值;直到账户资金充足,调用将失败
422 无效的参数 检查请求体——通常是格式不正确的 messages 数组或不受支持的字段
429 Rate limited 指数退避;DeepSeek根据流量动态调整限制
500 / 503 服务器/过载 带抖动的重试;在事件期间检查状态页面

Python中的最小重试模式:

import time
from openai import OpenAI, APIStatusError

def call_with_retry(client, **kwargs):
    for attempt in range(5):
        try:
            return client.chat.completions.create(**kwargs)
        except APIStatusError as e:
            if e.status_code in (429, 500, 503) and attempt < 4:
                time.sleep(2 ** attempt)
                continue
            raise

记录响应头中返回的请求ID——这是提交有用支持报告的最快方式。完整的分类法在 DeepSeek API error codes.

值得了解的第三方SDK选项

如果您想要在原始OpenAI客户端之上添加一层,目前有两个处于活跃维护状态:

  • Vercel AI SDK ——DeepSeek提供者是可通过@ai-sdk/deepseek模块访问的,默认前缀是https://api.deepseek.com。适用于Next.js和Edge运行时。
  • LangChain / LlamaIndex ——将他们的OpenAI兼容适配器指向DeepSeek的基础URL。无需DeepSeek特定的包。

对于本地破解,社区维护的 deepseek-cli Python包封装了API以供终端使用——适用于一次性提示,但不是生产依赖。

认证和密钥卫生

Split-screen IDE showing OpenAI and Anthropic SDK clients both calling the DeepSeek API in Python

认证是在标准上的携带令牌 Authorization 头部。将密钥视为密码:永远不要提交它,按项目范围密钥,并在离职时更换。The DeepSeek API authentication 指南涵盖了头部格式和轮换策略;如果您是从零开始的,那么 get a DeepSeek API key 演示是通往更广泛API主题目录的最短路径。对于更广泛的API端主题目录,中心索引了每个参考和教程。 DeepSeek API docs and guides SDK和变更

关于历史低谷时段折扣怎么办?

50%/75%非高峰API折扣已于2025年9月5日停止,并且没有在V4中重新引入。如果教程将其列为有效,则该教程已过时。

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有官方SDK吗?

不是作为一个独立的品牌包。DeepSeek发布了一个与OpenAI兼容和与Anthropic兼容的API接口,因此您可以安装上游 openai or anthropic 修改一行:将 base_url plus api_key这是Python和Node推荐的路径。LangChain和Vercel AI SDK等第三方封装库无需修改即可使用。查看 DeepSeek OpenAI软件开发工具包 compatibility.

我如何从deepseek-chat迁移到deepseek-v4-flash?

和将于2026-07-24 15:59 UTC退役,因此请在此之前进行交换。完整参考见 model 参数。基础URL、端点路径、认证头和请求形状保持不变。旧版ID deepseek-chat and deepseek-reasoner currently route to deepseek-v4-flash 是的。安装 DeepSeek API documentation.

我可以使用Anthropic Python SDK与DeepSeek一起使用吗?

是的。安装 anthropic, set ANTHROPIC_BASE_URL=https://api.deepseek.com/anthropic,并使用DeepSeek API密钥作为 ANTHROPIC_API_KEY. Pass model="deepseek-v4-pro" or "deepseek-v4-flash"。一些Anthropic特定的字段(top_k, mcp_servers, budget_tokens)在此表面上被忽略,因此在移植前请测试功能一致性。更多关于指南的内容涵盖了应用端。 DeepSeek API code examples page.

API和DeepSeek聊天应用之间的区别是什么?

API是无状态的——您的客户端在每次调用时都会重新发送对话历史。网页聊天和移动应用在服务器端保持会话历史,因此用户可以看到跨轮次的过往对话。它们共享相同的底层模型,但界面是独立的。如果您想要一个无需编写前端代码的托管用户体验,那么 DeepSeek chat 。

在发送请求之前,我该如何计算令牌数量?

Use a standard 兼容OpenAI tokenizer for an estimate, then trust the usage block以获取确切计数。对于提前预算,请使用 DeepSeek token counter 提供快速预检功能,并 DeepSeek cost estimator 在您预期的流量下,将每月支出投影到 V4-Flash 和 V4-Pro。

来源s & Methodology

Last source check: April 30, 2026

Primary sources

Technical references

Methodology

Pricing figures were checked against the 官方DeepSeek定价页面 and normalised into estimated monthly costs using sample token usage scenarios. Actual costs may vary depending on caching, input/output ratio, regional availability, and provider updates.

Data confidence

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

Editorial note

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