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 短暂无法提供服务。两个服务对 轻量使用都是免费的,这也是它们适合课堂的原因;但免费也意味着没有正常运行 时间的保证。

为什么这是好的起步工具

延伸阅读