繁中 ▾
取得 API 金鑰

Uncensored AI如何使用 AI 圖像 API

Python Chat Completions API:串流輸出與錯誤處理

本 Chat Completions API Python 教學將帶您從安裝到建立生產環境用的客戶端:首次請求、串流輸出、工具呼叫、JSON 模式與錯誤處理。每個範例都針對 OpenAI 相容的端點,並使用 uncensored 模型 ID。

更新

傳送帶上的膠囊進入腔體,並以光流的形式離開:一次請求與串流回覆

01Uncensored AI

重點摘要

  1. 文字 API 獨立於圖像生成模型,處理提示詞建構、腳本撰寫與中繼資料擷取。

  2. OpenAI 相容端點允許使用標準 SDK 直接整合,無需開發自訂協定。

  3. 串流輸出支援即時 token 交付,對於互動式提示詞精煉工作流程至關重要。

  4. Token 計費採用量付費制,並對上下文視窗與請求速率有特定限制。

安裝並進行首次請求

您需要 Python 3.8 或更新版本以及 OpenAI 套件。在 API 金鑰頁面建立金鑰;一鍵試用可獲得 $0.50 的信用額度,無需付款。

pip install openai
from openai import OpenAI

client = OpenAI(
    base_url="https://api.uncensoredaiimage.com/v1",
    api_key="YOUR_KEY",
)

response = client.chat.completions.create(
    model="uncensored",
    messages=[
        {"role": "system", "content": "You are a concise assistant."},
        {"role": "user", "content": "What is a mutex?"},
    ],
    temperature=0.7,
)

print(response.choices[0].message.content)
print(response.usage)

此動作會發送 POST /v1/chat/completions。訊息是一個包含 role 為 system、user、assistant 或 tool 的字典列表。回覆位於 choices[0].message.content,而 usage 會回報提示詞與完成 token 的數量,以便你計算成本:每 1M 輸入 token $0.15,每 1M 輸出 token $0.50。

使用環境變數,而非硬編碼金鑰

將金鑰排除在版本控制之外。如果您未傳遞它們,SDK 會從環境中讀取 OPENAI_API_KEY 和 OPENAI_BASE_URL,這使得同一個腳本可以針對不同的端點運作。

import os
from openai import OpenAI

client = OpenAI(
    base_url=os.environ.get("LLM_BASE_URL", "https://api.uncensoredaiimage.com/v1"),
    api_key=os.environ["LLM_API_KEY"],
    timeout=120,
    max_retries=0,
)

設定 max_retries=0 會關閉 SDK 的自動重試,讓您可以自行控制重試政策,如下方錯誤章節所示。對於長補全,設定較長的逾時是合理的,因為上下文視窗為 100,000 token,且回覆可能很長。

串流輸出

對於聊天介面,請在收到 token 時進行串流。設定 stream=True 並進行迭代。請索取用量,以便最後一個區塊包含 token 計數。

stream = client.chat.completions.create(
    model="uncensored",
    messages=[{"role": "user", "content": "Explain TCP slow start briefly."}],
    stream=True,
    stream_options={"include_usage": True},
)

parts = []
for chunk in stream:
    if chunk.choices and chunk.choices[0].delta.content:
        piece = chunk.choices[0].delta.content
        parts.append(piece)
        print(piece, end="", flush=True)
    if chunk.usage:
        usage = chunk.usage

print()
print("tokens:", usage.prompt_tokens, usage.completion_tokens)

傳輸協定為伺服器發送事件 (SSE)。請記住一件事:串流請求會佔用一個您的並行槽位,直到串流結束為止。完整金鑰有 8 個槽位,試用金鑰有 2 個。如果您放棄串流,請關閉它以釋放槽位。

對話狀態

API 是無狀態的。每次輪次你都需要重新傳送歷史紀錄。追加助理回覆,然後是下一個使用者訊息。

history = [{"role": "system", "content": "You are a helpful tutor."}]

def chat(user_text):
    history.append({"role": "user", "content": user_text})
    r = client.chat.completions.create(model="uncensored", messages=history)
    reply = r.choices[0].message.content
    history.append({"role": "assistant", "content": reply})
    return reply

print(chat("Define recursion."))
print(chat("Now give a Python example."))

歷史記錄在每次呼叫時都視為輸入進行計費,因此長對話每個回合的成本較高。一旦超過您設定的限制,請修剪最舊的訊息,並保留系統提示詞。

JSON 模式與工具呼叫

JSON 模式

傳遞 response_format={"type": "json_object"} 並在提示詞中告知模型您希望取得的鍵。解析結果並處理失敗情況,因為模型仍可能產生格式錯誤的輸出。

import json

r = client.chat.completions.create(
    model="uncensored",
    messages=[{"role": "user", "content": "Return JSON with keys city and country for Lyon."}],
    response_format={"type": "json_object"},
)
data = json.loads(r.choices[0].message.content)
print(data)

工具呼叫

