昨天我們用 Function Calling 做了一個「加法計算器」。
今天要更進一步 —— 讓 AI 幫我們「查天氣」,當一個小小氣象主播。
為了方便示範,我們先自己寫一個假的 get_weather 函數。
(真實情境下,你可以去串接 OpenWeatherMap 或中央氣象局 API)
import os, json
from openai import OpenAI
from dotenv import load_dotenv
load_dotenv()
client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
# 假的天氣 API
def get_weather(location: str) -> str:
    weather_data = {
        "台北": "今天台北晴時多雲,最高溫 32 度",
        "台中": "今天台中午後可能有雷陣雨,最高溫 31 度",
        "高雄": "今天高雄炎熱,最高溫 34 度,注意防曬"
    }
    return weather_data.get(location, f"目前沒有 {location} 的天氣資料")
    
我們要用 tools 把 get_weather 的規格告訴 AI:
tools = [
    {
        "type": "function",
        "function": {
            "name": "get_weather",
            "description": "查詢指定城市的天氣狀況",
            "parameters": {
                "type": "object",
                "properties": {
                    "location": {
                        "type": "string",
                        "description": "要查詢的城市,例如:台北、台中、高雄"
                    }
                },
                "required": ["location"]
            }
        }
    }
]
user_input = "請問台中今天的天氣如何?"
response = client.chat.completions.create(
    model="gpt-4o-mini",
    messages=[{"role": "user", "content": user_input}],
    tools=tools
)
tool_call = response.choices[0].message.tool_calls[0]
# 把參數取出來
args = json.loads(tool_call.function.arguments)
result = get_weather(args["location"])
print("查詢結果:", result)
followup = client.chat.completions.create(
    model="gpt-4o-mini",
    messages=[
        {"role": "user", "content": user_input},
        {"role": "assistant", "tool_calls": response.choices[0].message.tool_calls},
        {"role": "tool", "tool_call_id": tool_call.id, "content": result}
    ]
)
print("氣象主播:", followup.choices[0].message.content)
讓我們來看看成果:
這整段程式碼是在告訴我們
今天我們成功讓 AI查天氣。使用者輸入問題之後,AI決定呼叫我們定義出來的函式程式執行 回傳結果給 AI
再把答案講得更自然
明天我們要繼續練習 Function Calling 做一個 小計算機,讓 AI 幫我們做四則運算。幫助我們更加運用AI!