iT邦幫忙

2025 iThome 鐵人賽

DAY 9
0

昨天我們用 Function Calling 做了一個「加法計算器」。
今天要更進一步 —— 讓 AI 幫我們「查天氣」,當一個小小氣象主播。

Step 1:準備一個假的天氣 API

為了方便示範,我們先自己寫一個假的 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} 的天氣資料")
    

Step 2:告訴 AI 有這個工具

我們要用 tools 把 get_weather 的規格告訴 AI:

tools = [
    {
        "type": "function",
        "function": {
            "name": "get_weather",
            "description": "查詢指定城市的天氣狀況",
            "parameters": {
                "type": "object",
                "properties": {
                    "location": {
                        "type": "string",
                        "description": "要查詢的城市,例如:台北、台中、高雄"
                    }
                },
                "required": ["location"]
            }
        }
    }
]

Step 3:呼叫 API

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)

Step 4:模擬完整對話

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)

讓我們來看看成果:
https://ithelp.ithome.com.tw/upload/images/20250923/20169376EIFu15Rt4E.png
這整段程式碼是在告訴我們

  • tools:告訴 AI 有一個叫 get_weather 的功能可以用
  • AI:判斷使用者的問題需要查天氣,回傳 location="台中"
  • 程式部分:執行 get_weather("台中"),拿到真實天氣
  • 回傳結果給 AI:讓 AI 幫我們用自然語言整理成答案

今天我們成功讓 AI查天氣。使用者輸入問題之後,AI決定呼叫我們定義出來的函式程式執行 回傳結果給 AI
再把答案講得更自然
明天我們要繼續練習 Function Calling 做一個 小計算機,讓 AI 幫我們做四則運算。幫助我們更加運用AI!


上一篇
Day 8:哎呀還能叫外掛?Function Calling 初體驗
下一篇
Day 10:數學不會算?用 Function Calling 做小計算機
系列文
AI 三十天,哎呀每天都很難:OpenAI API 生存指南10
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言