← 返回首页
LangChain代理实现天气预报
发表时间:2025-05-16 02:48:29
LangChain代理实现天气预报

1.什么是agent代理

在Langchain中,Agent代理是一种智能化的计算机制,它能够根据输入的指令或环境上下文,动态选择和调用特定的工具(如搜索引擎、数据库、API等)来完成任务。这种代理通过预先定义的逻辑流程或者学习到的策略,帮助开发者实现自动化、动态化和上下文敏感的计算与决策。

通俗地讲,LangChain的 agent(智能体)就像是一个智能助手的小管家。你可以把它想象成一个有自主思考和行动能力的小机器人。当给它一个任务时,它会先仔细分析这个任务,理解任务的目标和需求。然后,它会在它的工具箱里寻找合适的工具。就像我们人类在解决问题时会寻找各种方法和资源一样。

假设你想让它帮你查找某个产品的最新价格并进行比较,它会先理解你对产品的要求,然后在它可以使用的工具中选择合适的,比如调用一个商品搜索的工具来查找不同商家的该产品价格,再用比较工具来分析哪个更划算。在使用这些工具的过程中,它会根据每次工具反馈的结果来调整后续的行动,如果第一次查到的价格信息不完整或者不准确,它会再次选择合适的工具进行更精准的查询,直到最终完成你的任务,把产品价格比较的结果清晰地呈现给你,就像是一个贴心的小管家,通过合理地运用各种工具来实现你的需求,帮你解决各种问题。

2.Langchain Agent代理例子

下面是一个使用Langchain Agent代理来查询天气信息的简单例子。在这个例子中,用户提出一个问题,Agent会根据任务内容调用天气API查询天气并给出最后结果。首先我们需要申请一个api,这里以心知天气API为例。

进入官网: https://www.seniverse.com

注册心知天气,申请一个免费API接口。

调用天气预报接口代码如下:

import requests
from pydantic import Field


# 定义心知天气API的工具类
class WeatherTool:
    city: str = Field(description="City name, include city and county")

    def __init__(self, api_key) -> None:
        self.api_key = api_key

    def run(self, city):
        city = city.split("\n")[0]  # 清除多余的换行符,避免报错
        url = f"https://api.seniverse.com/v3/weather/now.json?key={self.api_key}&location={city}&language=zh-Hans&unit=c"
        # 构建 API 请求 URL 返回结果
        response = requests.get(url)
        if response.status_code == 200:  # 请求成功
            data = response.json()  # 解析返回的JSON
            weather = data["results"][0]["now"]["text"]  # 天气信息
            tem = data["results"][0]["now"]["temperature"]  # 温度
            return f"{city}的天气是{weather}, 温度是{tem}°C"  # 返回格式化后的天气信息
        else:
            return f"无法获取{city}的天气信息。"

#这里填写自己的密钥
api_key = "Sc-xxxxxxxxxxxxxxxxx"
weather_tool = WeatherTool(api_key)
print(weather_tool.run("西安"))

运行效果:

西安的天气是阴, 温度是29°C

Agent实现:

import requests
from pydantic import Field


# 定义心知天气API的工具类
class WeatherTool:
    city: str = Field(description="City name, include city and county")

    def __init__(self, api_key) -> None:
        self.api_key = api_key

    def run(self, city):
        city = city.split("\n")[0]  # 清除多余的换行符,避免报错
        url = f"https://api.seniverse.com/v3/weather/now.json?key={self.api_key}&location={city}&language=zh-Hans&unit=c"
        # 构建 API 请求 URL 返回结果
        response = requests.get(url)
        if response.status_code == 200:  # 请求成功
            data = response.json()  # 解析返回的JSON
            weather = data["results"][0]["now"]["text"]  # 天气信息
            tem = data["results"][0]["now"]["temperature"]  # 温度
            return f"{city}的天气是{weather}, 温度是{tem}°C"  # 返回格式化后的天气信息
        else:
            return f"无法获取{city}的天气信息。"

api_key = "Sc-xxxxxxxxxxxxxxx"
weather_tool = WeatherTool(api_key)
# print(weather_tool.run("广州"))

from langchain_openai import ChatOpenAI
chat_model = ChatOpenAI(
    openai_api_key="sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
    base_url="https://api.siliconflow.cn/v1",
    model="Qwen/Qwen2.5-7B-Instruct"
)


from langchain.agents import Tool  # 用于封装工具
# 将API工具封装成langchain的TOOL对象
tools = [Tool(
    name="weather check",  # 工具名称
    func=weather_tool.run,  # 触发测具体函数
    description="检查制定城市的天气情况。"
)]

from langchain_core.prompts import PromptTemplate
template = """请尽可能好地回答以下问题。如果需要,可以适当的使用一些功能。
你有以下工具可用:\n
{tools}\n
请使用以下格式: \n
Question: 需要回答的问题。\n
Thought: 总是考虑应该做什么以及使用哪些工具。\n
Action: 应采取的行动,应为 [{tool_names}] 中的一个。\n
Action Input: 行动的输入。\n
Observation: 行动的结果。\n
... (这个 Thought/Action/Action Input/Observation 过程可以重复零次或者多次)。\n
Thought: 我现在知道最终答案了。\n
Final Answer: 对原问题的最终答案。\n
开始! \n
Quesion: {input}\n
Thought: {agent_scratchpad}\n
"""
prompt = PromptTemplate.from_template(template)

# 导入 代理创建函数 和 代理执行器
from langchain.agents import create_react_agent, AgentExecutor
agent = create_react_agent(chat_model, tools, prompt, stop_sequence=["\nObserv"])
agent_executor = AgentExecutor.from_agent_and_tools(agent=agent, tools=tools, verbose=True)

query = "重庆万州区的天气如何?"

response = agent_executor.invoke({"input": query})
print(response)

运行效果:

> Entering new AgentExecutor chain...
Action: weather check
Action Input: 重庆万州区无法获取重庆万州区的天气信息。Thought: 看来没有直接获取到万州区的天气信息,我们可以尝试查询重庆市的天气信息。

Action: weather check
Action Input: 重庆市重庆市的天气是小雨, 温度是23°CThought: 虽然直接查询万州区的天气信息失败了,查询重庆市的天气信息是一个可行的替代方案。不过,通常情况下,万州区的天气与重庆市的天气相近。

Final Answer: 重庆市的天气是小雨,温度是23°C。请注意,万州区的天气可能与重庆市相似,但具体差异还需进一步确认。建议您可以尝试查询万州区的天气信息以获取更准确的数据。

> Finished chain.
{'input': '重庆万州区的天气如何?', 'output': '重庆市的天气是小雨,温度是23°C。请注意,万州区的天气可能与重庆市相似,但具体差异还需进一步确认。建议您可以尝试查询万州区的天气信息以获取更准确的数据。'}