Skip to content

如何将人工介入流程添加到预构建的ReAct代理中

先决条件

本指南假设您熟悉以下内容:

本指南将展示如何将人工介入流程添加到预构建的ReAct代理中。请参阅本教程以了解如何开始使用预构建的ReAct代理

您可以在工具调用前添加一个断点,通过将interrupt_before=["tools"]传递给create_react_agent来实现。请注意,您需要使用检查点器才能使此操作生效。

设置

首先,让我们安装所需的包并设置API密钥

%%capture --no-stderr
%pip install -U langgraph langchain-openai
import getpass
import os


def _set_env(var: str):
    if not os.environ.get(var):
        os.environ[var] = getpass.getpass(f"{var}: ")


_set_env("OPENAI_API_KEY")

为LangGraph开发设置LangSmith

注册LangSmith,可以快速发现并解决您的LangGraph项目中的问题,提高项目性能。LangSmith允许您使用跟踪数据来调试、测试和监控使用LangGraph构建的LLM应用程序——更多关于如何开始的信息,请参阅这里

代码

# First we initialize the model we want to use.
from langchain_openai import ChatOpenAI

model = ChatOpenAI(model="gpt-4o", temperature=0)


# For this tutorial we will use custom tool that returns pre-defined values for weather in two cities (NYC & SF)
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")


tools = [get_weather]

# We need a checkpointer to enable human-in-the-loop patterns
from langgraph.checkpoint.memory import MemorySaver

memory = MemorySaver()

# Define the graph

from langgraph.prebuilt import create_react_agent

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

API Reference: ChatOpenAI | tool | MemorySaver | create_react_agent

使用方法

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()
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"))

API Reference: HumanMessage

================================ Human Message =================================

what is the weather in SF, CA?
================================== Ai Message ==================================
Tool Calls:
  get_weather (call_YjOKDkgMGgUZUpKIasYk1AdK)
 Call ID: call_YjOKDkgMGgUZUpKIasYk1AdK
  Args:
    location: SF, CA
我们可以验证图形在正确的位置停止了:

snapshot = graph.get_state(config)
print("Next step: ", snapshot.next)
Next step:  ('tools',)
现在我们可以选择批准或编辑工具调用,然后再继续到下一个节点。如果我们想批准工具调用,我们只需继续使用None输入流式传输图。如果我们想编辑工具调用,则需要更新状态以包含正确的工具调用,然后在更新应用后我们才能继续。

我们可以尝试恢复并会看到出现错误:

print_stream(graph.stream(None, config, stream_mode="values"))
================================== Ai Message ==================================
Tool Calls:
  get_weather (call_YjOKDkgMGgUZUpKIasYk1AdK)
 Call ID: call_YjOKDkgMGgUZUpKIasYk1AdK
  Args:
    location: SF, CA
================================= Tool Message =================================
Name: get_weather

Error: AssertionError('Unknown Location')
 Please fix your mistakes.
================================== Ai Message ==================================
Tool Calls:
  get_weather (call_CLu9ofeBhtWF2oheBspxXkfE)
 Call ID: call_CLu9ofeBhtWF2oheBspxXkfE
  Args:
    location: San Francisco, CA
此错误出现的原因是我们工具的参数“San Francisco, CA”并不是工具所识别的位置。

让我们展示如何编辑工具调用以搜索“San Francisco”而不是“San Francisco, CA”——因为我们当前编写的工具将“San Francisco, CA”视为未知位置。我们将更新状态,然后继续流式传输图表,并且应该不会出现任何错误。

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': '1ef801d1-5b93-6bb9-8004-a088af1f9cec'}}

print_stream(graph.stream(None, config, stream_mode="values"))
================================== Ai Message ==================================
Tool Calls:
  get_weather (call_CLu9ofeBhtWF2oheBspxXkfE)
 Call ID: call_CLu9ofeBhtWF2oheBspxXkfE
  Args:
    location: San Francisco
================================= Tool Message =================================
Name: get_weather

It's always sunny in sf
================================== Ai Message ==================================

The weather in San Francisco is currently sunny.
太好了!我们的图表正确更新,查询了旧金山的天气,并从工具中得到了正确的“旧金山永远阳光明媚”的回复,然后相应地回复了用户。

Comments