当前位置: 首页 > news >正文

【基于 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}&current_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,适合出门,但需要注意防暑降温。建议穿轻便、透气的衣服,并携带遮阳帽或太阳镜保护自己免受阳光直射。此外,记得保持水分充足,随身
携带水瓶,避免长时间在阳光下活动,适当寻求阴凉处休息。如果感到任何不适,请及时进入室内或阴凉处休息。

相关文章:

  • 棒球裁判员学习指南·棒球1号位
  • dify插件接入fastmcp示例
  • Satori:元动作 + 内建搜索机制,让大模型实现超级推理能力
  • 一文理解扩散模型(生成式AI模型)(1)
  • 初等数论--莫比乌斯函数
  • OSPF综合应用
  • muduo源码解析
  • Bitacora:基因组组件中基因家族识别和注释的综合工具
  • PPO近端策略优化算法
  • 《Python星球日记》 第54天:卷积神经网络进阶
  • SQL注入问题
  • 用jsp简单实现C语言标准化测试系统
  • 2505d,d的借用检查器
  • 【Redis】string 字符串
  • Kubernetes 生产实战(十五):生产环境敏感信息纳入Secret管理指南
  • DB4S:一个开源跨平台的SQLite数据库管理工具
  • ThreadPoolExecutor源码阅读以及手写简单线程池 —— JDK17
  • @Transactional注解失效
  • 用c语言实现——一个交互式的中序线索二叉树系统,支持用户动态构建、线索化、遍历和查询功能
  • 超详细Kokoro-82M本地部署教程
  • 年轻小将绽放光芒!中国短跑男女接力队直通东京世锦赛
  • 华泰柏瑞基金总经理韩勇因工作调整卸任,董事长贾波代为履职
  • 国家出口管制工作协调机制办公室部署开展打击战略矿产走私出口专项行动
  • 陕西澄城樱桃在上海推介,向长三角消费者发出“甜蜜之邀”
  • 哥伦比亚总统称将在访华期间签署“一带一路”倡议意向书,外交部回应
  • 文旅部:加强对景区索道、游船等设施设备安全隐患排查整治