DeepSeek高级功能与工具调用
本文基于 2026 年真实的 DeepSeek API(OpenAI 兼容) 介绍工具调用(Function Calling)、流式输出、推理模型 R1 的
reasoning_content处理与 JSON 结构化输出。所有代码使用openaiSDK +baseURL: "https://api.deepseek.com",不使用任何虚构包或方法,可直接作为面试回答。
目录
- ⚠️ 修订说明:弃用虚构 API
- 🔧 工具调用(OpenAI 格式 Function Calling)
- 🔄 流式输出
- 🧠 推理模型 R1:分离 reasoning_content 与 content
- 📦 JSON 结构化输出
- 🖼️ 关于多模态
- 📝 总结
⚠️ 修订说明:弃用虚构 API
旧版本使用了 new DeepSeekClient()、client.generate({ prompt, tools: true })、client.registerTools()、client.generateStream()、deepseek-multimodal 等——这些都不存在。DeepSeek 是 OpenAI 兼容 API,工具调用、流式、JSON 输出全部走 标准 chat.completions.create 接口。下文据此重写。
🔧 工具调用(OpenAI 格式 Function Calling)
DeepSeek 的工具调用与 OpenAI 完全一致:在请求里传 tools 数组(每个工具是 { type: "function", function: {...} }),模型决定是否调用并在响应里返回 tool_calls。
定义工具
import OpenAI from "openai";
const client = new OpenAI({
apiKey: process.env.DEEPSEEK_API_KEY,
baseURL: "https://api.deepseek.com",
});
const tools = [
{
type: "function",
function: {
name: "get_weather",
description: "获取指定城市的天气信息",
parameters: {
type: "object",
properties: {
city: { type: "string", description: "城市名称,如北京、上海" },
date: { type: "string", description: "日期 YYYY-MM-DD,可选" },
},
required: ["city"],
},
},
},
];
完整调用流程:tool_calls → 执行 → role tool 回注
标准三步:① 模型返回 tool_calls;② 本地执行函数;③ 把结果以 role: "tool" 消息回注,再次请求拿到最终答复。
// 本地函数实现
async function executeTool(name, args) {
if (name === "get_weather") {
// 实际项目替换为真实天气 API
return { city: args.city, date: args.date ?? "today", temperature: "25°C", condition: "晴朗" };
}
throw new Error(`未知工具: ${name}`);
}
async function chatWithTools(userText) {
const messages = [{ role: "user", content: userText }];
// ① 第一次请求:模型可能要求调用工具
let resp = await client.chat.completions.create({
model: "deepseek-chat",
messages,
tools,
tool_choice: "auto",
});
let msg = resp.choices[0].message;
// ② 如果有 tool_calls,逐个执行并回注
while (msg.tool_calls?.length) {
messages.push(msg); // 先把带 tool_calls 的 assistant 消息加入历史
for (const call of msg.tool_calls) {
const args = JSON.parse(call.function.arguments);
const result = await executeTool(call.function.name, args);
messages.push({
role: "tool",
tool_call_id: call.id, // 必须回填对应的 id
content: JSON.stringify(result),
});
}
// ③ 带着工具结果再次请求
resp = await client.chat.completions.create({
model: "deepseek-chat",
messages,
tools,
});
msg = resp.choices[0].message;
}
console.log("最终回复:", msg.content);
return msg.content;
}
chatWithTools("北京明天天气怎么样?");
关键点(面试常考):
tool_calls的function.arguments是 JSON 字符串,需JSON.parse。- 回注时用
role: "tool"且必须带tool_call_id。- 用
while循环支持多轮工具调用,直到模型不再请求工具。
tool_choice 控制调用行为
"auto"(默认):模型自行决定是否调用。"none":禁止调用,强制直接回答。{ type: "function", function: { name: "get_weather" } }:强制调用指定工具。
🔄 流式输出
流式只需 stream: true,逐块读取 delta.content:
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;
}
流式 + 工具调用时,
tool_calls也会分片到达(delta.tool_calls带index),需要按index拼接function.name与function.arguments字符串后再JSON.parse。
🧠 推理模型 R1:分离 reasoning_content 与 content
调用 deepseek-reasoner 时,响应会同时包含推理过程 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; // 真正返回给用户的答案
}
return { reasoning, answer };
}
注意事项:
- 多轮对话只回传
content,不要把reasoning_content加回messages。 - 推理模型通常不支持
temperature、top_p、tools等部分参数(以官方文档为准);需要工具调用时用deepseek-chat。
📦 JSON 结构化输出
要求模型返回合法 JSON,用 response_format: { type: "json_object" },并在提示里明确描述字段结构:
async function extractProduct(reviewText) {
const completion = await client.chat.completions.create({
model: "deepseek-chat",
messages: [
{
role: "system",
content:
'从评论中抽取信息,仅输出 JSON:{"sentiment":"positive|negative|neutral","keyPoints":string[]}',
},
{ role: "user", content: reviewText },
],
response_format: { type: "json_object" },
});
const data = JSON.parse(completion.choices[0].message.content);
return data;
}
extractProduct("这块智能手表续航很好,屏幕清晰,就是价格略高。");
json_object模式保证输出是合法 JSON,但不保证字段完全符合你的业务 schema,仍需做一次校验(如用 Zod)。若用 OpenAI 模型可进一步用json_schema+strict: true强约束结构(见 AI API集成与调用技巧 的 Structured Outputs 专节)。
🖼️ 关于多模态
旧教程里的 deepseek-multimodal 模型 并不存在。截至 2026 年,DeepSeek 主线 API(deepseek-chat / deepseek-reasoner)以文本为主;如确有图像理解需求,请以官方文档当时公布的多模态模型/视觉模型为准,或改用具备成熟视觉能力的模型(如 GPT-5 系列、Gemini 2.5 Pro/Flash、Claude 4.x)。不要臆造模型 ID。
📝 总结
- DeepSeek 高级功能全部走 OpenAI 兼容接口:工具调用用
tools+tool_calls+role: "tool"回注;流式用stream: true;JSON 用response_format。 - R1(
deepseek-reasoner)单独返回reasoning_content,需与content分离,且不回传到下一轮。 - 弃用一切虚构 API(
DeepSeekClient、generate、registerTools、deepseek-multimodal)。 - 工具调用要点:
arguments是 JSON 字符串、回注必须带tool_call_id、用循环支持多轮调用。