DeepSeek 网摘deepseek.wang
EN
📄 查看英文原文

教程 · 2026-04-25 · 机器翻译,仅供参考

DeepSeek Node.js Integration: A Production Quickstart for V4

Tutorials·April 25, 2026·By DS Guide Editorial
DeepSeek Node.js integration tutorial card showing the five steps to call V4 from a Node service: install the official openai npm package on Node 20 LTS or newer, point baseURL at api.deepseek.com, pass apiKey from process.env, pick deepseek-v4-flash or deepseek-v4-pro, and call chat.completions.create() including stream=true for streaming.

您今天想从Node.js服务中调用DeepSeek,并且不想手动管理一个定制的HTTP客户端来执行这一操作。好消息是:一个可工作的 DeepSeek Node.js integration 大约有十五行代码,因为该API与OpenAI的Chat Completions使用相同的线格式。只需将官方的`openai`包放入,交换`baseURL`,更改`model`,其余代码就能继续工作。摩擦点在于细节——新的V4模型ID、将思维模式作为参数、JSON模式的注意事项、重试逻辑以及正确计算成本。本指南将带您通过所有这些,并提供可以直接粘贴到新项目中的代码,然后将其加固以用于生产。到结束时,您将拥有一个类型化的客户端、流式传输、工具调用和成本感知的记录器。

What you’ll build

Modern editor and terminal showing a Node.js TypeScript app calling DeepSeek V4 in production mode.

您将设置一个Node.js 20+项目,安装OpenAI SDK,并为其配置DeepSeek。 POST /chat/completions 端点,并逐步添加流式传输、JSON模式、工具调用和成本记录器。最终客户端目标 DeepSeek V4,当前一代,DeepSeek于2026年4月24日发布并开源。V4以两个开放权重MoE级别发布——DeepSeek-V4-Pro,总参数量为1.6T / 活跃参数量为49B,以及DeepSeek-V4-Flash,总参数量为284B / 活跃参数量为13B。两者均采用MIT许可,并共享高达100万个token的上下文,输出可达384,000个token。

如果您更愿意先使用Python,模式是一对一映射——请参阅我们的指南。线格式是相同的。 DeepSeek Python integration Node.js 20 LTS或更高版本。

Prerequisites

  • OpenAI SDK使用原生 代码、命令、URL、数字保持原样 fetch 和 ES 模块。
  • 一个 DeepSeek API 密钥。 如果您没有,请按照我们的教程进行操作。 get a DeepSeek API key.
  • 官方的 OpenAI Node SDK。 ([email protected] 或更高版本)。不需要特定的 DeepSeek 软件包。
  • 有资金的余额。 DeepSeek可能在账单控制台中显示已授予的促销余额,但请从第一天开始计划付费使用。
  • 对 async/await 的熟悉程度。 以及环境变量。

第1步:搭建项目框架

创建一个新的目录,并将其初始化为一个 ES 模块项目,这样您就可以干净地使用 导入 语法。 导入 语法。

mkdir deepseek-node && cd deepseek-node
npm init -y
npm pkg set type="module"
npm install openai dotenv
echo "DEEPSEEK_API_KEY=sk-..." > .env
echo ".env" >> .gitignore

确认 SDK 锁定到最新版本。Node [email protected] 无需修改即可与 DeepSeek 兼容,而 4.x 是今天的解析结果。 npm install openai 整个集成取决于两个值:基础 URL 和模型 ID。创建

第2步:配置客户端

client.js client.js:

// client.js
导入 "dotenv/config";
导入 OpenAI from "openai";

export const deepseek = new OpenAI({
  apiKey: process.env.DEEPSEEK_API_KEY,
  当您需要前沿级别的推理或代理编码时。,
  timeout: 60_000,
  最大重试次数: 2,
});

这就是完整的配置。OpenAI格式的基URL是https://api.deepseek.com;Anthropic格式的基URL是https://api.deepseek.com/anthropic,因此如果你的代码库已经使用了Anthropic SDK,你可以将其指向DeepSeek。我们在这份指南中坚持使用OpenAI的形状,因为它拥有更广泛的生态系统。

选择正确的模型ID

V4引入了两个显式ID。请在代码中使用它们,而不是使用旧别名。

