
您打开了DeepSeek文档,找到了快速入门指南,现在您想要了解接下来的十个要点——流式传输、JSON输出、工具调用、思考模式、经得起代码审查的成本计算。本页收集了我在生产环境中针对V4-Flash和V4-Pro这两个模型实际运行的DeepSeek API示例,这两个模型在2026年4月取代了旧的`deepseek-chat`和`deepseek-reasoner`标识。每个代码片段都已针对`https://api.deepseek.com`上的实时OpenAI兼容端点进行测试,并附有关于哪些功能会出错、哪些成本高于预期以及哪些功能仍处于Beta测试状态的说明。到结束时,您将获得八个最常见API模式的复制粘贴代码,以及每个级别的成本计算示例。
What the DeepSeek API actually is

DeepSeek的API是一个使用OpenAI Chat Completions线格式进行通信的HTTP服务。标准的聊天端点是 POST /chat/completions against the base URL https://api.deepseek.com. DeepSeek官方快速入门 显示相同的形状——一个JSON体, model, messages以及通常的采样旋钮。
在任何代码之前,有两个实际要点:
- The API is stateless. 与网页聊天或移动应用不同,API不会记住之前的对话。每个请求都必须包含完整的对话历史,在
messages. - 两个当前模型ID。 DeepSeek V4-Flash (总容量284B / 活跃容量13B)以及 DeepSeek V4-Pro (1.6T / 49B活跃)。两者都是MIT下的开放权重MoE,默认使用1,000,000个token的上下文,输出最多384,000个token。
Legacy deepseek-chat and deepseek-reasoner 仍然可以使用,但旧的deepseek-chat和deepseek-reasoner端点将在2026年7月24日15:59 UTC全面退役。在此之前,它们将路由到 deepseek-v4-flash 分别在非思考模式和思考模式下。迁移只需一行代码更改您的 model= argument; base_url 保持原位。关于完整的迁移故事,请参阅我们的 DeepSeek V4 overview.
示例 1:最小请求 — curl 和 Python
最简单的调用方式。首先在curl中:
curl https://api.deepseek.com/chat/completions
-H "Authorization: Bearer $DEEPSEEK_API_KEY"
-H "Content-Type: application/json"
-d '{
"model": "deepseek-v4-flash",
"messages": [
{"role": "system", "content": "You are a terse senior engineer."},
{"role": "user", "content": "What is a MoE router, in two sentences?"}
]
}'
然后使用OpenAI SDK在Python中的等效代码——无需重写,只需交换基本URL:
import os
from openai import OpenAI
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 terse senior engineer."},
{"role": "user", "content": "What is a MoE router, in two sentences?"},
],
temperature=1.3,
)
pr整数(resp.choices[0].message.content)
Note temperature=1.3DeepSeek发布针对特定任务的默认值:代码和数学为0.0,数据分析为1.0,通用聊天和翻译为1.3,创意写作为1.5。导入0.7的GPT风格默认值将给出比模型能力更平缓的答案。
如果您的代码库已经支持Anthropic,该API与OpenAI ChatCompletions和Anthropic风格的端点兼容,因此Anthropic SDK也针对相同的基URL工作。更多关于这一点的内容请参阅我们的 DeepSeek OpenAI SDK compatibility guide.
示例 2:多轮对话(重发历史记录)
因为API是无状态的,所以你需要在客户端维护会话:
history = [
{"role": "system", "content": "You are a Postgres tutor."},
]
def ask(user_msg: str) -> str:
history.append({"role": "user", "content": user_msg})
resp = client.chat.completions.create(
model="deepseek-v4-flash",
messages=history,
temperature=1.3,
)
answer = resp.choices[0].message.content
history.append({"role": "assistant", "content": answer})
return answer
pr整数(ask("Explain CTEs in one paragraph."))
pr整数(ask("Show a recursive example."))
每次调用都会重新发送整个 history 数组。这听起来很浪费,但DeepSeek的自动上下文缓存能够检测到重复的前缀,并以缓存命中的速率计费较旧的标记。我们将在 DeepSeek context caching.
示例 3:流式响应
对于聊天用户界面,你希望获得即时生成的令牌。设置 stream=True 并迭代:
stream = client.chat.completions.create(
model="deepseek-v4-flash",
messages=[{"role": "user", "content": "Write a haiku about caching."}],
stream=True,
temperature=1.5,
)
for chunk in stream:
delta = chunk.choices[0].delta.content or ""
pr整数(delta, end="", flush=True)
当启用思考模式时,推理内容会在最终内容开始之前,以单独的 delta.reasoning_content 字段流进来。详细模式存在于 DeepSeek API streaming.
示例 4:思考模式(推理努力)

