agents

package
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Feb 4, 2025 License: MIT Imports: 18 Imported by: 0

Documentation

Index

Constants

View Source
const (
	CapabilityTaskPlanning = "task_planning"
	CapabilityLevelBasic   = 1
)

Capability constants

Variables

This section is empty.

Functions

func NewTaskRequirements

func NewTaskRequirements() *capabilities.TaskRequirements

NewTaskRequirements creates a new task requirements instance

Types

type Agent

type Agent struct {
	Name                  string
	Role                  string
	Goals                 []string
	Backstory             string
	KnowledgeSources      []KnowledgeSource
	Memory                *memory.BaseMemory
	Tools                 []core.Tool
	LLMProvider           core.LLMProvider
	Executor              *core.Executor
	Config                *AgentConfig
	Capabilities          *AgentCapabilities
	TaskMonitor           *TaskMonitor
	Priority              tasks.TaskPriority
	MaxWorkload           int
	CurrentTasks          int
	Performance           map[string]float64
	DelegationPrefs       *DelegationPreference
	CollaborationScore    float64
	SupervisionNeeded     bool
	LastCollaborators     []string
	SuccessfulDelegations int
	FailedDelegations     int

	PriorityQueue    *PriorityQueue
	PriorityStrategy string
	PriorityWeights  map[string]float64 // Weights for different priority factors

	DelegationStats    *DelegationStats
	DelegationHistory  []DelegationResult
	PreferredDelegates map[string]float64 // Agent ID -> success rate

	FeedbackMetrics   *FeedbackMetrics
	LearningRate      float64
	AdaptationHistory []string
	// contains filtered or unexported fields
}

Agent represents an AI agent that can execute tasks

func NewAgent

func NewAgent(name string, role string, goals []string, provider core.LLMProvider) *Agent

NewAgent creates a new agent instance

func (*Agent) AddCollaborator

func (a *Agent) AddCollaborator(collaborator string)

AddCollaborator records a successful collaboration with another agent

func (*Agent) AddTask

func (a *Agent) AddTask(task *tasks.Task) error

AddTask adds a task to the priority queue

func (*Agent) AdjustLearningRate

func (a *Agent) AdjustLearningRate(performance float64)

AdjustLearningRate adjusts the learning rate based on performance

func (*Agent) AssessTaskPriority

func (a *Agent) AssessTaskPriority(task *tasks.Task) tasks.TaskPriority

AssessTaskPriority evaluates and returns the agent's assessment of task priority

func (*Agent) CalculateTaskPriority

func (a *Agent) CalculateTaskPriority(task *tasks.Task) float64

CalculateTaskPriority computes a priority score for a task

func (*Agent) CanAcceptTask

func (a *Agent) CanAcceptTask(taskPriority tasks.TaskPriority) bool

CanAcceptTask checks if agent can take on new task based on priority and workload

func (*Agent) CanDelegate

func (a *Agent) CanDelegate(task *tasks.Task, targetAgent *Agent) (bool, DelegationType, []string)

CanDelegate checks if the agent can delegate a specific task

func (*Agent) CanHandleTask

func (a *Agent) CanHandleTask(reqs *capabilities.TaskRequirements) (bool, []string, error)

CanHandleTask checks if the agent can handle the given task requirements

func (*Agent) DecrementTasks

func (a *Agent) DecrementTasks()

DecrementTasks decreases current task count

func (*Agent) DelegateTask

func (a *Agent) DelegateTask(ctx context.Context, task *tasks.Task, targetAgent *Agent) (*DelegationResult, error)

DelegateTask attempts to delegate a task to another agent

func (*Agent) ExecuteTask

func (a *Agent) ExecuteTask(ctx context.Context, taskDescription string, expectedOutput string, taskContext string) (string, error)

ExecuteTask executes a task with the given description

func (*Agent) FindBestDelegate

func (a *Agent) FindBestDelegate(task *tasks.Task, agents []*Agent) *Agent

FindBestDelegate finds the most suitable agent for delegation

func (*Agent) GetDelegationScore

func (a *Agent) GetDelegationScore() float64

GetDelegationScore returns a score indicating how well the agent handles delegations

func (*Agent) GetDelegationStats

func (a *Agent) GetDelegationStats() *DelegationStats

GetDelegationStats returns current delegation statistics

func (*Agent) GetInvolvedAgents

func (a *Agent) GetInvolvedAgents(conflict *types.Conflict) []*Agent

GetInvolvedAgents returns the Agent objects for the agent IDs in the conflict