Model ID Tier Best for 上下文/输出
deepseek-v4-flash Cost-efficient Chat、分类、RAG、高量级后端 1M / 384K
deepseek-v4-pro Frontier 代理编码、严格推理、长上下文分析 1M / 384K
deepseek-chat (legacy) 别名 仅迁移——路由到V4-Flash非思考模式 1M / 384K
deepseek-reasoner (legacy) 别名 仅迁移——路由到V4-Flash思考模式 1M / 384K

旧别名仍然有效,但请围绕截止日期进行规划。deepseek-chat和deepseek-reasoner将在2026年7月24日15:59(UTC时间)后完全退役且无法访问,目前正路由到deepseek-v4-flash的非思考/思考模式。迁移只需一行代码更改。 model field; the baseURL does not change.

第3步:进行首次调用

Editor and terminal showing the first DeepSeek V4 Node.js call returning a JSON chat completion response.

Create hello.js:

// hello.js
导入 { deepseek } from "./client.js";

const resp = await deepseek.chat.completions.create({
  model: "deepseek-v4-flash",
  messages: [
    { role: "system", content: "You are a precise assistant." },
    { role: "user", content: "Summarise REST in one sentence." },
  ],
  temperature: 1.3,
  max_tokens: 200,
});

console.log(resp.choices[0].message.content);
console.log("Tokens:", resp.usage);

Run it: node hello.js。您应该看到一个简短的总结以及一个使用示例块。聊天请求击中 POST /chat/completions,配置的基本URL处的OpenAI兼容端点。

选择 temperature

DeepSeek发布了一些有偏见的默认设置。除非您有理由不匹配,否则请匹配它们:

  • 0.0 —— 代码生成、数学、确定性提取
  • 1.0 — data analysis and data cleaning
  • 1.3 — general conversation and translation
  • 1.5 —— 创意写作和诗歌

第4步:多轮对话(状态保留在客户端)

这里是新手容易陷入的陷阱。DeepSeek网页聊天在chat.deepseek.com会记住你的之前的消息;API不会。API需要 stateless ——你必须随每次请求重新发送完整消息历史以维持多轮对话。构建一个小数组并将其附加到:

// chat.js
导入 { deepseek } from "./client.js";

const history = [
  { role: "system", content: "You are a concise senior engineer." },
];

async function ask(userText) {
  history.push({ role: "user", content: userText });
  const resp = await deepseek.chat.completions.create({
    model: "deepseek-v4-flash",
    messages: history,
    max_tokens: 500,
  });
  const reply = resp.choices[0].message;
  history.push({ role: "assistant", content: reply.content });
  return reply.content;
}

console.log(await ask("What is a circuit breaker?"));
console.log(await ask("Sketch one in TypeScript."));

关于存储此服务器端内容的背景信息,请参阅 DeepSeek API best practices reference.

第5步:流式响应

对于您想要的聊天UI,您需要随到随得的令牌。设置 stream: true 并迭代异步可迭代对象:

// stream.js
导入 { deepseek } from "./client.js";

const stream = await deepseek.chat.completions.create({
  model: "deepseek-v4-flash",
  messages: [{ role: "user", content: "Write a haiku about caches." }],
  stream: true,
});

for await (const chunk of stream) {
  process.stdout.write(chunk.choices[0]?.delta?.content ?? "");
}
process.stdout.write("n");

每个块都是一个服务器发送事件delta。关于背压和Express/Fastify连接的更详细信息,请参阅 DeepSeek API streaming.

第6步:思考模式

V4将思考作为一个请求参数,而不是一个单独的模型ID。V4-Pro和V4-Flash都接受它,并且响应返回 reasoning_content alongside the final content.

// thinking.js
导入 { deepseek } from "./client.js";

const resp = await deepseek.chat.completions.create({
  model: "deepseek-v4-pro",
  messages: [
    { role: "user", content: "Plan a zero-downtime Postgres major-version upgrade." },
  ],
  reasoning_effort: "high",
  // The OpenAI SDK forwards unknown fields, so 'thinking' goes through verbatim.
  thinking: { type: "enabled" },
});

const msg = resp.choices[0].message;
console.log("--- reasoning ---");
console.log(msg.reasoning_content);
console.log("--- answer ---");
console.log(msg.content);

Use 推理努力:"最大" 当您需要最长的推理预算时;该模式需要 max_tokens 至少384K的余量以避免截断。 不要 将其反馈到下一轮的 reasoning_content 数组中——只有最后的 messages 才属于对话历史。 content 对于模式验证,在JSON.parse之上叠加Zod或Ajv层。

