curl 快速開始
最簡化的 JSON 模式請求如下所示。它使用 Base URL https://api.uncensoredllmapi.com/v1、模型 uncensored,並將你的金鑰作為 Bearer token 使用:
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 設為該函式。你將獲得符合你的結構定義格式的參數 JSON,無需在提示詞中鍵入欄位清單。無論如何,在信任結果前請進行驗證,並記錄產生任何意外結果之請求的 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,該 ID 會透過 X-Request-Id 標頭回傳。
服務僅支援文字,上下文視窗為 100,000 token,包含你的工具定義與結果。涉及未成年人的性內容不被允許,此規定同樣適用於結構化輸出與工具驅動輸出,與純文字聊天一致。
