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/

相关推荐
bin91532 分钟前
解锁Java开发新姿势:飞算JavaAI深度探秘 #飞算JavaAl炫技赛 #Java开发
java·人工智能·python·java开发·飞算javaai·javaai·飞算javaal炫技赛
居然JuRan6 分钟前
LangChain从0到1实战:手把手教你实现RAG
人工智能
摆烂工程师8 分钟前
GPT-5 对应用户可以使用的次数,以及解决 GPT-5 没有推送的问题
人工智能·gpt·程序员
cscshaha31 分钟前
《从零构建大语言模型》学习笔记1,环境配置
人工智能·深度学习·语言模型·llm·从零构建大语言模型
双翌视觉2 小时前
机械手的眼睛,视觉系统如何让机器人学会精准抓取
人工智能·机器人·自动化
IvanCodes2 小时前
OpenAI 最新开源模型 gpt-oss (Windows + Ollama/ubuntu)本地部署详细教程
人工智能·语言模型·chatgpt·开源
2301_769006782 小时前
祝贺!1464种期刊被收录,CSCD 核心期刊目录更新!(附下载)
大数据·数据库·人工智能·搜索引擎·期刊
天天代码码天天2 小时前
C# OnnxRuntime Yolov8 纸箱检测
人工智能
猫头虎-人工智能2 小时前
ChatGPT模型选择器详解:全面了解GPT-4o、GPT-4.5、o3等模型的切换与使用策略(2025最新版)
人工智能·chatgpt·开源·aigc·ai编程·ai写作·ai-native
小苏兮2 小时前
飞算JavaAI深度解析:专为Java生态而生的智能引擎
java·开发语言·人工智能·java开发·飞算javaai炫技赛