
您需要一个能够调用DeepSeek V4、返回干净结构化输出且在旧版`deepseek-chat` ID退役时不会中断的LangChain管道。这是一个合理的要求,尽管LangChain、DeepSeek以及数十篇博客文章中散布的文档仍主要展示V3时代的示例。本指南将指导您从端到端使用DeepSeek与LangChain:安装官方`langchain-deepseek`包,将其连接到`deepseek-v4-flash`和`deepseek-v4-pro`,启用思考模式,流式传输令牌,调用工具,并将模型嵌入到一个小型RAG链中。到那时,您将拥有一个可运行的Python脚本,以及决定在生产中使用哪个V4级别的成本数字。
What you’ll build

目标是创建一个单一的Python项目,展示四个团队实际需要的四种模式:一个简单的聊天调用、一个流式调用、一个调用工具的调用和一个检索增强链。所有四种都使用相同的 ChatDeepSeek 对象,只是配置不同。到最后,你可以交换字符串 model= 之间的 deepseek-v4-flash and deepseek-v4-pro 而不触及其他任何东西。
在所有这些工作之前,有两个事实需要牢记。首先,当前一代是 DeepSeek V4,发布于2026年4月24日,以两个开放重量的MoE模型ID发货: deepseek-v4-pro (1.6T total / 49B active parameters, frontier tier) and deepseek-v4-flash (284B / 13B活跃,成本效益级别)。两者都采用MIT许可。其次,LangChain提供了一个官方集成包, langchain-deepseek,与LangChain核心团队共同维护。该包在PyPI上以MIT许可发布,langchain-core和langchain-openai作为必需依赖项——这表明包装器是LangChain的OpenAI聊天模型基类的子类。
Prerequisites
- Python 3.10或更高版本(LangChain 0.3+需要它)。
- 从开发者控制台获取DeepSeek API密钥——请参阅我们关于如何操作的教程。 get a DeepSeek API key 如果您还没有这样做的话。
- 一个虚拟环境(venv、uv或poetry)以保持依赖项隔离。
- 大约1美元的信用额度即可跟随学习;本文中的V4-Flash示例调用成本仅为几分之一美分。
- 熟悉以下基础知识: DeepSeek API入门流程 有帮助但不是必需的。
第1步:安装LangChain DeepSeek包
LangChain DeepSeek 集成位于 langchain-deepseek 包中。请在您的虚拟环境中使用 pip 安装它:
pip install -U langchain-deepseek langchain-core
如果您计划在步骤 5 中遵循 RAG 示例,还需要安装一个向量存储和一个嵌入提供者——DeepSeek 目前没有发布第一方嵌入 API,因此请与您已经使用的任何嵌入器配对:
pip install -U langchain-community langchain-text-splitters faiss-cpu sentence-transformers
然后导出您的密钥。安装langchain-deepseek并设置环境变量DEEPSEEK_API_KEY:
export DEEPSEEK_API_KEY="sk-..."
第2步:最小化ChatDeepSeek调用
包装类是 ChatDeepSeek。在底层它继承自 BaseChatOpenAI,这就是为什么您已经知道的每个OpenAI风格的参数—— temperature, max_tokens, 超时 — works as expected. The class reads the API key from the DEEPSEEK_API_KEY env var and points at the DeepSeek API base URL by default, so the only required argument is the model ID.
将此保存为 quickstart.py。它使用成本效益较高的层级:
from langchain_deepseek import ChatDeepSeek
llm = ChatDeepSeek(
model="deepseek-v4-flash",
temperature=0,
max_tokens=512,
超时=60,
max_retries=2,
)
messages = [
("system", "You are a concise technical writer."),
("human", "Explain MoE routing in two sentences."),
]
response = llm.invoke(messages)
print(response.content)
print(返回一个类似于)
有两点需要注意。列表使用LangChain的元组简写而不是显式的 messages 对象——两者都可行,元组更短。并且 对象——两者都可行,元组更短。并且 / 对象——两者都可行,元组更短。并且 返回一个类似于 返回一个类似于 的字典,这是您连接到自己的成本跟踪的。 {"input_tokens": …, "output_tokens": …, "total_tokens": …}在包装器后面,每个调用都会击中
——与OpenAI兼容的端点。该API是 POST /chat/completions on https://api.deepseek.com — the OpenAI-compatible endpoint. The API is stateless: DeepSeek 不会在服务器端记住之前的回合,因此多回合对话需要每次请求都重新发送完整数组。网页聊天和移动应用的行为不同——它们会为您保留会话历史。API 不会。 messages 输出列是您需要关注的:V4-Pro 的输出成本比 V4-Flash 高出大约 12 倍。有关涵盖两个级别的示例,请参阅我们的
第3步:选择合适的V4等级
两个 V4 级别共享相同的 API 接口和相同的 1,000,000 个 token 的上下文窗口,最多可输出 384,000 个 token。区别在于每任务成本和基准上限。以下是当前的费率表,摘自 官方DeepSeek定价页面 as of April 2026:
| Model | Input cache hit | Input cache miss | Output | Best for |
|---|---|---|---|---|
deepseek-v4-flash |
$0.0028 / 1M | $0.14 / 1M | $0.28 / 1M | 标准聊天,RAG,分类,草稿编写 |
deepseek-v4-pro |
$0.0145 / 1M (list; promo $0.003625 through 2026-05-31) | $0.435 promo / $1.74 list per 1M | $0.87 promo / $3.48 list per 1M | 边界编码,代理循环,严格推理 |
输出列是您需要关注的:V4-Pro 的输出成本比 V4-Flash 高出大约 12 倍。有关涵盖两个级别的示例,请参阅我们的 DeepSeek API pricing 页面或在我们的中运行数字 DeepSeek pricing calculator.
Worked example — V4-Flash at scale
想象一下每月有100万次LangChain调用,使用一个2,000个token的缓存系统提示,一个200个token的用户消息(与该前缀不缓存),以及一个300个token的回答。 deepseek-v4-flash 数学分解如下:
- Cached input: 2,000 × 1,000,000 = 2.0B tokens × $0.0028/M = $5.60
- Uncached input: 200 × 1,000,000 = 0.2B tokens × $0.14/M = $28.00
- Output: 300 × 1,000,000 = 0.3B tokens × $0.28/M = $84.00
- 总计:117.60美元/月
运行相同的工作负载 deepseek-v4-pro 在这里,你将花费1,421美元——相同的调用模式,费用大约是之前的10倍。在基准提升能够获得回报的地方使用Pro版本;在其他所有地方默认使用Flash版本。
第4步:启用思考模式