func (*Agent) GetNextTask

func (a *Agent) GetNextTask() *tasks.Task

GetNextTask gets the next task from the priority queue

func (*Agent) GetPerformanceReport

func (a *Agent) GetPerformanceReport() map[string]interface{}

GetPerformanceReport generates a performance report

func (*Agent) GetPerformanceScore

func (a *Agent) GetPerformanceScore() float64

GetPerformanceScore returns overall performance score

func (*Agent) GetResourceRequirements

func (a *Agent) GetResourceRequirements(ctx context.Context, task *tasks.Task) (map[string]int, error)

GetResourceRequirements returns the agent's resource needs for a task

func (*Agent) GetTaskApproach

func (a *Agent) GetTaskApproach(ctx context.Context, task *tasks.Task) (string, error)

GetTaskApproach returns the agent's approach to executing a task

func (*Agent) GetVoteDecision

func (a *Agent) GetVoteDecision(ctx context.Context, voteContext string) (string, string, error)

GetVoteDecision asks the agent to vote on a task with explanation

func (*Agent) IncrementTasks

func (a *Agent) IncrementTasks()

IncrementTasks increases current task count

func (*Agent) InitializeMemory

func (a *Agent) InitializeMemory(workDir string, config *memory.MemoryConfig) error

InitializeMemory initializes memory components for the agent

func (*Agent) Mediate

func (a *Agent) Mediate(ctx context.Context, conflict *types.Conflict) (string, error)

Mediate has the agent act as a mediator for a conflict

func (*Agent) ProcessTaskFeedback

func (a *Agent) ProcessTaskFeedback(task *tasks.Task, success bool, executionTime time.Duration, feedback string)

ProcessTaskFeedback processes feedback after task completion

func (*Agent) ResolveConflict

func (a *Agent) ResolveConflict(ctx context.Context, conflict *types.Conflict) (string, error)

ResolveConflict has the agent make a decision about a conflict

func (*Agent) UpdateCollaborationScore

func (a *Agent) UpdateCollaborationScore(score float64)

UpdateCollaborationScore updates the agent's collaboration effectiveness score

func (*Agent) UpdateDelegationFeedback

func (a *Agent) UpdateDelegationFeedback(result *DelegationResult)

UpdateDelegationFeedback updates delegation success metrics

func (*Agent) UpdateDelegationStats

func (a *Agent) UpdateDelegationStats(success bool)

UpdateDelegationStats updates delegation success/failure statistics

func (*Agent) UpdatePerformance

func (a *Agent) UpdatePerformance(metric string, value float64)

UpdatePerformance records agent's performance for a task

func (*Agent) WithCapability

func (a *Agent) WithCapability(cap capabilities.Capability, level capabilities.CapabilityLevel) error

WithCapability adds or updates a capability for the agent

func (*Agent) WithCodeExecution

func (a *Agent) WithCodeExecution(allow bool, mode string) *Agent

WithCodeExecution adds code execution capabilities to the agent

func (*Agent) WithDelegationPreferences

func (a *Agent) WithDelegationPreferences(prefs *DelegationPreference) *Agent

WithDelegationPreferences sets the agent's delegation preferences

func (*Agent) WithKnowledge

func (a *Agent) WithKnowledge(sources ...KnowledgeSource) error

WithKnowledge adds knowledge sources to the agent

func (*Agent) WithMaxRetryLimit

func (a *Agent) WithMaxRetryLimit(limit int) *Agent

WithMaxRetryLimit sets the maximum retry limit for task execution

func (*Agent) WithMaxWorkload

func (a *Agent) WithMaxWorkload(max int) error

WithMaxWorkload sets the agent's maximum concurrent tasks

func (*Agent) WithMemory

func (a *Agent) WithMemory(storage memory.Storage, config *memory.MemoryConfig) error

WithMemory adds memory capabilities to the agent

func (*Agent) WithMultimodal

func (a *Agent) WithMultimodal(enabled bool) *Agent

WithMultimodal adds multimodal capabilities to the agent

func (*Agent) WithPriority

func (a *Agent) WithPriority(priority tasks.TaskPriority) error

WithPriority sets the agent's priority level

func (*Agent) WithPriorityStrategy

func (a *Agent) WithPriorityStrategy(strategy string, weights map[string]float64) error

WithPriorityStrategy sets the agent's priority handling strategy

func (*Agent) WithTools

func (a *Agent) WithTools(tools ...core.Tool) *Agent

WithTools adds tools to the agent

type AgentCapabilities

type AgentCapabilities struct {
	Capabilities       map[capabilities.Capability]capabilities.CapabilityLevel
	Priority           int
	MaxConcurrentTasks int
	CurrentTasks       int
}

AgentCapabilities represents an agent's capabilities and limitations

func NewAgentCapabilities

func NewAgentCapabilities() *AgentCapabilities

NewAgentCapabilities creates a new capabilities instance

func (*AgentCapabilities) CanAcceptTask

func (ac *AgentCapabilities) CanAcceptTask() bool

CanAcceptTask checks if agent can accept more tasks based on capabilities

type AgentConfig

type AgentConfig struct {
	AllowDelegation    bool
	AllowCodeExecution bool
	CodeExecutionMode  string // "safe" or "unsafe"
	Multimodal         bool
	MaxRetryLimit      int
}

AgentConfig holds configuration for an agent

type AgentExecutor

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

AgentExecutor wraps the core executor with agent-specific functionality

func NewAgentExecutor

func NewAgentExecutor(agent *Agent, tools []core.Tool, opts ...execution.ExecutorOption) *AgentExecutor

NewAgentExecutor creates a new agent executor instance

func (*AgentExecutor) ExecuteTask

func (e *AgentExecutor) ExecuteTask(ctx context.Context, taskDescription string, expectedOutput string, taskContext string) (string, error)

ExecuteTask executes a specific task with context

type AgentOption

type AgentOption func(*Agent)

AgentOption defines functional options for configuring an agent

type AssignedTaskPriority

type AssignedTaskPriority struct {
	Priority     tasks.TaskPriority
	Deadline     time.Time
	Importance   float64
	Urgency      float64
	Dependencies []string
}

AssignedTaskPriority represents the priority level of a task

type CapabilityMatch

type CapabilityMatch struct {
	Score   float64
	Reasons []string
}

CalculateMatch calculates how well an agent matches task requirements

func CalculateMatch

func CalculateMatch(agentName string, capabilities *AgentCapabilities, reqs *capabilities.TaskRequirements) *CapabilityMatch

type CommunicationChannel

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

CommunicationChannel manages message exchange between agents

func NewCommunicationChannel

func NewCommunicationChannel(memory *memory.SharedMemory) *CommunicationChannel

NewCommunicationChannel creates a new communication channel

func (*CommunicationChannel) AcknowledgeMessage

func (cc *CommunicationChannel) AcknowledgeMessage(msgID string) error

AcknowledgeMessage marks a message as read

func (*CommunicationChannel) ClearExpiredMessages

func (cc *CommunicationChannel) ClearExpiredMessages()

ClearExpiredMessages removes expired messages

func (*CommunicationChannel) GetMessageStatus

func (cc *CommunicationChannel) GetMessageStatus(msgID string) (MessageStatus, bool)

GetMessageStatus returns the status of a message

func (*CommunicationChannel) GetMessages

func (cc *CommunicationChannel) GetMessages(agentID string, unreadOnly bool) []*Message

GetMessages retrieves messages for an agent

func (*CommunicationChannel) SendMessage

func (cc *CommunicationChannel) SendMessage(ctx context.Context, msg *Message) error

SendMessage sends a message from one agent to another

func (*CommunicationChannel) SendMessageWithProtocol

func (cc *CommunicationChannel) SendMessageWithProtocol(ctx context.Context, msg *Message, protocol ProtocolType) error

SendMessageWithProtocol sends a message using a specific protocol

func (*CommunicationChannel) SetDefaultProtocol

func (cc *CommunicationChannel) SetDefaultProtocol(protocol ProtocolType)

SetDefaultProtocol sets the default protocol for message delivery

type DelegationPreference

type DelegationPreference struct {
	PreferredTypes    []DelegationType
	CollaborationTags []string
	SupervisorRoles   []string
	ExcludedTasks     []string
}

DelegationPreference represents an agent's delegation preferences

type DelegationResult

type DelegationResult struct {
	Success      bool
	AgentID      string
	TaskID       string
	ErrorMessage string
	Feedback     string
}

DelegationResult represents the result of a task delegation

type DelegationStats

type DelegationStats struct {
	TotalDelegations      int
	SuccessfulDelegations int
	FailedDelegations     int
	AverageSuccessRate    float64
	PreferredAgents       map[string]int
	TaskTypes             map[string]int
}

DelegationStats tracks delegation performance

type DelegationType

type DelegationType string

DelegationType represents how a task can be delegated

