在前幾天,我們完成了 OpenAI 與 Gemini API Key 的註冊與設定。
今天,我們要讓 Agent 不再靠繁瑣的 if/else 判斷,而是用 LLM 來理解指令與決策。
這樣做的好處是:
if/elif/else
換句話說,LLM 讓 Agent 的「智慧感」大幅提升 🚀
替代 if/else 的決策
Gemini API 作為智慧核心
chat/completions
API 呼叫 Gemini 模型互動循環 (Loop)
# LLM Agent with Gemini
import google.generativeai as genai
# 設定 Gemini API 金鑰(請使用完整的有效金鑰)
genai.configure(api_key="YOUR_GEMINI_API_KEY")
# 初始化模型
model = genai.GenerativeModel("gemini-1.5-flash")
# 開始對話
chat = model.start_chat(history=[])
def llm_decision_agent(user_input):
try:
response = chat.send_message(user_input)
return response.text
except Exception as e:
return f"錯誤:{e}\n請檢查你的 Gemini API 金鑰是否正確。"
def agent_loop():
print("嗨!我是你的 LLM Agent(Gemini 驅動)。")
print("輸入 '離開' 結束對話。")
while True:
user_input = input("\n請輸入指令: ")
if user_input.lower() == "離開":
print("掰掰~祝你今天順利!")
break
result = llm_decision_agent(user_input)
print(result)
# 執行 Agent
agent_loop()
💡 小提醒