繁中 ▾
取得 API 金鑰

將 Gemini API 範例程式碼移植至 OpenAI 風格 API

此 Gemini API 範例逐行轉換為 OpenAI 風格 API:涵蓋提示詞、聊天歷史、串流輸出、JSON 與函式呼叫,並提供可直接貼上的 Python 與 Node 程式碼。

更新於

兩座玻璃橋承載程式碼區塊,中間有適配器板,象徵 API 之間的程式碼移植
一把黃銅鑰匙連接多個插座,說明單一 API 金鑰可接入多個工具

重點摘要

  1. 角色從 model 變更為 assistant,區塊變更為內容。
  2. 金鑰與端點移至客戶端建構子;模型 ID 為 uncensored。
  3. JSON 模式與工具對應至 response_format 與 tools。
  4. 圖片、音訊與嵌入向量無法移植;此 API 僅支援文字。

對照表

典型的 Gemini API 範例在 Python 中使用模型物件、generate_content 呼叫與 .text 屬性。將其移植至 OpenAI 風格 API API 意味著將其替換為客戶端、chat.completions.create 呼叫與 choices[0].message.content。概念保持一致;僅名稱改變。

概念Gemini SDK 風格OpenAI 風格(此 API)
驗證與端點SDK 中配置的 API 金鑰base_url 加上 Bearer 金鑰
模型Gemini 模型名稱uncensored
系統提示詞system_instructionrole 為 system 的訊息
歷史中的 assistant 角色模型assistant
訊息文字partscontent
最大長度max_output_tokensmax_tokens(選填)
JSON 輸出response_mime_typeresponse_format json_object
串流輸出generate_content 串流輸出create 上的 stream=True

Google 程式庫的不同版本方法名稱有所不同,因此請查閱其最新文件以獲取您要移植的確切呼叫。OpenAI 端則保持穩定,適用於任何 OpenAI 客戶端。本網站與 Google 無隸屬關係:我們提供 ID 為 uncensored 的獨立開放權重模型,因此輸出風格會與 Gemini 不同。

範例 1:單一提示詞

之前,在典型的 Gemini 呼叫中:

import google.generativeai as genai

genai.configure(api_key="GEMINI_KEY")
model = genai.GenerativeModel("gemini-model-name")
resp = model.generate_content(
    "Write a two-sentence product blurb for a hiking backpack.",
    generation_config={"temperature": 0.7, "max_output_tokens": 200},
)
print(resp.text)

之後,在此 API 上:

from openai import OpenAI

client = OpenAI(base_url="https://api.geminiuncensored.top/v1", api_key="YOUR_KEY")
resp = client.chat.completions.create(
    model="uncensored",
    messages=[{"role": "user", "content": "Write a two-sentence product blurb for a hiking backpack."}],
    temperature=0.7,
    max_tokens=200,
)
print(resp.choices[0].message.content)

注意變動的項目。金鑰與端點現在位於客戶端建構子中。生成設定變為頂層參數,而非設定字典。提示詞變為訊息列表,而非字串。金鑰整合指南顯示如何安全地儲存金鑰。

範例 2:系統提示詞與聊天歷史

Gemini 歷史紀錄使用角色 model 表示先前的回答,並將文字包裝在 parts 中。OpenAI 格式的角色為 assistant,文字位於 content 中。小型輔助程式會轉換歷史紀錄:

def to_openai(history):
    # history: list of dicts with role user or model, and parts as a list of text
    out = []
    for turn in history:
        role = "assistant" if turn["role"] == "model" else turn["role"]
        out.append({"role": role, "content": "".join(turn["parts"])})
    return out

history = [
    {"role": "user", "parts": ["My name is Dana."]},
    {"role": "model", "parts": ["Nice to meet you, Dana."]},
]

messages = [{"role": "system", "content": "You are a friendly assistant."}]
messages += to_openai(history)
messages.append({"role": "user", "content": "What is my name?"})

resp = client.chat.completions.create(model="uncensored", messages=messages)
print(resp.choices[0].message.content)

系統提示詞從建構子參數移至第一則訊息。兩者在實務上皆為無狀態:您在每次呼叫時重新傳送歷史,因此輸入 token 會隨對話增長。上下文視窗為 100,000 token,提示詞與完成內容合計。

範例 3:串流輸出

在 Gemini 中,您會遍歷區塊並讀取 chunk.text。在此,您從每個區塊讀取差異值:

stream = client.chat.completions.create(
    model="uncensored",
    messages=[{"role": "user", "content": "Tell a very short story about a lighthouse."}],
    stream=True,
)
for chunk in stream:
    if chunk.choices and chunk.choices[0].delta.content:
        print(chunk.choices[0].delta.content, end="", flush=True)

