curl 快速入门
最小的有效 JSON 模式请求如下所示。它使用基础 URL https://api.uncensoredllmapi.com/v1、模型 uncensored 以及你的 Bearer 令牌作为密钥:
curl https://api.uncensoredllmapi.com/v1/chat/completions -H "Authorization: Bearer $UNCENSORED_API_KEY" -H "Content-Type: application/json" -d '{
"model": "uncensored",
"response_format": {"type": "json_object"},
"messages": [
{"role": "system", "content": "Reply only with a JSON object."},
{"role": "user", "content": "Create a tavern NPC with keys name, trade and rumour."}
]
}'
choices[0].message.content 中的助手消息是一个包含 JSON 对象的字符串。你仍需自行解析。不要跳过提示词中的指令:JSON 模式将输出限制为对象,但它无法猜测你需要的键。指定键,并最好展示一行示例,才能获得稳定的结构。
如果你还没有密钥,API 密钥页面 在注册后一键发放 $0.50 的试用额度。该额度无需付款,有效期 7 天,每人限领一次。
带验证的 Python JSON 模式
将模型输出视为任何其他外部输入。解析它,根据模式检查它,如果失败则重试有限次数。Pydantic 使这变得简单:
import json, os
from openai import OpenAI
from pydantic import BaseModel, ValidationError
client = OpenAI(
base_url="https://api.uncensoredllmapi.com/v1",
api_key=os.environ["UNCENSORED_API_KEY"],
)
class Npc(BaseModel):
name: str
trade: str
rumour: str
SYSTEM = (
"Reply only with a JSON object with exactly these keys: "
"name, trade, rumour. Each value is a string."
)
def make_npc(setting, tries=3):
for _ in range(tries):
r = client.chat.completions.create(
model="uncensored",
response_format={"type": "json_object"},
messages=[
{"role": "system", "content": SYSTEM},
{"role": "user", "content": f"Setting: {setting}"},
],
temperature=0.7,
max_tokens=300,
)
choice = r.choices[0]
if choice.finish_reason == "length":
continue # cut off, so the JSON is incomplete
try:
return Npc(**json.loads(choice.message.content))
except (json.JSONDecodeError, ValidationError, TypeError):
continue
raise RuntimeError("no valid JSON after retries")
print(make_npc("a river port in a plague year"))
该片段中有三个习惯值得借鉴。代码在解析前检查 finish_reason,因为回复在达到 max_tokens 时会在对象中间结束。它使用适中的 temperature,因为高 temperature 会增加输出格式错误的概率。它还限制重试次数,以免坏提示词导致无限循环。由于失败或被拒绝的请求不收费,重试预算是一个延迟问题,而非成本问题。
常见的 JSON 模式错误
- 在提示词中要求 JSON,但未在
response_format中设置。 模型通常会配合,但可能会将对象包裹在文本或代码块中。请同时设置两者。 - 将
max_tokens设置得太低。 估算最长有效答案并增加余量。长列表很容易超过 300 个 token。 - 期望顶级数组。 JSON 模式要求对象。如果需要列表,请请求
{"items": [...]}。 - 堆叠出现在 JSON 中的停止序列。
stop参数会被透传,如果停止字符串出现在值内部,会截断回复。 - 在流式输出中使用 JSON 模式并解析每个块。 先收集完整文本,然后在最后解析一次。
采样设置如 temperature、top_p、seed 和惩罚项会被透传。对于提取任务,约 0.2 的低 temperature 和固定的 seed 能产生最可重复的输出。对于上面 NPC 的创意生成,只要进行验证,较高的值也可以。
函数调用:完整循环
工具调用允许模型请求你的代码执行某项操作,然后继续处理结果。流程有四个步骤:你声明工具,模型回复 tool_calls,你执行它们,然后通过带有 role: "tool" 的消息发送结果。
import json, os
from openai import OpenAI
client = OpenAI(
base_url="https://api.uncensoredllmapi.com/v1",
api_key=os.environ["UNCENSORED_API_KEY"],
)
tools = [{
"type": "function",
"function": {
"name": "lookup_inventory",
"description": "Return the stock count for an item in the shop.",
"parameters": {
"type": "object",
"properties": {"item": {"type": "string"}},
"required": ["item"],
},
},
}]
def lookup_inventory(item):
stock = {"healing potion": 4, "rope": 12}
return {"item": item, "count": stock.get(item.lower(), 0)}
messages = [{"role": "user", "content": "Do you still have healing potions?"}]
for _ in range(4): # hard cap on tool rounds
r = client.chat.completions.create(
model="uncensored", messages=messages, tools=tools, tool_choice="auto"
)
msg = r.choices[0].message
if not msg.tool_calls:
print(msg.content)
break
messages.append(msg)
for call in msg.tool_calls:
args = json.loads(call.function.arguments)
result = lookup_inventory(**args)
messages.append({
"role": "tool",
"tool_call_id": call.id,
"content": json.dumps(result),
})
参数以 JSON 字符串形式到达,你必须解析它们,模型偶尔会产生与你的模式不匹配的参数。在执行任何副作用之前验证它们。不要将它们传递给 shell、SQL 字符串或文件路径而不进行检查。
tool_choice 字段让你可以控制行为。将其保留为 "auto",由模型决定。指定特定工具以强制调用,这在希望通过工具定义进行结构化提取而非使用 JSON 模式时很有用。
Node 中的流式函数调用
使用 stream: true 时,函数调用会分片到达。每个块携带函数名或参数字符串的片段,按位置索引。你需要按索引拼接片段,并在流结束时进行解析。
import OpenAI from "openai";
const client = new OpenAI({
baseURL: "https://api.uncensoredllmapi.com/v1",
apiKey: process.env.UNCENSORED_API_KEY,
});
const stream = await client.chat.completions.create({
model: "uncensored",
stream: true,
messages: [{ role: "user", content: "Check stock for rope." }],
tools: [{
type: "function",
function: {
name: "lookup_inventory",
description: "Return the stock count for an item.",
parameters: {
type: "object",
properties: { item: { type: "string" } },
required: ["item"],
},
},
}],
});
const calls = [];
for await (const chunk of stream) {
const delta = chunk.choices[0]?.delta;
for (const tc of delta?.tool_calls ?? []) {
const slot = (calls[tc.index] ??= { id: "", name: "", args: "" });
if (tc.id) slot.id = tc.id;
if (tc.function?.name) slot.name += tc.function.name;
if (tc.function?.arguments) slot.args += tc.function.arguments;
}
}
for (const c of calls) {
console.log(c.name, JSON.parse(c.args));
}
请记住,流式请求会占用一个并发槽位,直到流结束。完整密钥允许 8 个并发请求和每分钟 300 个请求,试用密钥允许 2 个和 60 个。触发任一限制将返回 HTTP 429,代码为 concurrency 或 rate_limited。使用总量在流结束时报告,这便于记录成本。
JSON 模式或工具定义
两者都提供结构化数据,那么你应该使用哪一个?决定的问题是模型是在生成数据还是选择动作。
当输出本身就是产品时使用 JSON 模式:NPC 表、标签列表、带有置信度字段的分类。你控制整个提示词,得到一个对象,并且只需支付一次请求费用。
当模型必须决定是否采取行动,或者有多种不同行动可选时使用函数。每个函数的模式记录了契约,tool_choice 允许你强制或允许调用,上一节的循环处理多步工作。成本是每轮额外的一次请求,加上每次将函数定义计入输入。
提取的一种实用中间路径:声明一个参数为你想要字段的函数,并将 tool_choice 设置为该函数。你获得的参数字符串遵循你的模式结构,而无需将键列表写入提示词。无论哪种方式,在信任结果前请进行验证,并记录产生意外结果的请求的 X-Request-Id 值。
费用说明
JSON 和函数调用像其他任何 token 一样计费:每 1M 输入 $0.15,每 1M 输出 $0.50。函数定义在每次请求中计入输入,你发送回的每个函数结果都会增加下一次请求的输入。
示例:一个使用工具的助手回合,包含 600 个 token 的工具定义和提示词,150 个 token 的模型调用,然后是第二个请求,包含 900 个输入 token(之前的消息加上工具结果)和 200 个 token 的回复。
- 请求一:600 输入和 150 输出。输入 600 x $0.15 / 1M = $0.00009。输出 150 x $0.50 / 1M = $0.000075。小计 $0.000165。
- 请求二:900 输入和 200 输出。输入 900 x $0.15 / 1M = $0.000135。输出 200 x $0.50 / 1M = $0.0001。小计 $0.000235。
- 该回合总计:$0.0004。
按此费率,1,000 次回合成本为 $0.40。额度以整数金额预付,从 $20 到 $500(奖励:$50 起 +5%,$100 起 +10%,$200 起 +15%),通过加密货币支付,支持 TRC20 上的 USDT 或 Base 上的 USDC。查看 定价页面 获取当前数据。
下一步操作
所有请求字段的参考信息在 API 文档 中。如果你正在为真实流量准备应用,生产环境清单 是接下来要阅读的页面,如果请求行为异常,支持 可以提供帮助。保留你的请求 ID,它通过 X-Request-Id 头部返回,以便随时查阅。
服务仅支持文本,上下文窗口为 100,000 个 token,包括你的工具定义和结果。不允许涉及未成年人的性内容,这也适用于结构化输出和工具驱动的输出,正如普通聊天一样。
