Gemini generateContent
MarkdownGoogle Gemini 的原生格式,適用於 Gemini CLI、Google GenAI SDK與REST 用戶端。
完整指南
https://api.ailoot.ai/v1beta/models/{model}:generateContentcurl "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": "為咖啡店想三個名字。"}]}
]
}' 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)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);{
"candidates": [
{
"content": {
"role": "model",
"parts": [{ "text": "1.「咖啡豆與蒸氣」2.「晨間研磨」3.「轉角咖啡館」" }]
},
"finishReason": "STOP"
}
],
"usageMetadata": {
"promptTokenCount": 9,
"candidatesTokenCount": 27,
"totalTokenCount": 36
},
"modelVersion": "gemini-3.8-flash"
}身分驗證
- x-goog-api-keyheader必填
金鑰
sk-…。也可使用Authorization: Bearer或x-api-key。為相容 Google,也接受?key=作為位址參數—優先順序最低;?api_key=會以 400 拒絕。建議使用標頭,以避免金鑰出現在紀錄中。
路徑
- modelstring必填
支援 Gemini 格式的模型 ID,例如
gemini-3.8-flash或gemini-3.1-pro。共 27 個。
https://api.ailoot.ai/v1beta/models/{model}:streamGenerateContent?alt=ssehttps://api.ailoot.ai/v1beta/models請求本文
- contentsarray必填
訊息包含
role(user/model)與parts:text, inlineData/fileData, functionCall/functionResponse。附件限模型可接受的輸入類型。 - systemInstructionobject選填
文字形式的系統指令:
{"parts": [{"text": "…"}]}。 - generationConfigobject選填
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"]。 - safetySettingsarray選填
物件必須包含
category與threshold,並可選填method。值必須為具體模型支援的值。 - toolsarray選填
用戶端宣告的
functionDeclarations由您的應用程式執行。文字模型也接受{"googleSearch": {}}與{"urlContext": {}}:可分別使用,或一併放入以下陣列:tools。Google Search與URL context 均不得搭配functionDeclarations在同一個請求中使用。對於影像輸出,僅支援用戶端函式。其他內建工具與顯式快取均不受支援。Search/URL context 可能需要按完整輸入上限預留費用;實際的toolUsePromptTokenCount計入輸入 token 數。 - toolConfigobject選填
functionCallingConfig:mode (AUTO/ANY/NONE/VALIDATED/MODE_UNSPECIFIED), allowedFunctionNames.
若模型不支援欄位、附件或工具組合,請求會在預留金額前被拒絕,不會扣款。會收到 HTTP 400包含status INVALID_ARGUMENT與錯誤類別invalid_request (在ErrorInfo.reason — INVALID_REQUEST). 無效 JSON、路徑參數錯誤與其他驗證失敗也會回傳400; 請閱讀錯誤文字與Request ID。功能依模型而異,請在目錄確認支援的格式與輸入類型。
PDF、音訊、影片與連結
對於支援相應輸入的 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。請求本文大小、上下文、允許的輸入與回應上限,均依模型與格式驗證。
| 輸入 | 支援的 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}}Search與URL context
用戶端宣告的functionDeclarations由您的應用程式執行。文字模型也接受{"googleSearch": {}}與{"urlContext": {}}:可分別使用,或一併放入以下陣列:tools。Google Search與URL context 均不得搭配functionDeclarations在同一個請求中使用。對於影像輸出,僅支援用戶端函式。其他內建工具與顯式快取均不受支援。Search/URL context 可能需要按完整輸入上限預留費用;實際的toolUsePromptTokenCount計入輸入 token 數。
{"tools": [{"googleSearch": {}}, {"urlContext": {}}]}影像輸出
Gemini 格式的回應中,只有下列模型能輸出影像:gemini-3.1-flash-image。這項功能獨立於/v1/images/generations:其他影像模型在此無法運作。此模型最多支援 131072 個輸入 token、32768 個回應 token;最長回應的完整費用將預先保留。
responseModalities —非空且不得重複的 TEXT/IMAGE 集合。imageConfig.imageSize:1K/2K/4K; aspectRatio:1:1, 2:3, 3:2, 3:4, 4:3, 4:5, 5:4, 9:16, 16:9, 21:9, 1:4, 4:1, 1:8, 8:1. 此模型僅接受文字與內嵌 PNG/JPEG/WebP;不接受 PDF、音訊、影片、fileData 及內建的 Search/URL context。您的金鑰適用的可用性與價格,可查閱目錄與GET /v1/models。
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
reply = generate("gemini-3.1-flash-image", {
"contents": [{"role": "user", "parts": [{"text": "水彩畫:黎明時分的燈塔"}]}],
"generationConfig": {
"responseModalities": ["TEXT", "IMAGE"],
"imageConfig": {"aspectRatio": "1:1", "imageSize": "1K"},
},
})
index = 0
for candidate in reply.get("candidates", []):
for part in candidate.get("content", {}).get("parts", []):
if "text" in part:
print(part["text"])
blob = part.get("inlineData", {})
if blob.get("mimeType", "").startswith("image/") and blob.get("data"):
index += 1
extension = {"image/png": "png", "image/jpeg": "jpg",
"image/webp": "webp"}.get(blob["mimeType"], "bin")
pathlib.Path(f"gemini-image-v{index}.{extension}").write_bytes(
base64.b64decode(blob["data"]))
print("All returned images:", index)完整的函式呼叫流程
函式由用戶端執行。請原樣回傳模型的完整原始 content,包含 thoughtSignature,不要修改;接著回傳 functionResponse,沿用相同的 name,以及 functionCall 中若有提供的 id。
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")回應
- candidates[]。content.partsarray
模型回應。
- usageMetadataobject
promptTokenCount,candidatesTokenCount,totalTokenCount。