Open AI API Python:使用 OpenAI SDK 搭配我們的模型

對於 OpenAI API 的 Python 程式碼,你不需要特殊的函式庫。一旦你設定了不同的 base URL 和金鑰,官方的 openai 套件即可與此服務搭配使用,且模型 ID 為 uncensored。以下提供完整的逐步操作說明與可複製貼上的範例。
重點摘要
- 安裝 openai,然後將 base_url 和 api_key 傳給客戶端;程式碼的其他部分不需要變更。
- 串流輸出、JSON 模式和函式呼叫都透過相同的 SDK 方法運作。
- 捕獲 RateLimitError 並重試;限制為每分鐘 300 次請求,且完整金鑰最多支援 8 個並行請求。
- 成本為每 1M 輸入 token $0.15,每 1M 輸出 token $0.50,僅對成功的請求收費。
安裝並進行首次呼叫
你需要 Python 3.9 或更新版本以及官方 SDK。先在 金鑰頁面建立 API 金鑰;新帳戶可以點擊一次,無需信用卡即可領取 $0.50 的免費試用額度。
pip install openai
export API_KEY="your-key-here"
現在是最小的可運作腳本。客戶端會取得 base URL 和金鑰;請求則使用模型 ID uncensored。
import os
from openai import OpenAI
client = OpenAI(
base_url="https://api.aiapisource.com/v1",
api_key=os.environ["API_KEY"],
)
resp = client.chat.completions.create(
model="uncensored",
messages=[
{"role": "system", "content": "You are a concise writing assistant."},
{"role": "user", "content": "Give me three opening lines for a mystery novel."},
],
temperature=0.8,
)
print(resp.choices[0].message.content)
print(resp.usage.prompt_tokens, resp.usage.completion_tokens)
這就是完整的整合。服務實作了 POST /v1/chat/completions 和 GET /v1/models,涵蓋了大多數腳本的需求。它僅為文字模型,因此不提供影像、音訊和嵌入端點。
這是什麼,以及這不是什麼
SDK 由 OpenAI 開發,但此處的端點並非 OpenAI 的。這是一個託管的開放權重模型,由獨立供應商運行,並經過調整以在法律允許的成人用途下無內容拒絕地回答。不會路由到 GPT 或其他供應商模型。這就是為什麼你要更改 Base URL:你正在與接受相同請求格式的伺服器進行通訊。
如果你正在遷移現有專案,請搜尋 OpenAI( 和硬編碼的模型名稱。僅這兩個地方需要編輯。本站上的 GPT API 生產檢查清單 涵蓋了適用於任何 OpenAI 格式端點的習慣,例如超時和重試。
串流輸出回覆
對於聊天介面,你需要在產生 token 時取得它們。設定 stream=True 並進行迭代。如果你需要帳單數據,請在最後詢問用量:
stream = client.chat.completions.create(
model="uncensored",
messages=[{"role": "user", "content": "Write a four-line poem about a night train."}],
stream=True,
stream_options={"include_usage": 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("\ntokens:", chunk.usage.prompt_tokens, chunk.usage.completion_tokens)
chunk.choices 的保護很重要:最後一個 chunk 可能包含用量而沒有 choices。此外,串流請求會佔用你的一個並行槽位,直到串流結束,因此請務必讀取至結束或關閉它。
JSON 模式
當你的程式碼需要解析答案時,切換到 JSON 模式並在提示詞中描述金鑰:
import json
resp = client.chat.completions.create(
model="uncensored",
response_format={"type": "json_object"},
messages=[
{"role": "user", "content": "Return JSON with keys name (string) and traits (list of 3 strings) for a fictional ship captain."}
],
)
character = json.loads(resp.choices[0].message.content)
print(character["name"], character["traits"])
通常能得到有效的 JSON,但不保證符合你想要的確切結構,因此請檢查金鑰,並在失敗時重試一次。
函式呼叫
在 tools 中描述函式,執行模型要求的任何操作,並使用 role: "tool" 將結果傳回:
import json
tools = [{
"type": "function",
"function": {
"name": "roll_dice",
"description": "Roll a die with the given number of sides",
"parameters": {
"type": "object",
"properties": {"sides": {"type": "integer"}},
"required": ["sides"],
},
},
}]
messages = [{"role": "user", "content": "Roll a 20-sided die for my character."}]
first = client.chat.completions.create(model="uncensored", messages=messages, tools=tools)
msg = first.choices[0].message
if msg.tool_calls:
messages.append(msg)
for call in msg.tool_calls:
args = json.loads(call.function.arguments)
result = {"value": 14, "sides": args["sides"]} # replace with real logic
messages.append({"role": "tool", "tool_call_id": call.id, "content": json.dumps(result)})
final = client.chat.completions.create(model="uncensored", messages=messages, tools=tools)
print(final.choices[0].message.content)
else:
print(msg.content)
你可以傳遞 tool_choice 來強制執行函式。參數以 JSON 字串形式提供,因此使用前務必透過 json.loads 解析並驗證。
錯誤、重試與非同步
SDK 會自行重試某些失敗,你可以使用 max_retries 設定重試次數。對於速率限制,請捕獲異常並等待。當超過每分鐘限制時,API 會返回 HTTP 429 並帶有代碼 rate_limited;當太多請求同時運行時,會返回 concurrency;在臨時超載時會返回 Retry-After: 5 標頭。
import time
from openai import RateLimitError
def ask(prompt, tries=4):
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:
time.sleep(5 * (attempt + 1))
raise RuntimeError("Still rate limited after retries")
對於批次處理,請使用非同步客戶端並將並行度限制在限制以下。完整金鑰允許 8 個並行請求和每分鐘 300 次;試用金鑰允許 2 個和每分鐘 60 次。
import asyncio, os
from openai import AsyncOpenAI
aclient = AsyncOpenAI(base_url="https://api.aiapisource.com/v1", api_key=os.environ["API_KEY"])
sem = asyncio.Semaphore(6)
async def one(prompt):
async with sem:
r = await aclient.chat.completions.create(
model="uncensored",
messages=[{"role": "user", "content": prompt}],
)
return r.choices[0].message.content
async def main():
prompts = [f"Write a tagline for product number {i}." for i in range(20)]
results = await asyncio.gather(*(one(p) for p in prompts))
print(len(results), "done")
asyncio.run(main())
使用 8 個槽位中的 6 個,會為同一金鑰上的其他流量留下空間。
保持對話
API 是無狀態的。它在呼叫之間不記住任何內容,因此聊天只是你每次傳送的訊息列表。將回覆附加到列表中,然後再次傳送整個列表:
history = [{"role": "system", "content": "You are a patient writing coach."}]
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("Give me a prompt for a short story."))
print(chat("Make it darker and set it in a harbour town."))
每次呼叫都會比上次發送更多的 token,且每次呼叫都會對輸入 token 計費。當列表變長時,請刪除最早的對話輪次或將其替換為簡短摘要。上下文視窗為 100,000 個 token(包含提示詞與補全),這相當多,但長歷史記錄會使每次請求的成本更高且啟動更慢。
採樣參數會原樣透傳:temperature、top_p、stop、seed 以及頻率和存在懲罰。當你希望進行可重複的測試執行時,請設定 seed 和低溫度。
在大量執行前估算成本
計費基於預付額度:每 1M 輸入 token $0.15,每 1M 輸出 token $0.50。失敗或被拒絕的請求不會收費,且額度永不過期。假設一批 10,000 次請求,每次包含 1,500 個輸入 token 和 400 個輸出 token。輸入為 15,000,000 個 token,即 15 x $0.15 = $2.25。輸出為 4,000,000 個 token,即 4 x $0.50 = $2.00。該批次成本為 $4.25。
回應標頭包含 X-Balance-USD,因此你可以透過程式碼 client.chat.completions.with_raw_response.create(...) 讀取剩餘餘額。儲值金額為 $20 至 $500 之間的任意整數金額,從 $50 起加贈 5%,從 $100 起加贈 10%,從 $200 起加贈 15%。定價頁面 列出了付款方式,而 快速入門 列出了所有支援的參數,包括 stop、seed 和懲罰項。
更多指南
問答
我可以將官方的 OpenAI Python 套件與此 API 搭配使用嗎?
是的。安裝 openai,將 base_url 設為服務端點,將 api_key 設為你的金鑰,並使用模型 uncensored 呼叫 chat.completions.create。
我需要為串流輸出或工具使用不同的函式庫嗎?
不需要。串流輸出、JSON 模式和函式呼叫都透過相同的 SDK 方法運作,並使用一般參數。
這是 OpenAI 的模型嗎?
不是。這是由獨立供應商營運的開放權重模型。請求格式相同,因此 SDK 可以運作。
我的提示詞會用來訓練模型嗎?
不會。透過 API 傳送的提示詞不會用於訓練。
只差一張表單,即可取得金鑰
建立帳號、複製金鑰、更改 base URL。這就是整個設定過程。