跳到内容

LangGraph 监督器

函数

名称 描述
create_supervisor

创建一个多代理监督器。

create_supervisor

create_supervisor(
    agents: list[Pregel],
    *,
    model: LanguageModelLike,
    tools: (
        list[BaseTool | Callable] | ToolNode | None
    ) = None,
    prompt: Prompt | None = None,
    response_format: Optional[
        Union[
            StructuredResponseSchema,
            tuple[str, StructuredResponseSchema],
        ]
    ] = None,
    pre_model_hook: Optional[RunnableLike] = None,
    post_model_hook: Optional[RunnableLike] = None,
    parallel_tool_calls: bool = False,
    state_schema: StateSchemaType | None = None,
    config_schema: Type[Any] | None = None,
    output_mode: OutputMode = "last_message",
    add_handoff_messages: bool = True,
    handoff_tool_prefix: Optional[str] = None,
    add_handoff_back_messages: Optional[bool] = None,
    supervisor_name: str = "supervisor",
    include_agent_name: AgentNameMode | None = None
) -> StateGraph

创建一个多代理监督器。

参数

名称 类型 描述 默认值
agents list[Pregel]

要管理的代理列表。代理可以是 LangGraph CompiledStateGraph、函数式 API 工作流,或任何其他 Pregel 对象。

必填
model LanguageModelLike

监督器使用的语言模型。

必填
工具 list[BaseTool | Callable] | ToolNode | None

监督器要使用的工具。

None
prompt Prompt | None

监督器可选提示词。可以是以下之一:

  • str:这会转换为 SystemMessage 并添加到 `state["messages"]` 消息列表的开头。
  • SystemMessage:这会添加到 `state["messages"]` 消息列表的开头。
  • Callable:此函数应接收完整的图状态,其输出随后传递给语言模型。
  • Runnable:此可运行对象应接收完整的图状态,其输出随后传递给语言模型。
None
response_format Optional[Union[StructuredResponseSchema, tuple[str, StructuredResponseSchema]]]

最终监督器输出的可选模式。

如果提供,输出将按照给定模式格式化并以“structured_response”状态键返回。如果未提供,structured_response 将不会出现在输出状态中。可以作为以下形式传递:

- an OpenAI function/tool schema,
- a JSON Schema,
- a TypedDict class,
- or a Pydantic class.
- a tuple (prompt, schema), where schema is one of the above.
    The prompt will be used together with the model that is being used to generate the structured response.

重要

response_format 要求模型支持 .with_structured_output

注意

response_format 要求您的状态模式中包含 structured_response 键。您可以使用预构建的 langgraph.prebuilt.chat_agent_executor.AgentStateWithStructuredResponse

None
pre_model_hook Optional[RunnableLike]

一个可选节点,用于在监督器代理中的 LLM 节点(即调用 LLM 的节点)之前添加。对于管理长消息历史记录(例如,消息修剪、摘要等)非常有用。前模型钩子必须是一个可调用对象或一个可运行对象,它接收当前图状态并以以下形式返回状态更新:

# At least one of `messages` or `llm_input_messages` MUST be provided
{
    # If provided, will UPDATE the `messages` in the state
    "messages": [RemoveMessage(id=REMOVE_ALL_MESSAGES), ...],
    # If provided, will be used as the input to the LLM,
    # and will NOT UPDATE `messages` in the state
    "llm_input_messages": [...],
    # Any other state keys that need to be propagated
    ...
}

重要

messagesllm_input_messages 至少提供一个,并将其用作 agent 节点的输入。其余的键将添加到图状态中。

警告

如果您在前模型钩子中返回 messages,您应该通过以下方式覆盖 messages 键:

{
    "messages": [RemoveMessage(id=REMOVE_ALL_MESSAGES), *new_messages]
    ...
}
None
post_model_hook Optional[RunnableLike]

一个可选节点,用于在监督器代理中的 LLM 节点(即调用 LLM 的节点)之后添加。对于实现人工干预、防护栏、验证或其他后处理非常有用。后模型钩子必须是一个可调用对象或一个可运行对象,它接收当前图状态并返回状态更新。

注意

仅在 langgraph-prebuilt>=0.2.0 中可用。

None
parallel_tool_calls bool

是否允许监督器 LLM 并行调用工具(仅限 OpenAI 和 Anthropic)。使用此参数控制监督器是否可以一次性将控制权移交给多个代理。如果为 True,将启用并行工具调用。如果为 False,将禁用并行工具调用(默认)。

