中文 ▾

unfilteredaiapi.comhttps://api.unfilteredaiapi.com/v1

Unfiltered AI

面向开发者的原始无审查 LLM API。

Unfiltered AI获取 API 密钥

Node.js AI API:Express 中的流式输出、工具调用与错误处理

本 Node.js AI API 教程带你从空文件夹开始,构建一个能流式输出聊天回复、调用工具并处理速率限制错误的 Express 路由。你只需在官方 OpenAI 包中更改 base URL 和密钥,然后发送模型 uncensored 即可。

连接到服务器机柜的六边形齿轮,向浏览器窗口流式传输光粒子

要点

  • 安装 openai 包并将 baseURL 设置为 https://api.unfilteredaiapi.com/v1.
  • 使用 stream: true 进行流式输出,并将 chunks 作为服务器发送事件转发给浏览器。
  • 工具调用以 tool_calls 形式到达;以 role tool 返回结果。
  • 429 表示 rate_limited、concurrency 或临时过载;在 Retry-After 延迟后重试。

设置:安装并发送第一个请求

你需要 Node 18 或更高版本。创建一个项目,安装 SDK 和 Express,并切换到 ES 模块。

mkdir ai-node && cd ai-node
npm init -y
npm pkg set type=module
npm install openai express
# base URL: https://api.unfilteredaiapi.com/v1   model: uncensored
export AI_API_KEY="YOUR_KEY"

从 API 密钥页面获取密钥。新账户可一键领取 $0.50 试用额度,有效期 7 天。然后创建 client.js:

import OpenAI from "openai";

const client = new OpenAI({
  baseURL: "https://api.unfilteredaiapi.com/v1",
  apiKey: process.env.AI_API_KEY,
});

const res = await client.chat.completions.create({
  model: "uncensored",
  messages: [{ role: "user", content: "Give me three names for a tavern keeper." }],
});
console.log(res.choices[0].message.content);

使用 node client.js 运行它。下面的每个代码片段都会重新定义客户端,以便其独立运行。如果你已使用 OpenAI 包,这就是整个迁移过程:不同的 baseURL、你的密钥和模型 ID。该服务兼容 OpenAI 且仅支持文本,具有 100,000 token 上下文窗口。请参阅 文档 了解所有支持的方法。

流式输出回复

流式输出会即时发送生成的 token,让用户立即看到文本。设置 stream: true 并迭代 chunk:

import OpenAI from "openai";

const client = new OpenAI({
  baseURL: "https://api.unfilteredaiapi.com/v1",
  apiKey: process.env.AI_API_KEY,
});

const stream = await client.chat.completions.create({
  model: "uncensored",
  messages: [{ role: "user", content: "Describe a rainy harbor town." }],
  stream: true,
  stream_options: { include_usage: true },
});

for await (const chunk of stream) {
  const delta = chunk.choices[0]?.delta?.content;
  if (delta) process.stdout.write(delta);
  if (chunk.usage) console.log("\nusage:", chunk.usage);
}

使用情况出现在最后一个 chunk 中,这让你可以记录每次请求的实际 token 计数。请记住一个事实:流式请求会占用其并发槽位,直到流结束。如果客户端断开连接,请中止上游调用,以便快速释放槽位。

向浏览器流式输出的 Express 路由

这里有一个带有 POST /chat 路由的小型服务器。它将流作为服务器发送事件(SSE)转发,并在浏览器关闭连接时取消上游请求。

import express from "express";
import OpenAI from "openai";

const client = new OpenAI({
  baseURL: "https://api.unfilteredaiapi.com/v1",
  apiKey: process.env.AI_API_KEY,
});

const app = express();
app.use(express.json({ limit: "1mb" }));

app.post("/chat", async (req, res) => {
  const { messages } = req.body;
  if (Array.isArray(messages) === false) return res.status(400).json({ error: "messages required" });

  res.set({
    "Content-Type": "text/event-stream",
    "Cache-Control": "no-cache",
    Connection: "keep-alive",
  });

  const controller = new AbortController();
  req.on("close", () => controller.abort());

  try {
    const stream = await client.chat.completions.create(
      { model: "uncensored", messages, stream: true },
      { signal: controller.signal }
    );
    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");
  } catch (err) {
    res.write("data: " + JSON.stringify({ error: err.status || 500 }) + "\n\n");
  } finally {
    res.end();
  }
});

app.listen(3000, () => console.log("listening on 3000"));

切勿将密钥放在浏览器代码中。上述路由将其保留在服务器上,这才是它应有的位置。FastAPI 聊天机器人后端 文章中展示了 Python 下的相同模式。

调用工具

工具调用遵循 OpenAI 格式:在 tools 中描述函数,模型通过 tool_calls 回复,你执行函数并将结果作为 role: "tool" 消息发回。

import OpenAI from "openai";

const client = new OpenAI({
  baseURL: "https://api.unfilteredaiapi.com/v1",
  apiKey: process.env.AI_API_KEY,
});

