• 跳过至主导航
  • 跳过前往主要内容
  • 跳过至主侧边栏

三十而立

立志,躬行

  • 静女其姝

DeepSeek JavaScript API 库

2025年2月26日 by glacier 请您留言

安装

npm install openai

使用

该库的完整 API:https://github.com/openai/openai-node/blob/HEAD/api.md
许多代码示例:https://github.com/openai/openai-node/tree/master/examples
下面的代码展示了如何开始使用聊天完成 API。

import OpenAI from 'openai';

const client = new OpenAI({
  baseURL: 'https://api.deepseek.com',
  apiKey: '<your API key>'
});

async function main() {
  const chatCompletion = await client.chat.completions.create({
    messages: [{ role: 'user', content: 'Say this is a test' }],
    model: 'deepseek-chat',
  });
  console.log(chatCompletion.choices[0].message.content);
}

main();

流式响应

我们使用服务器发送事件(SSE)为流式响应提供支持。

import OpenAI from 'openai';

const client = new OpenAI({
  baseURL: 'https://api.deepseek.com',
  apiKey: '<your API key>'
});

async function main() {
  const stream = await client.chat.completions.create({
    model: 'deepseek-chat',
    messages: [{ role: 'user', content: 'Say this is a test' }],
    stream: true,
  });
  for await (const chunk of stream) {
    process.stdout.write(chunk.choices[0]?.delta?.content || '');
  }
}

main();

如果需要取消流,可以从循环中 break 或调用 stream.controller.abort()。

聊天完成串流助手

该库还为流式聊天完成提供了一些便利,例如:

import OpenAI from 'openai';

const client = new OpenAI({
  baseURL: 'https://api.deepseek.com',
  apiKey: '<your API key>'
});

async function main() {
  const stream = await client.beta.chat.completions.stream({
    model: 'deepseek-chat',
    messages: [{ role: 'user', content: 'Say this is a test' }],
    stream: true,
  });

  stream.on('content', (delta, snapshot) => {
    process.stdout.write(delta);
  });
  // 或者,等同于:
  for await (const chunk of stream) {
    process.stdout.write(chunk.choices[0]?.delta?.content || '');
  }
  const chatCompletion = await stream.finalChatCompletion();
  console.log(chatCompletion); // {id: "…", choices: […], …}

}

main();

关于流式响应助手的更多信息:https://github.com/openai/openai-node/blob/HEAD/helpers.md

请求和响应类型

该库包含所有请求参数和响应字段的 TypeScript 定义。您可以像这样导入和使用它们:

import OpenAI from 'openai';

const client = new OpenAI({
  baseURL: 'https://api.deepseek.com',
  apiKey: '<your API key>'
});

async function main() {
  const params: OpenAI.Chat.ChatCompletionCreateParams = {
    messages: [{ role: 'user', content: 'Say this is a test' }],
    model: 'deepseek-chat',
  };
  const chatCompletion: OpenAI.Chat.ChatCompletion = await client.chat.completions.create(params);
}

main();

每个方法、请求参数和响应字段的文档都在 docstrings 中提供,并会在大多数现代编辑器中悬停显示。

文件上传

与文件上传相对应的请求参数可以多种形式传递:

  • File(或具有相同结构的对象)
  • 一个 fetch Response(或具有相同结构的对象)
  • 一个 fs.ReadStream
  • 我们的 toFile 助手的返回值
import fs from 'fs';
import fetch from 'node-fetch';
import OpenAI, { toFile } from 'openai';

const client = new OpenAI({
  baseURL: 'https://api.deepseek.com',
  apiKey: '<your API key>'
});

// 如果您可以访问 Node `fs`,我们建议您使用 `fs.createReadStream()`:
await client.files.create({ file: fs.createReadStream('input.jsonl'), purpose: 'fine-tune' });

// 或者,如果您有 web `File` API,您可以传递一个 `File` 实例:
await client.files.create({ file: new File(['my bytes'], 'input.jsonl'), purpose: 'fine-tune' });

// 您还可以传递一个 `fetch` `Response`:
await client.files.create({ file: await fetch('https://somesite/input.jsonl'), purpose: 'fine-tune' });

// 最后,如果上述方法都不方便,可以使用我们的 `toFile` 助手:
await client.files.create({
  file: await toFile(Buffer.from('my bytes'), 'input.jsonl'),
  purpose: 'fine-tune',
});
await client.files.create({
  file: await toFile(new Uint8Array([0, 1, 2]), 'input.jsonl'),
  purpose: 'fine-tune',
});

处理错误

当库无法连接到应用程序接口,或应用程序接口返回非成功状态代码(即 4xx 或 5xx 响应)时,将抛出一个 APIError 子类:

import OpenAI from 'openai';

const client = new OpenAI({
  baseURL: 'https://api.deepseek.com',
  apiKey: '<your API key>'
});

async function main() {
  const job = await client.fineTuning.jobs
    .create({ model: 'deepseek-chat', training_file: 'file-abc123' })
    .catch(async (err) => {
      if (err instanceof OpenAI.APIError) {
        console.log(err.request_id);
        console.log(err.status); // 400
        console.log(err.name); // BadRequestError
        console.log(err.headers); // {server: 'nginx', ...}
      } else {
        throw err;
      }
    });
}

main();

错误代码如下:

状态代码错误类型
400BadRequestError
401AuthenticationError
403PermissionDeniedError
404NotFoundError
422UnprocessableEntityError
429RateLimitError
>=500InternalServerError
N/AAPIConnectionError

重试

默认情况下,某些错误会自动重试 2 次,指数退避时间较短。连接错误(例如,由于网络连接问题)、408 请求超时、409 冲突、429 速率限制和 >=500 内部错误默认都会重试。

可以使用 maxRetries 选项配置或禁用此功能:

// 为所有请求配置默认值:
const client = new OpenAI({
  maxRetries: 0, // default is 2
});

// 或按请求配置:
await client.chat.completions.create({ messages: [{ role: 'user', content: 'How can I get the name of the current day in JavaScript?' }], model: 'gpt-4o' }, {
  maxRetries: 5,
});

超时

请求默认在 10 分钟后超时。您可以使用 timeout 选项对此进行配置:

// 为所有请求配置默认值:
const client = new OpenAI({
  timeout: 20 * 1000, // 20 seconds (default is 10 minutes)
});

// 覆盖每个请求:
await client.chat.completions.create({ messages: [{ role: 'user', content: 'How can I list all files in a directory using Python?' }], model: 'gpt-4o' }, {
  timeout: 5 * 1000,
});

超时时,将抛出 APIConnectionTimeoutError 错误。

请注意,超时的请求默认会重试两次。

请求 ID

有关调试请求的更多信息,请参阅这些文档:https://platform.openai.com/docs/api-reference/debugging-requests

SDK 中的所有对象响应都提供了一个 _request_id 属性,该属性是从 x-request-id 响应头中添加的,因此您可以快速记录失败的请求并将其报告给 DeepSeek。

import OpenAI from 'openai';

const client = new OpenAI({
  baseURL: 'https://api.deepseek.com',
  apiKey: '<your API key>'
});

async function main() {
  const completion = await client.chat.completions.create({ messages: [{ role: 'user', content: 'Say this is a test' }], model: 'deepseek-chat' });
  console.log(completion._request_id) // req_123
}

main();

您还可以使用 .withResponse() 方法访问请求 ID:

const { data: stream, request_id } = await client.chat.completions
.create({
model: 'deepseek-chat',
messages: [{ role: 'user', content: 'Say this is a test' }],
stream: true,
})
.withResponse();

自动分页

OpenAI API 中的列表方法是分页的。您可以使用 for await …语法遍历所有页面中的项目:

async function fetchAllFineTuningJobs(params) {
  const allFineTuningJobs = [];
  // 根据需要自动获取更多页面。
  for await (const fineTuningJob of client.fineTuning.jobs.list({ limit: 20 })) {
    allFineTuningJobs.push(fineTuningJob);
  }
  return allFineTuningJobs;
}

或者,您也可以一次申请一个页面:

let page = await client.fineTuning.jobs.list({ limit: 20 });
for (const fineTuningJob of page.data) {
  console.log(fineTuningJob);
}

// 提供了手动分页的便捷方法:
while (page.hasNextPage()) {
  page = await page.getNextPage();
  // ...
}

实时 API 测试版

实时 API 使您能够构建低延迟、多模式的会话体验。它目前支持将文本和音频作为输入和输出,以及通过 WebSocket 连接进行函数调用。

import { OpenAIRealtimeWebSocket } from 'openai/beta/realtime/websocket';

const rt = new OpenAIRealtimeWebSocket({ model: 'gpt-4o-realtime-preview-2024-12-17' });

rt.on('response.text.delta', (event) => process.stdout.write(event.delta));

更多信息,请参阅:https://github.com/openai/openai-node/blob/HEAD/realtime.md

自动函数调用

我们提供了 openai.beta.chat.completions.runTools({…}) 方便的助手,用于在 /chat/completions 端点使用函数工具调用,该工具会自动调用您提供的 JavaScript 函数,并将结果发送回 /chat/completions 端点,只要模型请求工具调用就会循环播放。

更多信息请参阅:https://github.com/openai/openai-node/blob/HEAD/helpers.md#automated-function-calls

分类: 未分类

读者互动

发表回复 取消回复

您的邮箱地址不会被公开。 必填项已用 * 标注

主侧边栏

近期文章

  • Immich 文档:硬件转码
  • Immich 文档:反向代理
  • Immich 文档:Config File
  • Immich 文档:外部图库
  • Immich 文档:快速开始

近期评论

  • 一位WordPress评论者 发表在《世界,您好!》

归档

  • 2025 年 3 月
  • 2025 年 2 月
  • 2019 年 6 月
  • 2019 年 5 月
  • 2019 年 4 月

分类

  • Immich 文档
  • PhotoPrism 文档
  • 未分类

其他操作

  • 登录
  • 条目 feed
  • 评论 feed
  • WordPress.org

Copyright © 2025 · Genesis Sample on Genesis Framework · WordPress · 登录