跳到内容

LangGraph Supervisor (主管)

函数

名称 描述
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]]]

一个可选的最终主管输出模式(schema)。

如果提供,输出将被格式化以匹配给定的模式,并返回在 '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 的节点)之前添加。对于管理长消息历史(例如,消息修剪、摘要等)非常有用。模型前钩子必须是一个可调用对象或一个 runnable,它接收当前图状态并以以下形式返回状态更新:

# 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 的节点)之后添加。对于实现人在回路(human-in-the-loop)、护栏(guardrails)、验证或其他后处理非常有用。模型后钩子必须是一个可调用对象或一个 runnable,它接收当前图状态并返回状态更新。

注意

仅在 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 消息上的 name 属性。目前,只有 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

移交工具的可选描述。如果未提供,描述将是 向智能体 <agent_name> 寻求帮助

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' 工具。