繁中 ▾
取得 API 金鑰

無審查 ChatGPT API Node.js:設定步驟

官方的 openai 套件可直接使用。將其指向新的 Base URL,使用模型 ID uncensored,即可擁有具備串流輸出、工具與 JSON 模式的 Node.js 客戶端。

更新於

六邊形模組連接終端機,資料串流流向聊天氣泡

開始前你需要準備的事項

要進行 無審查 chatgpt api node js 設定,你需要三樣東西:Node 18 或更新版本、API 金鑰,以及官方的 openai 套件。無需安裝其他東西。該服務使用 OpenAI 請求格式,因此只要你將 Base URL 改為 https://api.unfilteredchatgpt.top/v1 並將模型改為 uncensored,原本用於任何 OpenAI 風格端點的 SDK 即可運作。

請清楚了解這是什麼。它不是 ChatGPT,也不是來自 OpenAI 或其他大型供應商的官方 API。它是由獨立供應商執行的開放權重模型,經過微調以在合法成人用途下提供無審查的回答。它不會產生涉及未成年人的性內容。

建立帳號(使用 Google 或電子郵件與密碼),然後開啟 API 金鑰頁面。那裡提供一鍵獲得 $0.50試用額度,有效期 7 天,無需綁定信用卡。將金鑰匯出為環境變數,使其不會出現在你的原始碼中:

# https://api.unfilteredchatgpt.top/v1 is the base URL, uncensored is the model id
export API_KEY="paste-your-key-here"

安裝 SDK 並檢查金鑰

建立資料夾、安裝套件,並對 /v1/models 發送一個請求。如果金鑰正確,你會收到一個 JSON 列表,其中包含 uncensored 模型。

# project setup, then call the API once to confirm the key works
npm init -y
npm install openai
curl https://api.unfilteredchatgpt.top/v1/models -H "Authorization: Bearer $API_KEY"   # model id: uncensored

使用 ES 模組以讓頂層 await 運作。將檔案命名為 index.mjs,或在 package.json 中加入 "type": "module"。如果你偏好 CommonJS,請將程式碼包裝在 async 函式中,並使用 require("openai")。

你的第一個聊天完成請求

這是完整的最低要求。與標準 OpenAI 範例的唯一差異在於設定 baseURL 與 model 的兩行程式碼。

// index.mjs (Node 18 or newer)
import OpenAI from "openai";

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

const res = await client.chat.completions.create({
  model: "uncensored",
  messages: [
    { role: "system", content: "You are a blunt, witty co-writer for adult fiction." },
    { role: "user", content: "Describe a rainy border town in four sentences." },
  ],
  temperature: 0.9,
});

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

使用 node index.mjs 執行。你會收到回覆文字以及一個包含提示詞和 completion token 計數的 usage 物件。系統訊息是用來設定人格和語調的地方,此模型會嚴格遵循它,因此請明確指定你的需求。temperature、top_p、stop、seed 和 penalty 等參數會直接傳遞給模型。

上下文視窗為 100,000 token,包含提示詞與 completion token 總計。max_tokens 為可選參數。若未設定,completion 可使用視窗剩餘的所有空間,這對於長場景很有用,但若迴圈出錯則會很昂貴,因此請在測試程式碼中設定它。

串流接收到達的 token

對於聊天介面或 CLI,你希望在生成過程中顯示文字。設定 stream: true 並遍歷各個區塊。usage 會出現在串流結尾。

import OpenAI from "openai";

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

const stream = await client.chat.completions.create({
  model: "uncensored",
  stream: true,
  stream_options: { include_usage: true },
  messages: [{ role: "user", content: "Tell me a short story about a lighthouse keeper." }],
});

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);
}

一個細節對生產環境程式碼很重要。串流請求會在其串流結束前佔用 concurrency 槽位。完整金鑰允許 8 個並行請求,試用金鑰允許 2 個,因此如果你的使用者放棄串流卻未關閉它們,請在客戶端終止請求(SDK 支援 AbortController signal),否則你會比預期更早遇到 concurrency 錯誤。

工具呼叫與 JSON 模式

兩者都透過標準欄位運作。對於工具,傳遞 tools 並可選傳遞 tool_choice。模型會回傳 tool_calls,你執行函式,然後以 role: "tool" 將結果作為訊息送回。串流回應也會包含 tool_calls。

import OpenAI from "openai";

const client = new OpenAI({ baseURL: "https://api.unfilteredchatgpt.top/v1", apiKey: process.env.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 final = await client.chat.completions.create({ model: "uncensored", messages, tools });
  console.log(final.choices[0].message.content);
}

對於結構化輸出,JSON 模式只需額外設定一個欄位。在提示詞中提及 JSON 並描述你需要的結構,因為該旗標保證的是語法而非你的 schema。

import OpenAI from "openai";

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

const res = await client.chat.completions.create({
  model: "uncensored",
  response_format: { type: "json_object" },
  messages: [
    { role: "system", content: "Reply with JSON only: {\"name\": string, \"traits\": string[]}" },
    { role: "user", content: "Invent a cynical ship captain." },
  ],
});

const character = JSON.parse(res.choices[0].message.content);
console.log(character.name, character.traits);

在實際程式碼中,務必將 JSON.parse 包裝在 try/catch 中。如果模型在 max_tokens 處截斷,JSON 將不完整。

處理錯誤與速率限制

完整金鑰允許 8 個並行請求和每分鐘 300 次請求。試用金鑰允許 2 個並行請求和每分鐘 60 次請求。超過限制時,你會收到 HTTP 429 錯誤,錯誤代碼為 rate_limited(每分鐘過多)或 concurrency(同時過多)。暫時過載也會返回 429,並帶有 Retry-After: 5 標頭。所有情況的修復方法相同:等待並重試,並限制重試次數。

import OpenAI from "openai";

const client = new OpenAI({ baseURL: "https://api.unfilteredchatgpt.top/v1", apiKey: process.env.API_KEY, maxRetries: 0 });
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));

