無審查 LLM API JavaScript:Fetch 與 SDK
正在尋找無審查 LLM API JavaScript 範例?將官方的 openai 套件或純 fetch 呼叫指向新的 base URL,並傳送 model ID 為 uncensored。以下是用於聊天、串流輸出、JSON 模式和函式呼叫的可用 Node 程式碼,以及從瀏覽器安全使用的方法。

重點摘要
- 與標準 OpenAI 程式碼相比,只有兩個值會改變:base URL 和 API 金鑰;模型為 uncensored。
- 純 fetch 在 Node 18+ 和瀏覽器中均可運作;openai 套件更簡短且能為您處理串流輸出。
- 切勿將金鑰放在前端程式碼中。請從伺服器路由呼叫 API,讓瀏覽器與該路由通訊。
- 處理 HTTP 429:讀取錯誤碼和 Retry-After 標頭,然後重試。
兩分鐘完成專案設定
在上述任何程式碼執行之前,你需要一個小型專案。使用 node --version 檢查你的 Node 版本;18 或更新版本具有全域 fetch,而 20 或更新版本是較安全的選擇,因為較舊版本已停止維護。然後建立資料夾並安裝你需要的唯一相依性:
mkdir llm-demo && cd llm-demo
npm init -y
npm pkg set type=module
npm install openai
export API_KEY="paste-your-key-here"
curl -s https://api.unfilteredimagegenerator.cc/v1/models -H "Authorization: Bearer $API_KEY"
最後的 curl 指令是一個有用的基本檢查。它呼叫 GET /v1/models,應列出模型 ID uncensored。如果收到 401,表示金鑰有誤或包含多餘的空格或換行;如果請求掛起,請確認 Base URL 以 /v1 結尾,且你沒有重複新增 /chat/completions。SDK 會自動附加 /chat/completions,因此其 baseURL 應停在 /v1,而原始 fetch 呼叫則需要完整路徑。
將金鑰保留在程式碼庫之外。使用 node --env-file=.env app.mjs(Node 20.6 及以上版本)載入 .env 檔案即可滿足本機開發需求,並將 .env 加入 .gitignore。在生產環境中,請使用主機提供的密鑰儲存庫。你可以從 API 金鑰頁面取得金鑰與一次性試用額度。
使用 fetch 快速開始
最短的有效呼叫根本不需要套件。Node 18 及更新版本隨附 fetch,每個目前的瀏覽器也是如此。你將 JSON 主體傳送至 base URL 下的 /chat/completions,並帶有 bearer token:
const BASE = "https://api.unfilteredimagegenerator.cc/v1";
const KEY = process.env.API_KEY;
const res = await fetch(`${BASE}/chat/completions`, {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${KEY}`,
},
body: JSON.stringify({
model: "uncensored",
messages: [
{ role: "system", content: "You are a blunt, concise assistant." },
{ role: "user", content: "Give me three plot twists for a heist story." },
],
temperature: 0.8,
}),
});
if (res.ok === false) {
throw new Error(`HTTP ${res.status}: ${await res.text()}`);
}
const data = await res.json();
console.log(data.choices[0].message.content);
console.log("balance:", res.headers.get("X-Balance-USD"));
將其儲存為 ES 模組(.mjs,或在 package.json 中使用 "type": "module"),以便頂層 await 能運作。回應包含 X-Request-Id 標頭,你可以記錄下來以供支援使用,以及 X-Balance-USD,這對於低餘額警告很有用。要取得金鑰,請使用 API 金鑰頁面;新帳戶可以在那裡領取 $0.50 的試用額度。
使用 openai 套件
官方 SDK 之所以能運作,是因為 API 使用相同的協定。使用 npm install openai 安裝它並設定 baseURL:
import OpenAI from "openai";
const client = new OpenAI({
baseURL: "https://api.unfilteredimagegenerator.cc/v1",
apiKey: process.env.API_KEY,
});
const completion = await client.chat.completions.create({
model: "uncensored",
messages: [{ role: "user", content: "Write a villain monologue in 80 words." }],
max_tokens: 200,
});
console.log(completion.choices[0].message.content);
console.log(completion.usage);
你從 SDK 所知道的一切都會延續:temperature、top_p、stop、seed 以及頻率和存在懲罰都會通過。SDK 會自行重試某些失敗;如果你偏好自行控制,請將 maxRetries: 0 傳遞給建構子,並如後所述自行處理 429。如果你需要確認模型列表,await client.models.list() 會呼叫 GET /v1/models。
包裝 SDK 的框架通常會以「base URL」和「API 金鑰」等名稱公開相同的兩個設定。文件頁面 有支援欄位的完整列表。
串流輸出接收到的 token
串流輸出使用伺服器發送事件:設定 stream: true 並讀取區塊。使用 SDK 時,它是一個非同步迭代器:
// client configured with base URL https://api.unfilteredimagegenerator.cc/v1
const stream = await client.chat.completions.create({
model: "uncensored",
stream: true,
stream_options: { include_usage: true },
messages: [{ role: "user", content: "Tell a short ghost story." }],
});
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。不使用 SDK 時,你自己解析 data: 行:
// client configured with base URL https://api.unfilteredimagegenerator.cc/v1
const res = await fetch(`${BASE}/chat/completions`, {
method: "POST",
headers: { "Content-Type": "application/json", "Authorization": `Bearer ${KEY}` },
body: JSON.stringify({
model: "uncensored",
stream: true,
messages: [{ role: "user", content: "Count to five in words." }],
}),
});
const reader = res.body.getReader();
const decoder = new TextDecoder();
let buffer = "";
while (true) {
const { done, value } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
const lines = buffer.split("\n");
buffer = lines.pop();
for (const line of lines) {
if (line.startsWith("data: ") === false) continue;
const payload = line.slice(6).trim();
if (payload === "[DONE]") continue;
const delta = JSON.parse(payload).choices[0]?.delta?.content;
if (delta) process.stdout.write(delta);
}
}
將最後一個部分行保留在 buffer 中;區塊邊界可能會落在行的中間。另一個細節:串流請求會保留其並行請求槽位直到串流結束,因此關閉或中止你不再需要的串流。
JSON 模式與工具呼叫
對於機器可讀的輸出,設定 response_format: { type: "json_object" } 並在提示詞中描述鍵:
// client configured with base URL https://api.unfilteredimagegenerator.cc/v1
const r = await client.chat.completions.create({
model: "uncensored",
response_format: { type: "json_object" },
messages: [
{ role: "system", content: 'Reply as JSON: {"title": string, "tags": string[]}' },
{ role: "user", content: "A noir story set on a space station." },
],
});
const obj = JSON.parse(r.choices[0].message.content);
工具呼叫遵循 OpenAI 的格式:傳遞 tools 和可選的 tool_choice,執行模型要求的函式,並使用 role: "tool" 傳送結果。
// client configured with base URL https://api.unfilteredimagegenerator.cc/v1
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 my attack." }];
const first = await client.chat.completions.create({ model: "uncensored", messages, tools });
const call = first.choices[0].message.tool_calls?.[0];
if (call) {
const sides = JSON.parse(call.function.arguments).sides;
messages.push(first.choices[0].message);
messages.push({
role: "tool",
tool_call_id: call.id,
content: String(1 + Math.floor(Math.random() * sides)),
});
const final = await client.chat.completions.create({ model: "uncensored", messages, tools });
console.log(final.choices[0].message.content);
}
始終在 try 區塊內解析 arguments。開放權重模型偶爾會產生格式錯誤的參數,一次重試的成本比崩潰更低。
從瀏覽器安全使用
從頁面 JavaScript 直接呼叫 API 在技術上是可行的,但金鑰會出現在你的套件中,任何人都可以複製它並消耗你的餘額。能維持的模式是一個薄伺服器路由,它新增金鑰並轉發請求。這是一個最小化的 Express 版本,透過它進行串流輸出:
import express from "express";
import OpenAI from "openai";
const app = express();
app.use(express.json({ limit: "1mb" }));
const client = new OpenAI({
baseURL: "https://api.unfilteredimagegenerator.cc/v1",
apiKey: process.env.API_KEY,
});
app.post("/api/chat", async (req, res) => {
const stream = await client.chat.completions.create({
model: "uncensored",
stream: true,
messages: req.body.messages.slice(-20),
});
res.setHeader("Content-Type", "text/event-stream");
for await (const chunk of stream) {
res.write(`data: ${JSON.stringify(chunk)}\n\n`);
}
res.end();
});
app.listen(3000);
該路由會將歷史記錄截斷為最後 20 則訊息,這有助於讓帳單可預測,也是加入你自己的使用者登入與每使用者限制的地方。上游主體限制為 8 MB,因此你在端點側設定 1 MB 上限是一個合理的防護措施。相同的結構也適用於 Next.js 路由處理程式、Cloudflare Workers 或任何 serverless 函式;僅需調整包裝程式。
保留對話狀態並取消請求
API 是無狀態的,因此聊天只是你建立並重新傳送的一個陣列。在每個工作階段中將其保留在記憶體中,並推送每次交談的兩方:
// client configured with base URL https://api.unfilteredimagegenerator.cc/v1
const history = [
{ role: "system", content: "You are the narrator of a dark fantasy campaign." },
];
async function say(text) {
history.push({ role: "user", content: text });
const r = await client.chat.completions.create({ model: "uncensored", messages: history });
const reply = r.choices[0].message;
history.push({ role: "assistant", content: reply.content });
return reply.content;
}
console.log(await say("I open the iron door."));
console.log(await say("I light the torch and step inside."));
在實際應用程式中,有兩個調整很重要。首先是截斷。保留系統訊息和最後 N 輪對話,或將較舊的對話摘要為一條短訊息,因為每次請求時,每個舊輪次都會作為輸入再次計費。100,000 token 的視窗雖然很大,但沒有理由為 60,000 token 的閒聊付費。一個粗略的經驗法則是每個英文 token 約四個字元;若要精確計數,請從上一個回應讀取 usage.prompt_tokens。
其次,讓使用者取消。傳遞 AbortController 訊號,以便關閉的分頁或停止按鈕能結束串流並釋放並行請求槽位:
// client configured with base URL https://api.unfilteredimagegenerator.cc/v1
const ctrl = new AbortController();
setTimeout(() => ctrl.abort(), 15000);
try {
const stream = await client.chat.completions.create(
{ model: "uncensored", stream: true, messages: history },
{ signal: ctrl.signal },
);
for await (const chunk of stream) {
process.stdout.write(chunk.choices[0]?.delta?.content ?? "");
}
} catch (err) {
if (err.name === "AbortError") console.log("\ncancelled");
else throw err;
}
使用純 fetch 的相同概念是 fetch(url, { signal: ctrl.signal })。如果不使用它,放棄的串流會繼續執行直到完成,而在限制為 8 個並行請求的金鑰上,其中幾個可能會阻塞你的實際使用者。
處理 429 和其他錯誤
完整金鑰允許 8 個並行請求和每分鐘 300 個請求。試用金鑰允許 2 個和 60 個。當你超過限制時,API 會回傳 HTTP 429 並帶有錯誤碼:rate_limited 表示每分鐘請求數,concurrency 表示同時請求過多。在短暫的突發過載時,你也會收到帶有 Retry-After: 5 的 429。一個小型包裝器涵蓋所有三種情況:
async function chat(body, tries = 4) {
for (let i = 0; i < tries; i++) {
const res = await fetch(`${BASE}/chat/completions`, {
method: "POST",
headers: { "Content-Type": "application/json", "Authorization": `Bearer ${KEY}` },
body: JSON.stringify(body),
});
if (res.status === 429) {
const wait = Number(res.headers.get("Retry-After")) || 2 ** i;
await new Promise((r) => setTimeout(r, wait * 1000));
continue;
}
return res;
}
throw new Error("still rate limited");
}
對於批次工作,請自行限制並行數量,而非依賴重試:一個具有 6 個工作執行緒的簡單佇列會保持在 8 的並行限制之下。失敗或被拒絕的請求不會計費,因此當首次嘗試出錯時,重試不會產生額外費用。X-RateLimit-Limit-Requests 與 X-RateLimit-Limit-Concurrency 標頭會告訴你哪些限制適用於你的金鑰。在執行大型迴圈前請查看 定價:每 100 萬個輸入 token 為 $0.15,每 100 萬個輸出 token 為 $0.50,價格便宜,但如果程式碼錯誤導致迴圈重複傳送 90,000 個 token 的歷史記錄,仍會產生帳單。
可重複使用的客戶端模組
一旦第一次呼叫運作,請將設定移至單一檔案,以便應用程式的其他部分看不到 base URL 或金鑰。這是一個小型模組,具有型別輔助函數,以 TypeScript 編寫,但如果刪除註解則為有效的 JavaScript:
// llm.ts
import OpenAI from "openai";
export const client = new OpenAI({
baseURL: "https://api.unfilteredimagegenerator.cc/v1",
apiKey: process.env.API_KEY,
});
export async function ask(system, user, temperature = 0.7) {
const r = await client.chat.completions.create({
model: "uncensored",
temperature,
messages: [
{ role: "system", content: system },
{ role: "user", content: user },
],
});
return {
text: r.choices[0].message.content ?? "",
tokens: r.usage,
};
}
每次回答都傳回 usage 物件,讓你可以稍後在一個地方新增成本追蹤:輸入 token 乘以 0.15 加上輸出 token 乘以 0.50,除以一百萬,即該次呼叫的美元成本。因為模組擁有 model ID,未來的變更只需一行編輯,而不必在程式碼庫中搜尋。
在發布之前測試整合
執行三個快速檢查,你幾乎就能發現所有設定錯誤。第一,執行一般的非串流請求,如快速入門所示。第二,在終端機中執行串流請求,以確認文字是否逐段出現,以及最終的使用量區塊是否到達。第三,故意製造錯誤:傳送帶有錯誤金鑰的請求,並確認程式碼顯示易讀的訊息,而非空白頁面。401 回應主體為 JSON,請將其列印出來。
對於自動化測試,不要在每次執行時呼叫實際 API。將 ask 包裝在介面中,並替換為返回固定字串的模擬物件,然後保留一個小型煙霧測試,該測試使用一行提示詞和低 max_tokens 請求實際端點。該煙霧測試的成本不到一分錢。為 CI 使用單獨的金鑰,以便你可以撤銷它而不影響生產環境,並在測試記錄中讀取速率限制標頭 X-RateLimit-Limit-Requests 和 X-RateLimit-Limit-Concurrency,以便你看到哪些限制適用。
當出現你無法解釋的故障時,請透過支援頁面聯絡團隊時,包含回應標頭中的 X-Request-Id 值。這讓他們能找到該特定請求。
更多指南
問答
我需要特殊的 SDK 嗎?
不需要。只要設定 base URL 和金鑰,Node 的標準 openai 套件即可運作;純 fetch 則無需任何套件即可使用。
從客戶端 JavaScript 呼叫 API 安全嗎?
使用真實金鑰時不行,因為任何人都可以從你的網頁讀取它。請在兩者之間加入小型伺服器路由,並將金鑰保留在環境變數中。
我應該傳送哪個模型 ID?
將 uncensored 設為 model 值。你可以透過呼叫 GET /v1/models 來確認。
支援函式呼叫和 JSON 模式嗎?
兩者皆可。函式呼叫使用 tools 和 tool_choice 欄位搭配 role: tool 的結果,JSON 模式則使用 response_format 搭配 json_object。
達到速率限制時會發生什麼事?
當遭遇暫時性過載時,會收到 HTTP 429,其 code 為 rate_limited 或 concurrency,或 Retry-After 標頭為 5。請等待後重試請求。