最短的運作範例
詢問 如何在 Python 中呼叫 gemini api 的人通常會想到 Google 自己的程式庫。該程式庫有自己的用戶端、金鑰和請求格式。本頁介紹不同的途徑。端點位於 https://api.nsfwgemini.cc/v1,它複製了 OpenAI 聊天完成格式,運行單一開放權重模型,且並非由 Google 營運。由於格式是通用的,標準的 openai 套件可以原封不動地使用。
pip install openai
from openai import OpenAI
client = OpenAI(
base_url="https://api.nsfwgemini.cc/v1",
api_key="YOUR_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 noir story."},
],
)
print(resp.choices[0].message.content)
print(resp.usage)
與標準 OpenAI 腳本相比有三個變更:base_url、金鑰和模型名稱。該行之後的程式碼都是標準的 SDK 用法。從 API 金鑰頁面取得金鑰。新帳戶可以一鍵領取 $0.50 的試用額度,有效期 7 天,無需付款資訊。
將金鑰保留在程式碼之外
硬編碼金鑰僅適用於十秒鐘的測試,一旦檔案進入版本控制庫就會成為問題。請從環境變數讀取:
import os
from openai import OpenAI
client = OpenAI(
base_url="https://api.nsfwgemini.cc/v1",
api_key=os.environ["NSFWGEMINI_API_KEY"],
)
在你的殼層中匯出變數(export NSFWGEMINI_API_KEY=...)或將其放入 .env 檔案中,讓你的工具載入並讓版本控制忽略。SDK 發送的驗證標頭為 Authorization: Bearer <key>,這是此 API 所需的格式,因此無需其他設定。
如果呼叫返回 401,常見原因包括複製錯誤、殼層命令產生的意外換行符,或是來自其他站點的金鑰。列印 len(key) 以找出隱藏空白,而不必顯示金鑰本身。
多輪聊天與採樣選項
API 是無狀態的。它不會記住先前的請求,因此每次都需要重新發送對話。建立一個列表並追加:
history = [{"role": "system", "content": "You are a dry, witty co-writer."}]
def ask(text):
history.append({"role": "user", "content": text})
r = client.chat.completions.create(
model="uncensored",
messages=history,
temperature=0.9,
top_p=0.95,
max_tokens=400,
)
answer = r.choices[0].message.content
history.append({"role": "assistant", "content": answer})
return answer
print(ask("Start a scene in a lighthouse."))
print(ask("Now add a visitor nobody expected."))
temperature、top_p、stop、seed及頻率與存在懲罰會傳遞給模型。max_tokens為選填。若省略,回覆可能耗盡 100,000 token 視窗(含提示詞)。建議設定,因為失控回覆會以每 1M token $0.50 計費。
由於每次呼叫都會重新發送完整歷史,輸入成本會隨著對話長度增長。當列表變長時,請刪除舊輪次或將其摘要化。
簡單的修剪規則對聊天應用程式很有效:保留系統訊息,保留最後約十輪對話,並將較早的內容替換為一次額外呼叫產生的簡短摘要。這能保持提示詞精簡且帳單可預測,並因系統訊息始終保留在列表中而保持角色語氣穩定。記住上下文視窗總共為 100,000 token,因此即使是很長的聊天也能容納,但能容納不等於便宜。
串流回覆
對於人類會查看的內容,請使用串流輸出。伺服器會發送伺服器發送事件(SSE),SDK 會將其轉換為迭代器:
stream = client.chat.completions.create(
model="uncensored",
messages=[{"role": "user", "content": "Describe a market at dawn in 120 words."}],
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("\n", chunk.usage)
用量資訊會在串流結束時到達,因此即使你從未看到非串流回應,也能記錄 token 計數。要記住的一條規則:串流請求會保留其並行槽位直到串流結束。如果你啟動串流但未關閉它,該槽位會保持忙碌。請迭代至結束,或在 finally 區塊中關閉串流。
JSON 模式與工具呼叫
當其他程式消耗輸出時,請要求 JSON:
import json
r = client.chat.completions.create(
model="uncensored",
response_format={"type": "json_object"},
messages=[
{"role": "system", "content": "Reply only with a JSON object."},
{"role": "user", "content": "Give a title and three tags for a short story about a ferry."},
],
)
data = json.loads(r.choices[0].message.content)
print(data)
如上所述在指示中提及 JSON 字詞,並無論如何將 json.loads 包裝在 try 區塊中。因小型 max_tokens 而截斷的回覆將無法解析。
工具呼叫使用與 OpenAI API 相同的欄位:tools、tool_choice、回覆中的工具呼叫,以及你以 role: "tool" 作為訊息傳回的結果。
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"],
},
},
}]
msgs = [{"role": "user", "content": "Roll a twenty-sided die for me."}]
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": "17"})
final = client.chat.completions.create(model="uncensored", messages=msgs, tools=tools)
print(final.choices[0].message.content)
在生產環境中,請在存取 tool_calls 之前檢查其是否存在,因為模型可能會選擇直接回答。
速率限制、重試與你的餘額
完整金鑰允許 8 個並行請求和每分鐘 300 個請求。試用金鑰允許 2 個和 60 個。當你超過限制時,API 會回應 HTTP 429。錯誤程式碼對於每分鐘請求數為 rate_limited,對於同時過多請求為 concurrency。在短暫過載時,你也會收到 429,並帶有 Retry-After: 5 標頭。
import time
from openai import OpenAI, RateLimitError
client = OpenAI(base_url="https://api.nsfwgemini.cc/v1", api_key="YOUR_KEY", max_retries=0)
def call_with_retry(messages, tries=4):
for attempt in range(tries):
try:
return client.chat.completions.create(model="uncensored", messages=messages)
except RateLimitError:
time.sleep(5 * (attempt + 1))
raise RuntimeError("still rate limited after retries")
SDK 預設會重試幾次;在此設定 max_retries=0 會使你的迴圈成為唯一的重試機制,這更便於理解邏輯。如果你使用執行緒分散工作,請將執行緒池上限設為 8 個工作者,或在試用金鑰上設為 2。
要讀取回應標頭,請使用原始回應包裝函式:
raw = client.chat.completions.with_raw_response.create(
model="uncensored",
messages=[{"role": "user", "content": "Say hello."}],
)
print(raw.headers.get("X-Request-Id"))
print(raw.headers.get("X-Balance-USD"))
print(raw.headers.get("X-RateLimit-Limit-Requests"))
completion = raw.parse()
X-Balance-USD 顯示剩餘的額度,對於應在耗盡前停止的腳本很有幫助。聯絡 支援 時請保留 X-Request-Id。
非同步程式碼與批次
對於處理許多項目的腳本,例如文字檔案資料夾或故事提示詞列表,非同步用戶端可保持程式碼簡短。重要部分是限制同時執行的呼叫數量。訊號量可以透過幾行程式碼達成:
import asyncio
from openai import AsyncOpenAI
client = AsyncOpenAI(base_url="https://api.nsfwgemini.cc/v1", api_key="YOUR_KEY")
gate = asyncio.Semaphore(6)
async def one(prompt):
async with gate:
r = await client.chat.completions.create(
model="uncensored",
messages=[{"role": "user", "content": prompt}],
max_tokens=200,
)
return r.choices[0].message.content
async def main():
prompts = [f"Write a one-line tagline for product number {i}." for i in range(30)]
results = await asyncio.gather(*(one(p) for p in prompts))
for text in results:
print(text)
asyncio.run(main())
訊號量設為 6,這低於完整金鑰的 8 個請求上限,並為第二個腳本預留空間。在試用金鑰上,將其設為 2。沒有這個閘道,asyncio.gather 會立即觸發所有 30 次呼叫,大多數會以程式碼為 concurrency 的 429 錯誤返回。這些失敗的呼叫不會收費,但會浪費時間並使日誌雜亂。
也要留意每分鐘上限。緊密的短請求迴圈可能在達到並行上限之前,就在完整金鑰上達到每分鐘 300 個請求(試用金鑰為 60 個)。如果你看到 rate_limited 錯誤,請在批次之間加入短暫睡眠,而不是更頻繁地重試。
浪費一下午的錯誤
- 使用 Google 的套件名稱。 安裝 Gemini 程式庫並將其指向此 URL 會失敗,因為請求格式不同。請安裝
openai。 - 缺少
/v1的 base URL。 SDK 會將/chat/completions附加到你提供的任何內容上。將 URL 保持為https://api.nsfwgemini.cc/v1。 - 傳遞舊的模型名稱。 從教學複製的程式碼通常帶有模型如
gpt-4o-mini或 Gemini 名稱。此 API 只有一個模型 ID,uncensored。 - 忘記歷史會被重新發送。 在第 3 輪時看似便宜的聊天,在第 80 輪成本會高得多,因為每次呼叫都包含所有先前的輪次。
- 未加防護地解析 JSON。 截斷或格式錯誤的回覆會引發異常。捕獲它並重試一次。
- 期望其他模態。 API 僅限文字。沒有影像生成、音訊、嵌入或微調,因此呼叫這些端點的程式碼在此無法運作。
最後一個習慣:在開發期間列印 resp.usage。提示詞和補全 token 計數會顯示每次呼叫的實際成本,這通常會讓原本預估的人感到驚訝。
Python 的成本
計費計算 token:每 1M 輸入 $0.15,每 1M 輸出 $0.50。一次請求輸入 2,000 token,輸出 500 token,成本為 2,000 x $0.15 / 1,000,000 = $0.0003 輸入加上 500 x $0.50 / 1,000,000 = $0.00025 輸出,總計 $0.00055。$0.50 的免費試用額度可涵蓋約 909 次此類呼叫。$20 的儲值可涵蓋約 36,000 次。
失敗與被拒請求不收費,額度不會過期。完整價目表與紅利階梯($50 起 +5%、$100 起 +10%、$200 起 +15%)見定價頁面,文件列出所有支援參數。限合法成人用途;涉及未成年人的性內容一律封鎖。
