multiagent

package
v0.0.0-...-ca21e7b Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 16, 2025 License: Apache-2.0 Imports: 17 Imported by: 0

README

Enhanced Multi-Agent System

基于CloudWeGo/Eino框架的增强多智能体系统,提供了高级的思考、规划和协作能力。

功能特性

🧠 智能思考能力
  • 深度思考模式:支持多步骤思考过程
  • 复杂度分析:自动评估任务复杂度
  • 思考历史记录:完整的思考过程追踪
📋 任务规划能力
  • 动态规划:根据任务复杂度动态生成执行计划
  • 依赖分析:自动识别任务间的依赖关系
  • 计划更新:支持执行过程中的计划调整
👥 多智能体协作
  • 专家智能体:支持多个专业领域的智能体
  • 并行执行:支持多个智能体并行处理任务
  • 结果聚合:智能聚合多个智能体的执行结果
🔄 持续反馈机制
  • 执行监控:实时监控任务执行状态
  • 质量评估:对执行结果进行质量评估
  • 自适应调整:根据反馈自动调整执行策略
📊 状态管理
  • 会话管理:支持多轮对话和上下文保持
  • 状态持久化:支持状态的序列化和恢复
  • 执行历史:完整的执行过程记录

架构设计

核心组件
  1. 主智能体 (Host Agent)

    • 负责整体协调和决策
    • 执行思考和规划过程
    • 管理专家智能体的调度
  2. 专家智能体 (Specialist Agents)

    • 专门处理特定领域的任务
    • 支持并行执行
    • 提供专业的解决方案
  3. 状态管理器 (State Manager)

    • 维护系统的全局状态
    • 支持状态的序列化和恢复
    • 提供状态查询和更新接口
  4. 执行引擎 (Execution Engine)

    • 基于Eino框架的图执行引擎
    • 支持复杂的工作流编排
    • 提供错误处理和重试机制
执行流程
graph TD
    A[用户输入] --> B[对话分析]
    B --> C[主智能体思考]
    C --> D{复杂度判断}
    D -->|简单| E[直接回答]
    D -->|复杂| F[创建执行计划]
    F --> G[专家智能体执行]
    G --> H[结果收集]
    H --> I[反馈处理]
    I --> J{是否继续}
    J -->|是| K[更新计划]
    J -->|否| L[生成最终答案]
    K --> G
    E --> M[结束]
    L --> M

使用方法

基本使用
package main

import (
    "context"
    "fmt"
    "github.com/cloudwego/eino/flow/agent/multiagent/enhanced"
    "github.com/cloudwego/eino/schema"
)

func main() {
    // 使用默认配置
    config := enhanced.GetDefaultConfig()
    
    // 创建增强多智能体系统
    ctx := context.Background()
    agent, err := enhanced.NewEnhancedMultiAgent(ctx, config)
    if err != nil {
        panic(err)
    }
    
    // 准备输入消息
    input := []*schema.Message{
        {
            Role:    schema.User,
            Content: "请帮我分析一下如何优化Go语言Web服务的性能",
        },
    }
    
    // 执行
    result, err := agent.Generate(ctx, input)
    if err != nil {
        panic(err)
    }
    
    fmt.Println("结果:", result.Content)
}
流式处理
// 流式执行
stream, err := agent.Stream(ctx, input)
if err != nil {
    panic(err)
}

for {
    chunk, err := stream.Recv()
    if err != nil {
        if err.Error() == "EOF" {
            break
        }
        panic(err)
    }
    fmt.Print(chunk.Content)
}
自定义配置
// 创建自定义配置
config := &enhanced.EnhancedMultiAgentConfig{
    Name: "我的多智能体系统",
    Host: enhanced.EnhancedHost{
        Model: enhanced.ModelConfig{
            Provider: "openai",
            Model:    "gpt-4",
            Parameters: map[string]any{
                "temperature": 0.7,
                "max_tokens":  2048,
            },
        },
        SystemPrompt: "你是一个智能助手...",
        Thinking: enhanced.ThinkingConfig{
            MaxSteps:           5,
            Timeout:            time.Minute * 2,
            EnableDeepThink:    true,
            ComplexityAnalysis: true,
        },
    },
    Specialists: []*enhanced.EnhancedSpecialist{
        {
            Name:        "代码专家",
            IntendedUse: "处理编程相关任务",
            Model: enhanced.ModelConfig{
                Provider: "openai",
                Model:    "gpt-4",
            },
            SystemPrompt: "你是一个专业的程序员...",
        },
    },
}