V4中将旧的“聊天与推理器”分割合并为模型上的一个参数。两种变体都支持1M标记的上下文和三种推理模式:非思考、思考、思考_max。您可以通过 reasoning_effort 以及通过 thinking 传递的 extra_body:
resp = client.chat.completions.create(
model="deepseek-v4-pro",
messages=[{"role": "user",
"content": "Plan a zero-downtime migration from MySQL 5.7 to 8.0."}],
reasoning_effort="high",
extra_body={"thinking": {"type": "enabled"}},
max_tokens=8192,
)
msg = resp.choices[0].message
pr整数("REASONING:n", msg.reasoning_content)
pr整数("ANSWER:n", msg.content)
标志。响应返回 reasoning_content alongside the final content. Use reasoning_effort="max" 用于最重的负载——该模式需要 max_model_len >= 393216 启用思考以避免截断。对于简单的聊天,请保持思考关闭:它会消耗输出标记在您可能不需要的推理轨迹上。
示例 5:JSON 模式
对于结构化提取设置 response_format={"type": "json_对象"}. JSON mode is designed 以返回有效的JSON,但不保证——适用三条规则:
- 在系统或用户提示中包含单词“json”。
- 展示你想要的模式的小示例。
- Set
max_tokens足够高,以至于输出不能在对象中间被截断。
SYSTEM = """Extract invoice fields as json.
Example:
{"invoice_no": "INV-001", "total_usd": 42.50, "line_items": 3}
"""
resp = client.chat.completions.create(
model="deepseek-v4-flash",
messages=[
{"role": "system", "content": SYSTEM},
{"role": "user", "content": open("invoice.txt").read()},
],
response_format={"type": "json_对象"},
max_tokens=2048,
temperature=0.0,
)
import json
data = json.loads(resp.choices[0].message.content or "{}")
明确处理空内容的情况——这 or "{}" 有其存在的理由。更多模式在 DeepSeek API JSON mode.
示例 6:工具调用(函数调用)
工具调用使用与OpenAI兼容的模式,在思考和非思考模式中均受支持:
tools = [{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get current weather for a city.",
"parameters": {
"type": "对象",
"properties": {"city": {"type": "字符串"}},
"required": ["city"],
},
},
}]
resp = client.chat.completions.create(
model="deepseek-v4-flash",
messages=[{"role": "user", "content": "Weather in Dublin?"}],
tools=tools,
)
call = resp.choices[0].message.tool_calls[0]
pr整数(call.function.name, call.function.arguments)
本地解决调用,然后将结果作为 {"role": "tool", "tool_call_id": ..., "content": ...} 消息发送回,并再次调用。参见 DeepSeek API function calling 完整的往返过程。
示例 7:FIM 完成功能(Beta)
中间填充是针对代码编辑器和自动完成的。它仅支持非思考模式,目前处于Beta测试阶段——请指向Beta基URL:
beta = OpenAI(api_key=os.environ["DEEPSEEK_API_KEY"],
base_url="https://api.deepseek.com/beta")
resp = beta.completions.create(
model="deepseek-v4-flash",
prompt="def fibonacci(n):n if n < 2:n return nn return ",
suffix="nnpr整数(fibonacci(10))",
max_tokens=64,
)
pr整数(resp.choices[0].text)
示例 8:聊天前缀完成(Beta)

当您需要模型从特定的开局继续时,设置 前缀:True 在辅助消息的末尾并点击Beta端点:
messages = [
{"role": "user", "content": "Write quicksort in Python."},
{"role": "assistant", "content": "```pythonn", "prefix": True},
]
resp = beta.chat.completions.create(
model="deepseek-v4-pro",
messages=messages,
stop=["```"],
)
pr整数(resp.choices[0].message.content)
快速参数参考
| Parameter | Type | Notes |
|---|---|---|
model |
字符串 | deepseek-v4-flash or deepseek-v4-pro |
temperature |
0.0–2.0 | 0.0 代码/数学,1.0 分析,1.3 聊天,1.5 创意 |
top_p |
0–1 | 核心采样;温度的替代方案 |
max_tokens |
整数 | 在V4上最多384,000;使用JSON模式时必需 |
reasoning_effort |
字符串 | "high" or "max"; pair with thinking flag |
stream |
布尔类型 | SSE数据块;当启用时,分别对推理流进行推理 |
response_format |
对象 | {"type": "json_对象"} 用于JSON模式 |
tools |
数组 | OpenAI风格的函数定义 |
成本计算示例 — 两个级别
截至2026年4月的价格,从 DeepSeek’s official pricing page. Flash的输入费用为每百万令牌0.14美元,输出费用为每百万令牌0.28美元;缓存命中费用降至0.0028美元——自2026年4月26日以来降低了约98%。V4-Pro在2026年5月31日之前享有75%的促销活动:每1M缓存未命中输入费用为0.435美元,每1M输出费用为0.87美元(标价1.74美元/1M输入,3.48美元/1M输出),缓存命中输入费用为0.003625美元(标价0.0145美元)。
工作负载:每月1,000,000次调用,系统提示(已缓存)为2,000个令牌,用户消息(未缓存)为200个令牌,响应为300个令牌。
| Token bucket | 量 | V4-Flash | V4-Pro |
|---|---|---|---|
| Cached input | 20亿个token | $5.60 | $7.25促销价(原价$29.00) |
| Uncached input | 2亿个token | $28.00 | $87.00促销价(原价$348.00) |
| Output | 0.3B个token | $84.00 | $261.00促销价(列表价$1,044.00) |
| 总计/每月 | $117.60 | $355.25 促销价(列表价$1,421.00) |
人们常犯的两个错误:跳过未缓存输入行(每个新用户消息都会错过与系统前缀的缓存),以及在一个估计中混合不同层级。选择一个并坚持下去。高峰时段折扣于2025年9月5日结束,V4版本后尚未恢复。对于交互式估计,请使用 DeepSeek pricing calculator.
错误处理模式
该API返回与OpenAI兼容的错误封装。您最常遇到的代码:
401 Unauthorized— 错误或缺失API密钥。402 Insufficient Balance— 充值账户。429 请求过多— 退后并带有抖动重试。finish_reason="length"— 输出被截断;请提高。max_tokens.finish_reason="content_filter"— 请求被安全层阻止。
import time, random
from openai import RateLimitError, APIError
def call_with_retry(**kw):
for attempt in range(5):
try:
return client.chat.completions.create(**kw)
except RateLimitError:
time.sleep((2 ** attempt) + random.random())
except APIError as e:
if 500 <= e.status_code < 600:
time.sleep(2 ** attempt)
continue
raise
raise RuntimeError("exhausted retries")
要查看完整的按代码编写的操作指南,请参阅 DeepSeek API error codes.
Where to go next

