Skip to content

LangGraph 的 createSupervisor 解析 #133

@Pines-Cheng

Description

@Pines-Cheng

这是 LangGraph 中 createSupervisor 函数的 TypeScript 类型定义,用于创建多智能体监督者。让我详细解释一下各个参数:

核心参数

1. agents - 智能体列表

agents: Agent[]  // 要管理的智能体列表

2. llm - 语言模型

llm: LanguageModel  // 监督者使用的语言模型

3. tools - 工具集

tools: Tool[]  // 监督者可用的工具

可选参数

4. prompt - 提示词配置

prompt?: string | SystemMessage | Function | Runnable
  • string: 转换为 SystemMessage 添加到消息开头
  • SystemMessage: 直接添加到消息开头
  • Function: 接收完整图状态,输出传给语言模型
  • Runnable: 接收完整图状态,输出传给语言模型

5. responseFormat - 响应格式

responseFormat?: ZodSchema | JSONSchema | { prompt: string, schema: ZodSchema | JSONSchema }
  • 用于结构化输出
  • 支持 Zod schema 或 JSON schema
  • 要求模型支持 .withStructuredOutput()

6. outputMode - 输出模式

outputMode?: 'full_history' | 'last_message'  // 默认: 'last_message'
  • full_history: 添加完整的智能体消息历史
  • last_message: 只添加最后一条消息

7. addHandoffBackMessages - 移交消息

addHandoffBackMessages?: boolean

是否在移交控制权时添加 (AIMessage, ToolMessage) 对

8. includeAgentName - 智能体名称显示

includeAgentName?: undefined | 'inline'
  • undefined: 依赖 LLM 提供商的 name 属性(目前只有 OpenAI 支持)
  • 'inline': 直接将智能体名称添加到消息内容中
    <name>agent_name</name><content>How can I help you?</content>

使用示例

import { createSupervisor } from '@langchain/langgraph';
import { ChatOpenAI } from '@langchain/openai';

const supervisor = createSupervisor({
  agents: [researchAgent, writerAgent, reviewerAgent],
  llm: new ChatOpenAI({ model: "gpt-4" }),
  tools: [webSearchTool, calculatorTool],
  prompt: "You are a supervisor managing a team of AI agents...",
  outputMode: 'last_message',
  addHandoffBackMessages: true,
  supervisorName: 'MainSupervisor',
  includeAgentName: 'inline'
});

返回值

返回一个 StateGraph 实例,可以用来构建和运行多智能体工作流。

重要注意事项

  1. 结构化输出: responseFormat 需要模型支持 .withStructuredOutput()
  2. 额外调用: 图会在智能体循环结束后单独调用 LLM 生成结构化响应
  3. 状态管理: 使用 MessagesAnnotation 作为默认状态模式

这个函数是构建复杂多智能体系统的核心工具,允许你创建一个协调多个专门智能体工作的监督者。

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions