DeepSeek 的 API 与 OpenAI 接口高度兼容,因此借助 LangChain 的 @langchain/deepseek 包,可以非常简洁地接入。这篇文章带你从零跑通一个最小示例:读取 DeepSeek 的环境变量,然后调用模型完成一次对话。
一、准备工作
先准备一个 Node.js 项目(本文基于 Node 20+),并安装依赖:
mkdir langchain-deepseek-demo && cd langchain-deepseek-demo
npm init -y
npm install langchain @langchain/core @langchain/deepseek
这里安装四个包:
langchain:LangChain 主包,提供链、Agent 等高层能力;@langchain/core:核心抽象;@langchain/deepseek:DeepSeek 的聊天模型集成,内部基于 OpenAI 兼容协议实现。
二、配置环境变量
@langchain/deepseek 默认会读取名为 DEEPSEEK_API_KEY 的环境变量。你可以在 DeepSeek 开放平台 申请 API Key,然后:
export DEEPSEEK_API_KEY="sk-你的密钥"
为了避免把密钥写进代码,也建议在项目里放一个 .env.example 作为模板:
DEEPSEEK_API_KEY=sk-your-api-key-here
注意:
@langchain/deepseek的ChatDeepSeek已经内置了https://api.deepseek.com的 baseURL,正常情况下无需手动配置。
三、编写代码
由于 LangChain 的包是纯 ESM 模块,需要在 package.json 中声明 "type": "module",然后创建 index.js:
import { ChatDeepSeek } from "@langchain/deepseek";
// 1. 读取环境变量
const apiKey = process.env.DEEPSEEK_API_KEY;
if (!apiKey) {
console.error("未找到环境变量 DEEPSEEK_API_KEY,请先设置");
process.exit(1);
}
console.log("已读取环境变量 DEEPSEEK_API_KEY:", `${apiKey.slice(0, 6)}...`);
// 2. 初始化 DeepSeek 聊天模型
const model = new ChatDeepSeek({
model: "deepseek-chat",
apiKey,
temperature: 0.7,
});
// 3. 调用 API 并打印结果
const response = await model.invoke("用一句话介绍你自己");
console.log("\n模型回复:");
console.log(response.content);
代码分三步,非常直观:读取环境变量、构造模型实例、发起调用。
四、运行
确保环境变量已设置,然后直接运行:
node index.js
你会看到类似输出:
已读取环境变量 DEEPSEEK_API_KEY: sk-e24...
模型回复:
我是 DeepSeek,由深度求索公司创造的 AI 助手,随时为你提供帮助。
至此,你已经成功用 LangChain 调通了 DeepSeek API。
五、进阶用法
流式输出
对话内容较长时,流式输出体验更好:
const stream = await model.stream("写一首关于秋天的短诗");
for await (const chunk of stream) {
process.stdout.write(chunk.content);
}
多轮对话
用消息数组维护上下文:
import { HumanMessage, SystemMessage } from "@langchain/core/messages";
const messages = [
new SystemMessage("你是一个简洁的中文助手。"),
new HumanMessage("LangChain 是什么?"),
];
const res = await model.invoke(messages);
console.log(res.content);
把历史消息不断追加进数组,就能实现多轮对话。
结构化输出
需要让模型返回固定结构时,可以配合 schema 做结构化输出,方便程序进一步处理。
六、常见问题:版本兼容
一个容易踩的坑是版本冲突。例如 langchain@1.2.12 会强制要求 @langchain/core@1.1.16,而当前 @langchain/deepseek 依赖的新版 @langchain/openai 需要更新的 core,运行时可能报:
ERR_PACKAGE_PATH_NOT_EXPORTED: Package subpath './errors' is not defined by "exports"
解决办法是让整个依赖树保持一致的较新版本:
npm install langchain@latest @langchain/core@latest @langchain/openai@latest @langchain/deepseek@latest
另外,@langchain/deepseek 是纯 ESM 包,如果在 CommonJS 项目里用 require 引入会报错,使用 import 或把 package.json 的 type 设为 module 即可。
七、小结
用 LangChain 调用 DeepSeek 的完整流程只有三步:设置 DEEPSEEK_API_KEY 环境变量、new ChatDeepSeek(...) 初始化模型、invoke/stream 发起调用。得益于 DeepSeek 的 OpenAI 兼容接口和 LangChain 的统一抽象,你几乎可以零成本切换不同模型,并继续叠加链、工具、Agent 等更复杂的能力。