// 使用默认值填充其他配置
defaultConfig := enhanced.GetDefaultConfig()
config.Session = defaultConfig.Session
config.Performance = defaultConfig.Performance
config.Logging = defaultConfig.Logging
config.ExecutionControl = defaultConfig.ExecutionControl
config.System = defaultConfig.System

配置说明

主智能体配置 (EnhancedHost)
  • Model: 模型配置,包括提供商、模型名称和参数
  • SystemPrompt: 系统提示词
  • Thinking: 思考配置,控制思考过程的行为
  • Planning: 规划配置,控制任务规划的行为
专家智能体配置 (EnhancedSpecialist)
  • Name: 专家名称
  • IntendedUse: 预期用途描述
  • Model: 模型配置
  • SystemPrompt: 专家的系统提示词
  • Concurrency: 并发数量
  • Timeout: 执行超时时间
会话配置 (SessionConfig)
  • HistoryLength: 历史记录长度
  • ContextWindow: 上下文窗口大小
  • ContextProcessing: 上下文处理配置
性能配置 (PerformanceConfig)
  • Concurrency: 并发控制配置
  • MemoryManagement: 内存管理配置
  • Caching: 缓存配置
  • Monitoring: 监控配置

扩展开发

自定义处理器

可以通过实现相应的接口来自定义处理器:

// 自定义对话分析器
type CustomConversationAnalyzer struct {
    // 自定义字段
}

func (c *CustomConversationAnalyzer) PreHandler(ctx context.Context, input any, state *enhanced.EnhancedState) (any, error) {
    // 自定义预处理逻辑
    return input, nil
}

func (c *CustomConversationAnalyzer) PostHandler(ctx context.Context, output any, state *enhanced.EnhancedState) error {
    // 自定义后处理逻辑
    return nil
}
自定义回调
// 实现自定义回调
type CustomCallback struct {}

func (c *CustomCallback) OnSystemStart(ctx context.Context, state *enhanced.EnhancedState) error {
    fmt.Println("系统启动")
    return nil
}

func (c *CustomCallback) OnSystemEnd(ctx context.Context, state *enhanced.EnhancedState) error {
    fmt.Println("系统结束")
    return nil
}

// 更多回调方法...

最佳实践

1. 合理配置专家智能体
  • 根据业务需求配置专门的专家智能体
  • 为每个专家设置合适的系统提示词
  • 控制专家的并发数量以平衡性能和资源消耗
2. 优化思考和规划配置
  • 根据任务复杂度调整思考步数
  • 设置合理的超时时间
  • 启用复杂度分析以提高决策质量
3. 监控和日志
  • 启用详细的日志记录
  • 监控系统性能指标
  • 定期分析执行历史以优化配置
4. 错误处理
  • 设置合理的重试策略
  • 实现优雅的降级机制
  • 记录和分析错误模式

性能优化

1. 并发控制
  • 合理设置专家智能体的并发数量
  • 使用连接池管理模型API连接
  • 实现请求去重和缓存机制
2. 内存管理
  • 定期清理历史记录
  • 使用流式处理减少内存占用
  • 实现状态的增量更新
3. 网络优化
  • 使用HTTP/2连接复用
  • 实现智能重试和熔断机制
  • 优化请求批处理

故障排除

常见问题
  1. 编译错误

    • 检查Go版本是否符合要求
    • 确保所有依赖包已正确安装
  2. 运行时错误

    • 检查模型API配置是否正确
    • 验证网络连接是否正常
  3. 性能问题

    • 检查并发配置是否合理
    • 监控内存和CPU使用情况
调试技巧
  • 启用调试模式获取详细日志
  • 使用性能分析工具定位瓶颈
  • 分析执行历史找出问题模式

贡献指南

欢迎贡献代码和建议!请遵循以下步骤:

  1. Fork 项目
  2. 创建功能分支
  3. 提交更改
  4. 创建 Pull Request

许可证

本项目采用 Apache License 2.0 许可证。详见 LICENSE 文件。

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func WithConversationAnalyzer

func WithConversationAnalyzer(handler MessageHandler) base.AgentOption

WithConversationAnalyzer 为对话分析节点添加消息处理器

func WithDirectAnswerHandler

