用DeepSeek V4打造你的智能体,超简单版本

用DeepSeek V4打造你的智能体,超简单版本

hejiashenghejiasheng
7 次阅读
DeepSeek智能体Node.js
文章目录

零基础上手:用 DeepSeek V4 打造你的首个 AI 智能体 (Agent)

为什么需要智能体?

打造智能体不仅充满乐趣,更因为它能实实在在地提升效率。相比传统的聊天机器人,智能体能够理解复杂任务、拆解步骤并调用外部工具来解决实际问题。

打造智能体难吗?

入门非常简单。 虽然想要做到极致的精准需要持续的调优经验,但通过现有的 SDK,你可以在几分钟内搭建出一个具备基础能力的原型。

技术栈选择

目前 Node.js 和 Python 都有非常成熟的 SDK 支持。本文将以 Node.js 为例,带你快速跑通流程。


核心原理:从 Chat 到 Agent 的进化

很多开发者已经习惯了调用 API 做一个简单的聊天机器人(Chat),但总觉得智能体(Agent)遥不可及。

其实,两者的核心区别仅在于一步:赋予模型“使用工具”的能力

  • Chat: 接收输入 -> 生成文本。
  • Agent: 接收输入 -> 思考是否需要工具 -> 调用工具获取数据 -> 汇总结果 -> 生成最终回复。

1. 基础篇:DeepSeek Chat 官方示例

在构建 Agent 之前,我们先看一个标准的对话调用。DeepSeek 兼容 OpenAI SDK,这让迁移变得极其简单。

js
// 安装 SDK: npm install openaiimport OpenAI from "openai";const openai = new OpenAI({  baseURL: 'https://api.deepseek.com',  apiKey: process.env.DEEPSEEK_API_KEY, // 建议使用环境变量存储 Key});async function main() {  const completion = await openai.chat.completions.create({    messages: [{ role: "system", content: "你是一个得力的助手。" }],    model: "deepseek-chat",     stream: false,  });  console.log("模型回复:", completion.choices[0].message.content);}main();

要点说明:

  • BaseURL: 必须指向 https://api.deepseek.com
  • API Key: 请前往 DeepSeek 开发者平台获取。
  • 兼容性: 只要是支持 OpenAI 协议的库,都可以无缝接入 DeepSeek。

2. 进阶篇:构建你的首个 Agent

从 DeepSeek V4 开始,模型对 tool_calls(工具调用)的支持已经非常完美。这是实现业界通用 Agent 的基石。

实战例子:具备“天气查询”与“计算器”能力的 Agent

下面的代码演示了模型如何自主决定调用哪些工具来完成一个复合任务。

js
import OpenAI from "openai";const openai = new OpenAI({  baseURL: "https://api.deepseek.com",  apiKey: process.env.DEEPSEEK_API_KEY || "你的API_KEY",});const MODEL = "deepseek-chat";const MAX_ROUNDS = 5; // 限制思考轮数,防止死循环/** 模拟外部 API:获取天气 */function fakeWeather(city) {  const tempC = Math.round(15 + Math.random() * 15);  return { city, temp_c: tempC, condition: "晴转多云" };}/** 工具分发器:执行具体的逻辑 */function dispatchTool(name, rawArgs) {  let args = {};  try {    args = typeof rawArgs === "string" ? JSON.parse(rawArgs) : rawArgs;  } catch (e) {    return JSON.stringify({ ok: false, error: "参数解析失败" });  }  if (name === "get_weather") {    return JSON.stringify({ ok: true, ...fakeWeather(args.city) });  }  if (name === "calc") {    const { a, b, op } = args;    let result;    switch (op) {      case "+": result = a + b; break;      case "-": result = a - b; break;      case "*": result = a * b; break;      case "/": result = b !== 0 ? a / b : "除零错误"; break;      default: return JSON.stringify({ ok: false, error: "不支持的运算" });    }    return JSON.stringify({ ok: true, result });  }  return JSON.stringify({ ok: false, error: "未知工具" });}/** 定义工具 Schema:告诉模型你有哪些能力 */const TOOLS = [  {    type: "function",    function: {      name: "get_weather",      description: "查询指定城市当前的模拟气温。",      parameters: {        type: "object",        properties: {          city: { type: "string", description: "城市名称,如:北京" },        },        required: ["city"],      },    },  },  {    type: "function",    function: {      name: "calc",      description: "基础算术计算器,支持加减乘除。",      parameters: {        type: "object",        properties: {          a: { type: "number" },          b: { type: "number" },          op: { type: "string", enum: ["+", "-", "*", "/"] },        },        required: ["a", "b", "op"],      },    },  },];async function runAgent(userText) {  const messages = [    { role: "system", content: "你是一个全能助手。请调用工具获取信息,并以中文简短回复。" },    { role: "user", content: userText },  ];  for (let i = 0; i < MAX_ROUNDS; i++) {    const response = await openai.chat.completions.create({      model: MODEL,      messages,      tools: TOOLS,    });    const msg = response.choices[0].message;    messages.push(msg); // 将模型的思考过程存入历史    if (!msg.tool_calls) {      return msg.content; // 没有工具调用,说明任务完成    }    // 处理工具调用请求    for (const tool of msg.tool_calls) {      const result = dispatchTool(tool.function.name, tool.function.arguments);      console.log(`[执行工具] ${tool.function.name}: ${result}`);      messages.push({        role: "tool",        tool_call_id: tool.id,        content: result,      });    }  }}// 测试任务const question = "查一下北京和上海的模拟气温,再帮我算出两者温差是多少度。";runAgent(question).then(res => console.log("\n最终回答:", res));

总结

通过上面的例子,你可以看到:Agent 的本质就是“模型思考 + 工具执行”的循环。DeepSeek V4 强大的逻辑推理能力,使得它能精准地判断何时该查数据、何时该算数。

打造一个属于自己的 Agent,其实就是这么简单。


这是我关于 智能体 的 系列教程的第一篇。我基于这一套 Agent 逻辑开发了 MarkWrite 编辑器,它能借助大模型实现文章润色、自动标签生成等功能。后续我将分享更多关于智能体实战的干货,欢迎关注!

入门了一切就都好办了。

评论区0

还没有评论,快来抢沙发吧~

登录 后可发表评论