在V4中,思考模式是一个 request parameter,而不是一个单独的模型ID。您可以为任意层级开启它。使用LangChain时,您可以通过它作为 extra_body传递,因为包装器继承自OpenAI的基类:
from langchain_deepseek import ChatDeepSeek
reasoner = ChatDeepSeek(
model="deepseek-v4-pro",
temperature=0,
max_tokens=8192,
reasoning_effort="high",
extra_body={"thinking": {"type": "enabled"}},
)
result = reasoner.invoke(
"A train leaves Chicago at 9:00 averaging 60 mph. "
"A second train leaves the same station at 10:30 averaging 80 mph "
"on a parallel track. When does the second train catch up?"
)
print("Reasoning content:")
print(result.additional_kwargs.get("reasoning_content"))
print("nAnswer:")
print(result.content)
思考模式响应返回 reasoning_content alongside the final content。LangChain在 response.additional_kwargs["reasoning_content"]上呈现推理跟踪;面向用户的答案保持在 response.content上。 reasoning_effort="max" 以获得最大努力——请注意,文档要求至少 max_model_len 384K个token以避免截断跟踪。
深度探索自身文档中的温度指导,这值得贴在墙上:
- 0.0 — 代码生成,数学
- 1.0 — 数据分析,数据清洗
- 1.3 — general conversation, translation
- 1.5 — creative writing
兼容旧版ID仍被接受——目前如此
如果您维护的是较旧的代码库,您可能会看到 deepseek-chat or deepseek-reasoner 在示例中。DeepSeek-R1,通过model="deepseek-reasoner"指定,不支持工具调用或结构化输出,而那些功能通过model="deepseek-chat"支持。该指导反映了V3时代。今天,这两个遗留ID都路由到标准LangChain形状。 deepseek-v4-flash (non-thinking and thinking respectively) and will be 于2026年7月24日15:59 UTC完全退役。从那天起,带有旧ID的请求将失败。迁移只需一行 model= swap; the base_url does not change.
第5步:流式传输、工具调用和RAG
流式传输令牌
对于聊天用户界面,流式传输是不可或缺的。ChatDeepSeek实现了LangChain的标准 .stream() 方法:
for chunk in llm.stream("Write a haiku about MoE routing."):
print(chunk.content, end="", flush=True)
当启用思考模式时,推理块与答案块一起流式传输 — 检查 chunk.additional_kwargs 每个事件以区分它们。
Tool calling
ChatDeepSeek公开 bind_tools() 包装器支持两种结构化输出的方法:'function_calling',它使用DeepSeek的工具调用功能,以及'json_mode',它使用DeepSeek的JSON模式功能。一个最小示例:
from langchain_core.tools import tool
from langchain_deepseek import ChatDeepSeek
@tool
def get_weather(city: str) -> str:
"""Return current weather for a city."""
return f"{city}: 14°C, light rain"
llm = ChatDeepSeek(model="deepseek-v4-flash", temperature=0)
agent = llm.bind_tools([get_weather])
reply = agent.invoke("What's the weather in Manchester?")
print(reply.tool_calls)
来自LangChain源的一个注意事项:为了与其他聊天模型兼容,包括了对strict-mode架构的遵循,并且如果指定,将按照OpenAI规范传递给API——然而,DeepSeek API可能会忽略该参数。将strict模式视为尽力而为,而非保证。
结构化JSON输出
For response_format={"type": "json_object"},请记住JSON模式是 designed 返回有效的JSON,但不保证。始终在系统提示中包含单词“json”以及一个小示例架构,并设置 max_tokens 高到足以避免在物体中间截断响应。模型也可能偶尔返回空内容——请显式处理这种情况。 DeepSeek API JSON mode 本指南涵盖了常见问题。
一个小的RAG链
将DeepSeek Chat放入标准的LangChain检索器+提示+LLM管道中。请注意,DeepSeek目前不提供第一方嵌入API,因此请与一个单独的嵌入器(此处为本地sentence-transformer)搭配使用。更深入的教程请参阅我们的 DeepSeek RAG tutorial.
from langchain_deepseek import ChatDeepSeek
from langchain_community.vectorstores import FAISS
from langchain_community.embeddings import HuggingFaceEmbeddings
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.runnables import RunnablePassthrough
from langchain_core.output_parsers import StrOutputParser
docs = ["DeepSeek V4 launched April 24, 2026.",
"V4-Flash is 284B total / 13B active parameters.",
"V4-Pro is 1.6T total / 49B active parameters."]
emb = HuggingFaceEmbeddings(model_name="all-MiniLM-L6-v2")
store = FAISS.from_texts(docs, emb)
retriever = store.as_retriever(search_kwargs={"k": 2})
prompt = ChatPromptTemplate.from_messages([
("system", "Answer using only the provided context. If unsure, say so."),
("human", "Context:n{context}nnQuestion: {question}"),
])
llm = ChatDeepSeek(model="deepseek-v4-flash", temperature=0)
chain = (
{"context": retriever, "question": RunnablePassthrough()}
| prompt
| llm
| StrOutputParser()
)
print(chain.invoke("How many active parameters does V4-Flash use?"))
Step 6: Verify it worked
一个有效的集成显示三个迹象:
response.content包含一个合理的答案。返回一个类似于被填充了非零的令牌计数。response.response_metadata["model_name"]反映了您请求的模型(或它解析到的别名,对于旧ID)。
如果您启用了思考模式,也请检查 additional_kwargs["reasoning_content"] 非空。空推理但有填充的答案通常意味着请求退回到非思考模式——请验证您的 extra_body 是否已通过。
Common errors and fixes
| Symptom | Likely cause | Fix |
|---|---|---|
AuthenticationError: 401 |
Missing or wrong API key | Re-export DEEPSEEK_API_KEY;重启shell |
找不到错误:模型未找到 |
模型ID拼写错误,或自2026年7月24日起使用已弃用的名称 | Use deepseek-v4-flash or deepseek-v4-pro |
Empty content in JSON mode |
提示中缺少单词“json”,或 max_tokens too low |
添加JSON模式示例;引发 max_tokens |
| 截断推理内容 | reasoning_effort="max" 因上下文预算不足 |
Set max_tokens ≥ 384,000 或降低到 "high" |
| 工具未被调用 | 工具描述过于模糊 | 重写文档字符串以描述 when 使用此工具 |
速率限制错误 |
超过您账户的RPM限制 | 使用指数退避重试;参见 DeepSeek API rate limits |
当LangChain不是正确选择时
并非每个DeepSeek项目都能从LangChain包装器中受益。对于从脚本或Lambda发起的单次API调用,官方的OpenAI SDK指向 https://api.deepseek.com 更短且部件更少。当您需要编排时,LangChain才体现出其价值:提示、检索器、工具调用、代理、内存或LangSmith跟踪表面链。如果您的项目是“发送一个提示,得到一个答案”,请直接调用 POST /chat/completions 。如果您的项目是“检索、规划、调用工具、总结”,LangChain可以节省实际时间。
Next steps

