4. langgraph中的react agent使用 (在react agent添加人机交互)

1. 初始化模型

首先,我们需要初始化要使用的模型。

python 复制代码
# First we initialize the model we want to use.
from langchain_openai import ChatOpenAI

model = ChatOpenAI(
    temperature=0,
    model="glm-4-plus",
    openai_api_key="your_api_key",
    openai_api_base="https://open.bigmodel.cn/api/paas/v4/"
)

2. 定义自定义工具

我们将使用一个自定义工具来返回预定义的天气信息。

python 复制代码
from typing import Literal
from langchain_core.tools import tool

@tool
def get_weather(location: str):
    """Use this to get weather information from a given location."""
    if location.lower() in ["nyc", "new york"]:
        return "It might be cloudy in nyc"
    elif location.lower() in ["sf", "san francisco"]:
        return "It's always sunny in sf"
    else:
        raise AssertionError("Unknown Location, please try again use different expression")

tools = [get_weather]

3. 设置检查点

为了支持人机交互模式,我们需要一个检查点。

python 复制代码
from langgraph.checkpoint.memory import MemorySaver

memory = MemorySaver()

4. 定义图形

使用LangGraph的预构建功能来创建一个REACT代理。

python 复制代码
from langgraph.prebuilt import create_react_agent

graph = create_react_agent(
    model, tools=tools, interrupt_before=["tools"], checkpointer=memory
)

5. 打印工具流

定义一个工具来美化打印流。

python 复制代码
def print_stream(stream):
    """A utility to pretty print the stream."""
    for s in stream:
        message = s["messages"][-1]
        if isinstance(message, tuple):
            print(message)
        else:
            message.pretty_print()

6. 发送查询并打印结果

发送一个查询并打印结果。

python 复制代码
from langchain_core.messages import HumanMessage

config = {"configurable": {"thread_id": "42"}}
inputs = {"messages": [("user", "what is the weather in SF, CA?")]}

print_stream(graph.stream(inputs, config, stream_mode="values"))

输出示例:

复制代码
================================[1m Human Message [0m=================================
what is the weather in SF, CA?
================================[1m Ai Message [0m==================================
Tool Calls:
  get_weather (call_9208192248525421766)
 Call ID: call_9208192248525421766
  Args:
    location: SF, CA

7. 获取当前状态

获取当前状态以了解下一步操作。

python 复制代码
snapshot = graph.get_state(config)
print("Next step: ", snapshot.next)

输出示例:

复制代码
Next step:  ('tools',)

8. 继续处理流

继续处理流以获取更多结果。

python 复制代码
print_stream(graph.stream(None, config, stream_mode="values"))

输出示例:

复制代码
================================[1m Ai Message [0m==================================
Tool Calls:
  get_weather (call_9208192248525421766)
 Call ID: call_9208192248525421766
  Args:
    location: SF, CA
================================[1m Tool Message [0m=================================
Name: get_weather

Error: AssertionError('Unknown Location, please try again use different expression')
 Please fix your mistakes.
================================[1m Ai Message [0m==================================
Tool Calls:
  get_weather (call_9208192214165585200)
 Call ID: call_9208192214165585200
  Args:
    location: San Francisco, CA

9. 更新状态

根据工具的错误信息更新状态。

python 复制代码
state = graph.get_state(config)

last_message = state.values["messages"][-1]
last_message.tool_calls[0]["args"] = {"location": "San Francisco"}

graph.update_state(config, {"messages": [last_message]})

输出示例:

复制代码
{'configurable': {'thread_id': '42',
  'checkpoint_ns': '',
  'checkpoint_id': '1efa3728-5fb2-6e2f-8004-c28044c43c8b'}}

10. 再次打印流

再次打印流以获取最终结果。

python 复制代码
print_stream(graph.stream(None, config, stream_mode="values"))

输出示例:

复制代码
================================[1m Ai Message [0m==================================
Tool Calls:
  get_weather (call_9208192214165585200)
 Call ID: call_9208192214165585200
  Args:
    location: San Francisco
================================[1m Tool Message [0m=================================
Name: get_weather

It's always sunny in sf
================================[1m Ai Message [0m==================================

The weather in San Francisco is always sunny!

参考链接:https://langchain-ai.github.io/langgraph/how-tos/create-react-agent-hitl/

相关推荐
MARS_AI_9 分钟前
云蝠智能 VoiceAgent 2.0:全栈语音交互能力升级
人工智能·自然语言处理·交互·信息与通信·agi
top_designer15 分钟前
Substance 3D Stager:电商“虚拟摄影”工作流
人工智能·3d·设计模式·prompt·技术美术·教育电商·游戏美术
雷神大青椒15 分钟前
离别的十字路口: 是否还记得曾经追求的梦想
人工智能·程序人生·职场和发展·玩游戏
m0_650108241 小时前
多模态大模型 VS. 图像视频生成模型浅析
人工智能·技术边界与协同·mllm与生成模型·技术浅谈
ai_xiaogui1 小时前
Mac苹果版Krita AI一键安装教程:AIStarter+ComfyUI零基础部署全流程(X86/ARM双架构)
arm开发·人工智能·macos·comfyui·一键部署·ai绘画教程·kritaai
lapiii3582 小时前
[智能体设计模式] 第11章:目标设定与监控模式
人工智能·设计模式
这张生成的图像能检测吗2 小时前
(论文速读)WFF-Net:用于表面缺陷检测的可训练权重特征融合卷积神经网络
人工智能·深度学习·神经网络·缺陷检测·图像分割
shayudiandian2 小时前
RNN与LSTM详解:AI是如何“记住”信息的?
人工智能·rnn·lstm
美人鱼战士爱学习2 小时前
2025 Large language models for intelligent RDF knowledge graph construction
人工智能·语言模型·知识图谱
jz_ddk2 小时前
[算法] 算法PK:LMS与RLS的对比研究
人工智能·神经网络·算法·信号处理·lms·rls·自适应滤波