multiagent

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Nov 27, 2025 License: Apache-2.0 Imports: 15 Imported by: 0

Documentation

Overview

Package multiagent provides multi-agent collaboration capabilities

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func SetDefaultChannelStore

func SetDefaultChannelStore(store ChannelStore)

SetDefaultChannelStore 设置全局默认的 ChannelStore(用于第三方实现)

Types

type AgentMessage

type AgentMessage struct {
	ID           string                 `json:"id"`
	From         string                 `json:"from"`
	To           string                 `json:"to"`
	Topic        string                 `json:"topic"`
	Type         MessageType            `json:"type"`
	Payload      interface{}            `json:"payload"`
	Metadata     map[string]string      `json:"metadata"`
	Timestamp    time.Time              `json:"timestamp"`
	TraceContext propagation.MapCarrier `json:"trace_context,omitempty"` // 追踪上下文
}

AgentMessage 消息(为避免与 Message 冲突)

func NewAgentMessage

func NewAgentMessage(from, to string, msgType MessageType, payload interface{}) *AgentMessage

NewAgentMessage 创建新消息

type AgentSession

type AgentSession struct {
	ID           string
	Participants []string
	Messages     []*AgentMessage
	State        map[string]interface{}
	CreatedAt    string
	UpdatedAt    string
}

AgentSession Agent 会话

type Assignment

type Assignment struct {
	AgentID   string      `json:"agent_id"`
	Role      Role        `json:"role"`
	Subtask   interface{} `json:"subtask"`
	Status    TaskStatus  `json:"status"`
	Result    interface{} `json:"result,omitempty"`
	StartTime time.Time   `json:"start_time,omitempty"`
	EndTime   time.Time   `json:"end_time,omitempty"`
}

Assignment represents an agent's assignment in a task

type BaseCollaborativeAgent

type BaseCollaborativeAgent struct {
	*core.BaseAgent
	// contains filtered or unexported fields
}

BaseCollaborativeAgent provides a base implementation of CollaborativeAgent

func NewBaseCollaborativeAgent

func NewBaseCollaborativeAgent(id, description string, role Role, system *MultiAgentSystem) *BaseCollaborativeAgent

NewBaseCollaborativeAgent creates a new base collaborative agent

func (*BaseCollaborativeAgent) Collaborate

Collaborate participates in a collaborative task

func (*BaseCollaborativeAgent) Execute

Execute implements the Agent interface

func (*BaseCollaborativeAgent) GetRole

func (a *BaseCollaborativeAgent) GetRole() Role

GetRole returns the agent's role

func (*BaseCollaborativeAgent) ReceiveMessage

func (a *BaseCollaborativeAgent) ReceiveMessage(ctx context.Context, message Message) error

ReceiveMessage handles incoming messages

func (*BaseCollaborativeAgent) SendMessage

func (a *BaseCollaborativeAgent) SendMessage(ctx context.Context, message Message) error

SendMessage sends a message to another agent

func (*BaseCollaborativeAgent) SetRole

func (a *BaseCollaborativeAgent) SetRole(role Role)

SetRole sets the agent's role

func (*BaseCollaborativeAgent) Vote

func (a *BaseCollaborativeAgent) Vote(ctx context.Context, proposal interface{}) (bool, error)

Vote participates in consensus decision making

type ChannelStore

type ChannelStore interface {
	// GetOrCreateChannel 获取或创建指定 agent 的消息 channel
	GetOrCreateChannel(agentID string) chan *AgentMessage

	// GetChannel 获取指定 agent 的消息 channel,如果不存在返回 nil
	GetChannel(agentID string) chan *AgentMessage

	// ListChannels 列出所有 channel 的 agent ID
	ListChannels() []string

	// Subscribe 订阅主题,返回接收消息的 channel
	Subscribe(topic string) <-chan *AgentMessage

	// Unsubscribe 取消订阅主题
	Unsubscribe(topic string)

	// GetSubscribers 获取指定主题的所有订阅者 channel
	GetSubscribers(topic string) []chan *AgentMessage

	// Close 关闭存储(可选的清理操作)
	Close() error
}

ChannelStore 定义 channel 存储接口,允许第三方实现不同的存储后端 例如:内存、Redis、NATS、Kafka 等

type CollaborationType

type CollaborationType string

CollaborationType defines the type of collaboration

const (
	CollaborationTypeParallel     CollaborationType = "parallel"
	CollaborationTypeSequential   CollaborationType = "sequential"
	CollaborationTypeHierarchical CollaborationType = "hierarchical"
	CollaborationTypeConsensus    CollaborationType = "consensus"
	CollaborationTypePipeline     CollaborationType = "pipeline"
)

type CollaborativeAgent

type CollaborativeAgent interface {
	core.Agent

	// GetRole returns the agent's role
	GetRole() Role

	// SetRole sets the agent's role
	SetRole(role Role)

	// ReceiveMessage handles incoming messages
	ReceiveMessage(ctx context.Context, message Message) error

	// SendMessage sends a message to another agent
	SendMessage(ctx context.Context, message Message) error

	// Collaborate participates in a collaborative task
	Collaborate(ctx context.Context, task *CollaborativeTask) (*Assignment, error)

	// Vote participates in consensus decision making
	Vote(ctx context.Context, proposal interface{}) (bool, error)
}

CollaborativeAgent interface for agents that can collaborate

type CollaborativeTask

type CollaborativeTask struct {
	ID          string                 `json:"id"`
	Name        string                 `json:"name"`
	Description string                 `json:"description"`
	Type        CollaborationType      `json:"type"`
	Input       interface{}            `json:"input"`
	Output      interface{}            `json:"output,omitempty"`
	Status      TaskStatus             `json:"status"`
	Assignments map[string]Assignment  `json:"assignments"`
	Results     map[string]interface{} `json:"results"`
	StartTime   time.Time              `json:"start_time"`
	EndTime     time.Time              `json:"end_time,omitempty"`
	Metadata    map[string]interface{} `json:"metadata,omitempty"`
}

CollaborativeTask represents a task for multi-agent collaboration

type Communicator

type Communicator interface {
	// Send 发送消息
	Send(ctx context.Context, to string, message *AgentMessage) error

	// Receive 接收消息
	Receive(ctx context.Context) (*AgentMessage, error)

	// Broadcast 广播消息
	Broadcast(ctx context.Context, message *AgentMessage) error

	// Subscribe 订阅主题
	Subscribe(ctx context.Context, topic string) (<-chan *AgentMessage, error)

	// Unsubscribe 取消订阅
	Unsubscribe(ctx context.Context, topic string) error

	// Close 关闭
	Close() error
}

Communicator Agent 通信器接口

type InMemoryChannelStore

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

InMemoryChannelStore 内存实现的 ChannelStore

func NewInMemoryChannelStore

func NewInMemoryChannelStore() *InMemoryChannelStore

NewInMemoryChannelStore 创建内存 channel 存储

func (*InMemoryChannelStore) Close

func (s *InMemoryChannelStore) Close() error

Close 实现 ChannelStore 接口

func (*InMemoryChannelStore) GetChannel

func (s *InMemoryChannelStore) GetChannel(agentID string) chan *AgentMessage

GetChannel 实现 ChannelStore 接口

func (*InMemoryChannelStore) GetOrCreateChannel

func (s *InMemoryChannelStore) GetOrCreateChannel(agentID string) chan *AgentMessage

GetOrCreateChannel 实现 ChannelStore 接口

func (*InMemoryChannelStore) GetSubscribers

func (s *InMemoryChannelStore) GetSubscribers(topic string) []chan *AgentMessage

GetSubscribers 实现 ChannelStore 接口

func (*InMemoryChannelStore) ListChannels

func (s *InMemoryChannelStore) ListChannels() []string

ListChannels 实现 ChannelStore 接口

func (*InMemoryChannelStore) Subscribe

func (s *InMemoryChannelStore) Subscribe(topic string) <-chan *AgentMessage

Subscribe 实现 ChannelStore 接口

func (*InMemoryChannelStore) Unsubscribe

func (s *InMemoryChannelStore) Unsubscribe(topic string)

Unsubscribe 实现 ChannelStore 接口

type MemoryCommunicator

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

MemoryCommunicator 内存通信器(单机多Agent)

func NewMemoryCommunicator

func NewMemoryCommunicator(agentID string) *MemoryCommunicator

NewMemoryCommunicator 创建内存通信器,使用全局默认的 ChannelStore

func NewMemoryCommunicatorWithStore

func NewMemoryCommunicatorWithStore(agentID string, store ChannelStore) *MemoryCommunicator

NewMemoryCommunicatorWithStore 创建内存通信器,使用指定的 ChannelStore

func (*MemoryCommunicator) Broadcast

func (c *MemoryCommunicator) Broadcast(ctx context.Context, message *AgentMessage) error

Broadcast 广播消息

func (*MemoryCommunicator) Close

func (c *MemoryCommunicator) Close() error

Close 关闭

func (*MemoryCommunicator) Receive

func (c *MemoryCommunicator) Receive(ctx context.Context) (*AgentMessage, error)

Receive 接收消息

func (*MemoryCommunicator) Send

func (c *MemoryCommunicator) Send(ctx context.Context, to string, message *AgentMessage) error

Send 发送消息

func (*MemoryCommunicator) Subscribe

func (c *MemoryCommunicator) Subscribe(ctx context.Context, topic string) (<-chan *AgentMessage, error)

Subscribe 订阅主题

func (*MemoryCommunicator) Unsubscribe

func (c *MemoryCommunicator) Unsubscribe(ctx context.Context, topic string) error

Unsubscribe 取消订阅

type Message

type Message struct {
	ID        string                 `json:"id"`
	From      string                 `json:"from"`
	To        string                 `json:"to"`
	Type      MessageType            `json:"type"`
	Content   interface{}            `json:"content"`
	Priority  int                    `json:"priority"`
	Timestamp time.Time              `json:"timestamp"`
	ReplyTo   string                 `json:"reply_to,omitempty"`
	Metadata  map[string]interface{} `json:"metadata,omitempty"`
}

Message represents a message between agents

type MessageRouter

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

MessageRouter 消息路由器

func NewMessageRouter

func NewMessageRouter() *MessageRouter

NewAgentMessageRouter 创建消息路由器

func (*MessageRouter) RegisterPatternRoute

func (r *MessageRouter) RegisterPatternRoute(pattern string, handler RouteHandler) error

RegisterPatternRoute 注册模式路由(正则)

func (*MessageRouter) RegisterRoute

func (r *MessageRouter) RegisterRoute(pattern string, handler RouteHandler) error

RegisterRoute 注册路由

func (*MessageRouter) Route

func (r *MessageRouter) Route(ctx context.Context, message *AgentMessage) (*AgentMessage, error)

Route 路由消息

func (*MessageRouter) UnregisterRoute

func (r *MessageRouter) UnregisterRoute(pattern string)

UnregisterRoute 注销路由

type MessageType

type MessageType string

MessageType defines the type of message

const (
	MessageTypeRequest      MessageType = "request"
	MessageTypeResponse     MessageType = "response"
	MessageTypeBroadcast    MessageType = "broadcast"
	MessageTypeNotification MessageType = "notification"
	MessageTypeCommand      MessageType = "command"
	MessageTypeReport       MessageType = "report"
	MessageTypeVote         MessageType = "vote"
)

type MultiAgentSystem

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

MultiAgentSystem manages multiple agents working together

func NewMultiAgentSystem

func NewMultiAgentSystem(log loggercore.Logger, opts ...SystemOption) *MultiAgentSystem

NewMultiAgentSystem creates a new multi-agent system

func (*MultiAgentSystem) CreateTeam

func (s *MultiAgentSystem) CreateTeam(team *Team) error

CreateTeam creates a new team of agents

func (*MultiAgentSystem) ExecuteTask

ExecuteTask executes a collaborative task

func (*MultiAgentSystem) RegisterAgent

func (s *MultiAgentSystem) RegisterAgent(id string, agent CollaborativeAgent) error

RegisterAgent registers an agent in the system

func (*MultiAgentSystem) SendMessage

func (s *MultiAgentSystem) SendMessage(message Message) error

SendMessage sends a message between agents

func (*MultiAgentSystem) UnregisterAgent

func (s *MultiAgentSystem) UnregisterAgent(id string) error

UnregisterAgent removes an agent from the system

type NATSCommunicator

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

NATSCommunicator NATS 通信器(分布式)

func NewNATSCommunicator

func NewNATSCommunicator(agentID string, config *NATSConfig) (*NATSCommunicator, error)

NewNATSCommunicator 创建 NATS 通信器

func (*NATSCommunicator) Broadcast

func (c *NATSCommunicator) Broadcast(ctx context.Context, message *AgentMessage) error

Broadcast 广播消息

func (*NATSCommunicator) Close

func (c *NATSCommunicator) Close() error

Close 关闭

func (*NATSCommunicator) Receive

func (c *NATSCommunicator) Receive(ctx context.Context) (*AgentMessage, error)

Receive 接收消息

func (*NATSCommunicator) Send

func (c *NATSCommunicator) Send(ctx context.Context, to string, message *AgentMessage) error

Send 发送消息

func (*NATSCommunicator) Subscribe

func (c *NATSCommunicator) Subscribe(ctx context.Context, topic string) (<-chan *AgentMessage, error)

Subscribe 订阅主题

func (*NATSCommunicator) Unsubscribe

func (c *NATSCommunicator) Unsubscribe(ctx context.Context, topic string) error

Unsubscribe 取消订阅

type NATSConfig

type NATSConfig struct {
	URL         string
	ClusterID   string
	Credentials string
	TLS         *tls.Config
}

NATSConfig NATS 配置

type NegotiatingAgent

type NegotiatingAgent struct {
	*BaseCollaborativeAgent
	// contains filtered or unexported fields
}

NegotiatingAgent demonstrates an agent that can negotiate

func NewNegotiatingAgent

func NewNegotiatingAgent(id string, system *MultiAgentSystem) *NegotiatingAgent

NewNegotiatingAgent creates a new negotiating agent

func (*NegotiatingAgent) Negotiate

func (a *NegotiatingAgent) Negotiate(ctx context.Context, proposal interface{}, partners []string) (interface{}, error)

Negotiate conducts negotiation with other agents

type NegotiationRound

type NegotiationRound struct {
	Round    int                    `json:"round"`
	Proposal interface{}            `json:"proposal"`
	Offers   map[string]interface{} `json:"offers"`
	Accepted bool                   `json:"accepted"`
}

NegotiationRound represents a round of negotiation

type Role

type Role string

Role defines the role of an agent in collaboration

const (
	RoleLeader      Role = "leader"
	RoleWorker      Role = "worker"
	RoleCoordinator Role = "coordinator"
	RoleSpecialist  Role = "specialist"
	RoleValidator   Role = "validator"
	RoleObserver    Role = "observer"
)

type RouteHandler

type RouteHandler func(ctx context.Context, message *AgentMessage) (*AgentMessage, error)

RouteHandler 路由处理器

type SessionManager

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

SessionManager 会话管理器

func NewSessionManager

func NewSessionManager() *SessionManager

NewSessionManager 创建会话管理器

func (*SessionManager) AddMessage

func (m *SessionManager) AddMessage(sessionID string, message *AgentMessage) error

AddMessage 添加消息到会话

func (*SessionManager) CloseSession

func (m *SessionManager) CloseSession(sessionID string) error

CloseSession 关闭会话

func (*SessionManager) CreateSession

func (m *SessionManager) CreateSession(participants []string) (*AgentSession, error)

CreateSession 创建会话

func (*SessionManager) GetSession

func (m *SessionManager) GetSession(sessionID string) (*AgentSession, error)

GetSession 获取会话

type SpecializedAgent

type SpecializedAgent struct {
	*BaseCollaborativeAgent
	// contains filtered or unexported fields
}

SpecializedAgent demonstrates a specialized collaborative agent

func NewSpecializedAgent

func NewSpecializedAgent(id, specialization string, system *MultiAgentSystem) *SpecializedAgent

NewSpecializedAgent creates a new specialized agent

func (*SpecializedAgent) Collaborate

func (a *SpecializedAgent) Collaborate(ctx context.Context, task *CollaborativeTask) (*Assignment, error)

Collaborate overrides base collaboration with specialized logic

type SystemOption

type SystemOption func(*MultiAgentSystem)

SystemOption configures the multi-agent system

func WithMaxAgents

func WithMaxAgents(max int) SystemOption

WithMaxAgents sets the maximum number of agents

func WithTimeout

func WithTimeout(timeout time.Duration) SystemOption

WithTimeout sets the default timeout

type TaskStatus

type TaskStatus string

TaskStatus represents the status of a task

const (
	TaskStatusPending   TaskStatus = "pending"
	TaskStatusAssigned  TaskStatus = "assigned"
	TaskStatusExecuting TaskStatus = "executing"
	TaskStatusCompleted TaskStatus = "completed"
	TaskStatusFailed    TaskStatus = "failed"
	TaskStatusCancelled TaskStatus = "cancelled"
)

type Team

type Team struct {
	ID           string                 `json:"id"`
	Name         string                 `json:"name"`
	Leader       string                 `json:"leader"`
	Members      []string               `json:"members"`
	Purpose      string                 `json:"purpose"`
	Capabilities []string               `json:"capabilities"`
	Metadata     map[string]interface{} `json:"metadata,omitempty"`
}

Team represents a team of agents

Jump to

Keyboard shortcuts

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