Uncensored AI API 代码示例:Python、Node.js 和 cURL
本页面收集了适用于无审查 AI API 的复制粘贴代码,该 API 遵循 OpenAI chat completions 格式。你将找到 Python、Node.js 和 cURL 的首次调用示例,使用 SDK 和原始 fetch 的流式输出,函数调用,针对 429 和 503 的重试逻辑,多轮对话状态,以及使用 max_tokens 控制成本。

要点
- 使用官方 openai SDK,将 base_url 设置为 https://api.uncensoredaiapis.com/v1 并将模型设置为 "uncensored";无需自定义客户端。
- 流式输出返回 SSE chunk,并自动附带一个包含用量信息的最终 chunk,其 choices 列表为空。
- 仅对 429 和 503(upstream_busy)进行重试;400、401、402 和 403 需要修复,而非重试。
- API 是无状态的:每轮重新发送历史,并使用 max_tokens 限制输出(可选;如果未设置,响应可能会持续到上下文窗口结束)。
首次调用: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 将返回服务器发送事件而不是单个 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 次请求的限制。带有代码 upstream_busy 的 503 表示服务暂时饱和;等待几秒是预期的响应。不要重试 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,更好的修复方法通常是一个小型客户端并发限制(一个信号量或一个具有五到十个工作者的队列),而不是更长的睡眠。每分钟 300 次请求意味着你可以维持每秒五个请求,这对于大多数应用程序来说已经足够了。
多轮对话状态
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 是单个请求输出的可选上限。如果不设置,响应可能会填满整个上下文窗口。有意设置它是你拥有的最简单的成本控制方法。
最坏情况下的算术计算会有所帮助。如果不限制输出,响应可能会填满整个上下文窗口,因此仅输出部分就可能高达 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 会自动添加一个携带使用情况的最后一个块。该块有一个空的 choices 数组,因此在读取 delta 之前请检查 choices 是否存在。
我的代码应该重试哪些错误?
对 429(速率限制,每个密钥每分钟 300 个请求)和 503 upstream_busy 使用指数退避和抖动进行重试。不要对 400、401、402 或 403 重试,因为相同的请求会再次失败。
调用之间会为我存储对话歷史吗?
不会。每个请求都是独立的,因此每次都需要发送完整的 messages 列表。上下文窗口为 100,000 token,涵盖提示词和补全的总和。