LangGraph 入门:构建带记忆功能的天气查询 Agent

12 阅读4分钟

背景

LangGraph 是 LangChain 生态中用于构建复杂 Agent 应用的框架。与简单的链式调用不同,LangGraph 通过图结构组织 AI 工作流,提供了状态管理、循环执行和工具调用等核心能力。本文通过实战代码,解析如何使用 create_react_agent 快速构建支持多轮对话的 Agent。


实现原理

ReAct 模式

create_react_agent 实现了经典的 ReAct(Reasoning + Acting)模式:

用户输入 → LLM 理解意图 → 决定调用工具 → 执行工具 → 观察结果 → 生成回复

记忆机制

LangGraph 的记忆功能由两部分组成:

组件作用类比
checkpointer存储引擎,决定对话历史存哪里硬盘/数据库
config["thread_id"]会话标识,区分不同对话文件名/会话ID

代码实现

完整代码

"""
LangGraph 快速入门示例 - 第一个 Agent 程序

本示例演示如何使用 LangGraph 的预构建组件创建一个简单的天气查询 Agent。
"""

from langgraph.prebuilt import create_react_agent
from langchain.chat_models import init_chat_model
from langgraph.checkpoint.memory import InMemorySaver
from pydantic import BaseModel
from dotenv import load_dotenv
from langchain_openai import ChatOpenAI
import os

# 加载环境变量
load_dotenv()


# 1. 定义工具函数
def get_weather(city: str) -> str:
    """获取指定城市的天气信息。
    
    Args:
        city: 城市名称
        
    Returns:
        天气描述字符串
    """
    return f"It's always sunny in {city}!"


# 2. 定义结构化输出格式
class WeatherResponse(BaseModel):
    """天气响应的结构化格式。"""
    conditions: str


# 3. 初始化模型(使用硅基流动平台的 Qwen 模型)
model = ChatOpenAI(
    model="Qwen/Qwen3-Next-80B-A3B-Instruct",
    openai_api_key=os.getenv("SILICONFLOW_API_KEY"),
    openai_api_base="https://api.siliconflow.cn/v1",
    temperature=0
)


# 4. 创建检查点器(用于记忆功能)
checkpointer = InMemorySaver()


# 5. 创建 Agent
agent = create_react_agent(
    model=model,
    tools=[get_weather],
    checkpointer=checkpointer,
    prompt="你是一个有帮助的助手,专门回答天气相关的问题。",
    response_format=WeatherResponse
)


# 6. 运行 Agent
def main():
    """主函数 - 演示 Agent 的使用。"""
    print("🤖 LangGraph Agent 已启动!")
    print("=" * 50)
    
    # 配置线程 ID(用于多轮对话)
    config = {"configurable": {"thread_id": "1"}}
    
    # 第一轮对话
    print("\n用户:what is the weather in san francisco?")
    sf_response = agent.invoke(
        {"messages": [{"role": "user", "content": "what is the weather in san francisco"}]},
        config
    )
    
    print(f"助手:{sf_response['messages'][-1].content}")
    print(f"结构化响应:{sf_response.get('structured_response')}")
    
    # 第二轮对话(测试记忆功能)
    print("\n用户:what about new york?")
    ny_response = agent.invoke(
        {"messages": [{"role": "user", "content": "what about new york?"}]},
        config
    )
    
    print(f"助手:{ny_response['messages'][-1].content}")
    print(f"结构化响应:{ny_response.get('structured_response')}")
    
    print("\n" + "=" * 50)
    print("✅ 示例运行完成!")


if __name__ == "__main__":
    main()

核心代码解析

工具定义

def get_weather(city: str) -> str:
    """获取指定城市的天气信息。"""
    return f"It's always sunny in {city}!"

工具函数的 docstring 是 LLM 判断是否调用该工具的关键依据。

结构化输出

class WeatherResponse(BaseModel):
    """天气响应的结构化格式。"""
    conditions: str

通过 Pydantic 模型约束输出格式,便于后续程序化处理。

记忆配置

# 存储引擎
checkpointer = InMemorySaver()

# 会话标识
config = {"configurable": {"thread_id": "1"}}

相同 thread_id 的多轮调用会共享对话历史。

Agent 创建

agent = create_react_agent(
    model=model,
    tools=[get_weather],
    checkpointer=checkpointer,
    prompt="你是一个有帮助的助手,专门回答天气相关的问题。",
    response_format=WeatherResponse
)

create_react_agent 封装了 ReAct 循环的复杂逻辑,开发者只需关注工具和业务逻辑。


运行效果

执行

pip install langgraph langchain langchain-openai pydantic python-dotenv
python 01快速入门.py

输出

🤖 LangGraph Agent 已启动!
==================================================

用户:what is the weather in san francisco?
助手:The weather in San Francisco is sunny.
结构化响应:conditions='sunny'

用户:what about new york?
助手:The weather in New York is also sunny.
结构化响应:conditions='sunny'

==================================================
✅ 示例运行完成!

技术亮点:第二个问题 "what about new york?" 是省略句,Agent 通过上下文理解用户询问的是纽约天气,体现了记忆功能的价值。


总结

本文通过实战代码展示了 LangGraph 的核心能力:

  1. 快速搭建create_react_agent 一行代码创建 ReAct Agent
  2. 工具集成:通过函数定义轻松扩展 Agent 能力
  3. 记忆功能checkpointer + thread_id 实现多轮对话
  4. 结构化输出:Pydantic 模型约束输出格式

进阶方向

  • 自定义 StateGraph 实现更复杂的工作流
  • 使用 PostgresSaver/RedisSaver 实现持久化存储
  • Human-in-the-loop 人机协作模式
  • 多 Agent 协作系统

参考


📌 本文首发于掘金,作者:AI探索者 🔗 转载请注明出处

💡 如果觉得有帮助,欢迎点赞、评论、收藏! 🎯 你的支持是我持续创作的动力!