文件
連線設定

Google GenAI SDK

Markdown

原生 Gemini 格式:適用於 Python與JavaScript 的 Google GenAI SDK,以及直接的 REST 請求。

完整指南

安裝

pip install google-genai

連線設定

位址為https://api.ailoot.ai不含/v1beta:SDK 會自行組合路徑/v1beta/models/<模型>:generateContent。在 Python 中,位址透過此設定指定:HttpOptions(base_url=…),JavaScript 則使用httpOptions.baseUrl。SDK 會透過此標頭傳送金鑰:x-goog-api-key。

from google import genai
from google.genai import types
import os

client = genai.Client(
    api_key=os.environ["AILOOT_API_KEY"],
    http_options=types.HttpOptions(base_url="https://api.ailoot.ai"),  # 不加 /v1beta
)

resp = client.models.generate_content(
    model="gemini-3.8-flash",
    contents="為咖啡店想三個名字。",
)
print(resp.text)

可傳入的內容

  • 頂層欄位:contents,systemInstruction,generationConfig,safetySettings,tools與toolConfig。
  • generationConfig接受temperature,topP,topK,maxOutputTokens,thinkingConfig,responseMimeType (text/plain或application/json), responseSchema或responseJsonSchema (JSON 物件), stopSequences (字串陣列), candidateCount: 1,整數型seed,數值型presencePenalty與frequencyPenalty。允許的範圍與功能取決於具體模型;需要 JSON 回應時,請選擇一種支援的結構描述形式與application/json。文字模型的responseModalities —僅接受["TEXT"]。
  • safetySettings —由物件組成的陣列,每個物件包含category,threshold及選填的method; 請依確切模型的說明文件選擇值。
  • 對於支援相應輸入的 Gemini 模型, parts[].inlineData包含mimeType與非空的 base64 資料;PDF 必須是真正的 PDF 文件。fileData包含公開的https位址,存於fileUri欄位,並包含檔案的 MIME 類型。YouTube 可省略 MIME 類型。http,非公開位址、 gs://與Google Files API 物件均不受支援,也不支援透過 Google Files API 上傳。影片可加入videoMetadata:startOffset/endOffset以秒數表示的字串 (例如1.5s)與fps須大於 0 且不超過 24。請求本文大小、上下文、允許的輸入與回應上限,均依模型與格式驗證。
  • 用戶端宣告的functionDeclarations由您的應用程式執行。文字模型也接受{"googleSearch": {}}與{"urlContext": {}}:可分別使用,或一併放入以下陣列:tools。Google Search與URL context 均不得搭配functionDeclarations在同一個請求中使用。對於影像輸出,僅支援用戶端函式。其他內建工具與顯式快取均不受支援。Search/URL context 可能需要按完整輸入上限預留費用;實際的toolUsePromptTokenCount計入輸入 token 數。
  • 若模型不支援欄位、附件或工具組合,請求會在預留金額前被拒絕,不會扣款。會收到 HTTP 400包含status INVALID_ARGUMENT與錯誤類別invalid_request (在ErrorInfo.reason — INVALID_REQUEST). 無效 JSON、路徑參數錯誤與其他驗證失敗也會回傳400; 請閱讀錯誤文字與Request ID。功能依模型而異,請在目錄確認支援的格式與輸入類型。
輸入支援的 MIME 類型
內嵌影像image/png, image/jpeg, image/webp
文件application/pdf; text/plain, text/html, text/css, text/csv, text/xml, text/rtf, text/markdown, text/javascript, application/x-javascript, text/x-python, application/x-python
音訊audio/wav, audio/mp3, audio/mpeg, audio/aiff, audio/aac, audio/ogg, audio/flac
影片video/mp4, video/mpeg, video/mov, video/quicktime, video/avi, video/x-flv, video/mpg, video/webm, video/wmv, video/3gpp
import json, os, urllib.request

def generate(model, payload):
    req = urllib.request.Request(
        "https://api.ailoot.ai/v1beta/models/" + model + ":generateContent",
        data=json.dumps(payload).encode(),
        headers={"x-goog-api-key": os.environ["AILOOT_API_KEY"],
                 "Content-Type": "application/json"},
    )
    # 只傳送一次。若逾時,請先在用量紀錄中查詢 Request ID,再決定是否重試。
    with urllib.request.urlopen(req, timeout=300) as response:
        print("Request ID:", response.headers.get("X-Request-ID"))
        return json.load(response)