const (
	// DirectDelegation - agent can directly execute the task
	DirectDelegation DelegationType = "direct"
	// CollaborativeDelegation - agent needs to collaborate with others
	CollaborativeDelegation DelegationType = "collaborative"
	// SupervisedDelegation - agent needs supervision
	SupervisedDelegation DelegationType = "supervised"
)

type Experience

type Experience struct {
	// ID uniquely identifies this experience
	ID string

	// AgentID identifies the agent that had the experience
	AgentID string

	// TaskID identifies the related task if any
	TaskID string

	// Capability is the capability being learned/improved
	Capability capabilities.Capability

	// Outcome describes what happened
	Outcome string

	// Confidence indicates certainty level (0-1)
	Confidence float64

	// Metadata contains additional context
	Metadata map[string]interface{}

	// Timestamp when experience occurred
	Timestamp time.Time
}

Experience represents a learning experience

type FeedbackMetrics

type FeedbackMetrics struct {
	TasksCompleted        int
	TasksFailed           int
	AverageCompletionTime time.Duration
	SuccessRate           float64
	TaskTypePerformance   map[string]float64
	CapabilityScores      map[capabilities.Capability]float64
	RecentFeedback        []string
}

FeedbackMetrics tracks agent performance metrics

type KnowledgeSource

type KnowledgeSource struct {
	Content  string
	Metadata map[string]interface{}
}

KnowledgeSource represents a source of background knowledge

func (KnowledgeSource) String

func (k KnowledgeSource) String() string

String returns a string representation of the knowledge source

type LLMProvider

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

LLMProvider handles interactions with language models

func NewLLMProvider

func NewLLMProvider(apiKey string, config types.LLMConfig) *LLMProvider

NewLLMProvider creates a new LLM provider instance

func (*LLMProvider) Complete

func (l *LLMProvider) Complete(ctx context.Context, prompt string) (string, error)

Complete generates a completion using the configured LLM

func (*LLMProvider) CompleteWithFunctions

func (l *LLMProvider) CompleteWithFunctions(ctx context.Context, prompt string, functions []core.FunctionDefinition) (string, error)

CompleteWithFunctions generates a completion with function calling support

type LearningConfig

type LearningConfig struct {
	// Strategy determines the learning approach
	Strategy LearningStrategy

	// EnableExperienceSharing allows sharing experiences between agents
	EnableExperienceSharing bool

	// MinConfidenceThreshold is minimum confidence needed to apply learning
	MinConfidenceThreshold float64

	// MaxExperienceAge is how long to retain experiences
	MaxExperienceAge time.Duration

	// MemoryScope determines visibility of learned experiences
	MemoryScope memory.MemoryScope
}

LearningConfig defines settings for agent learning behavior

type LearningMetrics

type LearningMetrics struct {
	// ExperienceCount is total number of experiences
	ExperienceCount int

	// SuccessRate is ratio of successful outcomes
	SuccessRate float64

	// ConfidenceAvg is average confidence across experiences
	ConfidenceAvg float64

	// CapabilityLevels maps capabilities to current levels
	CapabilityLevels map[capabilities.Capability]float64

	// LastUpdated indicates when metrics were last updated
	LastUpdated time.Time
}

LearningMetrics tracks learning progress

type LearningStrategy

type LearningStrategy string

LearningStrategy defines different approaches to agent learning

const (
	// ReinforcementLearning uses rewards/penalties to guide learning
	ReinforcementLearning LearningStrategy = "reinforcement"
	// SupervisedLearning learns from labeled examples
	SupervisedLearning LearningStrategy = "supervised"
	// UnsupervisedLearning discovers patterns without labels
	UnsupervisedLearning LearningStrategy = "unsupervised"
)

type LearningSystem

type LearningSystem struct {
	// Config contains learning settings
	Config *LearningConfig

	// Metrics tracks learning progress
	Metrics *LearningMetrics
	// contains filtered or unexported fields
}

LearningSystem manages agent learning and adaptation

func NewLearningSystem

func NewLearningSystem(config *LearningConfig) *LearningSystem

NewLearningSystem creates a new learning system with the given config

func (*LearningSystem) GetExperiences

func (ls *LearningSystem) GetExperiences(filter map[string]interface{}) []*Experience

GetExperiences returns experiences matching the filter

func (*LearningSystem) RecordExperience

func (ls *LearningSystem) RecordExperience(exp *Experience) error

RecordExperience adds a new learning experience

type Message