重要

目前仅 OpenAI 和 Anthropic 模型支持此功能。要控制其他提供商的并行工具调用,请在系统提示中添加明确的工具使用说明。

False
state_schema StateSchemaType | None

监督器图要使用的状态模式。

None
config_schema Type[Any] | None

用于配置的可选模式。使用此模式可通过 supervisor.config_specs 暴露可配置参数。

None
output_mode OutputMode

将受管代理输出添加到多代理工作流中消息历史记录的模式。可以是以下之一:

  • full_history: 添加完整的代理消息历史记录。
  • last_message: 仅添加最后一条消息(默认)。
'last_message'
add_handoff_messages bool

当发生移交时,是否向消息历史记录添加一对 (AIMessage, ToolMessage)。

True
handoff_tool_prefix Optional[str]

移交工具的可选前缀(例如,“delegate_to_”或“transfer_to_”)。如果提供,移交工具将被命名为 handoff_tool_prefix_agent_name。如果未提供,移交工具将被命名为 transfer_to_agent_name

None
add_handoff_back_messages Optional[bool]

当控制权返回给监督器时,是否向消息历史记录添加一对 (AIMessage, ToolMessage) 以指示已发生移交。

None
supervisor_name str

监督器节点的名称。

'supervisor'
include_agent_name AgentNameMode | None

用于指定如何将代理名称暴露给底层监督器 LLM。

  • None: 依赖 LLM 提供商在 AI 消息上使用名称属性。目前仅 OpenAI 支持此功能。
  • "inline":使用 XML 样式标签将代理名称直接添加到 AI 消息的内容字段中。示例:"How can I help you" -> "<name>agent_name</name><content>How can I help you?</content>"
None
示例
from langchain_openai import ChatOpenAI

from langgraph_supervisor import create_supervisor
from langgraph.prebuilt import create_react_agent

# Create specialized agents

def add(a: float, b: float) -> float:
    '''Add two numbers.'''
    return a + b

def web_search(query: str) -> str:
    '''Search the web for information.'''
    return 'Here are the headcounts for each of the FAANG companies in 2024...'

math_agent = create_react_agent(
    model="openai:gpt-4o",
    tools=[add],
    name="math_expert",
)

research_agent = create_react_agent(
    model="openai:gpt-4o",
    tools=[web_search],
    name="research_expert",
)

# Create supervisor workflow
workflow = create_supervisor(
    [research_agent, math_agent],
    model=ChatOpenAI(model="gpt-4o"),
)

# Compile and run
app = workflow.compile()
result = app.invoke({
    "messages": [
        {
            "role": "user",
            "content": "what's the combined headcount of the FAANG companies in 2024?"
        }
    ]
})

函数

名称 描述
create_handoff_tool

创建一个可以将控制权移交给请求代理的工具。

create_forward_message_tool

创建一个监督器可以用来按名称转发工作器消息的工具。

create_handoff_tool

create_handoff_tool(
    *,
    agent_name: str,
    name: str | None = None,
    description: str | None = None,
    add_handoff_messages: bool = True
) -> BaseTool

创建一个可以将控制权移交给请求代理的工具。

参数

名称 类型 描述 默认值
agent_name str

要移交控制权的代理名称,即多代理图中的代理节点名称。代理名称应简单、清晰、唯一,最好采用 snake_case,尽管您仅限于 LangGraph 节点接受的名称以及 LLM 提供商接受的工具名称(工具名称将如下所示:transfer_to_<agent_name>)。

必填
name str | None

移交工具的可选名称。如果未提供,工具名称将为 transfer_to_<agent_name>

None
description str | None

移交工具的可选描述。如果未提供,描述将为 Ask agent <agent_name> for help

None
add_handoff_messages bool

是否将移交消息添加到消息历史记录中。如果为 False,移交消息将从消息历史记录中省略。

True

create_forward_message_tool

create_forward_message_tool(
    supervisor_name: str = "supervisor",
) -> BaseTool

创建一个监督器可以用来按名称转发工作器消息的工具。

这有助于避免监督器将工作器查询重写给用户时发生的信息丢失,并且还可以节省一些 token。

参数

名称 类型 描述 默认值
supervisor_name str

监督器节点的名称(用于工具的命名空间)。

'supervisor'

返回

名称 类型 描述
BaseTool BaseTool

“forward_message”工具。