Skip to content

如何等待用户输入(功能API)

先决条件

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

**人机交互(HIL)**交互对于代理系统至关重要。等待用户输入是人机交互的一种常见模式,允许代理向用户提出澄清问题,并在收到用户输入之前暂停执行。

我们可以在LangGraph中使用interrupt()函数来实现这一点。interrupt允许我们暂停图执行以收集用户输入,并在收集到输入后继续执行。

本指南将演示如何使用LangGraph的功能API实现人机交互工作流。具体来说,我们将演示:

  1. 一个简单的使用示例
  2. 如何与ReAct代理一起使用

设置

首先,让我们安装所需的包并设置我们的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")

使用LangSmith进行更好的调试

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

简单用法

让我们通过一个简单的用例示例来进行演示。我们将创建三个任务:

  1. 添加 "bar"
  2. 暂停等待人类输入。在恢复时,添加人类输入。
  3. 添加 "qux"
from langgraph.func import entrypoint, task
from langgraph.types import Command, interrupt


@task
def step_1(input_query):
    """Append bar."""
    return f"{input_query} bar"


@task
def human_feedback(input_query):
    """Append user input."""
    feedback = interrupt(f"Please provide feedback: {input_query}")
    return f"{input_query} {feedback}"


@task
def step_3(input_query):
    """Append qux."""
    return f"{input_query} qux"

API Reference: entrypoint | task | Command | interrupt

我们现在可以将这些任务在一个简单的入口点中组合起来:

from langgraph.checkpoint.memory import MemorySaver

checkpointer = MemorySaver()


@entrypoint(checkpointer=checkpointer)
def graph(input_query):
    result_1 = step_1(input_query).result()
    result_2 = human_feedback(result_1).result()
    result_3 = step_3(result_2).result()

    return result_3

API Reference: MemorySaver

我们所做的,以启用人工介入的工作流程,就是在任务中调用了interrupt()

提示

前一任务(本例中为step_1)的结果被持久化了,因此在interrupt之后不会重新运行这些任务。

让我们发送一个查询字符串:

config = {"configurable": {"thread_id": "1"}}

for event in graph.stream("foo", config):
    print(event)
    print("\n")
{'step_1': 'foo bar'}


{'__interrupt__': (Interrupt(value='Please provide feedback: foo bar', resumable=True, ns=['graph:d66b2e35-0ee3-d8d6-1a22-aec9d58f13b9', 'human_feedback:e0cd4ee2-b874-e1d2-8bc4-3f7ddc06bcc2'], when='during'),)}
注意,我们在step_1之后使用interrupt暂停了执行。中断提供了继续执行的指令。要继续执行,我们需要发出一个命令,其中包含human_feedback任务所期望的数据。

# Continue execution
for event in graph.stream(Command(resume="baz"), config):
    print(event)
    print("\n")
{'human_feedback': 'foo bar baz'}


{'step_3': 'foo bar baz qux'}


{'graph': 'foo bar baz qux'}
恢复后,运行将继续通过剩余的步骤,并如预期的那样终止。

代理

我们将基于在如何使用函数式API创建ReAct代理指南中创建的代理进行扩展。

在这里,我们将扩展代理的功能,使其在需要时能够向人类求助。

定义模型和工具

首先,让我们定义我们将用于示例的工具和模型。与ReAct代理指南一样,我们将使用一个占位符工具,该工具可以获取某个位置的天气描述。

在这个示例中,我们将使用一个OpenAI聊天模型,但任何支持工具调用的模型都适用。

from langchain_openai import ChatOpenAI
from langchain_core.tools import tool

model = ChatOpenAI(model="gpt-4o-mini")


@tool
def get_weather(location: str):
    """Call to get the weather from a specific location."""
    # This is a placeholder for the actual implementation
    if any([city in location.lower() for city in ["sf", "san francisco"]]):
        return "It's sunny!"
    elif "boston" in location.lower():
        return "It's rainy!"
    else:
        return f"I am not sure what the weather is in {location}"

API Reference: ChatOpenAI | tool

要联系真人寻求帮助,我们只需添加一个调用interrupt的工具:

from langgraph.types import Command, interrupt


@tool
def human_assistance(query: str) -> str:
    """Request assistance from a human."""
    human_response = interrupt({"query": query})
    return human_response["data"]


tools = [get_weather, human_assistance]

API Reference: Command | interrupt

定义任务

我们的任务与ReAct代理指南中的描述基本相同:

  1. 调用模型:我们希望使用消息列表查询聊天模型。
  2. 调用工具:如果模型生成工具调用,我们希望执行它们。