type Message struct {
	ID          string
	Type        MessageType
	FromAgent   string
	ToAgent     string // Empty for broadcast
	Content     string
	Context     map[string]interface{}
	Priority    int
	Timestamp   time.Time
	ExpiresAt   *time.Time
	RequiresAck bool
	Acked       bool
	// Sequence number for ordered delivery
	Sequence uint64
}

Message represents a communication unit between agents

type MessageStatus

type MessageStatus struct {
	Attempts     int
	LastAttempt  time.Time
	NextAttempt  time.Time
	Status       string
	ErrorHistory []error
}

MessageStatus tracks message delivery state

type MessageType

type MessageType string

MessageType defines the type of communication between agents

const (
	// Direct message between agents
	MessageTypeDirect MessageType = "direct"
	// Broadcast message to all agents in team
	MessageTypeBroadcast MessageType = "broadcast"
	// Request for collaboration
	MessageTypeCollaboration MessageType = "collaboration"
	// Response to a collaboration request
	MessageTypeResponse MessageType = "response"
	// Feedback on task or collaboration
	MessageTypeFeedback MessageType = "feedback"
)

type PriorityQueue

type PriorityQueue struct {
	Tasks    []*tasks.Task
	Capacity int
	Strategy string // "fifo", "deadline", "importance", "balanced"
}

PriorityQueue manages tasks based on priority

type ProtocolConfig

type ProtocolConfig struct {
	MaxRetries      int
	RetryBackoff    time.Duration
	MaxBackoff      time.Duration
	DeliveryTimeout time.Duration
}

ProtocolConfig defines configuration for protocol handler

func DefaultProtocolConfig

func DefaultProtocolConfig() *ProtocolConfig

DefaultProtocolConfig returns default protocol configuration

type ProtocolHandler

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

ProtocolHandler manages communication protocols and error recovery

func NewProtocolHandler

func NewProtocolHandler(config *ProtocolConfig) *ProtocolHandler

NewProtocolHandler creates a new protocol handler

func (*ProtocolHandler) GetMessageStatus

func (ph *ProtocolHandler) GetMessageStatus(msgID string) (MessageStatus, bool)

GetMessageStatus returns the current status of a message

func (*ProtocolHandler) HandleMessageDelivery

func (ph *ProtocolHandler) HandleMessageDelivery(ctx context.Context, msg *Message, protocol ProtocolType) error

HandleMessageDelivery processes message delivery with protocol-specific handling

type ProtocolType

type ProtocolType string

ProtocolType defines different communication protocols

const (
	// ReliableDelivery ensures messages are delivered with acknowledgment
	ReliableDelivery ProtocolType = "reliable"
	// BestEffortDelivery attempts delivery without guarantees
	BestEffortDelivery ProtocolType = "best-effort"
	// OrderedDelivery ensures messages are processed in order
	OrderedDelivery ProtocolType = "ordered"
	// PriorityDelivery handles messages based on priority
	PriorityDelivery ProtocolType = "priority"
)

type TaskMonitor

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

TaskMonitor handles task progress tracking

func NewTaskMonitor

func NewTaskMonitor() *TaskMonitor

NewTaskMonitor creates a new task monitor

func (*TaskMonitor) AddProgressCallback

func (tm *TaskMonitor) AddProgressCallback(taskID string, callback func(string, float64, string))

AddProgressCallback adds a callback for task progress updates

func (*TaskMonitor) CompleteTask

func (tm *TaskMonitor) CompleteTask(taskID string, message string) error

CompleteTask marks a task as complete

func (*TaskMonitor) FailTask

func (tm *TaskMonitor) FailTask(taskID string, err error) error

FailTask marks a task as failed

func (*TaskMonitor) GetTaskProgress

func (tm *TaskMonitor) GetTaskProgress(taskID string) (*TaskProgress, error)

GetTaskProgress retrieves the current progress of a task

func (*TaskMonitor) StartTask

func (tm *TaskMonitor) StartTask(taskID, agentID string, reqs *capabilities.TaskRequirements) error

StartTask begins monitoring a new task

func (*TaskMonitor) UpdateProgress

func (tm *TaskMonitor) UpdateProgress(taskID string, progress float64, message string) error

UpdateProgress updates a task's progress

type TaskProgress

type TaskProgress struct {
	TaskID       string
	AgentID      string
	Status       string
	Progress     float64
	Messages     []string
	StartTime    time.Time
	EndTime      *time.Time
	Requirements *capabilities.TaskRequirements
}

TaskProgress tracks the progress of a task

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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