Uncensored AI API 程式碼範例:Python、Node.js 和 cURL
本頁彙整了適用於無審查 AI API 的複製貼上程式碼,該 API 採用 OpenAI 聊天補全格式。你會找到 Python、Node.js 與 cURL 的首次呼叫、透過 SDK 與原始 fetch 的串流輸出、函式呼叫、429 與 503 的重試邏輯、多輪狀態,以及使用 max_tokens 控制成本。

重點摘要
- 使用官方 openai SDK,將 base_url 設為 https://api.uncensoredaiapis.com/v1 並指定模型 "uncensored";不需要自訂用戶端。
- 串流輸出會傳回 SSE 區塊,並自動傳入包含空 choices 列表的最終用量區塊。
- 僅重試 429 與 503(upstream_busy);400、401、402 與 403 需要修正,而非重試。
- API 為無狀態:每輪需重新傳送歷史,並使用 max_tokens 限制輸出(選填;若未設定,回應可延伸至 context window 的結尾)。
首次呼叫:Python、Node.js 和 cURL
這些範例使用 https://api.uncensoredaiapis.com/v1、模型 uncensored,以及 POST /v1/chat/completions 或 GET /v1/models。請在 Authorization: Bearer <key> 標頭中傳送您的金鑰。如有需要,請建立帳戶,申請符合資格的試用額度,並在執行請求前確認顯示的餘額已就緒。
範例從名為 API_KEY 的環境變數讀取金鑰。在 Shell 中匯出一次後,所有程式碼片段都不需要編輯。切勿將金鑰貼入原始碼或在瀏覽器 JavaScript 中發送;請從後端呼叫 API。
export API_KEY="paste-your-key-here"Python,使用官方 openai 套件(v1 或更新版本)。與標準 OpenAI 設定唯一的差異在於 base_url 與模型名稱。
import os
from openai import OpenAI
client = OpenAI(
base_url="https://api.uncensoredaiapis.com/v1",
api_key=os.environ["API_KEY"],
)
resp = client.chat.completions.create(
model="uncensored",
messages=[{"role": "user", "content": "Write a two-line villain monologue."}],
max_tokens=200,
)
print(resp.choices[0].message.content)
print(resp.usage)Node.js,使用 openai npm 套件(v4 或更新版本)作為 ES 模組。
import OpenAI from "openai";
const client = new OpenAI({
baseURL: "https://api.uncensoredaiapis.com/v1",
apiKey: process.env.API_KEY,
});
const resp = await client.chat.completions.create({
model: "uncensored",
messages: [{ role: "user", content: "Write a two-line villain monologue." }],
max_tokens: 200,
});
console.log(resp.choices[0].message.content);
console.log(resp.usage);以及純淨的 cURL,這是檢查金鑰是否有效的最快方式:
curl https://api.uncensoredaiapis.com/v1/chat/completions \
-H "Authorization: Bearer $API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "uncensored",
"messages": [{"role": "user", "content": "Write a two-line villain monologue."}],
"max_tokens": 200
}'回應具有標準的 OpenAI 結構:choices[0].message.content 用於取得文字,以及包含提示詞與補全 token 計數的 usage 物件,你可將其乘以每 token 價格來追蹤支出。完整參數列表請參見文件。
透過 SDK 進行串流輸出(SSE)
設定 stream: true,API 會傳回伺服器傳送事件(server-sent events),而非單一 JSON 主體。兩個官方 SDK 會將其轉換為迭代器,因此你的程式碼會逐區塊迴圈處理,並列印每個 delta。系統會自動加入包含 token usage 的最後一個區塊;你不需要特別請求它。該區塊的 choices 清單為空,因此在讀取前請先檢查索引。
import os
from openai import OpenAI
client = OpenAI(
base_url="https://api.uncensoredaiapis.com/v1",
api_key=os.environ["API_KEY"],
)
stream = client.chat.completions.create(
model="uncensored",
messages=[{"role": "user", "content": "Describe a rainy harbor town in 120 words."}],
max_tokens=300,
stream=True,
)
for chunk in stream:
if chunk.choices and chunk.choices[0].delta.content:
print(chunk.choices[0].delta.content, end="", flush=True)
if chunk.usage:
print("\n\nusage:", chunk.usage)Node.js 版本使用 for await:
import OpenAI from "openai";
const client = new OpenAI({
baseURL: "https://api.uncensoredaiapis.com/v1",
apiKey: process.env.API_KEY,
});
const stream = await client.chat.completions.create({
model: "uncensored",
messages: [{ role: "user", content: "Describe a rainy harbor town in 120 words." }],
max_tokens: 300,
stream: true,
});
for await (const chunk of stream) {
const text = chunk.choices?.[0]?.delta?.content;
if (text) process.stdout.write(text);
if (chunk.usage) console.log("\n\nusage:", chunk.usage);
}串流輸出不會改變計費方式。你仍為相同的輸入與輸出 token 付費;你只是能更早看到第一個字,這對於聊天與角色扮演介面很重要,因為等待完整的 500 token 回應會感覺很慢。
使用原始 fetch 進行串流輸出
如果你不想依賴 SDK,例如在邊緣函式或小腳本中,你可以自行讀取串流輸出。網路格式為純淨的 SSE:每個事件都是以 data: 開頭的單行,後接 JSON 區塊,事件之間以空行分隔。網路區塊不會與事件邊界對齊,因此你必須緩衝並依換行符號分割。以下範例在 Node 18 或更新版本上執行(另存為 stream.mjs),且在支援標準 fetch 和 ReadableStream 的任何執行環境中皆可運作。
const res = await fetch("https://api.uncensoredaiapis.com/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: "Tell a 100-word ghost story." }],
max_tokens: 250,
stream: true,
}),
});
if (!res.ok) {
throw new Error(`HTTP ${res.status}: ${await res.text()}`);
}
const decoder = new TextDecoder();
let buffer = "";
for await (const bytes of res.body) {
buffer += decoder.decode(bytes, { stream: true });
const lines = buffer.split("\n");
buffer = lines.pop(); // keep the incomplete tail for the next round
for (const line of lines) {
if (!line.startsWith("data:")) continue;
const data = line.slice(5).trim();
if (data === "[DONE]") continue;
const chunk = JSON.parse(data);
const text = chunk.choices?.[0]?.delta?.content;
if (text) process.stdout.write(text);
if (chunk.usage) console.log("\n\nusage:", chunk.usage);
}
}在開始讀取之前,請檢查 res.ok。錯誤(如 401、402 或 403)會以包含 error 物件的一般 JSON 主體形式出現,而非事件串流,因此若將其解析為 SSE 會靜默產生空結果。在瀏覽器中,你可以使用相同的邏輯搭配 res.body.getReader(),但請記住,瀏覽器必須呼叫你自己的後端,絕不能直接使用金鑰呼叫此 API。
使用工具和 tool_choice 進行函式呼叫
函式呼叫使用 OpenAI 格式。你在 tools 中描述函式,當模型想要執行時,它會以 tool_calls 回應而非文字;你自行執行該函式,並將結果以 role: "tool" 和對應的 tool_call_id 作為訊息傳送回去。第二次請求則會回傳最終的自然語言答案。tool_choice 控制行為:"auto" 讓模型自行決定,"none" 禁止使用工具,而像 {"type": "function", "function": {"name": "get_order_status"}} 這樣的物件則會強制執行該函式。
import json
import os
from openai import OpenAI
client = OpenAI(
base_url="https://api.uncensoredaiapis.com/v1",
api_key=os.environ["API_KEY"],
)
def get_order_status(order_id: str) -> dict:
# Replace with a real lookup.
return {"order_id": order_id, "status": "shipped", "eta_days": 2}
tools = [{
"type": "function",
"function": {
"name": "get_order_status",
"description": "Look up the shipping status of an order by its id.",
"parameters": {
"type": "object",
"properties": {"order_id": {"type": "string"}},
"required": ["order_id"],
},
},
}]
messages = [{"role": "user", "content": "Where is order A-1042?"}]
first = client.chat.completions.create(
model="uncensored",
messages=messages,
tools=tools,
tool_choice="auto",
max_tokens=500,
)
msg = first.choices[0].message
if msg.tool_calls:
messages.append(msg) # keep the assistant turn that contains tool_calls
for call in msg.tool_calls:
args = json.loads(call.function.arguments)
result = get_order_status(**args)
messages.append({
"role": "tool",
"tool_call_id": call.id,
"content": json.dumps(result),
})
final = client.chat.completions.create(
model="uncensored",
messages=messages,
tools=tools,
max_tokens=500,
)
print(final.choices[0].message.content)
else:
print(msg.content)Node.js 中的相同迴圈:
import OpenAI from "openai";
const client = new OpenAI({
baseURL: "https://api.uncensoredaiapis.com/v1",
apiKey: process.env.API_KEY,
});
const getOrderStatus = ({ order_id }) => ({ order_id, status: "shipped", eta_days: 2 });
const tools = [{
type: "function",
function: {
name: "get_order_status",
description: "Look up the shipping status of an order by its id.",
parameters: {
type: "object",
properties: { order_id: { type: "string" } },
required: ["order_id"],
},
},
}];
const messages = [{ role: "user", content: "Where is order A-1042?" }];
const first = await client.chat.completions.create({
model: "uncensored", messages, tools, tool_choice: "auto", max_tokens: 500,
});
const msg = first.choices[0].message;
if (msg.tool_calls?.length) {
messages.push(msg);
for (const call of msg.tool_calls) {
const result = getOrderStatus(JSON.parse(call.function.arguments));
messages.push({ role: "tool", tool_call_id: call.id, content: JSON.stringify(result) });
}
const final = await client.chat.completions.create({
model: "uncensored", messages, tools, max_tokens: 500,
});
console.log(final.choices[0].message.content);
} else {
console.log(msg.content);
}兩個實用注意事項。首先,arguments 是由語言模型產生的 JSON 字串,因此在生產環境中務必將 json.loads 包在錯誤處理中,並在操作資料庫之前驗證欄位。其次,工具定義在每次請求中都會計入輸入 token,因此請保持描述簡短,且僅傳送與當前步驟相關的工具。
對 429 與 503 進行退避重試
有兩種錯誤值得重試。429 表示你已超過該金鑰每分鐘 300 次請求的速率限制。503 且程式碼為 upstream_busy 表示服務暫時飽和;等待幾秒鐘是預期的回應方式。不要重試 400(修正請求)、401(修正金鑰)、402 no_credit(儲值餘額)或 403 content_blocked(請求將被阻止)。錯誤共用一種 JSON 格式 {"error":{"code":...,"message":...}},因此你可以直接記錄程式碼。
OpenAI SDK 預設已重試連線錯誤、429 和 5xx 幾次,你可以透過 max_retries 提高該次數。如果你想要控制延遲,請停用內建的重試機制並自行包裝呼叫,使用帶有抖動的指數退避演算法,以免並行工作程式同時重試。
import os
import random
import time
from openai import OpenAI, APIStatusError, APIConnectionError
client = OpenAI(
base_url="https://api.uncensoredaiapis.com/v1",
api_key=os.environ["API_KEY"],
max_retries=0, # we handle retries ourselves
)
RETRYABLE = {429, 503}
def chat_with_retry(messages, max_attempts=5, **kwargs):
for attempt in range(max_attempts):
try:
return client.chat.completions.create(
model="uncensored", messages=messages, **kwargs
)
except APIStatusError as e:
if e.status_code not in RETRYABLE or attempt == max_attempts - 1:
raise
except APIConnectionError:
if attempt == max_attempts - 1:
raise
delay = min(30, 2 ** attempt) + random.uniform(0, 1)
time.sleep(delay)
resp = chat_with_retry(
[{"role": "user", "content": "Give me three names for a tavern."}],
max_tokens=100,
)
print(resp.choices[0].message.content)Node.js 中使用原始 fetch 的等效寫法:
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
async function chatWithRetry(body, maxAttempts = 5) {
for (let attempt = 0; attempt < maxAttempts; attempt++) {
const res = await fetch("https://api.uncensoredaiapis.com/v1/chat/completions", {
method: "POST",
headers: {
"Authorization": `Bearer ${process.env.API_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({ model: "uncensored", ...body }),
});
if (res.ok) return res.json();
const retryable = res.status === 429 || res.status === 503;
if (!retryable || attempt === maxAttempts - 1) {
throw new Error(`HTTP ${res.status}: ${await res.text()}`);
}
const delay = Math.min(30000, 2 ** attempt * 1000) + Math.random() * 1000;
await sleep(delay);
}
}
const data = await chatWithRetry({
messages: [{ role: "user", content: "Give me three names for a tavern." }],
max_tokens: 100,
});
console.log(data.choices[0].message.content);如果你經常遇到 429,更好的解決方案通常是在客戶端設定並行限制(使用訊號量或具有 5 到 10 個工作項目的佇列),而非更長的睡眠時間。以每分鐘 300 次請求計算,你可以維持每秒 5 次請求,這對大多數應用程式來說已足夠。
多輪對話狀態
API 為無狀態。它不會記住先前的請求,因此每次呼叫都必須包含你希望模型看到的歷史。維護一個訊息列表,附加使用者輪次,呼叫 API,附加助手回覆,然後重複。索引 0 的系統訊息包含人格或指示,且每次都會傳送。
import os
from openai import OpenAI
client = OpenAI(
base_url="https://api.uncensoredaiapis.com/v1",
api_key=os.environ["API_KEY"],
)
messages = [
{"role": "system", "content": "You are a dry-witted ship's AI. Keep replies under 80 words."}
]
def say(text: str) -> str:
messages.append({"role": "user", "content": text})
resp = client.chat.completions.create(
model="uncensored", messages=messages, max_tokens=300
)
reply = resp.choices[0].message.content
messages.append({"role": "assistant", "content": reply})
return reply
print(say("We just lost the main engine. Options?"))
print(say("Which of those is the least risky?"))由於整個歷史紀錄都會重新傳送,輸入成本會隨著每次對話輪次增加。上下文視窗為 100,000 token,涵蓋提示詞與補完的總和,因此在非常長的對話中,當 prompt + max_tokens 超過限制時,回應會在視窗末尾停止;只有提示詞本身超出視窗才會回傳 400 錯誤。常見策略包括:在保留系統訊息的前提下移除最舊的使用者與助手配對,或要求模型將較早的對話輪次摘要為一段簡短訊息並取代它們。請將歷史紀錄儲存到你自己的資料庫中,以對話 ID 為索引,以便重新啟動時不會遺失對話線索。如需長對話的範例與實際成本估算,請參閱 使用案例頁面。
使用 max_tokens 控制成本
定價為每百萬輸入 token $0.15,每百萬輸出 token $0.50,從預付額度中扣款。輸出的費用是輸入的約 3.3 倍,且 max_tokens 是單一請求輸出的可選上限。若未設定,回應可能會耗盡整個 context window。刻意設定此值是你所能採取的最簡單成本控制方式。
最壞情況的計算有助於估算。如果你不對輸出設限,回應可能會佔滿整個上下文視窗,因此僅輸出部分就可能高達 100,000 × $0.50 / 1,000,000 = $0.05。如果你將 max_tokens 設定為 300 以回覆聊天,最壞情況下的成本會降至 $0.00015。一次典型的對話輪次包含 1,500 個輸入 token 和 300 個輸出 token,成本約為 $0.000225 加上 $0.00015,總計低於 $0.001。
import os
from openai import OpenAI
client = OpenAI(
base_url="https://api.uncensoredaiapis.com/v1",
api_key=os.environ["API_KEY"],
)
INPUT_PER_M = 0.25
OUTPUT_PER_M = 1.00
resp = client.chat.completions.create(
model="uncensored",
messages=[{"role": "user", "content": "Summarise the plot of Hamlet in 5 sentences."}],
max_tokens=250,
)
u = resp.usage
cost = u.prompt_tokens * INPUT_PER_M / 1_000_000 + u.completion_tokens * OUTPUT_PER_M / 1_000_000
print(f"in={u.prompt_tokens} out={u.completion_tokens} cost=${cost:.6f}")
print("finish_reason:", resp.choices[0].finish_reason)注意 finish_reason。值為 length 表示回覆觸及你的上限而被截斷;如果經常發生此情況,請提高上限或在提示詞中要求更短的輸出,因為僅靠上限會截斷內容,而非讓模型精簡。將上限與指示(如目標字數)搭配使用,並為每次呼叫記錄 usage,以便查看實際平均值而非猜測。你的免費試用額度和餘額詳情位於 定價頁面。
問答
這個無審查 AI API 需要特殊的 SDK 嗎?
不需要。官方 openai Python 套件 (v1+) 與 openai npm 套件 (v4+) 即可使用。將 base_url 設為 https://api.uncensoredaiapis.com/v1, 並傳入金鑰,然後使用模型 id uncensored。
串流輸出包含 token 用量嗎?
是的。當 stream: true 時,API 會自動加入一個包含用量資訊的最後一個 chunk。該 chunk 的 choices 陣列為空,因此在讀取 delta 前請先檢查 choices 是否存在。
我的程式碼應該重試哪些錯誤?
對 429(速率限制,每支金鑰每分鐘 300 次請求)與 503 upstream_busy 使用指數退避與抖動重試。不要重試 400、401、402 或 403,因為相同的請求仍會失敗。
在呼叫之間,對話歷史會為我儲存嗎?
不會。每個請求都是獨立的,因此每次都要傳送完整的 messages 列表。上下文視窗為 100,000 token,涵蓋提示詞與補全的總和。