English 繁體中文 简体中文

如何為 AI 代理建立天氣工具?

林邦源博士 · AI 筆記 · 2026 年 11 月 8 日 · 約 4 分鐘閱讀

AI 代理無法走到戶外,也不知道你身在何處。天氣工具用一次呼叫同時解答這兩個 問題。互聯網上每部裝置都有一個號碼,稱為 網際網路協定(IP)位址,而這個 號碼登記在某個地區,所以一個查詢服務可以把它轉成大約的位置 — 只到城市, 不會到街道。工具接著向免費天氣服務查詢該城市目前的氣溫。兩個服務都毋須 註冊或金鑰。

工具

這是 tool02_weather.py 目前的內容:

# https://open-meteo.com/
import requests
def get_weather_from_ip():
    """
    Get the current temperature in Celsius for the user's location
    using the IP address and return it as a string.
    """
    location = requests.get("https://ipinfo.io/json", timeout=10).json()
    latitude, longitude = location["loc"].split(",")

    params = {
        "latitude": latitude,
        "longitude": longitude,
        "current": "temperature_2m",
        "temperature_unit": "celsius",
        "timezone": "auto",
    }

    weather_data = requests.get(
        "https://api.open-meteo.com/v1/forecast",
        params=params,
        timeout=10,
    ).json()

    return f"Current: {weather_data['current']['temperature_2m']}°C"

result = get_weather_from_ip()
print(result)

每一部分的作用

在自己的電腦上執行

下載 zip 檔案並 解壓到一個資料夾。zip 內有 tool02_weather.py、 pyproject.toml 和 README.md。在 Visual Studio Code 開啟這個資料夾,然後在終端機執行以下兩條指令:

uv sync
uv run tool02_weather.py

uv sync 只需要第一次執行。它會建立一個本地環境,只裝這個專案 需要的一個套件,不會裝到電腦其他地方。

你應該會看到一行,例如 Current: 24.6°C。跟你手機上的天氣應用 比較一下。

如果這一行始終沒有出現,原因幾乎總是以下三種之一:沒有連接互聯網、IP 位址 被 ipinfo.io 限制了請求頻率,或者 Open-Meteo 短暫未能提供服務。兩個服務對 輕量使用都是免費的,這也是它們適合課堂的原因;但免費也意味著沒有正常運行 時間的保證。

為甚麼這是好的起步工具

延伸閱讀