func WithDirectAnswerHandler(handler MessageHandler) base.AgentOption

WithDirectAnswerHandler 为直接回答节点添加消息处理器

func WithFeedbackProcessorHandler

func WithFeedbackProcessorHandler(handler MessageHandler) base.AgentOption

WithFeedbackProcessorHandler 为反馈处理节点添加消息处理器

func WithFinalAnswerHandler

func WithFinalAnswerHandler(handler MessageHandler) base.AgentOption

WithFinalAnswerHandler 为最终回答节点添加消息处理器

func WithPlanCreationHandler

func WithPlanCreationHandler(handler MessageHandler) base.AgentOption

WithPlanCreationHandler 为计划创建节点添加消息处理器

func WithPlanHandler

func WithPlanHandler(handler PlanHandler) base.AgentOption

func WithPlanUpdateHandler

func WithPlanUpdateHandler(handler MessageHandler) base.AgentOption

WithPlanUpdateHandler 为计划更新节点添加消息处理器

func WithSpecialistHandler

func WithSpecialistHandler(specialistName string, handler MessageHandler) base.AgentOption

WithSpecialistHandler 为指定专家节点添加消息处理器

Types

type ActionType

type ActionType string

ActionType represents the type of action an agent can take

const (
	ActionTypeUnknown ActionType = "unknown"
	ActionTypeThink   ActionType = "think"
	ActionTypePlan    ActionType = "plan"
	ActionTypeExecute ActionType = "execute"
	ActionTypeReflect ActionType = "reflect"
	ActionTypeAnswer  ActionType = "answer"
)

type ComplexityBranchHandler

type ComplexityBranchHandler struct {
	// contains filtered or unexported fields
}

ComplexityBranchHandler handles complexity-based branching

func NewComplexityBranchHandler

func NewComplexityBranchHandler(config *MultiAgentConfig) *ComplexityBranchHandler

NewComplexityBranchHandler creates a new complexity branch handler

func (*ComplexityBranchHandler) Evaluate

func (h *ComplexityBranchHandler) Evaluate(ctx context.Context, state *MultiAgentState) (string, error)

Evaluate determines the branch based on task complexity

type ConversationAnalyzerHandler

type ConversationAnalyzerHandler struct {
	// contains filtered or unexported fields
}

ConversationAnalyzerHandler analyzes conversation context

func NewConversationAnalyzerHandler

func NewConversationAnalyzerHandler(config *MultiAgentConfig) *ConversationAnalyzerHandler

NewConversationAnalyzerHandler creates a new conversation analyzer handler

func (*ConversationAnalyzerHandler) PostHandler

func (h *ConversationAnalyzerHandler) PostHandler(ctx context.Context, output *schema.Message, state *MultiAgentState) (*schema.Message, error)

PostHandler processes conversation analysis results

func (*ConversationAnalyzerHandler) PreHandler

func (h *ConversationAnalyzerHandler) PreHandler(ctx context.Context, input []*schema.Message, state *MultiAgentState) ([]*schema.Message, error)

PreHandler prepares input for conversation analysis

type ConversationContext

type ConversationContext struct {
	IsIndependentTopic bool              `json:"isIndependentTopic"`
	UserIntent         string            `json:"userIntent"`
	RelevantHistory    []*schema.Message `json:"relevantHistory"`
	KeyTopics          []string          `json:"keyTopics"`
	ContextSummary     string            `json:"contextSummary"`
	Complexity         TaskComplexity    `json:"complexity"`
	Metadata           map[string]any    `json:"metadata,omitempty"`
}

ConversationContext contains conversation analysis results

type ExecutionRecord

type ExecutionRecord struct {
	StepID    string            `json:"stepID"`
	Action    ActionType        `json:"action"`
	Input     []*schema.Message `json:"input"`
	Output    *schema.Message   `json:"output"`
	StartTime time.Time         `json:"startTime"`
	EndTime   time.Time         `json:"endTime"`
	Duration  time.Duration     `json:"duration"`
	Status    ExecutionStatus   `json:"status"`
	Error     string            `json:"error,omitempty"`
	Metadata  map[string]any    `json:"metadata,omitempty"`
}

ExecutionRecord represents a single execution step record

type ExecutionStatus

type ExecutionStatus string

ExecutionStatus represents the overall execution status