- 将LangChain集成与不同框架的等效流程进行比较——参见我们的 DeepSeek with LlamaIndex walkthrough.
- 使用我们的工具将相同模型连接到Streamlit UI DeepSeek Streamlit应用教程.
- 浏览我们其他模式 深入了解DeepSeek的逐步指南.
- 通过阅读完整内容来决定您的负载是选择Flash还是Pro DeepSeek V4 overview.
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
我应该如何安装LangChain DeepSeek集成?
Run pip install -U langchain-deepseek 在Python 3.10+虚拟环境中,然后导出您的密钥为 DEEPSEEK_API_KEY。该软件包包含 langchain-core and langchain-openai 作为依赖项。导入 ChatDeepSeek from langchain_deepseek。有关完整教程,包括如何获取密钥,请参阅我们关于获取DeepSeek API密钥的指南 用于标准聊天、RAG和分类,或.
今天我应该使用什么模型名与ChatDeepSeek配合?
Use deepseek-v4-flash 用于前沿编码和代理工作。有关等级指导的旧ID deepseek-v4-pro 用于V4模型在两个等级上。ChatDeepSeek继承 deepseek-chat and deepseek-reasoner 仍然可以使用,但已计划于2026年7月24日15:59 UTC退役,之后将无法使用。请参阅完整信息。 DeepSeek V4 overview 作为尽力而为,因为DeepSeek API可能会忽略该标志。对于更详细的说明,请浏览我们的
ChatDeepSeek支持工具调用和结构化输出吗?
ChatOllama bind_tools() and 作为尽力而为,因为DeepSeek API可能会忽略该标志。对于更详细的说明,请浏览我们的 从OpenAI的基类继承并路由到DeepSeek的功能调用或JSON模式端点。请处理。 ChatOllama 教程,它涵盖了设置过程。 DeepSeek API function calling reference.
我能否在本地使用LangChain运行DeepSeek,而不是通过API?
是的。V4权重是MIT许可的且开源。大多数团队通过Ollama或vLLM运行它们,并通过覆盖基本URL将ChatDeepSeek(或LangChain的)指向本地端点。硬件需求很大——Flash上的13B个活跃参数是更实际的本地目标。我们的 ChatOllama对于一百万次V4-Flash调用,带有2,000个token的缓存系统提示,200个token的用户消息和300个token的回答,预计每月约117.60美元:56美元的缓存输入,28美元的非缓存输入,84美元的输出。在V4-Pro上执行相同的工作负载大约需要1,421美元。使用我们的工具估算您自己的数字。 running DeepSeek on Ollama walkthrough covers the setup.
典型的LangChain + DeepSeek工作流程的成本是多少?
估算您自己的数字。 DeepSeek pricing calculator.
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
- Model cardDeepSeek on Hugging FaceWeights, license, usage notes per modelLast checked: April 30, 2026
- PricingDeepSeek API pricing page成本计算示例的参考利率Last checked: April 30, 2026
Technical references
- Technical reportDeepSeek-V3 technical report (arXiv:2412.19437)V3 architecture and training methodologyLast checked: April 30, 2026
- Technical reportDeepSeek-R1 paper (arXiv:2501.12948)R1 reasoning approach, distillation resultsLast 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
人工智能工具发展迅速。如果您发现过时的数字或损坏的链接,页脚中的联系链接是向编辑团队报告的最快方式。