0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【LangChain】天気エージェント作成

0
Last updated at Posted at 2026-02-23

はじめに

  • LangChainを使用して天気エージェント作成しました

前提条件

  • LangChainの必要なライブラリがインストール済みであること
  • 経度緯度を取得するために下記のライブラリをインストールすること
pip install geopy

経度緯度が取得できるか確認

  • 経度緯度が取得できるか確認します
from geopy.geocoders import Nominatim
## 関数
def get_lat_lon(pref_name):
  geolocator = Nominatim(user_agent="test_app")
  # 住所から位置情報を検索
  location = geolocator.geocode(pref_name)
  if location:
    # 緯度と経度を返す
    return location
  else:
    return None, None
# 実行例
pref = "京都"
loc = get_lat_lon(pref)
if loc:
  print(f"{pref}の座標: 緯度 {loc.latitude}, 経度 {loc.longitude}")
else:
  print("見つかりませんでした。")
  • 出力結果
京都の座標: 緯度 34.9861908, 経度 135.7601217

天気予報が取得できるかの確認

  • 天気情報が取得できるか確認をします
def get_weekly_forecast(location: str):
  """
  指定された地名の1週間の天気予報を取得するツール。
  location: 地名(例: '東京都', 'Osaka'"""
  WEATHER_CODE_MAP = {0: "快晴", 1: "晴れ", 2: "薄曇り", 3: "曇り", 45: "", 48: "霧氷", 51: "霧雨", 53: "霧雨", 55: "霧雨", 61: "小雨", 63: "", 65: "強い雨", 71: "小雪", 73: "", 75: "強い雪", 80: "にわか雨", 81: "", 82: "激しいにわか雨", 85: "にわか雪", 86: "大雪"}
  geolocator = Nominatim(user_agent="test_weather_app")
  loc = geolocator.geocode(location)
  if loc is None:
    return {"error": "Location not found"} 
  params = {
    "latitude": loc.latitude,
    "longitude": loc.longitude,
    "hourly": ["temperature_2m", "weather_code"],
    "timezone": "Asia/Tokyo"
  }
  response = requests.get("https://api.open-meteo.com/v1/forecast", params=params)
  data = response.json()
  # データを整形
  times = data["hourly"]["time"]
  temps = data["hourly"]["temperature_2m"]
  codes = data["hourly"]["weather_code"]   
  time_interval = 6
  result = {}
  for i in range(0, len(times), time_interval):
    t = times[i]
    result[t] = {
      "temperature": temps[i],
      "weather": WEATHER_CODE_MAP.get(codes[i], f"不明({codes[i]})"),
    }
  return result
## 実行例
pref = "京都"
res = get_weekly_forecast2(pref)
res
  • 出力結果
{'2026-02-23T00:00': {'temperature': 11.6, 'weather': '霧雨'},
 '2026-02-23T06:00': {'temperature': 10.6, 'weather': '晴れ'},
 '2026-02-23T12:00': {'temperature': 15.7, 'weather': '快晴'},
 ...(省略)
 '2026-03-01T12:00': {'temperature': 9.4, 'weather': '曇り'},
 '2026-03-01T18:00': {'temperature': 8.1, 'weather': '薄曇り'}}

天気エージェントを実装

  • 手動で上記の関数が機能していることを確認した上でエージェントの実装を進めていきます

実装するうえでLangChain関連のモジュールを確認する

  • モジュールの読み込みや実装中にエラーが生じた際にリファレンスガイドを確認することをおすすめします
  • エラーログや下記のリファレンスを参考に実装を進めていきます

  • 例えば「AgentExecutor」の使い方を確認します
"""
agent: 実行ループの各ステップで実行するアクションを決定するために実行するエージェント
tools: エージェントが呼び出すことができる有効なツール
verbose: 	読みやすさ重視のログ
"""
AgentExecutor(agent=agent, tools=tools, verbose=True)

エージェント実装例

出力例

後記

  • 最後まで読んで頂きありがとうございます
  • 実装する上でライブラリの読み込みがうまくいかなかったり、引数が違う事によりエラーが生じました
  • LangChainのリファレンスガイドを参考に進めることにより実装できるようになりました
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?