import json
from openai import OpenAI
client = OpenAI()
# 1. 定義 Agent 可用的工具庫 (Tools)
def get_weather(location: str):
"""模擬查詢天氣的 API"""
if "台北" in location:
return json.dumps({"location": "台北", "temperature": "25°C", "condition": "晴天"})
return json.dumps({"location": location, "temperature": "20°C", "condition": "陰天"})
def calculate(expression: str):
"""模擬數學計算器"""
try:
result = eval(expression)
return json.dumps({"result": result})
except Exception as e:
return json.dumps({"error": str(e)})
# 將函數對映至名稱
available_functions = {
"get_weather": get_weather,
"calculate": calculate
}
# 2. 定義提供給 LLM 的工具聲明 (Tool Definitions)
tools = [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "取得特定城市的目前天氣狀況",
"parameters": {
"type": "object",
"properties": {
"location": {"type": "string", "description": "城市名稱,例如:台北"}
},
"required": ["location"],
},
},
},
{
"type": "function",
"function": {
"name": "calculate",
"description": "執行基礎數學算式計算",
"parameters": {
"type": "object",
"properties": {
"expression": {"type": "string", "description": "數學算式,例如:'25 * 1.2'"}
},
"required": ["expression"],
},
},
}
]
# 3. Agent 核心執行循環 (The Agent Loop)
def run_agent(prompt: str):
messages = [
{"role": "system", "content": "你是一個自主 Agent。你可以思考並選擇呼叫工具來完成使用者的任務。"},
{"role": "user", "content": prompt}
]
print(f"🎯 任務目標: {prompt}\n" + "="*40)
# Agent Loop 開始
while True:
# LLM 思考 (Reasoning)
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=messages,
tools=tools,
tool_choice="auto"
)
response_message = response.choices[0].message
messages.append(response_message) # 將 LLM 的回應記錄回 Message 歷史
# 判斷是否需要呼叫工具 (Action)
tool_calls = response_message.tool_calls
if not tool_calls:
# 如果 LLM 沒有要求呼叫任何工具,代表任務完成,輸出最終回答
print(f"🤖 Agent 最終回答:\n{response_message.content}")
break
# 執行工具 (Acting) 並取得觀察結果 (Observation)
for tool_call in tool_calls:
function_name = tool_call.function.name
function_args = json.loads(tool_call.function.arguments)
print(f"🛠️ [Action] 呼叫工具: {function_name}({function_args})")
# 找到對應函數並執行
function_to_call = available_functions[function_name]
function_response = function_to_call(**function_args)
print(f"👀 [Observation] 工具傳回結果: {function_response}")
# 將工具執行的結果 append 回訊息列表,讓 LLM 在下一輪循環看到
messages.append({
"tool_call_id": tool_call.id,
"role": "tool",
"name": function_name,
"content": function_response,
})
print("-" * 40)
# 執行範例:一個需要跨工具多步驟推理的任務
run_agent("請幫我查台北的氣溫,然後算出如果氣溫上升 15% 會是多少度?")