Source: https://ailoot.ai/docs/zh-hant-tw/connect/google-genai/
Canonical: https://ailoot.ai/docs/zh-hant-tw/connect/google-genai/
Language: zh-hant-tw

[連線設定](https://ailoot.ai/docs/zh-hant-tw/) 

# Google GenAI SDK

[Markdown](https://ailoot.ai/docs/zh-hant-tw/connect/google-genai/index.md)

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

## [](https://ailoot.ai/docs/zh-hant-tw/connect/google-genai/#install)安裝

```bash
pip install google-genai
```

```bash
npm install @google/genai
```

## [](https://ailoot.ai/docs/zh-hant-tw/connect/google-genai/#client)連線設定

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

```python
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)
```

```js
import { GoogleGenAI } from "@google/genai";

const ai = new GoogleGenAI({
  apiKey: process.env.AILOOT_API_KEY,
  httpOptions: { baseUrl: "https://api.ailoot.ai" }, // 不加 /v1beta
});

const resp = await ai.models.generateContent({
  model: "gemini-3.8-flash",
  contents: "為咖啡店想三個名字。",
});
console.log(resp.text);
```

```bash
curl "https://api.ailoot.ai/v1beta/models/gemini-3.8-flash:generateContent" \
  -H "x-goog-api-key: $AILOOT_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "contents": [
      {"role": "user", "parts": [{"text": "為咖啡店想三個名字。"}]}
    ]
  }' 
```

## [](https://ailoot.ai/docs/zh-hant-tw/connect/google-genai/#body)可傳入的內容

- 頂層欄位：`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 |

```python
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}}
```

## [](https://ailoot.ai/docs/zh-hant-tw/connect/google-genai/#function-loop)函式的完整流程

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

```python
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")
```

## [](https://ailoot.ai/docs/zh-hant-tw/connect/google-genai/#stream)串流回應

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

```bash
curl -N "https://api.ailoot.ai/v1beta/models/gemini-3.8-flash:streamGenerateContent?alt=sse" \
  -H "x-goog-api-key: $AILOOT_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"contents": [{"role": "user", "parts": [{"text": "描述海上夕陽"}]}]}' 
```

Ailoot 會在費用計算完成後傳回 Gemini 的付費回應；串流文字會在模型完成後一次完整傳回，而非逐字傳回。Gemini 串流沒有服務訊息，因此較長的回應需要預留足夠的用戶端逾時時間。

## [](https://ailoot.ai/docs/zh-hant-tw/connect/google-genai/#models)可用模型

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](https://ailoot.ai/docs/zh-hant-tw/connect/anthropic-sdk/)。

還有疑問嗎？請提供 Request ID與問題描述，我們會協助釐清。[聯絡支援](mailto:support@ailoot.ai)

## Ailoot · 公司及其專案組合





Ailoot以累積的營運經驗、廣大的客戶群、穩定的服務及持續的KPI管理為基礎。





公司及其專案組合：數百萬客戶，每月銷售額達數十億。





Ailoot將這些營運經驗用於API存取，讓客戶的產品、代理、應用程式及自動化流程使用AI功能。