import base64, pathlib, sys

# 提供實際的本機 PDF、音訊或影片檔案,以及其支援的 MIME 類型。
path, mime = pathlib.Path(sys.argv[1]), sys.argv[2]
payload = {"contents": [{"role": "user", "parts": [
    {"text": "簡短說明檔案的內容。"},
    {"inlineData": {"mimeType": mime,
                    "data": base64.b64encode(path.read_bytes()).decode()}},
]}]}
print(generate("gemini-3.8-flash", payload))
# 另一種附件方式:{"fileData": {"mimeType": mime, "fileUri": public_https_url}}
# 使用實際的 YouTube URL:{"fileData": {"fileUri": youtube_url}}

函式的完整流程

傳入函式宣告,取得 functionCall,執行自己的函式,傳回 functionResponse,再請求下一個回應。請保存模型的完整 content,包括 thoughtSignature,不要自行建立簽章。

import json, os, urllib.request

def generate(model, payload):
    req = urllib.request.Request(
        "https://api.ailoot.ai/v1beta/models/" + model + ":generateContent",
        data=json.dumps(payload).encode(),
        headers={"x-goog-api-key": os.environ["AILOOT_API_KEY"],
                 "Content-Type": "application/json"},
    )
    # 只傳送一次。若逾時,請先在用量紀錄中查詢 Request ID,再決定是否重試。
    with urllib.request.urlopen(req, timeout=300) as response:
        print("Request ID:", response.headers.get("X-Request-ID"))
        return json.load(response)

tools = [{"functionDeclarations": [{
    "name": "multiply", "description": "將兩個數相乘",
    "parameters": {"type": "object", "properties": {
        "a": {"type": "number"}, "b": {"type": "number"}},
        "required": ["a", "b"]},
}]}]
contents = [{"role": "user", "parts": [{"text": "使用函式將 7 乘以 8"}]}]
for turn in range(4):  # 限制工具迴圈的次數;結果不明的請求不可重新傳送。
    reply = generate("gemini-3.8-flash", {"contents": contents, "tools": tools})
    content = reply["candidates"][0]["content"]
    contents.append(content)  # 保留全部(ALL)原始 parts 和 thoughtSignature,內容不得變更。
    results = []
    for part in content.get("parts", []):
        call = part.get("functionCall")
        if not call:
            continue
        if call["name"] != "multiply":
            raise ValueError("Unexpected function")
        args = call["args"]
        result = {"name": call["name"], "response": {"value": args["a"] * args["b"]}}
        if "id" in call:
            result["id"] = call["id"]
        results.append({"functionResponse": result})
    if not results:
        print(content)
        break
    contents.append({"role": "user", "parts": results})
else:
    raise RuntimeError("Tool loop limit reached")

串流回應

for chunk in client.models.generate_content_stream(
    model="gemini-3.8-flash",
    contents="描述海上夕陽",
):
    print(chunk.text, end="", flush=True)

可用模型

Gemini 格式共有 27 個可用識別碼:gemini-3.8-flash,gemini-3.1-pro,gemini-pro-agent,gemini-3.8-flash-tiered,gemini-3.8-flash-medium,gemini-3.8-flash-low,gemini-3.8-flash-high,gemini-3.7-flash,gemini-3.7-flash-tiered,gemini-3.7-flash-medium,gemini-3.7-flash-low,gemini-3.7-flash-high,gemini-3.6-flash,gemini-3.6-flash-tiered,gemini-3.6-flash-medium,gemini-3.6-flash-low,gemini-3.6-flash-high,gemini-3.5-flash-lite,gemini-3.1-pro-preview,gemini-3.1-pro-low,gemini-3.1-pro-high,gemini-3.1-flash-lite,gemini-3-flash,gemini-2.5-pro,gemini-2.5-flash,gemini-2.5-flash-thinking,gemini-2.5-flash-lite。

Gemini 模型也可透過 Anthropic Messages 格式使用,對只支援該格式的用戶端而言很方便:Anthropic SDK。

還有疑問嗎?請提供 Request ID與問題描述,我們會協助釐清。聯絡支援