Node.js AI API:Express 中的串流、工具與錯誤處理
本 node js ai api 教學帶您從空資料夾開始,建立可串流聊天回覆、呼叫工具並處理速率限制錯誤的 Express 路由。您只需在官方 OpenAI 套件中變更 Base URL 和金鑰,然後傳送模型 uncensored。
更新Unfiltered AI

重點摘要
- 安裝 openai 套件並將 baseURL 設為 https://api.unfilteredaiapi.com/v1.
- 使用 stream: true 進行串流,並將區塊作為伺服器發送的事件 (SSE) 轉發至瀏覽器。
- 工具呼叫以 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 並迭代 chunks:
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);
}
用量會在最後一個區塊出現,讓你能記錄每個請求的實際 token 計數。請記住一件事:串流請求會佔用其並行槽位,直到串流結束。如果客戶端斷線,請中止上游呼叫,以便快速釋放槽位。
向瀏覽器串流的 Express 路由
這是一個帶有 POST /chat 路由的小型伺服器。它將串流作為伺服器發送的事件轉發,並在瀏覽器關閉連線時取消上游請求。
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"));
切勿將金鑰放在瀏覽器程式碼中。上述路由將金鑰保留在伺服器上,這才是正確的位置。Python 的 FastAPI 聊天機器人後端 文章也展示了相同的模式。
呼叫工具
工具呼叫遵循 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)不應重試。限制詳情請見 FAQ。
執行並測試路由
使用 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 和讀取器,或小型 SSE 輔助函式庫來讀取串流。由於路由為 POST,原生 EventSource 物件不合適,因此請使用 fetch 並自行解碼區塊。
生產環境習慣
- 將金鑰保留在環境變數或機密儲存庫中,永遠不要放在儲存庫中。
- 限制請求主體大小。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 串流輸出回應嗎?
可以。傳入 stream: true 並使用 for await 進行迭代。加入包含 include_usage 的 stream_options,即可在最後一個 chunk 取得 token 計數。
API 支援函式呼叫嗎?
可以。傳送 tools 與 tool_choice,從回覆中讀取 tool_calls,並以 role tool 的訊息傳回結果。
伺服器在 HTTP 429 時應如何處理?
若有 Retry-After 值則等待該時間,否則進行指數退避,然後重試幾次。若錯誤代碼為 concurrency,請減少並行請求。