const (
	ExecutionStatusUnknown    ExecutionStatus = "unknown"
	ExecutionStatusPending    ExecutionStatus = "pending"
	ExecutionStatusAnalyzing  ExecutionStatus = "analyzing"
	ExecutionStatusPlanning   ExecutionStatus = "planning"
	ExecutionStatusStarted    ExecutionStatus = "started"
	ExecutionStatusRunning    ExecutionStatus = "running"
	ExecutionStatusExecuting  ExecutionStatus = "executing"
	ExecutionStatusCollecting ExecutionStatus = "collecting"
	ExecutionStatusCompleted  ExecutionStatus = "completed"
	ExecutionStatusSuccess    ExecutionStatus = "success"
	ExecutionStatusFailed     ExecutionStatus = "failed"
	ExecutionStatusTimeout    ExecutionStatus = "timeout"
	ExecutionStatusCancelled  ExecutionStatus = "cancelled"
)

type Feedback

type Feedback struct {
	ExecutionCompleted bool     `json:"execution_completed"`
	OverallQuality     float64  `json:"overall_quality"`
	PlanNeedsUpdate    bool     `json:"plan_needs_update"`
	Issues             []string `json:"issues"`
	Suggestions        []string `json:"suggestions"`
	Confidence         float64  `json:"confidence"`
	NextActionReason   string   `json:"next_action_reason"`
}

Feedback represents the feedback received from the user

type FeedbackProcessorHandler

type FeedbackProcessorHandler struct {
	// contains filtered or unexported fields
}

func NewFeedbackProcessorHandler

func NewFeedbackProcessorHandler(config *MultiAgentConfig) *FeedbackProcessorHandler

func (*FeedbackProcessorHandler) PostHandler

func (h *FeedbackProcessorHandler) PostHandler(ctx context.Context, output *schema.Message, state *MultiAgentState) (*schema.Message, error)

func (*FeedbackProcessorHandler) PreHandler

func (h *FeedbackProcessorHandler) PreHandler(ctx context.Context, input []*schema.Message, state *MultiAgentState) ([]*schema.Message, error)

type FinalAnswerHandler

type FinalAnswerHandler struct {
	// contains filtered or unexported fields
}

func NewFinalAnswerHandler

func NewFinalAnswerHandler(config *MultiAgentConfig) *FinalAnswerHandler

func (*FinalAnswerHandler) PostHandler

func (h *FinalAnswerHandler) PostHandler(ctx context.Context, output *schema.Message, state *MultiAgentState) (*schema.Message, error)

func (*FinalAnswerHandler) PreHandler

func (h *FinalAnswerHandler) PreHandler(ctx context.Context, input []*schema.Message, state *MultiAgentState) ([]*schema.Message, error)

type Host

type Host struct {
	Model        model.ToolCallingChatModel `yaml:"model" json:"model"`
	ReactAgent   *react.ReactAgent          `yaml:"react_agent" json:"react_agent"`
	SystemPrompt string                     `yaml:"system_prompt" json:"system_prompt"`
	Prompts      map[string]string          `yaml:"prompts,omitempty" json:"prompts,omitempty"`
	Thinking     ThinkingConfig             `yaml:"thinking" json:"thinking"`
	Planning     PlanningConfig             `yaml:"planning" json:"planning"`
}

Host represents the host agent configuration

type MessageHandler

type MessageHandler interface {
	OnMessage(ctx context.Context, message *schema.Message) (context.Context, error)
	OnStreamMessage(ctx context.Context, message *schema.StreamReader[*schema.Message]) (context.Context, error)
}

MessageHandler 通用消息处理器接口

type MultiAgent

type MultiAgent struct {
	Runnable         compose.Runnable[[]*schema.Message, *schema.Message]
	Graph            *compose.Graph[[]*schema.Message, *schema.Message]
	GraphAddNodeOpts []compose.GraphAddNodeOpt
	AgentOptions     []base.AgentOption
	Config           *MultiAgentConfig
}

MultiAgent represents the enhanced multi-agent system

func NewMultiAgent

func NewMultiAgent(ctx context.Context, config *MultiAgentConfig, agentOptions ...base.AgentOption) (*MultiAgent, error)

NewMultiAgent creates a new multi-agent system

func (*MultiAgent) ExportGraph

func (ema *MultiAgent) ExportGraph() (compose.AnyGraph, []compose.GraphAddNodeOpt)

ExportGraph exports the underlying graph