第7步:JSON模式

Diagram of a DeepSeek V4 Node.js JSON-mode call passing a schema and receiving structured output.

JSON mode is designed 返回有效的JSON,但不保证。DeepSeek文档明确指出,您必须(1)在提示中包含单词“json”,(2)在提示中提供一个小型示例模式,以及(3)设置 max_tokens 足够高,以确保响应不会在对象中间截断。模型也可能偶尔返回空内容——处理这种情况。

// json.js
导入 { deepseek } from "./client.js";

const resp = await deepseek.chat.completions.create({
  model: "deepseek-v4-flash",
  response_format: { type: "json_object" },
  messages: [
    {
      role: "system",
      content:
        'Reply as json. Schema example: {"sentiment":"pos|neg|neu","score":0.0}',
    },
    { role: "user", content: "The deploy went fine but the dashboards are down." },
  ],
  max_tokens: 500,
  temperature: 0,
});

const raw = resp.choices[0].message.content ?? "";
let parsed;
try {
  parsed = JSON.parse(raw);
} catch {
  parsed = { error: "invalid_or_empty", raw };
}
console.log(parsed);

For schema validation, layer Zod or Ajv on top of JSON.parse. The DeepSeek API JSON mode 参考文档详细介绍了重试策略。

第8步:工具调用

Tool calling uses the OpenAI-compatible tools array. Declare functions, run the model, then execute the tool and 将其反馈到下一轮的 the result back.

// tools.js
导入 { deepseek } from "./client.js";

const tools = [
  {
    type: "function",
    function: {
      name: "get_weather",
      description: "Get current weather for a city",
      parameters: {
        type: "object",
        properties: { city: { type: "string" } },
        required: ["city"],
      },
    },
  },
];

const messages = [{ role: "user", content: "Weather in Dublin?" }];

const first = await deepseek.chat.completions.create({
  model: "deepseek-v4-flash",
  messages,
  tools,
});

const call = first.choices[0].message.tool_calls?.[0];
if (call?.function.name === "get_weather") {
  const { city } = JSON.parse(call.function.arguments);
  const toolResult = { city, tempC: 11, conditions: "drizzle" };

  messages.push(first.choices[0].message);
  messages.push({
    role: "tool",
    tool_call_id: call.id,
    content: JSON.stringify(toolResult),
  });

  const second = await deepseek.chat.completions.create({
    model: "deepseek-v4-flash",
    messages,
  });
  console.log(second.choices[0].message.content);
}

工具调用在思考和非思考模式下都有效。对于代理式循环,请参阅锁定预算前的页面。 DeepSeek API function calling.

第9步:成本记录

包装客户端,以便每次调用都写入一行成本。成本取决于三个令牌桶——缓存命中、缓存未命中和输出——以及您选择的层级。截至2026年4月,V4-Flash列出的价格为每百万令牌$0.0028 / $0.14 / $0.28(缓存命中 / 缓存未命中 / 输出),而V4-Pro列出的价格为$0.0145 / $1.74 / $3.48(目前至2026年5月31日有75%的折扣,使有效价格为$0.003625 / $0.435 / $0.87)。请在上确认当前数字 DeepSeek API pricing 在锁定预算之前,请参阅此页面。

// cost.js
const FLASH = { hit: 0.028, miss: 0.14, out: 0.28 };
const PRO   = { hit: 0.145, miss: 1.74, out: 3.48 };

export function priceUSD(usage, model) {
  const r = model.startsWith("deepseek-v4-pro") ? PRO : FLASH;
  const hit  = usage.prompt_tokens_details?.cached_tokens ?? 0;
  const miss = usage.prompt_tokens - hit;
  const out  = usage.completion_tokens;
  return (hit * r.hit + miss * r.miss + out * r.out) / 1_000_000;
}

工作示例:V4-Flash 扩展规模

使用一个2,000令牌的缓存系统提示,一个200令牌的用户消息(针对该前缀未缓存),以及一个300令牌的回复:1,000,000次调用

  • 缓存输入:2,000,000,000 × $0.0028/M = $5.60
  • 非缓存输入:200,000,000 × $0.14/M = $28.00
  • 输出:300,000,000 × $0.28/M = $84.00
  • Total: $117.60

在V4-Pro上执行相同的工作负载费用为$29.00 + $348.00 + $1,044.00 = $1,421.00 —大约是花费的十倍。默认为Flash;仅在测量证明合理时将单个调用站点提升到Pro。