我们只是多了一个模型可以访问的工具。

from langchain_core.messages import ToolMessage
from langgraph.func import entrypoint, task

tools_by_name = {tool.name: tool for tool in tools}


@task
def call_model(messages):
    """Call model with a sequence of messages."""
    response = model.bind_tools(tools).invoke(messages)
    return response


@task
def call_tool(tool_call):
    tool = tools_by_name[tool_call["name"]]
    observation = tool.invoke(tool_call)
    return ToolMessage(content=observation, tool_call_id=tool_call["id"])

API Reference: ToolMessage | entrypoint | task

定义入口点

我们的入口点ReAct代理指南中的定义保持一致:

from langgraph.checkpoint.memory import MemorySaver
from langgraph.graph.message import add_messages

checkpointer = MemorySaver()


@entrypoint(checkpointer=checkpointer)
def agent(messages, previous):
    if previous is not None:
        messages = add_messages(previous, messages)

    llm_response = call_model(messages).result()
    while True:
        if not llm_response.tool_calls:
            break

        # Execute tools
        tool_result_futures = [
            call_tool(tool_call) for tool_call in llm_response.tool_calls
        ]
        tool_results = [fut.result() for fut in tool_result_futures]

        # Append to message list
        messages = add_messages(messages, [llm_response, *tool_results])

        # Call model again
        llm_response = call_model(messages).result()

    # Generate final response
    messages = add_messages(messages, llm_response)
    return entrypoint.final(value=llm_response, save=messages)

API Reference: MemorySaver | add_messages

使用方法

让我们用一个问题来调用我们的模型,这个问题需要人类的帮助。我们的问题还将需要调用get_weather工具:

def _print_step(step: dict) -> None:
    for task_name, result in step.items():
        if task_name == "agent":
            continue  # just stream from tasks
        print(f"\n{task_name}:")
        if task_name == "__interrupt__":
            print(result)
        else:
            result.pretty_print()
config = {"configurable": {"thread_id": "1"}}

user_message = {
    "role": "user",
    "content": (
        "Can you reach out for human assistance: what should I feed my cat? "
        "Separately, can you check the weather in San Francisco?"
    ),
}
print(user_message)

for step in agent.stream([user_message], config):
    _print_step(step)
{'role': 'user', 'content': 'Can you reach out for human assistance: what should I feed my cat? Separately, can you check the weather in San Francisco?'}

call_model:
================================== Ai Message ==================================
Tool Calls:
  human_assistance (call_joAEBVX7Abfm7TsZ0k95ZkVx)
 Call ID: call_joAEBVX7Abfm7TsZ0k95ZkVx
  Args:
    query: What should I feed my cat?
  get_weather (call_ut7zfHFCcms63BOZLrRHszGH)
 Call ID: call_ut7zfHFCcms63BOZLrRHszGH
  Args:
    location: San Francisco

call_tool:
================================= Tool Message =================================

content="It's sunny!" name='get_weather' tool_call_id='call_ut7zfHFCcms63BOZLrRHszGH'

__interrupt__:
(Interrupt(value={'query': 'What should I feed my cat?'}, resumable=True, ns=['agent:aa676ccc-b038-25e3-9c8a-18e81d4e1372', 'call_tool:059d53d2-3344-13bc-e170-48b632c2dd97'], when='during'),)
注意,我们生成了两个工具调用,尽管我们的运行被中断,但我们并没有阻塞get_weather工具的执行。

让我们检查一下我们在哪里被中断:

print(step)
{'__interrupt__': (Interrupt(value={'query': 'What should I feed my cat?'}, resumable=True, ns=['agent:aa676ccc-b038-25e3-9c8a-18e81d4e1372', 'call_tool:059d53d2-3344-13bc-e170-48b632c2dd97'], when='during'),)}
我们可以通过发出一个命令来恢复执行。请注意,我们在Command中提供的数据可以根据human_assistance的实现自定义以满足您的需求。

human_response = "You should feed your cat a fish."
human_command = Command(resume={"data": human_response})

for step in agent.stream(human_command, config):
    _print_step(step)
call_tool:
================================= Tool Message =================================

content='You should feed your cat a fish.' name='human_assistance' tool_call_id='call_joAEBVX7Abfm7TsZ0k95ZkVx'

call_model:
================================== Ai Message ==================================

For human assistance, you should feed your cat fish. 

Regarding the weather in San Francisco, it's sunny!
上方在我们恢复时提供了最终的工具消息,允许模型生成其响应。查看LangSmith跟踪以查看完整的运行分解:

  1. 初始查询的跟踪
  2. 恢复后的跟踪

Comments