如何为预构建的 ReAct 代理添加人工干预流程¶
本指南将展示如何为预构建的 ReAct 代理添加人工干预流程。有关如何开始使用预构建的 ReAct 代理,请参阅本教程。
你可以通过将 interrupt_before=["tools"]
传递给 create_react_agent
来在调用工具之前设置一个断点。请注意,要使此功能生效,你需要使用检查点器。
安装设置¶
首先,让我们安装所需的软件包并设置我们的 API 密钥。
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 构建的大语言模型应用程序 — 点击 此处 了解更多关于如何开始使用的信息。
代码¶
# 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: tool
使用方法¶
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
================================[1m Human Message [0m=================================
what is the weather in SF, CA?
==================================[1m Ai Message [0m==================================
Tool Calls:
get_weather (call_YjOKDkgMGgUZUpKIasYk1AdK)
Call ID: call_YjOKDkgMGgUZUpKIasYk1AdK
Args:
location: SF, CA
None
输入继续流式传输图即可。如果我们想编辑工具调用,则需要更新状态以包含正确的工具调用,然后在应用更新后,我们就可以继续操作。
我们可以尝试恢复操作,届时会看到出现一个错误:
==================================[1m Ai Message [0m==================================
Tool Calls:
get_weather (call_YjOKDkgMGgUZUpKIasYk1AdK)
Call ID: call_YjOKDkgMGgUZUpKIasYk1AdK
Args:
location: SF, CA
=================================[1m Tool Message [0m=================================
Name: get_weather
Error: AssertionError('Unknown Location')
Please fix your mistakes.
==================================[1m Ai Message [0m==================================
Tool Calls:
get_weather (call_CLu9ofeBhtWF2oheBspxXkfE)
Call ID: call_CLu9ofeBhtWF2oheBspxXkfE
Args:
location: 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'}}
==================================[1m Ai Message [0m==================================
Tool Calls:
get_weather (call_CLu9ofeBhtWF2oheBspxXkfE)
Call ID: call_CLu9ofeBhtWF2oheBspxXkfE
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 currently sunny.