tools = [{
    "type": "function",
    "function": {
        "name": "get_time",
        "description": "Current time in a city",
        "parameters": {
            "type": "object",
            "properties": {"city": {"type": "string"}},
            "required": ["city"],
        },
    },
}]

msgs = [{"role": "user", "content": "What time is it in Tokyo?"}]
r = client.chat.completions.create(model="uncensored", messages=msgs, tools=tools)
call = r.choices[0].message.tool_calls[0]
msgs.append(r.choices[0].message)
msgs.append({"role": "tool", "tool_call_id": call.id, "content": "14:05"})
final = client.chat.completions.create(model="uncensored", messages=msgs, tools=tools)
print(final.choices[0].message.content)

在實際程式碼中,請在存取之前檢查 tool_calls 是否不為空,因為模型可能會直接回覆。結果以 role: "tool" 訊息的形式回傳。

傳遞的採樣參數

這些參數會原封不動地傳遞給模型:temperature、top_p、stop、seed、frequency_penalty 和 presence_penalty。一些實用設定:

  • 提取與程式碼: temperature 設為 0 到 0.3,使答案在多次執行間保持穩定。
  • 創意寫作與角色扮演: temperature 設為 0.8 至 1.0,若文字出現循環則加入輕度的存在懲罰。
  • 可重現測試: 固定 seed 並保持其他設定不變。將可重現性視為盡力而為,而非保證。
  • 截斷輸出: 使用 stop 搭配標記字串,例如您的格式結束的行。

一次只更改一個設定,並在固定的提示詞集上進行比較。同時更改溫度和懲罰會使難以判斷什麼有效。

錯誤、限制與重試

請將三種情況分開處理。code 為 rate_limited 的 429 表示您超過了每分鐘請求數(完整金鑰為 300,試用金鑰為 60)。code 為 concurrency 的 429 表示同時請求過多(完整金鑰為 8,試用金鑰為 2)。帶有 Retry-After: 5 標頭的 429 表示暫時過載,請等待後再試。失敗或被拒絕的請求不會計費。

import time, random
from openai import APIStatusError, APIConnectionError, RateLimitError

def complete(messages, tries=5):
    for attempt in range(tries):
        try:
            return client.chat.completions.create(model="uncensored", messages=messages)
        except RateLimitError as e:
            wait = float(e.response.headers.get("Retry-After", 5))
            time.sleep(wait + random.random())
        except APIConnectionError:
            time.sleep(2 ** attempt)
        except APIStatusError as e:
            if e.status_code >= 500:
                time.sleep(2 ** attempt)
            else:
                raise
    raise RuntimeError("gave up after retries")

對於並行工作,請在您自己的程式碼中限制並行數量,而非依賴重試機制。ThreadPoolExecutor(max_workers=8) 或 asyncio.Semaphore(8) 對應完整金鑰的配額。超過 8 MB 的請求會被拒絕,這僅在您將大型文件嵌入提示詞時才具影響。

追蹤成本與餘額

每個回應都包含 X-Request-Id、X-Balance-USD、X-RateLimit-Limit-Requests 和 X-RateLimit-Limit-Concurrency。要使用 SDK 讀取標頭,請使用原始回應:

raw = client.chat.completions.with_raw_response.create(
    model="uncensored",
    messages=[{"role": "user", "content": "ping"}],
)
print(raw.headers.get("X-Balance-USD"), raw.headers.get("X-Request-Id"))
response = raw.parse()
print(response.choices[0].message.content)

您也可以呼叫 GET /v1/balance。在每個錯誤時記錄請求 ID;這是從 支援頁面 獲得協助最快的方式。儲值金額從 $20 到 $500,並享有 $50 起的獎金,以加密貨幣支付(TRC20 上的 USDT 或 Base 上的 USDC);請見 定價。

如果您偏好先使用原始 HTTP 進行測試,curl 指南 展示了相同的呼叫方式,而 文件 列出了所有端點。對於程式碼導向的提示詞,請見 用於程式設計的 uncensored AI。請記住這是一個純文字 API:它不會生成影像,儘管網站名稱可能暗示了這一點。

02Uncensored AI

問答

我需要特殊的函式庫嗎?

不會。官方的 openai Python 套件在設定 base_url 和 api_key 後即可運作。使用模型 uncensored。

最大上下文視窗是多少?

上下文視窗為 100,000 token,即提示詞與補全 token 的總和。max_tokens 為選填,因此補全可使用剩餘空間。

如何區分兩種 429 錯誤?

請查看錯誤代碼。rate_limited 表示每分鐘請求過多,concurrency 表示同時請求過多。Retry-After: 5 標頭標示暫時過載。

max_tokens 是必填嗎?

不是。它是選填的。當你想要限制回覆長度與成本時,請設定它。

Uncensored AIuncensoredaiimage.com

只需填寫一份表單即可取得金鑰

建立帳號、複製金鑰、更改基礎 URL。這就是整個設定過程。

取得 API 金鑰