【基于 LangChain 的异步天气查询2】GeoNames实现地区实时气温查询
目录
功能简介
一、创建GeoNames账号
1、进入官网
2、创建账号
二、运行代码
weather_runnable.py
main.py
运行结果
功能简介
本文主要通过Langchain,结合GeoNames实现了地区温度的实时查询,并通过GPT-4o对温度进行一段简短的描述。
一、创建GeoNames账号
1、进入官网
GeoNames官网地址:GeoNames
说明:GeoNames主要是用于获取地理经纬度,从而获取相应地理位置的信息。
2、创建账号
二、运行代码
weather_runnable.py
import aiohttp
import requests
from langchain_core.runnables import RunnableLambdaasync def fetch_weather(city: str) -> str:username = 'shipking'geonames_url = f"http://api.geonames.org/search?q={city}&maxRows=1&username={username}&type=json"print(f"🔍 请求 URL: {geonames_url}")response = requests.get(geonames_url)print(f"🌐 返回内容:{response.text[:200]}") # 仅打印前200字符避免太长data = response.json() # 现在应该不会再报错if response.status_code == 200:data = response.json()if data['totalResultsCount'] > 0:geoname = data['geonames'][0]lat, lon = geoname['lat'], geoname['lng']else:return f"未找到城市:{city}"else:return "GeoNames 请求失败"url = (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"当前{city}的气温是 {temp}°C" if temp is not None else "未获取到气温"except Exception as e:return f"请求过程中出错: {str(e)}"# 导出为 Runnable 实例
WeatherLookupAsyncRunnable = RunnableLambda(fetch_weather)
main.py
import asyncio
from weather_runnable import WeatherLookupAsyncRunnable
from langchain_core.prompts import ChatPromptTemplate
from langchain_openai import ChatOpenAIprompt = ChatPromptTemplate.from_template("请问{location}的天气如何?")
llm = ChatOpenAI(model="gpt-4o")# 不要再写 weather = WeatherLookupAsyncRunnable()
weather = WeatherLookupAsyncRunnable # ✅ 正确写法async def run():user_input = input("请输入城市名称(可中文):") # ✅ 自定义输入question = prompt.invoke({"location": user_input}).to_string()print("Prompt output:", question)weather_result = await weather.ainvoke(user_input)print("天气查询结果:", weather_result)llm_output = llm.invoke(f"根据{weather_result},简短描述一下今天是否适合出门,需要注意什么")print("LLM output:", llm_output.content)if __name__ == "__main__":asyncio.run(run())
运行结果
请输入城市名称(可中文):上海
Prompt output: Human: 请问上海的天气如何?
🔍 请求 URL: http://api.geonames.org/search?q=上海&maxRows=1&username=shipking&type=json
🌐 返回内容:{"totalResultsCount":4726,"geonames":[{"adminCode1":"23","lng":"121.45806",":"P","population":24874500,"countryCode":"CN","name":
🔍 请求 URL: http://api.geonames.org/search?q=京东&maxRows=1&username=shipking&type=json
🌐 返回内容:{"totalResultsCount":12,"geonames":[{"adminCode1":"29","lng":"100.84485","geonameId":1805676,"toponymName":"Jingdong Yizu Zizhixian","countryId":"1814991","fcl":"A","population":0,"countryCode":"CN","
天气查询结果: 当前京东的气温是 31.6°C
LLM output: 今天京东的气温为31.6°C,适合出门,但需要注意防暑降温。建议穿轻便、透气的衣服,并携带遮阳帽或太阳镜保护自己免受阳光直射。此外,记得保持水分充足,随身
携带水瓶,避免长时间在阳光下活动,适当寻求阴凉处休息。如果感到任何不适,请及时进入室内或阴凉处休息。