使用阿里百炼平台提供的qwen-max模型和openweathermap定义Agent实现实时城市天气查询的代码
本文介绍了基于Python和LangChain框架的天气查询系统实现。系统需要安装PyOWM和pypinyin组件,并配置OpenWeatherMap和阿里云百炼大模型的API密钥。程序通过将中文城市名转换为拼音后调用天气API查询,返回包含平均温度、最高/最低温度和体感温度的详细天气信息。示例运行显示查询"南京天气"成功返回了36.15度的温度数据,验证了系统的可行性。该系统
环境准备,需要安装以下组件:
天气所有者组件: pip install PyOWM
汉语转拼音组件: pip install pypinyin
需要在Members网站获取(https://home.openweathermap.org/api_keys)天气查询的api-key
需要在阿里云百炼大模型平台获取api-key
.env文件中配置如下:
# DeepSeek API密钥
DEEPSEEK_API_KEY=sk-2c7157f33d394d87a55f5bb8803329e9
#阿里云百炼大模型平台
OPENAI_API_KEY=sk-ae0851249faf4293afb215db25e40016
程序源代码如下:
import os
import sys
from dotenv import load_dotenv
from langchain_openai.chat_models.base import ChatOpenAI
from langchain.agents import Tool
from langchain.agents import initialize_agent
import requests
import pyowm
import pypinyin
from pypinyin import pinyin, Style
# 从.env文件加载环境变量
load_dotenv()
# 获取API密钥
api_key = os.getenv("OPENAI_API_KEY")
if not api_key:
print("错误: 请在.env文件中设置您的OPEN_API_KEY")
sys.exit(1)
#我们使用阿里百炼平台提供的qwen-max模型
llm = ChatOpenAI(
openai_api_key=api_key,
model_name="qwen-max",
openai_api_base="https://dashscope.aliyuncs.com/compatible-mode/v1/",
temperature=0.7,
max_tokens=8192
)
# 自定义工具,将小写字母转化为大写字母
def to_upper_tool(text:str)->str:
return text.upper()
to_upper_tool = Tool(
name="to_upper_tool",
func=to_upper_tool,
description="useful for when you need to convert a string to uppercase."
)
# 自定义工具,获取城市天气,使用openweathermap(https://home.openweathermap.org/)提供的天气数据
def get_weather_tool(test:str)->str:
#todo: get weather from weather api
#=====天气查询开始=========================
'''
获取城市天气,使用openweathermap(https://home.openweathermap.org/)提供的天气数据
'''
owm = pyowm.OWM('a71a46385b0ec779ca73941c509b0924') # TODO: Replace <api_key> with your API key
mgr = owm.weather_manager()
#== == == 汉语转拼音 == == == == == == == =
# 示例文本
text = test
# 转换为拼音,默认风格为NORMAL(不带声调)
pinyin_list = pypinyin.lazy_pinyin(text)
print(pinyin_list) # 输出: ['ni', 'hao', ',', 'shi', 'jie', '!']
s = ''
for ss in pinyin_list:
s += ss
print(s)
#开始转换
sf = mgr.weather_at_place(s + ', CN')
w = sf.weather
#转换的结果:
result=w.temperature('celsius');
print(type(result))
print(type(result['temp']))
s1=str(result['temp'])
s2 = str(result['temp_max'])
s3 = str(result['temp_min'])
s4 = str(result['feels_like'])
#拼接转换的结果
resultTemp=text+'平均温度:'+s1+'\n'+'最高温度:'+s2+'\n最低温度:'+s3+'\n体感温度:'+s4
print(resultTemp)
# =============================
#=========================================
#return "天气晴,温度28度"
return resultTemp;
get_weather_tool = Tool(
name="get_weather_tool",
func=get_weather_tool,
description="useful for when you need to get the weather of a city."
)
# 工具列表
tools = [to_upper_tool, get_weather_tool]
# 初始化代理
agent = initialize_agent(
agent="zero-shot-react-description",
tools=tools,
llm=llm,
verbose=True, # 显示调试信息
)
if __name__ == '__main__':
question=input('请输入您要查询天气的城市名称:')
result = agent.run(input=question) # 使用Agent进行对话
print(f"AI回复: {result}")
pass
运行结果:
请输入您要查询天气的城市名称:南京的天气情况
E:\test\pythonProject\prjLangChainTools\agentdemotongyi.py:98: LangChainDeprecationWarning: The method `Chain.run` was deprecated in langchain 0.1.0 and will be removed in 1.0. Use :meth:`~invoke` instead.
result = agent.run(input=question) # 使用Agent进行对话> Entering new AgentExecutor chain...
我需要使用get_weather_tool来获取南京的天气情况。
Action: get_weather_tool
Action Input: 南京['nan', 'jing']
nanjing
<class 'dict'>
<class 'float'>
南京平均温度:36.15
最高温度:36.15
最低温度:36.15
体感温度:39.81Observation: 南京平均温度:36.15
最高温度:36.15
最低温度:36.15
体感温度:39.81
Thought:我已得知南京的天气情况。
Final Answer: 南京的平均温度为36.15度,最高温度和最低温度均为36.15度,体感温度为39.81度。> Finished chain.
AI回复: 南京的平均温度为36.15度,最高温度和最低温度均为36.15度,体感温度为39.81度。Process finished with exit code 0
火山引擎开发者社区是火山引擎打造的AI技术生态平台,聚焦Agent与大模型开发,提供豆包系列模型(图像/视频/视觉)、智能分析与会话工具,并配套评测集、动手实验室及行业案例库。社区通过技术沙龙、挑战赛等活动促进开发者成长,新用户可领50万Tokens权益,助力构建智能应用。
更多推荐
所有评论(0)