步驟 1:安裝 SDK 並設定金鑰
該服務支援 OpenAI chat completions 協議,因此你不需要特殊的客戶端。安裝官方套件並將金鑰保存在環境變數中,不要放在原始碼裡。
pip install openai
export API_KEY="paste-your-key-here"
curl https://api.apertus.top/v1/models -H "Authorization: Bearer $API_KEY"
curl https://api.apertus.top/v1/chat/completions \
-H "Authorization: Bearer $API_KEY" -H "Content-Type: application/json" \
-d '{"model":"uncensored","messages":[{"role":"user","content":"ping"}]}'
GET /v1/models 呼叫是確認金鑰是否有效的最快方式,第二次請求則會傳送單字測試聊天。如果你還沒有金鑰,在此建立一個。新用戶可以在金鑰頁面一鍵領取 $0.50 的免費試用額度。無需綁定信用卡,有效期為 7 天。
使用虛擬環境(python -m venv .venv)以確保套件版本與專案綁定。如果你在筆記本中工作,請在啟動核心前設定變數,或使用 getpass 讀取,以免其落入已儲存的檔案中。
步驟 2:發送你的第一個請求
將客戶端指向 base URL 並傳遞 uncensored 作為模型。其餘程式碼與你為任何託管 LLM 編寫的程式碼相同。
import os
from openai import OpenAI
client = OpenAI(
base_url="https://api.apertus.top/v1",
api_key=os.environ["API_KEY"],
)
resp = client.chat.completions.create(
model="uncensored",
messages=[
{"role": "system", "content": "You are a concise technical assistant."},
{"role": "user", "content": "Explain what a context window is in two sentences."},
],
temperature=0.7,
max_tokens=200,
)
print(resp.choices[0].message.content)
print(resp.usage)
有三個細節從一開始就很有幫助。messages 列表是整個對話,因此模型只知道你傳送的內容。max_tokens 是選填項;若省略它,回覆可以使用剩餘的 100,000-token 上下文視窗。而 resp.usage 會顯示你被計費的 token,這是你在開發時檢查成本的方式。同一個端點也接受 seed、stop、top_p 以及頻率懲罰和存在懲罰。
步驟 3:保持對話持續
LLM 在呼叫之間沒有記憶。要建立聊天,請儲存每則訊息並重新發送列表。這個小迴圈將歷史記錄保存在 Python 列表中:
import os
from openai import OpenAI
client = OpenAI(base_url="https://api.apertus.top/v1", api_key=os.environ["API_KEY"])
history = [{"role": "system", "content": "Answer briefly."}]
while True:
text = input("you: ")
if text in ("q", "quit"):
break
history.append({"role": "user", "content": text})
resp = client.chat.completions.create(model="uncensored", messages=history)
answer = resp.choices[0].message.content
history.append({"role": "assistant", "content": answer})
print("llm:", answer)
由於每次呼叫都會重新發送歷史記錄,輸入 token 會隨著每次交談而增長。對於長時間的會話,在列表接近上下文限制之前,請刪除或摘要舊訊息。
一個有用的習慣是在每次交談時記錄 resp.usage.prompt_tokens。你會看到數字大致隨著每次交談的長度上升,這告訴你何時需要修剪。
步驟 4:串流輸出答案
串流輸出會在資料到達時顯示單詞,這在終端機或網頁 UI 中感覺更快。設定 stream=True 並遍歷區塊。串流使用伺服器發送事件,並以使用資料結束。
import os
from openai import OpenAI
client = OpenAI(base_url="https://api.apertus.top/v1", api_key=os.environ["API_KEY"])
stream = client.chat.completions.create(
model="uncensored",
messages=[{"role": "user", "content": "List five uses of a hash map."}],
stream=True,
)
for chunk in stream:
if chunk.choices and chunk.choices[0].delta.content:
print(chunk.choices[0].delta.content, end="", flush=True)
print()
要記住的一條規則:串流請求會佔用一個並行槽位,直到串流結束,因此請務必消耗或關閉串流。
步驟 5:獲取 JSON 並呼叫工具
JSON 模式
當程式而非人類讀取輸出時,設定 response_format 並在提示詞中描述你想要的形狀。
import json, os
from openai import OpenAI
client = OpenAI(base_url="https://api.apertus.top/v1", api_key=os.environ["API_KEY"])
resp = client.chat.completions.create(
model="uncensored",
response_format={"type": "json_object"},
messages=[{"role": "user", "content":
'Return JSON with keys "title" and "tags" (a list) for a post about Python generators.'}],
)
data = json.loads(resp.choices[0].message.content)
print(data["title"], data["tags"])
函式呼叫
傳遞 tools,模型即可要求你的程式碼執行函式。你執行後,以 role: "tool" 訊息回傳結果。
import json, os
from openai import OpenAI
client = OpenAI(base_url="https://api.apertus.top/v1", api_key=os.environ["API_KEY"])
tools = [{"type": "function", "function": {
"name": "add",
"description": "Add two numbers",
"parameters": {"type": "object",
"properties": {"a": {"type": "number"}, "b": {"type": "number"}},
"required": ["a", "b"]}}}]
messages = [{"role": "user", "content": "What is 17.5 plus 24.25?"}]
first = client.chat.completions.create(model="uncensored", messages=messages, tools=tools)
call = first.choices[0].message.tool_calls[0]
args = json.loads(call.function.arguments)
messages.append(first.choices[0].message.model_dump(exclude_none=True))
messages.append({"role": "tool", "tool_call_id": call.id, "content": str(args["a"] + args["b"])})
final = client.chat.completions.create(model="uncensored", messages=messages, tools=tools)
print(final.choices[0].message.content)
在實際程式碼中,在索引之前檢查 tool_calls 是否不為空。模型可能會直接回答。
步驟 6:處理錯誤和速率限制
完整金鑰允許 8 個並行請求和每分鐘 300 個請求;試用金鑰則允許 2 個和 60 個。超過限制時,API 會回傳 HTTP 429 並附上錯誤代碼 rate_limited(每分鐘過多)或 concurrency(同時過多)。在暫時過載時,它也會傳送 429 並帶有 Retry-After: 5。SDK 會引發 RateLimitError,因此請將呼叫包裝在短暫的重試迴圈中。
import os, time
from openai import OpenAI, RateLimitError
client = OpenAI(base_url="https://api.apertus.top/v1", api_key=os.environ["API_KEY"])
def ask(prompt, tries=5):
for attempt in range(tries):
try:
r = client.chat.completions.create(
model="uncensored",
messages=[{"role": "user", "content": prompt}])
return r.choices[0].message.content
except RateLimitError:
wait = 5 * (attempt + 1)
print("429, retrying in", wait, "s")
time.sleep(wait)
raise RuntimeError("gave up after retries")
print(ask("Name three Python web frameworks."))
對於批次作業,使用最多 8 個工作線程的執行緒池(試用金鑰為 2 個),以便保持在並行限制之下,而不是依賴重試。回應也帶有 X-Request-Id 和 X-Balance-USD 標頭,方便日誌和監控餘額。文件列出了每個參數,XAI API 頁面提供了另一個 OpenAI 相容的概覽。
非同步程式碼和常見錯誤
對於網頁伺服器和多個並行呼叫,使用同一套件中的非同步客戶端。它接受相同的參數,並保持一個信號量大小的請求池處於活動狀態,以便保持在並行限制之下。
import asyncio, os
from openai import AsyncOpenAI
client = AsyncOpenAI(base_url="https://api.apertus.top/v1", api_key=os.environ["API_KEY"])
sem = asyncio.Semaphore(8)
async def ask(prompt):
async with sem:
r = await client.chat.completions.create(
model="uncensored",
messages=[{"role": "user", "content": prompt}])
return r.choices[0].message.content
async def main():
prompts = [f"Give one tip about Python, number {i}." for i in range(20)]
answers = await asyncio.gather(*(ask(p) for p in prompts))
print(len(answers), "answers")
asyncio.run(main())
如果出現故障,請先檢查這些:
- API_KEY 的 KeyError。 變數未在運行 Python 的殼層中設定。再次匯出它或從檔案載入。
- 404 或連線錯誤。 base URL 缺少
/v1後綴或有拼寫錯誤。 - 驗證錯誤。 金鑰含有殘留的空格或換行符,或者你使用了錯誤的標頭傳送它。SDK 會為你設定
Authorization: Bearer。 - 找不到模型。 模型 ID 為
uncensored,為小寫。 - 空值或截斷的回覆。 你將
max_tokens設得太低。移除它或提高它。
腳本的成本
定價為每 1M 輸入 token $0.15,每 1M 輸出 token $0.50,從預付額度計費,無訂閱。假設一個腳本分類 1,000 條支援訊息,每條發送約 500 個輸入 token 並獲得約 200 個輸出 token。
- 輸入:1,000 × 500 = 500,000 token × $0.15 / 1M = $0.075。
- 輸出:1,000 × 200 = 200,000 token × $0.50 / 1M = $0.10。
- 總計:$0.175。
失敗或遭拒的請求不會收費,且額度永不過期。儲值金額為 $20 至 $500 的任意整數金額,可透過加密貨幣(TRC20 上的 USDT、Base 上的 USDC)支付,並享有 5% 的額外贈額(從 $50 起)、10%(從 $100 起)和 15%(從 $200 起)。提示詞不會用於訓練。請參閱 定價頁面 以取得詳細資訊。
