目錄
一、功能概述
二、文件結構
三、城市天氣實時查詢(運行代碼)
weather_runnable.py
main.py
運行結果
四、技術亮點
五、使用場景
一、功能概述
它實現了以下主要功能:
-
用戶輸入地點(城市名)
-
構造提示詞(Prompt)生成自然語言問題
-
異步調用 Open-Meteo API 查詢該城市當前氣溫
-
調用 OpenAI GPT-4o 模型,讓它基于氣溫給出外出建議
二、文件結構
your_project/
├── weather_runnable.py ? 自定義異步 Runnable 類
├── main.py ? 主程序,構建異步鏈并執行
三、城市天氣實時查詢(運行代碼)
weather_runnable.py
這是一個符合 LangChain LCEL 規范的異步組件,繼承自 Runnable
。
-
實現了
ainvoke
方法,用于異步調用天氣 API。 -
使用
aiohttp
獲取 Open-Meteo 提供的天氣數據。 -
支持城市:Beijing、Shanghai、New York(可擴展)。
# weather_runnable.py
import aiohttp
from typing import Any, Optional
from langchain_core.runnables import Runnableclass WeatherLookupAsyncRunnable(Runnable):"""異步版:調用 Open-Meteo API 獲取城市天氣"""def get_coordinates(self, city: str):city_map = {"Beijing": (39.9042, 116.4074),"Shanghai": (31.2304, 121.4737),"New York": (40.7128, -74.0060),}return city_map.get(city)def invoke(self, input: Any, config: Optional[dict] = None) -> str:raise NotImplementedError("這是一個異步組件,請使用 ainvoke() 調用。")async def ainvoke(self, input: Any, config: Optional[dict] = None) -> str:if not isinstance(input, str):raise ValueError("輸入必須是字符串(城市名)")coords = self.get_coordinates(input)if coords is None:return f"暫不支持城市:{input}"lat, lon = coordsurl = (f"https://api.open-meteo.com/v1/forecast?"f"latitude={lat}&longitude={lon}¤t_weather=true")try:async with aiohttp.ClientSession() as session:async with session.get(url) as response:if response.status != 200:return "天氣 API 請求失敗"data = await response.json()temp = data.get("current_weather", {}).get("temperature")return f"當前{input}的氣溫是 {temp}°C" if temp is not None else "未獲取到氣溫"except Exception as e:return f"請求過程中出錯: {str(e)}"
main.py
這是主程序,執行以下流程:
-
構造提示詞: 使用
ChatPromptTemplate
創建一個天氣查詢句子。 -
調用天氣服務: 執行自定義異步
Runnable
,獲取當前氣溫。 -
調用 GPT-4o: 讓 LLM 根據天氣數據生成建議,比如“適合出門”或“建議帶傘”。
# main.py
import asyncio
from weather_runnable import WeatherLookupAsyncRunnable
from langchain_core.prompts import ChatPromptTemplate
from langchain_openai import ChatOpenAI # ? 用 langchain_openai,不要再用老接口prompt = ChatPromptTemplate.from_template("請問{location}的天氣如何?")
llm = ChatOpenAI(model="gpt-4o")weather = WeatherLookupAsyncRunnable()async def run():# 1. 生成用戶問題question = prompt.invoke({"location": "Beijing"}).to_string()print("Prompt output:", question)# 2. 實際調用天氣 API(最關鍵)weather_result = await weather.ainvoke("Beijing")print("天氣查詢結果:", weather_result) # 3. 由 LLM 生成回復llm_output = llm.invoke(f"根據{weather_result},簡短描述一下今天是否適合出門,需要注意什么")print("LLM output:", llm_output.content)asyncio.run(run())
運行結果
Prompt output: Human: 請問Beijing的天氣如何?
天氣查詢結果: 當前Beijing的氣溫是 23.9°C
LLM output: 今天北京的氣溫是23.9°C,天氣較為宜人,非常適合出門活動。不過建議根據具體的天氣情況查看是否有降水或其它天氣變化,出門時根據個人體感選擇適合的衣物。此
外,可以適當攜帶水杯保持水分補充,同時注意防曬措施,以確保舒適的戶外體驗。
四、技術亮點
技術 | 用途 |
---|---|
LangChain Core / LCEL | 構建可組合的數據流 |
Runnable Async | 實現異步接口邏輯,非阻塞式 |
aiohttp | 高效異步 HTTP 請求庫 |
OpenAI GPT-4o | 生成智能出行建議 |
ChatPromptTemplate | 動態構造人類語言輸入 |
五、使用場景
-
AI 助理天氣模塊
-
旅游或日程規劃建議工具
-
多輪對話集成的一個工具鏈組件