
您拥有DeepSeek API密钥、现有的Python项目和一个问题,这个问题阻碍了每个第一次调用:您真的需要一个新的SDK吗,或者OpenAI客户端已经涵盖了这些功能?本教程将回答这个问题,然后指导您完成与V4生成(在2026年4月24日取代了`deepseek-chat`和`deepseek-reasoner`)的完整DeepSeek Python集成。到结束时,您将拥有一个工作客户端、一个流式传输示例、一个不会静默截断的JSON模式调用、一个思考模式模式,以及可以粘贴到财务审查中的成本计算。每个代码片段都可以在Python 3.10或更高版本上复制粘贴运行。
What you will build

您将构建一个小的Python模块,该模块使用官方OpenAI SDK与DeepSeek API通信——不需要DeepSeek特定的包。该模块将支持V4模型层级,通过单个参数在非思考模式和思考模式之间切换,流式传输令牌,请求结构化JSON,并记录令牌使用情况,以便您可以监控支出。整个模块大约有120行代码。
这是我今天在生产环境中运行的同形状,在迁移离旧系统后。 deepseek-chat and deepseek-reasoner ID。这些名称将在2026年7月24日15:59 UTC之后完全退役且无法访问,因此任何新的DeepSeek Python集成应针对 deepseek-v4-pro or deepseek-v4-flash 从第一天开始。如果您还没有获取API密钥,本指南涵盖了platform.deepseek.com注册和首次充值。 get a DeepSeek API key (推荐使用3.11或3.12以获得更好的异步行为)。
Prerequisites
- (推荐使用3.11或3.12以获得更好的异步行为)。 (3.11 or 3.12 recommended for better async behaviour).
- OpenAI Python SDK v1.40或更高版本:
pip install "openai>=1.40,<2.0". - 一个DeepSeek API密钥 至少有少量余额——如果账户余额为零,调用将返回HTTP 402错误。
- 一个环境变量
DEEPSEEK_API_KEY。请勿将密钥粘贴到源文件中。 - 可选但推荐:
python-dotenv用于本地开发,httpx已经包含在OpenAI SDK中。
为什么OpenAI SDK能工作
DeepSeek API使用与OpenAI/Anthropic兼容的API格式。通过修改配置,您可以使用OpenAI/Anthropic SDK或兼容OpenAI/Anthropic API的软件来访问DeepSeek API。在实践中,这意味着交换两个值—— base_url and api_key ——并将 model 字段指向一个DeepSeek ID。聊天请求击中 POST /chat/completions,与OpenAI兼容的端点,具有您已知的相同JSON体形状。完整参考信息位于 DeepSeek OpenAI SDK compatibility guide.
如果您更喜欢Anthropic SDK,这也行:DeepSeek公开了一个与相同基础URL兼容的Anthropic表面。本文将坚持使用OpenAI客户端,因为大多数现有的Python代码库已经依赖于它。
步骤 1 — 安装SDK并设置环境变量
创建一个虚拟环境并安装OpenAI客户端。下面的shell命令是bash风格的;PowerShell用户应使用 $env:DEEPSEEK_API_KEY 语法。
python -m venv .venv
source .venv/bin/activate
pip install "openai>=1.40,<2.0" python-dotenv
export DEEPSEEK_API_KEY="sk-..."
对于项目级别的配置,将密钥放在仓库根目录下的 .env 文件中,并添加 .env to .gitignore文件。 DeepSeek API认证指南详细介绍了密钥轮换和吊销。 将以下Python脚本保存为
步骤 2 — 您的第一个DeepSeek Python集成调用

