雖然不像 OpenAI API 那麼熱門,但 Gemini API 除了有不錯的回答表現,也提供給開發者更多的額度。
API 使用步驟
以下說明如何呼叫 Gemini API 產生結果:
- 安裝套件:
pip install -q -U google-genai
-
到 Google AI Studio 產生 Gemini 的 API Key。
-
第一次呼叫 Gemini API:
from google import genai
client = genai.Client(api_key="YOUR_API_KEY")
response = client.models.generate_content(
model="gemini-2.0-flash", #要使用的模型
contents="Explain how AI works in a few words" #問題內文
)
print(response.text) #回答結果
- (若有需要)「結構化輸出結果」功能,可讓模型精確輸出符合欄位格式的 JSON 資料。詳細內容可參考:透過 Gemini API 產生結構化輸出內容 - Google AI for Developers。以下是 Google 提供的範例,並加上註解:
from google import genai
from pydantic import BaseModel
class Recipe(BaseModel): # 輸出的格式
recipe_name: str
ingredients: list[str]
client = genai.Client(api_key="GEMINI_API_KEY")
response = client.models.generate_content(
model='gemini-2.0-flash',
contents='List a few popular cookie recipes. Be sure to include the amounts of ingredients.',
config={
'response_mime_type': 'application/json', #指定為 JSON 格式
'response_schema': list[Recipe], #指定格式 (類別)
},
)
# 將回應當成 JSON string
print(response.text)
# 當成物件使用
my_recipes: list[Recipe] = response.parsed
請參考:教學課程:開始使用 Gemini API - Google AI for Developers
頻率限制
RPD (每日要求配額): 在台灣時間每天下午 3PM 重置。
RPM (每分鐘要求次數): 在每分鐘的 00 秒重置。
TPM (每分鐘 Token 數量)。
更詳細的說明可參考 頻率限制 - Gemini API - Google AI for Developers、API Rate Limit Reset - Gemini API - Google AI Developers Forum。
超出任一項限制時,API 就會觸發速率限制的錯誤。可以在 Google Cloud 上檢查額度的使用情形:
目前 (2025 年 4 月) Gemini 的免費方案限制如下:
模型 | RPM | TPM | RPD |
---|---|---|---|
Gemini 2.0 Flash |
15 |
1,000,000 |
1,500 |
Gemini 2.5 Flash (預先發布) |
10 |
250,000 |
500 |
Gemini 2.5 Pro Experimental |
5 |
250,000 |
25 |
Gemini 2.0 Flash 模型可以用 Google 搜尋,免費方案限制為 500 RPD。其它模型與收費方案可以參考 Gemini Developer API 定價 - Gemini API - Google AI for Developers。
提示字工程
提示字設計 (Prompting Strategies) 是目前對話式 AI 能獲得準確答案的關鍵,如果遵照以下數個原則,較容易獲得想要的回答:
- 提供清楚明確的指示
- 加入少量範例 (使用正面的舉例,例如什麼是對的,避免用什麼是錯的)
- 說明問題的背景
- 指定回答的格式
可參考:提示設計簡介 - Gemini API - Google AI for Developers、提示設計策略 - Gemini API - Google AI for Developers、企業適用的有效 AI 提示撰寫祕訣 - Gemini for Workspace