async function chat(messages, attempt = 0) {
  try {
    return await client.chat.completions.create({ model: "uncensored", messages });
  } catch (err) {
    if (err.status === 429 && attempt < 5) {
      const wait = Number(err.headers?.["retry-after"] ?? 5) * 1000;
      await sleep(wait + attempt * 500);
      return chat(messages, attempt + 1);
    }
    throw err;
  }
}

上述的重試機制會停用 SDK 內建的自動重試功能,讓你能掌控重試時機。對於批次作業,可在前方加入小型佇列,例如使用 p-limit 並設定上限為 6,這樣在 8 個請求的上限下仍留有餘裕。最大請求主體為 8 MB,遠超過一般提示詞的大小,但貼入訊息中的 base64 資料可能會達到此限制。

失敗或遭拒的請求不會計費,因此錯誤重試不會產生額外費用。

保留對話歷史

該 API 為無狀態。每個請求必須攜帶模型應見的所有訊息,因此聊天機器人需要一個隨著每次對話輪次而增長的陣列。將系統訊息置於最前方,並在歷史記錄變長時,從最舊的使用者與助手訊息開始進行修剪。

import OpenAI from "openai";
import readline from "node:readline/promises";

const client = new OpenAI({ baseURL: "https://api.unfilteredchatgpt.top/v1", apiKey: process.env.API_KEY });
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });

const history = [{ role: "system", content: "You are a dry-humored narrator for an adult text adventure." }];

while (true) {
  const text = await rl.question("> ");
  if (text.length === 0) break;
  history.push({ role: "user", content: text });
  const res = await client.chat.completions.create({ model: "uncensored", messages: history, max_tokens: 600 });
  const reply = res.choices[0].message.content;
  history.push({ role: "assistant", content: reply });
  console.log(reply);
  while (history.length > 21) history.splice(1, 2); // keep system + last 20
}
rl.close();

由於輸入 token 在每次呼叫時都會計費,40 則訊息的歷史記錄成本遠高於 4 則。視窗上限為 100,000 個 token,因此你很少會觸及限制,但帳單會最先反映出來。長期的角色扮演對話適合以簡短的運行摘要取代最早的對話輪次,以獲得效益。

常見問題與解決方案

  • 401 或驗證錯誤。 金鑰遺失或有拼寫錯誤。請檢查 process.env.API_KEY 是否在執行 Node 的殼層中已設定,因為新的終端機分頁不會繼承已匯出的環境變數。
  • 每次呼叫都出現 404。 base URL 缺少 /v1,或路徑重複。請使用上方顯示的位址,讓 SDK 自動加上 /chat/completions。
  • 找不到模型。 模型 ID 為 uncensored,全部為小寫。呼叫 GET /v1/models 以查看該金鑰可使用哪些模型。
  • JSON 模式的 JSON 損毀。 輸出在 max_tokens 處被截斷。提高限制或縮短 Schema。
  • 導致應用程式當機的串流。 務必消耗或中止串流。開啟的串流會佔用其並行槽位。
  • 成本高於預期。 在每個回應中記錄 usage 並優先查看輸入 token。每次輪次都重新發送歷史記錄是常見原因。

如果仍有問題,請將回應中的 X-Request-Id 標頭值傳送給支援團隊。支援頁面有聯絡方式。

無 SDK:plain fetch

如果你想要零相依性,Node 18 內建了 fetch。回應標頭包含 X-Request-Id 用於支援問題,以及 X-Balance-USD 用於查看剩餘額度。

const res = await fetch("https://api.unfilteredchatgpt.top/v1/chat/completions", {
  method: "POST",
  headers: {
    "Authorization": `Bearer ${process.env.API_KEY}`,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    model: "uncensored",
    messages: [{ role: "user", content: "Say hello in one line." }],
  }),
});

console.log(res.headers.get("x-request-id"), res.headers.get("x-balance-usd"));
console.log((await res.json()).choices[0].message.content);

其他與 OpenAI 相容的工具運作方式相同。在任何允許你設定自定義端點的客戶端中(例如 SillyTavern 或 LangChain 的 OpenAI 包裝函式),輸入 Base URL、貼上你的金鑰,並將 uncensored 輸入為模型名稱。文件頁面有此操作的簡短版本,聊天機器人 API 文章展示了如何將這些呼叫轉換為完整的機器人。

上線前的成本檢查:輸入為每 1M 個 token $0.15,輸出為每 1M 個 token $0.50。5,000 個輸入 token 與 1,500 個輸出 token 的回覆成本為 $0.00075 + $0.00075 = $0.0015,因此 $20 的額度約可處理 13,333 次。定價頁面有儲值等級資訊。

問答

我可以使用官方的 openai npm 套件嗎?

可以。將 baseURL 設為 API 位址並使用模型 ID uncensored 即可,無需其他變更。

我需要哪個 Node 版本?

Node 18 或更新版本,內建 fetch 且與目前的 openai 套件相容。使用 ES 模組以支援頂層 await。

為什麼我會收到 429 錯誤?

你觸及了限制。程式碼 rate_limited 表示每分鐘請求過多,concurrency 表示同時請求過多。請等待並重試,並限制同時請求數量。

它支援串流輸出和函式呼叫嗎?

可以。串流輸出透過 SSE 運作,結尾帶有 usage,工具呼叫遵循 OpenAI 格式,包含串流輸出的 tool_calls。

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

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

取得 API 金鑰