func (*MultiAgent) Generate

func (ema *MultiAgent) Generate(ctx context.Context, input []*schema.Message, opts ...base.AgentOption) (*schema.Message, error)

Generate executes the enhanced multi-agent system

func (*MultiAgent) GetConfig

func (ema *MultiAgent) GetConfig() *MultiAgentConfig

GetConfig returns the configuration

func (*MultiAgent) Stream

func (ema *MultiAgent) Stream(ctx context.Context, input []*schema.Message, opts ...base.AgentOption) (*schema.StreamReader[*schema.Message], error)

Stream executes the enhanced multi-agent system in streaming mode

type MultiAgentConfig

type MultiAgentConfig struct {
	Name            string            `yaml:"name" json:"name"`
	Description     string            `yaml:"description,omitempty" json:"description,omitempty"`
	Host            Host              `yaml:"host" json:"host"`
	Specialists     []*Specialist     `yaml:"specialists" json:"specialists"`
	PromptTemplates map[string]string `yaml:"prompt_templates,omitempty" json:"prompt_templates,omitempty"`
	Session         SessionConfig     `yaml:"session" json:"session"`
	MaxRounds       int               `yaml:"max_rounds" json:"max_rounds"`
}

MultiAgentConfig represents the complete configuration for the multi-agent system

func GetDefaultConfig

func GetDefaultConfig(chatModel model.ToolCallingChatModel) *MultiAgentConfig

GetDefaultConfig returns a default configuration

func (*MultiAgentConfig) Validate

func (config *MultiAgentConfig) Validate() error

Validate validates the configuration

type MultiAgentState

type MultiAgentState struct {
	RoundNumber int       `json:"round_number"`
	StartTime   time.Time `json:"start_time"`

	// Conversation Context
	ConversationContext *ConversationContext `json:"conversation_context,omitempty"`
	OriginalMessages    []*schema.Message    `json:"original_messages"`

	// Task Planning
	CurrentPlan *TaskPlan   `json:"current_plan,omitempty"`
	PlanHistory []*TaskPlan `json:"plan_history,omitempty"`

	// Execution Status
	ExecutionStatus  ExecutionStatus    `json:"execution_status"`
	CurrentStep      string             `json:"current_step,omitempty"`
	ExecutionHistory []*ExecutionRecord `json:"execution_history,omitempty"`

	// Specialist Results
	SpecialistResults map[string]*StepResult `json:"specialist_results,omitempty"`

	// Collected Results
	CollectedResults []*schema.Message `json:"collected_results,omitempty"`

	// Feedback and Reflection
	FeedbackHistory []*Feedback `json:"feedback_history,omitempty"`
	ReflectionCount int         `json:"reflection_count"`

	// Execution Control
	MaxRounds      int  `json:"max_rounds"`
	ShouldContinue bool `json:"should_continue"`
	IsCompleted    bool `json:"is_completed"`

	// Final Answer
	FinalAnswer *schema.Message `json:"final_answer,omitempty"`

	// Metadata
	Metadata map[string]any `json:"metadata,omitempty"`
}

MultiAgentState represents the complete state of the enhanced multi-agent system

func (*MultiAgentState) AddCollectedResult

func (es *MultiAgentState) AddCollectedResult(result *schema.Message)

结果收集管理方法

func (*MultiAgentState) AddExecutionRecord

func (es *MultiAgentState) AddExecutionRecord(record *ExecutionRecord)

func (*MultiAgentState) AddFeedback

func (es *MultiAgentState) AddFeedback(feedback *Feedback)

反馈管理方法

func (*MultiAgentState) AddPlanToHistory

func (es *MultiAgentState) AddPlanToHistory(plan *TaskPlan)

func (*MultiAgentState) ClearSpecialistResults

func (es *MultiAgentState) ClearSpecialistResults()

func (*MultiAgentState) Clone

func (es *MultiAgentState) Clone() (*MultiAgentState, error)

Clone creates a deep copy of the state

func (*MultiAgentState) FromJSON

func (es *MultiAgentState) FromJSON(data []byte) error

FromJSON deserializes the state from JSON

func (*MultiAgentState) GetMetadata

func (es *MultiAgentState) GetMetadata(key string) (any, bool)

func (*MultiAgentState) IncrementReflection

func (es *MultiAgentState) IncrementReflection()

func (*MultiAgentState) IncrementRound

