DeepSeek快速入门与基础集成
本文基于 2026 年真实的 DeepSeek API 介绍如何快速上手并集成。DeepSeek 提供 OpenAI 兼容 API,因此直接复用
openaiSDK,只改baseURL即可,无需任何专用 SDK。可直接作为面试回答。
目录
- 🚀 什么是 DeepSeek
- 🧠 模型矩阵:deepseek-chat 与 deepseek-reasoner
- 📦 环境准备
- 🔍 基础集成示例
- ⚙️ 模型参数调优
- 🔌 集成到 Web 应用
- 💡 开源与自托管
- 📝 总结
🚀 什么是 DeepSeek
DeepSeek(深度求索)是国产大模型厂商,其模型以强推理能力、开源权重(MIT 许可)和极低价格著称。关键事实(截至 2026 年):
- OpenAI 兼容 API:端点为
https://api.deepseek.com,请求/响应格式与 OpenAI Chat Completions 一致。 - 开源权重:V3、R1 等核心模型以 MIT 许可开源,可商用、可自托管。
- 低成本定位:API 价格显著低于同档位闭源模型,适合大规模/成本敏感场景。
- 不存在
deepseek-sdk这种专用包——历史教程里的new DeepSeekClient()/client.generate({prompt})是虚构的,请勿使用。
🧠 模型矩阵:deepseek-chat 与 deepseek-reasoner
| 模型 ID | 对应能力 | 特点 | 典型用途 |
|---|---|---|---|
deepseek-chat | DeepSeek-V3 系列(MoE 通用对话) | 通用对话、指令遵循、工具调用 | 客服、写作、通用问答 |
deepseek-reasoner | DeepSeek-R1 系列(推理模型) | 先输出思维链,再给答案;返回 reasoning_content 与 content 两部分 | 数学、代码、复杂逻辑推理 |
面试要点:
deepseek-reasoner会在响应中单独返回reasoning_content(推理过程),业务里通常只展示content,把reasoning_content用于调试或折叠展示。推理模型一般不支持temperature、top_p、function calling等部分参数(以官方文档为准)。
📦 环境准备
安装依赖(OpenAI 兼容)
# 直接用 OpenAI 官方 SDK,无需任何 DeepSeek 专用包
npm install openai
获取 API 密钥
- 访问 DeepSeek 开放平台
- 注册并登录
- 创建 API Key
- 通过环境变量
DEEPSEEK_API_KEY注入,切勿硬编码
🔍 基础集成示例
对话补全
DeepSeek 用的是标准 Chat Completions(messages + model),不是 prompt:
import OpenAI from "openai";
const client = new OpenAI({
apiKey: process.env.DEEPSEEK_API_KEY,
baseURL: "https://api.deepseek.com", // 关键:指向 DeepSeek
});
async function generateText() {
const completion = await client.chat.completions.create({
model: "deepseek-chat",
messages: [
{ role: "system", content: "你是一个专业的技术写作助手。" },
{ role: "user", content: "请写一篇关于人工智能发展趋势的短文,约200字。" },
],
temperature: 0.7,
max_tokens: 400,
});
const text = completion.choices[0].message.content;
console.log("生成结果:", text);
return text;
}
generateText();
问答系统
async function answerQuestion(question, context = "") {
const messages = [
{ role: "system", content: "你是一个严谨的问答助手,基于给定上下文作答。" },
];
if (context) {
messages.push({ role: "user", content: `上下文:\n${context}\n\n问题:${question}` });
} else {
messages.push({ role: "user", content: question });
}
const completion = await client.chat.completions.create({
model: "deepseek-chat",
messages,
temperature: 0.3, // 问答求稳,温度调低
});
return completion.choices[0].message.content;
}
answerQuestion("什么是人工智能?");
answerQuestion("人工智能的主要应用领域有哪些?", "人工智能是模拟人类智能的计算机系统。");
多轮对话历史管理
对话历史就是不断累积的 messages 数组,把上一轮的 assistant 回复也加回去:
class ChatBot {
constructor() {
this.messages = [{ role: "system", content: "你是一个友好的助手。" }];
this.maxTurns = 10;
}
async send(userText) {
this.messages.push({ role: "user", content: userText });
const completion = await client.chat.completions.create({
model: "deepseek-chat",
messages: this.messages,
temperature: 0.7,
});
const reply = completion.choices[0].message.content;
this.messages.push({ role: "assistant", content: reply });
// 控制历史长度(保留 system + 最近若干轮)
if (this.messages.length > this.maxTurns * 2 + 1) {
this.messages = [this.messages[0], ...this.messages.slice(-this.maxTurns * 2)];
}
return reply;
}
}
const bot = new ChatBot();
await bot.send("你好,我叫小明。");
await bot.send("我刚才说我叫什么名字?");
流式输出
设置 stream: true 即可逐 token 接收,实现打字机效果:
async function streamChat(userText) {
const stream = await client.chat.completions.create({
model: "deepseek-chat",
messages: [{ role: "user", content: userText }],
stream: true,
});
let full = "";
for await (const chunk of stream) {
const delta = chunk.choices[0]?.delta?.content || "";
process.stdout.write(delta);
full += delta;
}
return full;
}
streamChat("用三句话介绍 Node.js 的事件循环。");
调用推理模型 deepseek-reasoner
推理模型返回的 delta 里会分别带 reasoning_content(思维链) 和 content(最终答案),需要分离处理:
async function reason(question) {
const stream = await client.chat.completions.create({
model: "deepseek-reasoner",
messages: [{ role: "user", content: question }],
stream: true,
});
let reasoning = "";
let answer = "";
for await (const chunk of stream) {
const d = chunk.choices[0]?.delta;
if (d?.reasoning_content) reasoning += d.reasoning_content; // 推理过程
if (d?.content) answer += d.content; // 最终答案
}
console.log("【推理过程,可折叠】", reasoning);
console.log("【最终答案】", answer);
return answer;
}
reason("一个房间有 3 盏灯和 3 个开关,如何用一次进房确定对应关系?");
注意:不要把
reasoning_content再拼回下一轮的messages,多轮对话只回传content,否则会报错或浪费上下文。
⚙️ 模型参数调优
DeepSeek 的对话模型(deepseek-chat)支持标准 OpenAI 参数:
temperature:随机性(0~2),创作调高、问答调低。top_p:核采样,与 temperature 二选一调。max_tokens:限制输出长度。stop:停止序列。frequency_penalty/presence_penalty:抑制重复 / 鼓励新主题。response_format: { type: "json_object" }:要求返回合法 JSON(需在 prompt 中说明 JSON 结构)。
const completion = await client.chat.completions.create({
model: "deepseek-chat",
messages: [{ role: "user", content: "写一首关于春天的现代诗。" }],
temperature: 1.0,
max_tokens: 200,
frequency_penalty: 0.5,
presence_penalty: 0.7,
stop: ["###"],
});
🔌 集成到 Web 应用
Express.js 中封装一个对话接口:
import express from "express";
import OpenAI from "openai";
import "dotenv/config";
const app = express();
app.use(express.json());
const client = new OpenAI({
apiKey: process.env.DEEPSEEK_API_KEY,
baseURL: "https://api.deepseek.com",
});
app.post("/api/chat", async (req, res) => {
try {
const { messages, model = "deepseek-chat", temperature = 0.7 } = req.body;
const completion = await client.chat.completions.create({ model, messages, temperature });
res.json({ success: true, content: completion.choices[0].message.content, usage: completion.usage });
} catch (err) {
res.status(500).json({ success: false, error: err.message });
}
});
// SSE 流式接口
app.post("/api/chat/stream", async (req, res) => {
res.setHeader("Content-Type", "text/event-stream; charset=utf-8");
res.setHeader("Cache-Control", "no-cache, no-transform");
const stream = await client.chat.completions.create({
model: "deepseek-chat",
messages: req.body.messages,
stream: true,
});
for await (const chunk of stream) {
const delta = chunk.choices[0]?.delta?.content || "";
if (delta) res.write(`data: ${JSON.stringify({ delta })}\n\n`);
}
res.write("data: [DONE]\n\n");
res.end();
});
app.listen(3000, () => console.log("DeepSeek 集成示例运行在 http://localhost:3000"));
💡 开源与自托管
DeepSeek 的模型权重以 MIT 许可开源,可下载到自有 GPU 集群推理,常用推理引擎:
- vLLM:高吞吐 OpenAI 兼容服务端,适合生产。
- SGLang:针对长上下文/复杂调度优化,对 R1 类推理模型友好。
# 用 vLLM 起一个 OpenAI 兼容服务(示意)
pip install vllm
python -m vllm.entrypoints.openai.api_server \
--model deepseek-ai/DeepSeek-V3 \
--served-model-name deepseek-chat
自托管后,客户端只需把 baseURL 指向你的 vLLM 服务地址即可,代码不变——这正是「OpenAI 兼容」的价值:云端 API 与自托管可无缝切换。
📝 总结
- DeepSeek = OpenAI 兼容 API,用
openaiSDK +baseURL: "https://api.deepseek.com",没有deepseek-sdk。 - 模型矩阵:
deepseek-chat(V3 通用对话) 与deepseek-reasoner(R1 推理,返回reasoning_content)。 - 支持流式(
stream: true)、JSON 输出(response_format)、标准对话参数。 - 权重 MIT 开源,可用 vLLM / SGLang 自托管,低成本是核心定位。