跳到主要内容
本 notebook 介绍了如何使用 OpenWeatherMap 组件来获取天气信息。 首先,你需要注册一个 OpenWeatherMap API 密钥:
  1. 前往 OpenWeatherMap 并此处注册一个 API 密钥
  2. pip install pyowm
然后我们需要设置一些环境变量
  1. 将你的 API KEY 保存到 OPENWEATHERMAP_API_KEY 环境变量中

使用包装器

pip install -qU pyowm
Note: you may need to restart the kernel to use updated packages.
import os

from langchain_community.utilities import OpenWeatherMapAPIWrapper

os.environ["OPENWEATHERMAP_API_KEY"] = ""

weather = OpenWeatherMapAPIWrapper()
weather_data = weather.run("London,GB")
print(weather_data)
In London,GB, the current weather is as follows:
Detailed status: overcast clouds
Wind speed: 4.12 m/s, direction: 10°
Humidity: 51%
Temperature:
  - Current: 12.82°C
  - High: 13.98°C
  - Low: 12.01°C
  - Feels like: 11.49°C
Rain: {}
Heat index: None
Cloud cover: 100%

使用工具

import os

from langchain.agents import create_agent


os.environ["OPENAI_API_KEY"] = ""
os.environ["OPENWEATHERMAP_API_KEY"] = ""

tools = [weather.run]
agent = create_agent("gpt-4.1-mini", tools)
input_message = {
    "role": "user",
    "content": "What's the weather like in London?",
}

for step in agent.stream(
    {"messages": [input_message]},
    stream_mode="values",
):
    step["messages"][-1].pretty_print()
================================ Human Message =================================

What's the weather like in London?
================================== Ai Message ==================================
Tool Calls:
  run (call_6vPq9neyy7oOnht29ExidE2g)
 Call ID: call_6vPq9neyy7oOnht29ExidE2g
  Args:
    location: London
================================= Tool Message =================================
Name: run

In London, the current weather is as follows:
Detailed status: overcast clouds
Wind speed: 4.12 m/s, direction: 10°
Humidity: 51%
Temperature:
  - Current: 12.82°C
  - High: 13.98°C
  - Low: 12.01°C
  - Feels like: 11.49°C
Rain: {}
Heat index: None
Cloud cover: 100%
================================== Ai Message ==================================

The weather in London is currently overcast with 100% cloud cover. The temperature is around 12.82°C, feeling like 11.49°C. The wind is blowing at 4.12 m/s from the direction of 10°. Humidity is at 51%. The high for the day is 13.98°C, and the low is 12.01°C.

以编程方式连接这些文档到 Claude、VSCode 等,通过 MCP 获取实时答案。
© . This site is unofficial and not affiliated with LangChain, Inc.