func (es *MultiAgentState) IncrementRound()

func (*MultiAgentState) SetCompleted

func (es *MultiAgentState) SetCompleted(completed bool)

func (*MultiAgentState) SetCurrentPlan

func (es *MultiAgentState) SetCurrentPlan(plan *TaskPlan)

计划管理方法

func (*MultiAgentState) SetCurrentStep

func (es *MultiAgentState) SetCurrentStep(stepID string)

func (*MultiAgentState) SetExecutionStatus

func (es *MultiAgentState) SetExecutionStatus(status ExecutionStatus)

执行记录管理方法

func (*MultiAgentState) SetFinalAnswer

func (es *MultiAgentState) SetFinalAnswer(answer *schema.Message)

func (*MultiAgentState) SetMaxRounds

func (es *MultiAgentState) SetMaxRounds(max int)

元数据管理方法

func (*MultiAgentState) SetMetadata

func (es *MultiAgentState) SetMetadata(key string, value any)

func (*MultiAgentState) SetOriginalMessages

func (es *MultiAgentState) SetOriginalMessages(messages []*schema.Message)

func (*MultiAgentState) SetRoundNumber

func (es *MultiAgentState) SetRoundNumber(round int)

基础字段管理方法

func (*MultiAgentState) SetShouldContinue

func (es *MultiAgentState) SetShouldContinue(should bool)

func (*MultiAgentState) SetStartTime

func (es *MultiAgentState) SetStartTime(t time.Time)

func (*MultiAgentState) ToJSON

func (es *MultiAgentState) ToJSON() ([]byte, error)

ToJSON serializes the state to JSON

func (*MultiAgentState) UpdateConversationContext

func (es *MultiAgentState) UpdateConversationContext(ctx *ConversationContext)

对话上下文管理方法

func (*MultiAgentState) UpdateSpecialistResult

func (es *MultiAgentState) UpdateSpecialistResult(specialist string, result *StepResult)

专家结果管理方法

type OperationData

type OperationData struct {
	Type     string    `json:"type"`
	StepID   string    `json:"stepID"`
	StepData *StepData `json:"step_data,omitempty"`
	Position string    `json:"position,omitempty"`
	Reason   string    `json:"reason,omitempty"`
}

OperationData defines the structure for plan update operations

type PlanCreationHandler

type PlanCreationHandler struct {
	// contains filtered or unexported fields
}

PlanCreationHandler handles task plan creation

func NewPlanCreationHandler

func NewPlanCreationHandler(config *MultiAgentConfig) *PlanCreationHandler

NewPlanCreationHandler creates a new plan creation handler

func (*PlanCreationHandler) PostHandler

func (h *PlanCreationHandler) PostHandler(ctx context.Context, output *schema.Message, state *MultiAgentState) (*schema.Message, error)

PostHandler processes plan creation results

func (*PlanCreationHandler) PreHandler

func (h *PlanCreationHandler) PreHandler(ctx context.Context, input []*schema.Message, state *MultiAgentState) ([]*schema.Message, error)

PreHandler prepares input for plan creation

type PlanExecutionHandler

type PlanExecutionHandler struct {
	// contains filtered or unexported fields
}

PlanExecutionHandler handles plan execution coordination

func NewPlanExecutionHandler

func NewPlanExecutionHandler(config *MultiAgentConfig) *PlanExecutionHandler

NewPlanExecutionHandler creates a new plan execution handler

func (*PlanExecutionHandler) Execute

Execute coordinates the execution of the current plan

type PlanHandler

type PlanHandler interface {
	OnPlanStepCreate(ctx context.Context, plan *TaskPlan, step *PlanStep) (context.Context, error)
	OnPlanStepUpdate(ctx context.Context, plan *TaskPlan, step *PlanStep) (context.Context, error)
	OnPlanStepStatusUpdate(ctx context.Context, plan *TaskPlan, step *PlanStep) (context.Context, error)
	OnPlanStepDelete(ctx context.Context, plan *TaskPlan, step *PlanStep) (context.Context, error)
	OnPlanOpEnd(ctx context.Context, plan *TaskPlan) (context.Context, error)
}

type PlanStep

type PlanStep struct {
	ID                 string         `json:"id"`
	Name               string         `json:"name"`
	Description        string         `json:"description"`
	AssignedSpecialist string         `json:"assignedSpecialist"`
	Priority           int            `json:"priority"`
	Status             StepStatus     `json:"status"`
	Dependencies       []string       `json:"dependencies,omitempty"`
	Parameters         map[string]any `json:"parameters,omitempty"`
	Result             *StepResult    `json:"result,omitempty"`
	Metadata           map[string]any `json:"metadata,omitempty"`
}

PlanStep represents a single step in a task plan

type PlanUpdate

type PlanUpdate struct {
	UpdateReason string           `json:"update_reason"`
	Operations   []*OperationData `json:"operations"`
	PlanMetadata *struct {
		Name        string `json:"name,omitempty"`
		Description string `json:"description,omitempty"`
	} `json:"plan_metadata,omitempty"`
}

PlanUpdateData represents the data for a plan update

type PlanUpdateHandler

type PlanUpdateHandler struct {
	// contains filtered or unexported fields
}

PlanUpdateHandler handles the plan update process

func NewPlanUpdateHandler

func NewPlanUpdateHandler(config *MultiAgentConfig) *PlanUpdateHandler

func (*PlanUpdateHandler) PostHandler

func (h *PlanUpdateHandler) PostHandler(ctx context.Context, output *schema.Message, state *MultiAgentState) (*schema.Message, error)

func (*PlanUpdateHandler) PreHandler

func (h *PlanUpdateHandler) PreHandler(ctx context.Context, input []*schema.Message, state *MultiAgentState) ([]*schema.Message, error)

type PlanUpdateType

type PlanUpdateType string

PlanUpdateType represents the type of plan update

const (
	PlanUpdateTypeUnknown          PlanUpdateType = "unknown"
	PlanUpdateTypeStepAdd          PlanUpdateType = "step_add"
	PlanUpdateTypeStepModify       PlanUpdateType = "step_modify"
	PlanUpdateTypeStepRemove       PlanUpdateType = "step_remove"
	PlanUpdateTypeStepReorder      PlanUpdateType = "step_reorder"
	PlanUpdateTypePriorityChange   PlanUpdateType = "priority_change"
	PlanUpdateTypeDependencyChange PlanUpdateType = "dependency_change"
	PlanUpdateTypeResourceChange   PlanUpdateType = "resource_change"
	PlanUpdateTypeStrategyChange   PlanUpdateType = "strategy_change"
)

type PlanningConfig

type PlanningConfig struct {
	PlanningPrompt string `yaml:"planning_prompt" json:"planning_prompt"`
}

PlanningConfig represents planning configuration

type ReflectionBranchHandler

type ReflectionBranchHandler struct {
	// contains filtered or unexported fields
}

ReflectionBranchHandler handles the decision logic for reflection branches

func NewReflectionBranchHandler

func NewReflectionBranchHandler(config *MultiAgentConfig) *ReflectionBranchHandler

type ResultCollectorHandler

type ResultCollectorHandler struct {
	// contains filtered or unexported fields
}

ResultCollectorHandler handles result collection and summarization

func NewResultCollectorHandler

func NewResultCollectorHandler(config *MultiAgentConfig) *ResultCollectorHandler

NewResultCollectorHandler creates a new result collector handler

func (*ResultCollectorHandler) ResultCollector

func (h *ResultCollectorHandler) ResultCollector(ctx context.Context, input []*schema.Message, state *MultiAgentState) (*schema.Message, error)

ResultCollectorLambda collects and summarizes specialist results

type SessionConfig

type SessionConfig struct {
	HistoryLength     int            `yaml:"history_length" json:"history_length"`
	ContextWindow     int            `yaml:"context_window" json:"context_window"`
	ContextProcessing map[string]any `yaml:"context_processing,omitempty" json:"context_processing,omitempty"`
	IntentAnalysis    map[string]any `yaml:"intent_analysis,omitempty" json:"intent_analysis,omitempty"`
	Persistence       map[string]any `yaml:"persistence,omitempty" json:"persistence,omitempty"`
}

SessionConfig represents session management configuration

type Specialist

type Specialist struct {
	Name         string `yaml:"name" json:"name"`
	IntendedUse  string `yaml:"intended_use" json:"intended_use"`
	ChatModel    model.BaseChatModel
	SystemPrompt string `yaml:"system_prompt" json:"system_prompt"`
	Invokable    compose.Invoke[[]*schema.Message, *schema.Message, base.AgentOption]
	Streamable   compose.Stream[[]*schema.Message, *schema.Message, base.AgentOption]
	ReactAgent   *react.ReactAgent
}

Specialist represents a specialist agent configuration

type SpecialistBranchHandler

type SpecialistBranchHandler struct {
	// contains filtered or unexported fields
}

SpecialistBranchHandler handles specialist selection and branching

func NewSpecialistBranchHandler

func NewSpecialistBranchHandler(config *MultiAgentConfig) *SpecialistBranchHandler

NewSpecialistBranchHandler creates a new specialist branch handler

func (*SpecialistBranchHandler) Evaluate

func (h *SpecialistBranchHandler) Evaluate(ctx context.Context, state *MultiAgentState) (string, error)

Evaluate determines which specialist should handle the current step

type SpecialistHandler

type SpecialistHandler struct {
	// contains filtered or unexported fields
}

SpecialistHandler handles specialist execution

func NewSpecialistHandler

func NewSpecialistHandler(specialist *Specialist) *SpecialistHandler

NewSpecialistHandler creates a new specialist handler

func (*SpecialistHandler) PostHandler

func (h *SpecialistHandler) PostHandler(ctx context.Context, output *schema.Message, state *MultiAgentState) (*schema.Message, error)

PostHandler processes specialist execution results

func (*SpecialistHandler) PreHandler

func (h *SpecialistHandler) PreHandler(ctx context.Context, input []*schema.Message, state *MultiAgentState) ([]*schema.Message, error)

PreHandler prepares input for specialist execution

type StatePostHandler

type StatePostHandler[O any] func(ctx context.Context, output O, state *MultiAgentState) (O, error)

StatePostHandler handles state updates after node execution

type StatePreHandler

type StatePreHandler[I any] func(ctx context.Context, input I, state *MultiAgentState) (I, error)

StatePreHandler handles state preparation before node execution

type StepData

type StepData struct {
	ID                 string         `json:"id"`
	Name               string         `json:"name"`
	Description        string         `json:"description"`
	AssignedSpecialist string         `json:"assignedSpecialist"`
	Priority           int            `json:"priority"`
	Dependencies       []string       `json:"dependencies,omitempty"`
	Parameters         map[string]any `json:"parameters,omitempty"`
}

type StepResult

type StepResult struct {
	Success      bool            `json:"success"`
	Target       string          `json:"target,omitempty"`
	Output       *schema.Message `json:"output"`
	Error        string          `json:"error,omitempty"`
	Confidence   float64         `json:"confidence"`
	QualityScore float64         `json:"qualityScore"`
	Metadata     map[string]any  `json:"metadata,omitempty"`
}

StepResult represents the result of executing a plan step

type StepStatus

type StepStatus string

StepStatus represents the status of a plan step

const (
	StepStatusUnknown   StepStatus = "unknown"
	StepStatusPending   StepStatus = "pending"
	StepStatusRunning   StepStatus = "running"
	StepStatusCompleted StepStatus = "completed"
	StepStatusFailed    StepStatus = "failed"
	StepStatusSkipped   StepStatus = "skipped"
)

type TaskComplexity

type TaskComplexity string

TaskComplexity represents the complexity level of a task

const (
	TaskComplexityUnknown     TaskComplexity = "unknown"
	TaskComplexitySimple      TaskComplexity = "simple"
	TaskComplexityModerate    TaskComplexity = "moderate"
	TaskComplexityComplex     TaskComplexity = "complex"
	TaskComplexityVeryComplex TaskComplexity = "very_complex"
)

type TaskPlan

type TaskPlan struct {
	ID          string          `json:"id"`
	Version     int             `json:"version"`
	Name        string          `json:"name"`
	Description string          `json:"description"`
	Status      ExecutionStatus `json:"status"`
	CreatedAt   time.Time       `json:"created_at"`
	UpdatedAt   time.Time       `json:"updated_at"`
	Steps       []*PlanStep     `json:"steps"`
	PlanUpdate  *PlanUpdate     `json:"plan_update,omitempty"`
	Metadata    map[string]any  `json:"metadata,omitempty"`
}

TaskPlan represents a complete task execution plan

type ThinkingConfig

type ThinkingConfig struct {
	MaxSteps       int    `yaml:"max_steps" json:"max_steps"`
	ThinkingPrompt string `yaml:"thinking_prompt" json:"thinking_prompt"`
}

ThinkingConfig represents thinking configuration

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL