繁中 ▾
取得 API 金鑰

Node.js LLM API:設定、串流輸出與工具

要在 Node.js 中使用此 API,請安裝官方的 openai 套件並將其指向不同的 base URL。你的現有聊天程式碼可繼續與模型 ID uncensored 配合運作。

更新於

綠色六邊形節點連結聊天氣泡與伺服器,說明 Node.js LLM API 整合

重點摘要

  • 執行 npm install openai,然後將 baseURL 設定為 https://api.gemininsfw.cc/v1.
  • 串流輸出使用 for await 遍歷回應;用量資訊在結尾提供。
  • 工具呼叫會出現在訊息中,結果則以 role tool 回傳。
  • 遇到 HTTP 429 時,請先讀取錯誤程式碼和 Retry-After 標頭,再進行重試。

llm api node 專案的快速設定

這是 llm api node 整合的快速途徑。你需要 Node 18 或更新版本、使用 ES 模組的專案,以及來自 金鑰頁面的 API 金鑰。

mkdir llm-demo && cd llm-demo
npm init -y
npm pkg set type=module
npm install openai
export API_KEY="your-key-here"

建立 index.js:

import OpenAI from "openai";

const client = new OpenAI({
  baseURL: "https://api.gemininsfw.cc/v1",
  apiKey: process.env.API_KEY,
});

const resp = await client.chat.completions.create({
  model: "uncensored",
  messages: [
    { role: "system", content: "You are a concise assistant." },
    { role: "user", content: "Give me three names for a fantasy tavern." },
  ],
  temperature: 0.8,
});

console.log(resp.choices[0].message.content);
console.log(resp.usage);

以 node index.js 執行。套件會將金鑰以 Authorization: Bearer 標頭傳送,因此你無需手動設定。

無 SDK:原生 fetch

如果你偏好零相依性,Node 18 內建 fetch。該 API 有兩個方法,POST /v1/chat/completions 和 GET /v1/models,因此撰寫輕量包裝器很簡單。

async function chat(messages) {
  const res = await fetch("https://api.gemininsfw.cc/v1/chat/completions", {
    method: "POST",
    headers: {
      "Authorization": `Bearer ${process.env.API_KEY}`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify({ model: "uncensored", messages }),
  });
  if (res.ok === false) {
    const err = await res.text();
    throw new Error(`HTTP ${res.status}: ${err}`);
  }
  return res.json();
}

const data = await chat([{ role: "user", content: "Hello" }]);
console.log(data.choices[0].message.content);

當你需要串流輔助功能、具型別的回應和內建重試機制時,SDK 是更好的選擇。原始版本適合小型腳本或對套件大小敏感的無伺服器函式。

Node 中的串流輸出

設定 stream: true 並使用 for await 遍歷結果。Token 會在到達時列印,用量資訊會在串流結束時報告。

const stream = await client.chat.completions.create({
  model: "uncensored",
  messages: [{ role: "user", content: "Tell a two-paragraph story about a lighthouse." }],
  stream: 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("\n", chunk.usage);
}

要將串流輸出轉發至瀏覽器,Express 處理常式可設定 Content-Type: text/event-stream 並將每個 delta 寫入 SSE data: 行。記住一條規則:串流請求會佔用其並行請求槽位,直到串流結束。如果瀏覽器斷線,請停止讀取上游串流以釋放槽位。使用 SDK 時,請呼叫 stream.controller.abort()。

工具呼叫與 JSON 模式

工具

傳入 tools 和可選的 tool_choice。當模型想要呼叫函式時,回覆會包含 tool_calls。你執行該函式並將輸出作為 role: "tool" 訊息回傳。

const tools = [{
  type: "function",
  function: {
    name: "roll_dice",
    description: "Roll an n-sided die",
    parameters: {
      type: "object",
      properties: { sides: { type: "integer" } },
      required: ["sides"],
    },
  },
}];

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

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

JSON 模式

加入 response_format: { type: "json_object" } 並在提示詞中要求 JSON。將 JSON.parse 包裹在 try/catch 中,以防輸出被截斷。

小型聊天伺服器的專案結構

對於實際應用程式,請將客戶端保留在一個模組中並在需要的地方匯入。這樣 base URL、金鑰和重試設定就集中在單一位置。

// llm.js
import OpenAI from "openai";

export const llm = new OpenAI({
  baseURL: "https://api.gemininsfw.cc/v1",
  apiKey: process.env.API_KEY,
  maxRetries: 2,
});

export async function complete(messages, opts = {}) {
  const r = await llm.chat.completions.create({
    model: "uncensored",
    messages,
    ...opts,
  });
  return r.choices[0].message.content;
}

然後你的路由處理常式呼叫 complete() 且不再碰觸金鑰。在伺服器上儲存對話歷史,以 session 為索引,並在歷史增長時修剪舊的輪次。由於 API 是無狀態的,每個請求必須包含你希望模型看到的所有訊息。

錯誤、重試與限制

SDK 會拋出帶有 status 欄位的 OpenAI.APIError 子類別。完整金鑰允許 8 個並行請求與每分鐘 300 次;試用金鑰允許 2 個與每分鐘 60 次。超過限制時,你會收到 HTTP 429 錯誤,代碼為 rate_limited 或 concurrency。在短時間過載期間,API 會傳送帶有 Retry-After: 5 的 429 錯誤。

const client = new OpenAI({
  baseURL: "https://api.gemininsfw.cc/v1",
  apiKey: process.env.API_KEY,
  maxRetries: 3,
  timeout: 120_000,
});

async function safeAsk(prompt) {
  try {
    const r = await client.chat.completions.create({
      model: "uncensored",
      messages: [{ role: "user", content: prompt }],
    });
    return r.choices[0].message.content;
  } catch (e) {
    if (e.status === 429) {
      console.error("limited, retry-after:", e.headers?.["retry-after"]);
    }
    throw e;
  }
}

對於批次處理,不要使用 Promise.all 發射所有請求。使用具有固定數量工作程式的小型佇列,例如 6 個,這樣你就不會超過完整金鑰的 8 個並行槽位。請求主體上限為 8 MB,上下文視窗為 100,000 token(提示詞和答案合計)。

成本與後續步驟

價格為每 1M 輸入 token $0.15,每 1M 輸出 token $0.50。一次聊天輪次包含 3,000 個提示詞 token 和 600 個回覆 token,成本為 3,000 x $0.15 / 1M = $0.00045 加上 600 x $0.50 / 1M = $0.0003,總計 $0.00075。一千次此類輪次總計 $0.75。失敗或拒絕的請求不會收費,回應標頭 X-Balance-USD 會顯示剩餘餘額。

新用戶可在金鑰頁面領取 $0.50 的免費試用額度,定價頁面 列出從 $20 到 $500 的儲值選項。如需更詳細的請求格式說明,請參閱 文件。此服務僅處理文字,因此圖片、音訊和嵌入呼叫將無法運作。

問答

支援 TypeScript 嗎?

支援。openai 套件內建型別,只需修改 baseURL 和模型名稱 uncensored。

可以在無伺服器函式中使用嗎?

可以。這是標準 HTTPS API,因此 fetch 可用。將金鑰保存在平台的機密儲存庫中,並注意金鑰的並行請求限制。

需要哪個 Node 版本?

Node 18 或更新版本是安全選擇,因為它內建 fetch 且能與最新版本的 openai 套件配合運作。

此服務有 Node 專屬套件嗎?

否。請使用官方的 openai 套件或對 OpenAI 相容端點使用原生 fetch。

只差一張表單,即可取得金鑰

建立帳號、複製金鑰、更改base URL。這就是整個設定過程。

取得 API 金鑰閱讀文件