跳转到主内容
极星编程网:以代码为星,赴技术山海!

DeepSeek与LangChain框架的集成方法

优先使用langchain-deepseek官方包+OpenAI兼容接口,通过ChatDeepSeek调用远程API;本地部署用OllamaLLM需注意工具调用和上下文限制;嵌入维度须与向量库严格对齐为1024;启用Messages API需配置response_format和anthropic-version头。 ☞☞☞AI 智能聊天, 问答助手, AI 智能搜索, 多模态理解力帮你轻松跨越从0到1的创作门槛☜☜☜ DeepSeek 与 LangChain 集成没有统一“标准路径”,关键取决于你用的是远程 API 还是本地模型,以及是否启用 RAG、Memory 或 Agent 等高级能力。直接结论:优先走
langchain-deepseek
官方包 + OpenAI 兼容接口路线,它覆盖 95% 的生产场景,且适配 DeepSeek-V4 的百万 token 上下文和双协议(ChatCompletions / Messages)。 用
ChatDeepSeek
调用远程 DeepSeek API(推荐默认方案) 这是最稳定、兼容性最好、无需维护模型服务的集成方式,尤其适合刚起步或资源有限的项目。 必须安装
langchain-deepseek
(不是
deepseek-api
或旧版
langchain
自带的
DeepSeek
类),否则会缺失 V4 的流式响应、tool calling 和 message 格式支持
api_key
必须通过环境变量传入(
DEEPSEEK_API_KEY
),硬编码在代码里会导致
ValueError: api_key must be provided
或被 IDE 自动提交到 Git
base_url
默认为
"https://api.deepseek.com"
,但 V4 支持
/v1
后缀;若遇到
404 Not Found
,显式设为
"https://api.deepseek.com/v1"
模型名要严格匹配官方命名:
"deepseek-chat"
(通用)、
"deepseek-coder"
(编程)、
"deepseek-math"
(数学),错写成
"deepseek-v4"
会返回
404
用
OllamaLLM
调用本地 DeepSeek 模型(如
deepseek-r1:7b
) 适用于有 GPU 且需离线、低延迟、可控推理参数的场景,但注意 LangChain 对 Ollama 的封装较浅,很多 V4 特性无法透出。 必须提前在本地运行 Ollama,并执行
ollama pull deepseek-r1:7b
(或其他已发布的量化版本) 初始化时
base_url
必须是
"http://localhost:11434"
,Ollama 不支持 HTTPS 或自定义端口重定向
OllamaLLM
不支持
tools
字段,调用函数时会静默忽略,需改用
ChatOllama
并手动构造
messages
列表 本地模型不自动继承 LangChain 的
ConversationBufferMemory
历史压缩逻辑,长对话容易触发
context length exceeded
,建议配合
ConversationBufferWindowMemory
限制轮数 嵌入模型(Embeddings)与向量库对齐失败的典型表现 当 RAG 效果差、检索结果不相关、Chroma 报
dimension mismatch
,大概率是嵌入维度没对齐,而不是模型本身问题。 稿定在线PS PS软件网页版 下载 DeepSeek 专业版 API 返回的嵌入维度通常是
1024
,但
OpenAIEmbeddings
默认输出
1536
,直接替换会崩溃 不要复用
HuggingFaceEmbeddings
加载任意 sentence-transformers 模型——DeepSeek 的 tokenizer 和归一化策略不同,会导致余弦相似度低于
0.9
验证方法:调用一次
embed_query("hello")
,打印
len(result)
,必须等于你初始化 Chroma 时传入的
collection_metadata={"hnsw:space": "cosine", "dimension": 1024}
若使用 FAISS,必须用
FAISS.from_documents(..., embedding=your_deepseek_embedding)
显式传入,不能依赖默认嵌入器 启用 DeepSeek-V4 的 Messages API 模式(Agent 场景必需) LangChain 的
AgentExecutor
和
ToolCallingAgent
默认依赖 Anthropic-style 的
messages
输入格式,而老式
ChatCompletions
(
prompt
+
stop
)无法解析 tool call 结构。 必须设置
model_kwargs={"response_format": {"type": "json_object"}}
才能启用 JSON 工具调用响应
ChatDeepSeek
初始化时加
default_header={"anthropic-version": "2023-06-01"}
可强制走 Messages 协议(V4 支持双模式) Agent 中使用的
tools
列表必须是
BaseTool
子类实例,不能是普通函数;否则会报
ValidationError: 2 validation errors for ToolCall
流式响应下,tool call 的
delta.content
是空字符串,真正 payload 在
delta.tool_calls
里,需用
StreamingStdOutCallbackHandler
以外的自定义 handler 解析 最容易被忽略的一点:DeepSeek-V4 的百万 token 上下文不是“开箱即用”的——LangChain 的
ConversationBufferMemory
默认把全部历史拼进 prompt,超过 100k 就会触发 token 截断且无提示。真要用长上下文,得自己实现基于
retriever
的稀疏记忆或用
SummaryBufferMemory
做摘要压缩。

相关文章