const tools = [{
  type: "function",
  function: {
    name: "roll_dice",
    description: "Roll a die with the given number of sides",
    parameters: {
      type: "object",
      properties: { sides: { type: "integer" } },
      required: ["sides"],
    },
  },
}];

const messages = [{ role: "user", content: "Roll a d20 for my attack." }];
const first = await client.chat.completions.create({
  model: "uncensored", messages, tools, tool_choice: "auto",
});

const msg = first.choices[0].message;
if (msg.tool_calls) {
  messages.push(msg);
  for (const call of msg.tool_calls) {
    const { sides } = JSON.parse(call.function.arguments);
    const result = 1 + Math.floor(Math.random() * sides);
    messages.push({ role: "tool", tool_call_id: call.id, content: String(result) });
  }
  const second = await client.chat.completions.create({ model: "uncensored", messages, tools });
  console.log(second.choices[0].message.content);
}

在实际代码中,始终在 try 块内解析 arguments,因为模型偶尔会返回格式错误的 JSON。对于无需工具的结构化输出,设置 response_format: { type: "json_object" } 并在提示词中提及 JSON。调用骰子或库存函数的游戏场景详见 构建游戏 NPC 和互动小说。

处理错误与速率限制

API 在三种情况下返回 HTTP 429。错误代码 rate_limited 表示每分钟请求过多:完整密钥为 300,试用密钥为 60。代码 concurrency 表示同时请求过多:完整密钥为 8,试用密钥为 2。在临时过载时,你还会收到带有 Retry-After: 5 头的 429。SDK 在抛出的错误中暴露状态,因此小型包装器可处理所有三种情况:

import OpenAI from "openai";

const client = new OpenAI({
  baseURL: "https://api.unfilteredaiapi.com/v1",
  apiKey: process.env.AI_API_KEY,
});

const sleep = (ms) => new Promise((r) => setTimeout(r, ms));

export async function chatWithRetry(params, tries = 4) {
  for (let i = 0; i < tries; i++) {
    try {
      return await client.chat.completions.create({ model: "uncensored", ...params });
    } catch (err) {
      if (err.status === 429 && i < tries - 1) {
        const wait = Number(err.headers?.["retry-after"]) || 2 ** i;
        await sleep(wait * 1000);
        continue;
      }
      throw err;
    }
  }
}

该包装器会等待服务器要求的延迟,然后回退到指数退避。注意,OpenAI 包也会自行重试某些错误;如果希望控制此行为,请在客户端设置 maxRetries。其他状态(如密钥错误的 401)不应重试。有关限制的更深入介绍请参阅 常见问题解答。

运行并测试路由

使用 node server.js 启动服务器,并在第二个终端中测试它。-N 标志关闭 curl 缓冲,以便你看到事件逐个到达:

# the server calls https://api.unfilteredaiapi.com/v1 with model uncensored
curl -N http://localhost:3000/chat   -H "Content-Type: application/json"   -d '{"messages":[{"role":"user","content":"Write a two-line riddle."}]}'

在浏览器中,使用 fetch 和 reader,或使用小型 SSE 辅助库读取流。由于路由是 POST,原生的 EventSource 对象不适用,因此请使用 fetch 并自行解码 chunk。

生产环境习惯

  • 将密钥保存在环境变量或密钥存储中,不要放在仓库中。
  • 限制请求体大小。API 最多接受 8 MB,但你的路由应接受小得多的值。
  • 限制发送的历史记录。在旧对话轮次花费你资金或填满 100,000 token 窗口之前将其修剪。
  • 当已有 8 个流打开时,对额外工作进行排队或拒绝,而不是让 API 向你的用户返回 429。
  • 记录 X-Request-Id 响应头,以便支持团队追踪单个请求。

检查余额和成本

每个响应都带有 X-Balance-USD 头,且 GET /v1/balance 直接返回余额。定价为每 1M 输入 token $0.15,每 1M 输出 token $0.50,从预付额度中扣除,失败或被拒绝的请求免费。一次包含 800 个输入和 250 个输出 token 的聊天轮次成本为 $0.000245,因此 10,000 次轮次成本为 $2.45。记录每个响应的 usage,你可以将账单预测误差控制在几美分以内。定价页面 列出了从 $20 到 $500 的充值选项。

问答

我应该使用哪个 npm 包?

官方 openai 包可用。将 baseURL 设置为 https://api.unfilteredaiapi.com/v1,传入密钥并使用模型 ID uncensored。

Node.js 支持流式输出回复吗?

支持。传入 stream: true 并使用 for await 迭代。添加包含 include_usage 的 stream_options,以便在最后一个 chunk 中获取 token 计数。

API 支持函数调用吗?

支持。发送 tools 和 tool_choice,从回复中读取 tool_calls,并以 role tool 的消息形式返回结果。

我的服务器在 HTTP 429 时应如何处理?

如果存在 Retry-After 值则等待该值,否则进行指数退避,然后重试几次。如果错误代码为 concurrency,请减少并行请求。

只差一张表单,即可获得密钥

创建账户,复制密钥,更改基础 URL。这就是全部设置。

获取 API 密钥阅读文档