如果您仍在设置身份验证,请从我们的操作流程开始学习如何 get a DeepSeek API key, then the DeepSeek API getting started tutorial. For broader context on every endpo整数, parameter and rate-limit tier, the DeepSeek API docs and guides 如果您需要上述代码片段的 JavaScript 对应版本,请参阅 DeepSeek Node.js 整数egration.
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.
Frequently asked questions
How do I make my first DeepSeek API call?
从 DeepSeek 平台控制台获取 API 密钥,安装 OpenAI SDK (pip install openai),然后使用 base_url="https://api.deepseek.com"实例化客户端。然后调用 client.chat.completions.create with model="deepseek-v4-flash" 和一个 messages 数组. The Example 1 snippet above is a working minimal call. Full setup steps live in our DeepSeek API getting started tutorial.
deepseek-v4-flash 和 deepseek-v4-pro 之间的区别是什么?
Flash总参数量为284B / 活跃参数量为13B,输入未命中费用为每百万令牌0.14美元,输出费用为每百万令牌0.28美元(缓存命中费用为0.0028美元,约比未命中费用低98%)。Pro版本参数量为1.6T / 活跃参数量为49B,在2026年5月31日之前的75%促销活动中,输入费用为0.435美元/1M,输出费用为0.87美元/1M(标价1.74美元/1M输入,3.48美元/1M输出)。两者共享相同的1M令牌上下文、思考模式、JSON模式、工具调用和流式传输。选择Flash进行聊天和高容量工作,Pro进行前沿层级的编码和代理任务。在详细比较 DeepSeek models hub.
Does the DeepSeek API remember previous messages?
No. 该 API 是无状态的:每个 POST /chat/completions 请求都必须包含完整的对话历史记录在 messages. 网页聊天和移动应用在服务器端维护会话历史记录,但开发者API不维护。重复的前缀将自动按较便宜的缓存命中费率计费。请参阅 DeepSeek context caching 如何构建提示以触发缓存。
Can I use the OpenAI Python SDK with DeepSeek?
是的。DeepSeek的API与OpenAI Chat Completions的线格式相匹配。只需更改 base_url to https://api.deepseek.com 提供您的DeepSeek API密钥——每个现有的调用站点都将继续工作。DeepSeek还提供了一个与Anthropic兼容的表面,供已使用该SDK的团队使用。兼容性注意事项已在我们文档中列出。 DeepSeek OpenAI SDK compatibility notes.
为什么DeepSeek在某些响应中返回reasoning_content?
当您使用 reasoning_effort="high" and extra_body={"thinking": {"type": "enabled"}}启用思考模式时,模型返回 reasoning_content alongside the final content. 推理字段包含模型所通过的链;内容字段是面向用户的答案。 deepseek-reasoner 产生了相同的形状,并于2026年7月24日退役。更多关于提示设计的信息,请参阅我们的 DeepSeek prompt engineering guide.
来源s & Methodology
Primary sources
- OfficialDeepSeek API documentationEndpo整数s, request/response shape, model IDsLast checked: April 30, 2026
- PricingDeepSeek API pricing pagePer-1M-token rates, billing units, cache-hit pricingLast checked: April 30, 2026
- OfficialDeepSeek官方快速入门Canonical /chat/completions请求体形状Last checked: April 30, 2026
- PricingDeepSeek's official pricing pageV4-Flash和V4-Pro的成本工时示例费率Last checked: April 30, 2026
Methodology
Pricing figures were checked against the 官方DeepSeek定价页面 and normalised 整数o 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 occasionally runs promotional discounts that are not always reflected in the headline page. The pricing dataset on this site auto-refreshes monthly; this article reflects the dataset on the date shown above.