文件。 文件。它针对 deepseek-v4-flash,这是成本效益高的默认选项,我推荐用于大多数工作负载。
import os
from openai import OpenAI
client = OpenAI(
api_key=os.environ["DEEPSEEK_API_KEY"],
base_url="https://api.deepseek.com",
)
response = client.chat.completions.create(
model="deepseek-v4-flash",
messages=[
{"role": "system", "content": "You are a precise technical assistant."},
{"role": "user", "content": "In one sentence, what is a Mixture-of-Experts model?"},
],
temperature=0.0,
max_tokens=200,
)
print(response.choices[0].message.content)
print("usage:", response.usage)
使用 python 文件。。您应该看到一个一句话的答案,以及一个列出提示、完成和总令牌的使用块。
选择V4-Flash与V4-Pro
这两个V4模型ID共享相同的API表面,但针对不同的价格点。今天推出两个模型。V4-Pro包含160亿总参数,每个令牌激活49亿。V4-Flash是高效的兄弟,总参数为284亿/活跃参数为130亿。两者都支持原生1M上下文,并且都是开放权重。
| 运行它。 | deepseek-v4-flash | deepseek-v4-pro |
|---|---|---|
| 字段 | 284B / 13B | 1.6T / 49B |
| 总计/活跃参数 | 1,000,000 tokens | 1,000,000 tokens |
| Max output | 384,000 tokens | 384,000 tokens |
| 每1MB输入(缓存命中) | $0.0028 | $0.0145 |
| 每1MB输入(缓存未命中) | $0.14 | $0.435 promo / $1.74 list |
| 每1MB输出 | $0.28 | $0.87 promo / $3.48 list |
| Best for | 聊天、分类、RAG | Frontier coding, agents |
2026年4月的价格,根据 official DeepSeek pricing page。DeepSeek对Flash收费为每百万输入令牌0.14美元和每百万输出令牌0.28美元,对Pro收费为每百万输入令牌0.435美元和每百万输出令牌0.87美元,在2026年5月31日前的75%促销期间(列表价1.74美元/3.48美元)。Pro的输出价格大约是Flash的12倍,因此默认使用Flash,只有在您有质量提升的测量结果时才升级。
步骤 3 — 多轮对话(API是无状态的)
这几乎让所有从聊天应用迁移到API的人感到困惑。chat.deepseek.com上的网页聊天将您的聊天历史保存在服务器端。API则不这样做。您必须重新发送完整的内容。 messages 每个请求都有的数组。
def chat_loop():
历史 = [{"role": "system", "content": "You are a precise technical assistant."}]
while True:
user_input = input("you: ").strip()
if not user_input:
break
历史.append({"role": "user", "content": user_input})
resp = client.chat.completions.create(
model="deepseek-v4-flash",
messages=历史,
temperature=1.3, # general conversation
max_tokens=800,
)
reply = resp.choices[0].message.content
历史.append({"role": "assistant", "content": reply})
print(f"deepseek: {reply}n")
两个实用提示。首先, 历史 在每个回合都会增长——一旦它威胁到超出您的预算,就将较老的回合总结成一条系统消息。其次,DeepSeek发布的温度建议是: 0.0 代码和数学, 1.0 数据分析, 1.3 通用聊天和翻译, 1.5 创意写作。将它们作为起点,而非圣经。
步骤 4 — 流式响应
对于任何面向用户的操作,使用流。它将感知到的延迟从“模型已损坏”降低到“模型运行快速”,而实际上并没有加快速度。
stream = client.chat.completions.create(
model="deepseek-v4-flash",
messages=[{"role": "user", "content": "Explain CSA attention in three short paragraphs."}],
stream=True,
max_tokens=600,
)
for chunk in stream:
delta = chunk.choices[0].delta
if delta.content:
print(delta.content, end="", flush=True)
print()
服务器发送的事件到达 聊天完成片段 对象。捕获 openai.APIConnection错误 如果您正在运行一个不可靠的网络——损坏的流不应该使您的工人崩溃。请 DeepSeek API streaming 引用说明了SSE帧和重新连接模式。
步骤 5 — 思考模式
V4将旧的“聊天与推理器”分离合并为一个单一参数。保持base_url不变,只需更新model为deepseek-v4-pro或deepseek-v4-flash。支持OpenAI ChatCompletions和Anthropic API。两种模型都支持1M的上下文和双模式(思考/非思考)。模型返回 reasoning_content alongside the final content 当思考正在进行时:
response = client.chat.completions.create(
model="deepseek-v4-pro",
messages=[
{"role": "user", "content": "A train leaves Chicago at 60mph; another leaves Denver at 75mph文件。y start 1,000 miles apart. When do they meet?"},
],
reasoning_effort="high",
extra_body={"thinking": {"type": "enabled"}},
max_tokens=4000,
)
msg = response.choices[0].message
print("THINKING:", getattr(msg, "reasoning_content", None))
print("ANSWER:", msg.content)
接受三个设置:对于非思考模式,省略两个参数——默认是启用思考,因此请传递 extra_body={"thinking": {"type": "disabled"}} 要退出(最快,最便宜);使用 reasoning_effort="high" 带有 thinking 标志的标准推理;使用 reasoning_effort="max" 适用于最重的设置。最大努力思考从提高 max_tokens 远远高于默认值——DeepSeek的文档建议至少使用384K个token的工作窗口,以避免截断推理跟踪。请注意,在迁移窗口期间,使用旧ID的遗留代码仍然可以工作:deepseek-chat和deepseek-reasoner将在2026年7月24日15:59(UTC时间)后完全退役且不可访问。(目前路由到deepseek-v4-flash非思考/思考模式)。 deepseek-reasoner 为了返回有效的JSON,但不保证一定如此。API可以返回空内容,或者更常见的是,由于某些原因在对象中间截断内容。
步骤 6 — 无陷阱的JSON模式
JSON mode is designed 运行一个烟雾测试,测试你在生产中实际使用的每条路径。部署前我运行的最小测试: max_tokens 设置得太低。三条规则让它变得无聊:
- Set
response_format={"type": "JSON_object"}. - Include the word JSON 在系统或用户提示中,附有一个小示例模式。
- Set
max_tokenshigh enough that the response cannot truncate.
import JSON
schema_hint = """
Return JSON in this exact shape:
{"sentiment": "positive|negative|neutral", "confidence": 0.0-1.0, "key_phrases": ["..."]}
"""
resp = client.chat.completions.create(
model="deepseek-v4-flash",
response_format={"type": "JSON_object"},
messages=[
{"role": "system", "content": "You are a sentiment classifier. Respond only with JSON. " + schema_hint},
{"role": "user", "content": "The dashboard finally loads in under a second. I'm impressed."},
],
temperature=0.0,
max_tokens=400,
)
raw = resp.choices[0].message.content
if not raw:
raise Runtime错误("空的 JSON response — retry or fall back.")
result = JSON.loads(raw)
print(result)
对于更深的模式——包括空重试和Pydantic验证——请参阅 DeepSeek API JSON mode reference.
步骤 7 — 工具调用
工具调用使用OpenAI tools 数组原文。V4两个等级都支持在非思考模式和思考模式下使用。
tools = [{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get current weather for a city.",
"parameters": {
"type": "object",
"properties": {"city": {"type": "string"}},
"required": ["city"],
},
},
}]
resp = client.chat.completions.create(
model="deepseek-v4-flash",
messages=[{"role": "user", "content": "What's the weather in Dublin?"}],
tools=tools,
)
call = resp.choices[0].message.tool_calls[0]
print(call.function.name, call.function.arguments)
模型返回一个 tool_calls 条目;您的代码执行函数,附加一个包含结果的 {"role": "tool", ...} message 带有 result, and calls the API again文件。 指南有一个完整的代理循环示例。 一个非流式调用返回一个非空的
步骤 8 — 验证是否成功

每个Python集成最终都会面临“每天100万次调用这个会花费多少?”的问题。以下是针对以下情况的示例:一个2,000个token的系统提示被缓存,一个200个token的用户消息未被缓存,以及一个300个token的回复:
- 和一个
contentand ausage包含非零令牌计数的块。 - 流式调用至少返回一个非空块。
delta.content. - JSON模式调用可以干净地通过
JSON.loads. - 思维模式调用暴露
reasoning_content在消息对象上。 - 无效的API密钥导致
openai.Authentication错误而不是崩溃。
Common errors and fixes
| 错误 | Likely cause | Fix |
|---|---|---|
401 未授权 |
错误或缺失的密钥 | 重新导出 DEEPSEEK_API_KEY; 如果泄露则旋转。 |
402 Insufficient Balance |
账户余额为 $0 | 在 platform.deepseek.com 充值;密钥正常。 |
429 请求频率限制 |
突发请求过高 | 指数退避;限制并发数。 |
空的 content 在JSON模式下 |
Prompt missing “JSON” / truncation | 添加模式示例;提升 max_tokens. |
| 答案在句子中间被截断 | max_tokens 太低 |
提升它;检查 finish_reason == "length". |
模型未找到 |
退役后的旧ID | 切换到 deepseek-v4-flash or deepseek-v4-pro. |
NotFound错误 on reasoning_effort |
OpenAI SDK 过旧 | 升级到 openai>=1.40. |
The DeepSeek API error codes 参考列表列出了每个状态码的重试指南。
实诚地计算您的集成成本
DeepSeek, DeepSeek Chat, R1, V3, V4, V4 Pro, V4 Flash, API, GPU, CUDA, Linux, Windows, macOS, iPhone, Android, Python, VS Code, OpenAI, GPT, Gemini, Claude, ChatGPT, JSON, CSV, PDF, Token, MoE, MLA, GRPO。 deepseek-v4-flash with a 2,000-token system prompt that gets cached, a 200-token user message that does not, and a 300-token reply:
- Cached input: 2,000 × 1,000,000 = 2,000,000,000 × $0.0028/M = $5.60
- Uncached input: 200 × 1,000,000 = 200,000,000 × $0.14/M = $28.00
- Output: 300 × 1,000,000 = 300,000,000 × $0.28/M = $84.00
- 总计:每100万次调用117.60美元
The same workload on deepseek-v4-pro 费用为29.00美元 + 348.00美元 + 1,044.00美元 = $1,421.00 大约多10倍。陷阱在于忘记未缓存的输入行:每个新用户消息都会对缓存的提示词前缀造成缓存未命中,即使系统提示被重复使用。跳过该行,你的预算将减少五分之一。
两个机械杠杆降低了成本:保持系统提示稳定,以便缓存命中率保持高(参见)。 DeepSeek context caching),并修剪 max_tokens 到你需要的实际输出。大多数生产答案适合在1,000-2,000个token内;384K适用于小众的长篇工作。
生产加固
三个习惯将原型与运行中的服务区分开来:
- 将每个调用包裹在重试辅助器中 处理429和5xx错误,并使用指数退避。不要重试4xx错误——它们是你代码中的错误,而不是暂时性故障。
- 在每个调用中记录令牌使用情况。 发货
提示令牌,完成令牌,以及任何推理令牌到你的可观察性堆栈。一个突然的推理token激增警报可以在账单到来之前捕捉到漂移的提示。 - 限制并发。 OpenAI SDK在底层使用
httpx;一个asyncio.Semaphore在异步客户端周围防止一个失控的工人类似熔化你的速率限制。
对于框架集成——代理循环、文档问答、向量检索——有专门的教程。 DeepSeek with LangChain and DeepSeek with LlamaIndex这两个库都将DeepSeek视为一个即插即用的与OpenAI兼容的提供者。
下一步

一旦基本集成稳固,最高频的后续操作包括:在Streamlit或FastAPI前端部署,添加检索功能,或迁移现有的OpenAI代码库。尝试使用 DeepSeek RAG教程 对于检索,使用 DeepSeek Streamlit app 快速UI的说明,或浏览全部主题集。 DeepSeek tutorials 查看相邻主题。如果你的代码库以JavaScript为主,则并行 DeepSeek Node.js集成 指南与这个相同。
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
我应该如何安装DeepSeek Python SDK?
没有独立的DeepSeek Python SDK。DeepSeek的API与OpenAI兼容,因此您可以使用 pip install "openai>=1.40,<2.0" 并将其指向 https://api.deepseek.com 您的DeepSeek API密钥进行安装。如果您更喜欢Anthropic SDK,同样的模式也适用。构造函数并传入您的DeepSeek API密钥。聊天完成、流式传输、JSON模式和工具调用的线格式是相同的。只有DeepSeek特定的参数,如 DeepSeek SDK 参考文档涵盖了所有支持的客户端。
在Python中我应该使用哪个模型ID?
Use deepseek-v4-flash 用于聊天、分类和大多数生产工作负载,或 deepseek-v4-pro for frontier-tier coding and agentic tasks文件。 legacy deepseek-chat and deepseek-reasoner 身份标识符仍然有效,但将于2026年7月24日15:59 UTC停止使用;在此之前,它们将被路由到 deepseek-v4-flash。请参阅 DeepSeek V4 模型页面以获取完整的世系信息。
DeepSeek是否可以在不更改代码的情况下与OpenAI Python客户端一起工作?
几乎如此——你更改两个值。在 base_url="https://api.deepseek.com" 上设置 OpenAI() 字段。当启用思考模式时,推理内容与最终内容在单独的字段中流式传输。将迭代器包裹在try/except块中,以防 reasoning_effort and the thinking 标志需要提供 extra_body argument文件。 DeepSeek OpenAI SDK compatibility 指南详细说明了每个边缘情况。
我应该如何从Python启用思考模式?
将 reasoning_effort="high" 与 extra_body={"thinking": {"type": "enabled"}} on either V4 model文件。 response object then exposes reasoning_content alongside the final content。使用 reasoning_effort="max" 进行最重的设置,并提高 max_tokens so the reasoning trace is not truncated文件。 DeepSeek API best practices 指南涵盖了每个努力程度何时值得延迟成本。
我可以使用DeepSeek Python集成进行令牌流式传输吗?
是的。设置 stream=True on client.chat.completions.create() 并迭代返回的对象——每个块都是一个 聊天完成片段 with a delta.content field. When thinking mode is enabled, reasoning content streams alongside final content on separate fields. Wrap the iterator in try/except for APIConnection错误 so flaky networks do not crash your worker文件。 DeepSeek API streaming 参考文档介绍了重新连接模式和SSE帧的格式。
Sources & Methodology
Primary sources
- OfficialDeepSeek API documentationEndpoints, 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
- PricingDeepSeek API pricing pageV4-Flash与V4-Pro层级选择的每百万令牌速率Last checked: April 30, 2026
Methodology
本文信息已对照官方DeepSeek文档、文章引用的主要来源以及上述日期的deepseekai.guide定价数据集进行核对。对于引用的第三方数据,原始来源已在行内链接,以便读者验证和重新检查。
Data confidence
High for facts cited inline with primary-source links; medium for context narrative.
Editorial note
人工智能工具发展迅速。如果您发现过时的数字或损坏的链接,页脚中的联系链接是向编辑团队报告的最快方式。