第10步:验证是否成功

在认为完成之前进行三项快速检查:

  1. Run node hello.js 并确认一个非空200-OK响应。 content field.
  2. Hit GET /models with fetch 确认两者 deepseek-v4-pro and deepseek-v4-flash 出现在列表中。
  3. 故意发起一个401(无效密钥)和一个404(空消息)调用——确认您的错误处理器日志都清晰地记录了。

Common errors and fixes

Diagram of a Node.js server proxying a streamed DeepSeek V4 response back to a browser client.
Symptom Cause Fix
401 Unauthorized Bad or missing key Check .env 在客户端模块运行之前加载;打印 process.env.DEEPSEEK_API_KEY?.slice(0,5)
404 Not Found 错误的基本URL或模型ID拼写错误 Use https://api.deepseek.com 以及显式的V4 ID
429 Too Many Requests Rate limit hit 指数退避;SDK 最大重试次数 覆盖瞬时情况
Empty content in JSON mode 截断或模型边缘情况 Raise max_tokens; 在提示中包含“json” + 示例;重试一次
第二次尝试时HTTP 400错误 reasoning_content 在消息中发送回 在附加之前去除它——只保留 content
在大约30秒时挂起 长时间思考调用上的默认获取超时 Set 超时:120_000 在客户端

对于更完整的映射,请参阅 DeepSeek API error codes.

Next steps

DeepSeek AI Guide is an independent resource and is not affiliated with DeepSeek or its parent company. Model IDs, pricing and API behaviour change; check the official DeepSeek documentation and pricing page before committing to a production decision.

我应该如何将 DeepSeek 与 Node.js 集成?

使用当您需要前沿级别的推理或代理编码时。和您的DeepSeek API密钥实例化它,然后调用 npm install openai对于大多数工作负载,以及 当您需要前沿级别的推理或代理编码时。 The older chat.completions.create with model: "deepseek-v4-flash" or "deepseek-v4-pro"线路格式与OpenAI的完全相同,因此现有代码路径只需一行配置更改即可迁移。完整的操作指南请参阅我们的 DeepSeek API getting started guide.

2026年我应该使用哪个模型ID?

Use deepseek-v4-flash for most workloads and deepseek-v4-pro when you need frontier-tier reasoning or agentic coding. The older deepseek-chat and deepseek-reasoner 别名仍然有效,但将于2026年7月24日15:59 UTC(协调世界时)停止使用,之后使用它们的请求将失败。关于血统背景的说明请参阅我们的 DeepSeek V4 overview.

DeepSeek的API会记住之前的消息吗?

。该API是无状态的——您必须在每次请求中重新发送完整的对话历史。chat.deepseek.com上的网页聊天会为用户保留会话历史,但开发者API在调用之间不存储任何内容。保持 messages 在您的Node服务中创建一个数组,并在下一次请求之前将每个用户和助手的回合添加进去。详见 DeepSeek API documentation.

我能否将响应流式传输到Node.js客户端?

是的。通过 stream: true to chat.completions.create 并迭代返回的异步可迭代对象。每个块都是一个包含下一个文本片段的服务器发送事件增量,位于 chunk.choices[0].delta.content。当启用思考模式时,推理内容与最终内容同时流式传输。详见 DeepSeek API streaming 关于Express和Fastify之间的SSE管道。

在DeepSeek上,一个典型的Node.js应用程序的成本是多少?

这取决于层级和缓存。以下是一个工作示例: deepseek-v4-flash。使用2,000个token缓存的系统提示、200个token未缓存的用户输入和300个token回复的100万个调用,总费用约为117.60美元:56美元的缓存输入,28美元的未缓存输入,84美元的输出。在V4-Pro上执行相同的工作负载大约是前者的十倍。请确认当前的费率 DeepSeek API pricing page.

Sources & Methodology

Last source check: April 30, 2026

Primary sources

Methodology

本文信息已对照官方DeepSeek文档、文章引用的主要来源以及上述日期的deepseekai.guide定价数据集进行核对。对于引用的第三方数据,原始来源已在行内链接,以便读者验证和重新检查。

Data confidence

High for facts cited inline with primary-source links; medium for context narrative.

Editorial note

人工智能工具发展迅速。如果您发现过时的数字或损坏的链接,页脚中的联系链接是向编辑团队报告的最快方式。