串流輸出使用伺服器發送事件。串流請求會佔用其並行請求槽位,直到串流結束:完整金鑰允許 8 個並行請求,試用金鑰允許 2 個。如果您提前跳出迴圈,請關閉串流。

Node.js

import OpenAI from "openai";

const client = new OpenAI({
  baseURL: "https://api.geminiuncensored.top/v1",
  apiKey: process.env.API_KEY,
});

const stream = await client.chat.completions.create({
  model: "uncensored",
  messages: [{ role: "user", content: "Name three birds." }],
  stream: true,
});
for await (const chunk of stream) {
  process.stdout.write(chunk.choices[0]?.delta?.content ?? "");
}

範例 4:JSON 輸出與函式呼叫

對於 JSON,Gemini 使用回應 MIME 類型。在此您使用 response_format。在提示詞中描述欄位,因為 JSON 模式保證語法有效,而非您的結構描述。

import json

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

函式呼叫對應到 tools。您不是傳遞函式宣告,而是傳遞包含 type: "function" 的物件列表,並在需要時設定 tool_choice,然後以帶有 role: "tool" 和對應 tool_call_id 的訊息回傳結果。串流工具呼叫會以片段形式出現在 delta.tool_calls 中。

tools = [{
    "type": "function",
    "function": {
        "name": "get_time",
        "description": "Get the current time in a city",
        "parameters": {
            "type": "object",
            "properties": {"city": {"type": "string"}},
            "required": ["city"],
        },
    },
}]
resp = client.chat.completions.create(
    model="uncensored",
    messages=[{"role": "user", "content": "What time is it in Tokyo?"}],
    tools=tools,
)
print(resp.choices[0].message.tool_calls)

無法遷移的部分

某些 Gemini 功能在此處沒有對應項目。此 API 僅支援文字:沒有圖片或音訊輸入、沒有圖片、音訊或影片生成、沒有嵌入向量也沒有微調。如果您的程式碼向 Gemini 傳送圖片或檔案,請保留這些呼叫,僅移植文字路徑。Grounding 或內建搜尋工具是 Gemini 端的功能,您將以自訂工具函式取代它們。

安全設定也不會隨之轉移。此模型經過調整,可在合法成人用途下無內容拒絕地回答,因此無需設定每類別的閾值。唯一的硬性限制是:絕對禁止涉及未成年人的性內容。閱讀 如何使用 Gemini API 替代方案 以決定要遷移哪些流量。

錯誤、限制與餘額標頭

OpenAI 客戶端會引發類型化例外。您最先遇到的兩個例外是因金鑰錯誤導致的驗證失敗,以及 HTTP 429。429 錯誤代碼告訴您原因:rate_limited 表示每分鐘請求數(完整金鑰為 300,試用金鑰為 60)以及 concurrency 表示同時請求過多。在暫時過載時,API 也會回傳帶有 Retry-After: 5 的 429。

import time
from openai import RateLimitError

def call(messages):
    for attempt in range(4):
        try:
            return client.chat.completions.create(model="uncensored", messages=messages)
        except RateLimitError as e:
            time.sleep(float(e.response.headers.get("Retry-After", 2)))
    raise RuntimeError("still rate limited")

每個回應都包含 X-Request-Id、X-Balance-USD 和速率限制標頭。讀取餘額標頭以知道何時儲值。文件 列出所有端點:POST /v1/chat/completions、POST /v1/responses 和 GET /v1/models。

成本與付款

定價為每 100 萬個輸入 token $0.15,每 100 萬個輸出 token $0.50,從預付額度扣除。前述背包範例,約 20 個輸入與 60 個輸出 token,費用為 20 x $0.15 / 1M 加上 60 x $0.50 / 1M,即 $0.000003 加上 $0.00003,總計 $0.000033。使用加密貨幣(TRC20 上的 USDT 或 Base 上的 USDC)儲值,金額可從 $20 到 $500 的整數;贈額為 $50 起 +5%、$100 起 +10%、$200 起 +15%。要測試遷移,請在 API 金鑰頁面上一鍵領取 $0.50 的免費試用額度。詳細資訊請見 定價頁面。

問答

我可以繼續在這個 API 中使用 Google 的程式庫嗎?

不行。該端點使用 OpenAI 協定,因此請搭配 Base URL 與 API 金鑰使用 OpenAI 客戶端。

輸出結果與 Gemini 相同嗎?

不相同。這是不同的開放權重模型,因此用詞與風格會有差異。請重新測試提示詞並調整系統提示詞。

串流輸出的運作方式相同嗎?

串流輸出使用伺服器發送事件(SSE),並將 stream 設為 true。請從每個區塊讀取 delta 內容。

我可以傳送圖片嗎?

不行。該 API 僅支援文字,因此請將圖片請求保留在支援該功能的服務上。

只差一張表單,即可取得金鑰

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