本週實作會使用 Google Gemini API。Gemini 3.5 Flash 有免費額度,足夠課堂使用。請在上課前完成以下步驟。
申請 API Key
1
到 Google AI Studio 申請 API Key
打開 Google AI Studio(aistudio.google.com),用你的 Google 帳號登入。
- 點選左側選單的 「Get API key」
- 點 「Create API key」
- 選擇一個 Google Cloud Project(如果沒有,它會自動建立一個)
- 複製產生的 API Key,妥善保存
注意事項
- API Key 就像密碼,不要分享給別人
- 不要放在公開的 GitHub repo 裡
- 如果不小心洩漏了,立刻到 Google AI Studio 刪除並重新產生
安裝 Python SDK
2
安裝所需套件
在課程的 conda 環境中安裝 Google Generative AI SDK 和 Streamlit。
# 確保已啟動 conda 環境
$conda activate bioagent
# 安裝 Google Generative AI SDK
$pip install google-genai
# 也安裝 Streamlit(實作會用到)
$pip install streamlit
測試 API Key
3
執行測試腳本
建立一個 test_gemini.py 檔案,貼上以下程式碼:
# test_gemini.py
from google import genai
client = genai.Client(api_key="你的API_KEY")
response = client.models.generate_content(
model="gemini-3.5-flash",
contents="用一句話解釋什麼是心電圖"
)
print(response.text)
然後在終端機執行:
$python test_gemini.py
成功畫面:如果看到一句關於心電圖的解釋,代表 API Key 設定成功!
設定環境變數(建議)
建議將 API Key 設定為環境變數,而不是直接寫在程式碼裡。這樣更安全,也方便管理。
在你的 shell 設定檔中加入環境變數:
# 在 ~/.zshrc 或 ~/.bashrc 加入
export GEMINI_API_KEY="你的API Key"
# 重新載入
$source ~/.zshrc
然後在 Python 程式碼中這樣使用:
import os
from google import genai
client = genai.Client(api_key=os.environ["GEMINI_API_KEY"])
免費額度說明
- Gemini 3.5 Flash 免費方案:每分鐘 15 次請求,每天 1500 次
- 對課堂實作來說綽綽有餘
- 如果超過免費額度,需要設定 Google Cloud 帳單(但通常不會用到)
- 本課程所有實作都在免費額度範圍內