今天我們將親自動手,體驗 Gemini API 的強大功能!透過實際的程式碼範例,你將了解如何與 Google 最先進的大語言模型進行互動。
Gemini 是 Google DeepMind 開發的多模態大語言模型,具備以下優勢:
讓我們建立第一個與 Gemini 對話的程式:
# gemini_hello.py
import google.generativeai as genai
from dotenv import load_dotenv
import os
# 載入環境變數
load_dotenv()
# 配置 API 金鑰
genai.configure(api_key=os.getenv('GEMINI_API_KEY'))
# 選擇模型
model = genai.GenerativeModel('gemini-2.5-flash')
def chat_with_gemini(message):
"""與 Gemini 進行基礎對話"""
try:
response = model.generate_content(message)
return response.text
except Exception as e:
return f"發生錯誤: {e}"
# 測試對話
if __name__ == "__main__":
print("🤖 Gemini AI 助理啟動!")
print("輸入 'quit' 離開程式\n")
while True:
user_input = input("你: ")
if user_input.lower() == 'quit':
print("再見!")
break
response = chat_with_gemini(user_input)
print(f"Gemini: {response}\n")
# 配置生成參數
generation_config = genai.types.GenerationConfig(
candidate_count=1,
max_output_tokens=1000,
temperature=0.7
)
model = genai.GenerativeModel(
'gemini-2.5-flash',
generation_config=generation_config
)
# 設定 AI 助理的角色
system_prompt = """
你是一個專業的程式設計導師,專門協助初學者學習 Python 和 AI 開發。
請用親切、耐心的語氣回答問題,並提供實用的程式碼範例。
"""
model = genai.GenerativeModel(
'gemini-2.5-flash',
system_instruction=system_prompt
)
讓我們建立一個能夠分析 Python 程式碼的小助手:
def analyze_code(code):
"""分析 Python 程式碼並提供建議"""
prompt = f"""
請分析以下 Python 程式碼:
```python
{code}
```
請提供:
1. 程式碼功能說明
2. 潛在的改進建議
3. 是否有語法錯誤或邏輯問題
"""
response = model.generate_content(prompt)
return response.text
# 測試程式碼分析
sample_code = """
def calculate_average(numbers):
total = 0
for num in numbers:
total += num
return total / len(numbers)
"""
print(analyze_code(sample_code))
試著執行今天的程式碼,並嘗試以下挑戰:
透過今天的實作,我們成功建立了與 Gemini API 的基礎連接。你已經學會如何:
明天我們將深入探討 Gemini CLI 工具,學習更多便利的操作方式。記住,最好的學習方式就是親自動手實作!