react

package
v0.0.13 Latest Latest
Warning

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

Go to latest
Published: Dec 7, 2025 License: MIT Imports: 16 Imported by: 0

README

ReAct Agent Framework

A production-ready implementation of ReAct (Reasoning and Acting) agents with advanced cognitive architectures including self-reflection, task planning, and memory optimization with forgetting curves.

Architecture Overview

┌─────────────────────────────────────────────────────────────────┐
│                         ReAct Agent                             │
├─────────────────────────────────────────────────────────────────┤
│                                                                 │
│  ┌───────────────┐  ┌──────────────┐  ┌──────────────────────┐  │
│  │ Execution     │  │ Task         │  │ Self                 │  │
│  │ Modes         │  │ Planning     │  │ Reflection           │  │
│  ├───────────────┤  ├──────────────┤  ├──────────────────────┤  │
│  │ • ReAct       │  │ • Decompose  │  │ • Strategy Analysis  │  │
│  │ • ReWOO       │  │ • Templates  │  │ • Performance        │  │
│  │ • Hybrid      │  │ • Parallel   │  │ • Learning           │  │
│  └───────────────┘  └──────────────┘  └──────────────────────┘  │
│                                                                 │
│  ┌───────────────┐  ┌──────────────┐  ┌──────────────────────┐  │
│  │ Memory        │  │ Tool         │  │ Execution            │  │
│  │ Optimizer     │  │ Registry     │  │ History              │  │
│  ├───────────────┤  ├──────────────┤  ├──────────────────────┤  │
│  │ • Forgetting  │  │ • Dynamic    │  │ • Tracking           │  │
│  │   Curve       │  │   Loading    │  │ • Metrics            │  │
│  │ • Compression │  │ • Validation │  │ • Analysis           │  │
│  │ • Indexing    │  │ • Execution  │  │ • Interceptors       │  │
│  └───────────────┘  └──────────────┘  └──────────────────────┘  │
│                                                                 │
└─────────────────────────────────────────────────────────────────┘

Core Features

🎯 Execution Modes
ReAct Mode (Classic)

Traditional ReAct loop with iterative Thought → Action → Observation cycles.

agent := react.NewReActAgent("my-agent", "Assistant",
    react.WithExecutionMode(react.ModeReAct))
  • Best for: Exploratory tasks, interactive queries, complex reasoning
  • Token usage: Standard (full reasoning traces)
  • Flexibility: Maximum adaptability
ReWOO Mode (Plan-then-Execute)

Reasoning Without Observation - creates plan upfront then executes.

agent := react.NewReActAgent("my-agent", "Assistant",
    react.WithExecutionMode(react.ModeReWOO))
  • Best for: Structured workflows, batch processing, predictable tasks
  • Token usage: ~65% reduction vs ReAct
  • Speed: Faster execution with less LLM calls
Hybrid Mode (Adaptive)

Automatically selects mode based on task complexity analysis.

agent := react.NewReActAgent("my-agent", "Assistant",
    react.WithExecutionMode(react.ModeHybrid))
  • Best for: General-purpose applications, varying workloads
  • Intelligence: Analyzes task keywords, length, and available tools
  • Balance: Optimal token/performance trade-off
🧠 Memory Optimization

Implements Ebbinghaus forgetting curve with intelligent compression strategies:

optimizer := react.NewMemoryOptimizer(
    24*time.Hour,  // retention period
    0.3,           // forget threshold
)

Features:

  • Forgetting Curve: R = e^(-t/S) where R is retention, t is time, S is strength
  • Compression Strategies:
    • Summarization: Groups similar memories into summaries
    • Merging: Combines semantically similar items
    • Pruning: Removes low-importance memories
  • Semantic Search: Embedding-based similarity matching
  • Category Organization: Automatic task categorization
  • Importance Scoring: Based on success, complexity, and access patterns
📊 Self-Reflection System

Multi-level reflection with pattern recognition and learning:

reflector := react.NewSelfReflector(
    3,                     // reflection depth
    100*time.Millisecond,  // reflection delay
)

Reflection Types:

  • Strategy Reflection: Identifies repeated patterns and tool usage
  • Performance Reflection: Analyzes success rates and efficiency
  • Learning Reflection: Extracts reusable insights
  • Error Reflection: Learns from failures
📋 Task Planning

Sophisticated planning with decomposition and parallelization:

planner := react.NewTaskPlanner(
    react.DecompositionFirst,  // or Interleaved
    5,                        // max decomposition depth
)

Features:

  • Plan Templates: Reusable patterns for common tasks
  • Task Decomposition: Breaks complex tasks into subtasks
  • Dependency Analysis: Identifies parallel execution opportunities
  • Critical Path: Marks essential vs optional steps
  • Optimization: Reorders steps for efficiency

Quick Start

package main

import (
    "context"
    "github.com/darwishdev/dspy-go/pkg/agents/react"
    "github.com/darwishdev/dspy-go/pkg/core"
)

func main() {
    // Create agent with all advanced features
    agent := react.NewReActAgent("research-agent", "Research Assistant",
        react.WithExecutionMode(react.ModeHybrid),
        react.WithReflection(true, 3),
        react.WithPlanning(react.Interleaved, 5),
        react.WithMemoryOptimization(24*time.Hour, 0.3),
        react.WithMaxIterations(10),
        react.WithTimeout(5*time.Minute),
    )

    // Initialize with typed signature
    type Input struct {
        Task string `json:"task"`
    }
    type Output struct {
        Result string `json:"result"`
    }

    signature := core.NewTypedSignature[Input, Output]()
    err := agent.Initialize(llm, signature.ToLegacySignature())

    // Register tools
    tools := []core.Tool{searchTool, calculatorTool, summarizerTool}
    for _, tool := range tools {
        agent.RegisterTool(tool)
    }

    // Execute with interceptors for monitoring
    result, err := agent.ExecuteWithInterceptors(
        context.Background(),
        map[string]interface{}{"task": "Analyze market trends"},
        []core.AgentInterceptor{loggingInterceptor, metricsInterceptor},
    )

    // Analyze performance
    history := agent.GetExecutionHistory()
    reflections := agent.Reflector.GetTopReflections(3)
    metrics := agent.Reflector.GetMetrics()
}

Configuration

Complete Configuration Options
config := react.ReActAgentConfig{
    // Core Execution
    MaxIterations:    10,              // Max reasoning cycles
    ExecutionMode:    ModeHybrid,      // ReAct/ReWOO/Hybrid
    Timeout:         5*time.Minute,    // Overall timeout

    // Memory Management
    MemoryRetention:      24*time.Hour,  // How long to retain memories
    ForgetThreshold:      0.3,           // Minimum retention score
    EnableMemoryOpt:      true,          // Enable optimization
    CompressionThreshold: 100,           // Items before compression

    // Self-Reflection
    EnableReflection:     true,               // Enable reflection system
    ReflectionDepth:      3,                  // Analysis depth
    ReflectionDelay:      100*time.Millisecond, // Delay between reflections
    ReflectionThreshold:  0.7,                // Confidence threshold

    // Task Planning
    PlanningStrategy:     Interleaved,   // DecompositionFirst/Interleaved
    MaxPlanDepth:        5,              // Max decomposition depth
    EnablePlanning:      true,           // Enable planning system

    // Tool Execution
    ToolTimeout:         30*time.Second, // Per-tool timeout
    ParallelTools:       true,           // Enable parallel execution
    MaxToolRetries:      3,              // Retry failed tools

    // Monitoring
    EnableInterceptors:  true,           // Enable interceptor support
}

Advanced Usage

Memory Statistics and Analysis
// Get memory statistics
stats := agent.Optimizer.GetStatistics()
// Returns: total_items, categories, retention_rate, compression_ratio,
//          category_distribution, avg_importance, avg_access_count

// Find relevant memories
memories := agent.Optimizer.Retrieve(ctx, map[string]interface{}{
    "task": "previous research query",
})
Plan Metrics and Optimization
// Get plan metrics
plan, _ := agent.Planner.CreatePlan(ctx, input, tools)
metrics := agent.Planner.GetPlanMetrics(plan)
// Returns: total_steps, parallel_steps, critical_steps,
//          estimated_time, strategy, parallelization, tool_usage

// Validate plan
err := agent.Planner.ValidatePlan(plan)
Reflection Insights
// Get detailed metrics
metrics := agent.Reflector.GetMetrics()
// Returns: total_reflections, avg_confidence, success_rate,
//          avg_iterations, improvements, reflection_types

// Calculate improvement rate
improvement := agent.Reflector.CalculateImprovement()

// Reset for new session
agent.Reflector.Reset()

Performance Characteristics

Token Efficiency (GPT-3.5 Benchmarks)
Mode Token Usage Success Rate Speed
ReAct Baseline (100%) 40.8% Standard
ReWOO ~35% 42.4% 2-3x faster
Hybrid 50-70% 41.5% 1.5-2x faster
Memory Performance
  • Compression Ratio: 50-70% reduction in memory footprint
  • Retrieval Speed: O(n log n) with category indexing
  • Accuracy: 85%+ relevance for top-5 retrievals
Test Coverage
  • Overall Coverage: 80.7%
  • Core Components: 85%+
  • Edge Cases: Comprehensive error handling

Tool Integration

Standard Tool Registration
// Implements core.Tool interface
type MyTool struct {
    name string
}

func (t *MyTool) Name() string { return t.name }
func (t *MyTool) Description() string { return "My custom tool" }
func (t *MyTool) Execute(ctx context.Context, params map[string]interface{}) (core.ToolResult, error) {
    // Implementation
}
// ... other required methods

agent.RegisterTool(&MyTool{})
Function Tools
tool := tools.NewFuncTool("search", "Search the web",
    schema,
    func(ctx context.Context, args map[string]interface{}) (*models.CallToolResult, error) {
        // Implementation
    })
agent.RegisterTool(tool)

Monitoring and Observability

Interceptor Support
// Built-in support for interceptors
agent.SetInterceptors([]core.AgentInterceptor{
    logging.NewInterceptor(),
    metrics.NewInterceptor(),
    tracing.NewInterceptor(),
})

// Or per-execution
result, err := agent.ExecuteWithInterceptors(ctx, input, interceptors)
Execution History
history := agent.GetExecutionHistory()
for _, record := range history {
    fmt.Printf("Task: %v\n", record.Input)
    fmt.Printf("Success: %v\n", record.Success)
    fmt.Printf("Actions taken: %d\n", len(record.Actions))
    fmt.Printf("Duration: %v\n", record.Duration)
}

Examples

See /examples/react_agent/ for complete examples including:

  • Multi-tool orchestration
  • All execution modes comparison
  • Memory optimization demonstration
  • Reflection analysis
  • Performance monitoring

Testing

# Run all tests
go test ./pkg/agents/react/...

# Run with coverage
go test -cover ./pkg/agents/react/...

# Run benchmarks
go test -bench=. ./pkg/agents/react/

# Run specific test suites
go test -run TestMemoryOptimizer ./pkg/agents/react/
go test -run TestTaskPlanner ./pkg/agents/react/
go test -run TestSelfReflector ./pkg/agents/react/

Production Considerations

Resource Management
  • Memory optimizer automatically manages memory footprint
  • Configurable compression thresholds
  • Automatic cleanup of old memories
Error Handling
  • Comprehensive error recovery
  • Atomic operations with rollback
  • Critical vs non-critical step failures
Scalability
  • Parallel tool execution support
  • Efficient memory indexing
  • Optimized dependency analysis

Contributing

See CONTRIBUTING.md for guidelines.

License

MIT License - see LICENSE for details.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type ActionRecord

type ActionRecord struct {
	Thought     string
	Action      string
	Tool        string
	Arguments   map[string]interface{}
	Observation string
	Success     bool
	Duration    time.Duration
}

ActionRecord tracks individual actions taken.

type CompressionStrategy

type CompressionStrategy int

CompressionStrategy defines how memory is compressed.

const (
	// CompressionSummarize creates summaries of similar memories.
	CompressionSummarize CompressionStrategy = iota
	// CompressionMerge merges similar memories.
	CompressionMerge
	// CompressionPrune removes low-importance memories.
	CompressionPrune
)

type ExecutionMode

type ExecutionMode int

ExecutionMode defines how the agent executes tasks.

const (
	// ModeReAct uses classic ReAct loop (Thought -> Action -> Observation).
	ModeReAct ExecutionMode = iota
	// ModeReWOO uses Reasoning Without Observation (plan-then-execute).
	ModeReWOO
	// ModeHybrid adaptively switches between ReAct and ReWOO.
	ModeHybrid
)

type ExecutionRecord

type ExecutionRecord struct {
	Timestamp   time.Time
	Input       map[string]interface{}
	Output      map[string]interface{}
	Actions     []ActionRecord
	Success     bool
	Error       error
	Reflections []string

	// Context Engineering metrics
	ContextVersion       int64                        `json:"context_version,omitempty"`
	ContextResponse      *contextmgmt.ContextResponse `json:"context_response,omitempty"`
	OptimizationsApplied []string                     `json:"optimizations_applied,omitempty"`
	CostSavings          float64                      `json:"cost_savings,omitempty"`
	ProcessingTime       time.Duration                `json:"processing_time,omitempty"`
}

ExecutionRecord tracks execution history for reflection.

type ForgettingCurve

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

ForgettingCurve implements Ebbinghaus forgetting curve.

func NewForgettingCurve

func NewForgettingCurve() *ForgettingCurve

NewForgettingCurve creates a new forgetting curve calculator.

func (*ForgettingCurve) Calculate

func (fc *ForgettingCurve) Calculate(age time.Duration, importance float64, accessCount int) float64

Calculate computes retention based on forgetting curve.

type MemoryCompressor

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

MemoryCompressor reduces memory footprint.

func NewMemoryCompressor

func NewMemoryCompressor() *MemoryCompressor

NewMemoryCompressor creates a new memory compressor.

type MemoryIndex

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

MemoryIndex provides fast access to memory items.

func NewMemoryIndex

func NewMemoryIndex() *MemoryIndex

NewMemoryIndex creates a new memory index.

func (*MemoryIndex) Add

func (mi *MemoryIndex) Add(item *MemoryItem)

Add adds an item to the index.

func (*MemoryIndex) Get

func (mi *MemoryIndex) Get(key string) (*MemoryItem, bool)

Get retrieves an item from the index.

func (*MemoryIndex) GetByCategory

func (mi *MemoryIndex) GetByCategory(category string) []*MemoryItem

GetByCategory retrieves items by category.

func (*MemoryIndex) Remove

func (mi *MemoryIndex) Remove(key string)

Remove removes an item from the index.

func (*MemoryIndex) Size

func (mi *MemoryIndex) Size() int

Size returns the number of items in the index.

type MemoryItem

type MemoryItem struct {
	Key          string
	Value        interface{}
	Category     string
	Importance   float64
	AccessCount  int
	LastAccessed time.Time
	Created      time.Time
	Embedding    []float64 // For semantic similarity
	Hash         string
}

MemoryItem represents an item in memory.

type MemoryOptimizer

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

MemoryOptimizer implements memory optimization with forgetting curve.

func NewMemoryOptimizer

func NewMemoryOptimizer(retention time.Duration, threshold float64) *MemoryOptimizer

NewMemoryOptimizer creates a new memory optimizer.

func NewMemoryOptimizerWithCompressionThreshold

func NewMemoryOptimizerWithCompressionThreshold(retention time.Duration, threshold float64, compressionThreshold int) *MemoryOptimizer

NewMemoryOptimizerWithCompressionThreshold creates a new memory optimizer with configurable compression threshold.

func (*MemoryOptimizer) GetStatistics

func (mo *MemoryOptimizer) GetStatistics() map[string]interface{}

GetStatistics returns memory statistics.

func (*MemoryOptimizer) Retrieve

func (mo *MemoryOptimizer) Retrieve(ctx context.Context, query map[string]interface{}) (interface{}, error)

Retrieve gets relevant information from memory.

func (*MemoryOptimizer) Store

func (mo *MemoryOptimizer) Store(ctx context.Context, input map[string]interface{}, output map[string]interface{}, success bool) error

Store saves information to optimized memory.

type Option

type Option func(*ReActAgentConfig)

Option configures a ReActAgent.

func WithContextEngineering

func WithContextEngineering(baseDir string, contextConfig contextmgmt.Config) Option

WithContextEngineering enables Manus-inspired context engineering for 10x cost reduction.

func WithContextOptimization

func WithContextOptimization(level contextmgmt.CompressionPriority, maxTokens int, cacheTarget float64) Option

WithContextOptimization configures context optimization level.

func WithExecutionMode

func WithExecutionMode(mode ExecutionMode) Option

WithExecutionMode sets the execution mode.

func WithMaxIterations

func WithMaxIterations(max int) Option

WithMaxIterations sets the maximum iterations.

func WithMemoryOptimization

func WithMemoryOptimization(retention time.Duration, threshold float64) Option

WithMemoryOptimization enables memory optimization.

func WithNativeFunctionCalling

func WithNativeFunctionCalling(config interceptors.FunctionCallingConfig) Option

WithNativeFunctionCalling enables native LLM function calling for tool selection. This uses the provider's built-in tool calling API instead of text-based parsing, which provides more reliable tool selection and eliminates parsing errors.

func WithPlanning

func WithPlanning(strategy PlanningStrategy, maxDepth int) Option

WithPlanning configures planning.

func WithProductionContextOptimization

func WithProductionContextOptimization() Option

WithProductionContextOptimization enables production-grade context optimization.

func WithReflection

func WithReflection(enabled bool, depth int) Option

WithReflection enables or disables reflection.

func WithTimeout

func WithTimeout(timeout time.Duration) Option

WithTimeout sets the execution timeout.

func WithXMLParsing

func WithXMLParsing(config interceptors.XMLConfig) Option

WithXMLParsing enables XML interceptor-based parsing for tool actions. This provides enhanced XML validation, security features, and error handling.

type Pattern

type Pattern struct {
	Name        string
	Occurrences int
	SuccessRate float64
	LastSeen    time.Time
	Context     map[string]interface{}
}

Pattern represents a recurring pattern in agent behavior.

type PerformanceMetrics

type PerformanceMetrics struct {
	TotalExecutions   int
	SuccessfulRuns    int
	FailedRuns        int
	AverageIterations float64
	AverageDuration   time.Duration
	ToolUsageStats    map[string]*ToolStats
	ErrorPatterns     map[string]int
}

PerformanceMetrics tracks agent performance over time.

type Plan

type Plan struct {
	ID                string
	Goal              string
	Steps             []PlanStep
	Strategy          PlanningStrategy
	CreatedAt         time.Time
	EstimatedDuration time.Duration
	Dependencies      map[string][]string // step dependencies
}

Plan represents a structured plan for task execution.

type PlanStep

type PlanStep struct {
	ID          string
	Description string
	Tool        string
	Arguments   map[string]interface{}
	Expected    string   // expected outcome
	Critical    bool     // if true, failure stops execution
	Parallel    bool     // can be executed in parallel
	DependsOn   []string // IDs of steps this depends on
	Timeout     time.Duration
}

PlanStep represents a single step in a plan.

type PlanStepTemplate

type PlanStepTemplate struct {
	Description   string
	ToolType      string
	ArgumentsFunc func(map[string]interface{}) map[string]interface{}
	Critical      bool
}

PlanStepTemplate is a template for a plan step.

type PlanTemplate

type PlanTemplate struct {
	Name        string
	TaskPattern string // regex or keyword pattern
	Steps       []PlanStepTemplate
	SuccessRate float64
	LastUsed    time.Time
}

PlanTemplate is a reusable plan structure.

type PlanTemplateLibrary

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

PlanTemplateLibrary stores reusable plan templates.

func NewPlanTemplateLibrary

func NewPlanTemplateLibrary() *PlanTemplateLibrary

NewPlanTemplateLibrary creates a new plan template library with common templates.

func (*PlanTemplateLibrary) AddTemplate

func (ptl *PlanTemplateLibrary) AddTemplate(template *PlanTemplate)

AddTemplate adds a plan template to the library.

func (*PlanTemplateLibrary) FindTemplate

func (ptl *PlanTemplateLibrary) FindTemplate(task string) *PlanTemplate

FindTemplate finds a matching template for a task.

type PlanningStrategy

type PlanningStrategy int

PlanningStrategy defines how the agent plans tasks.

const (
	// DecompositionFirst breaks down tasks upfront before execution.
	DecompositionFirst PlanningStrategy = iota
	// Interleaved adapts the plan during execution.
	Interleaved
)

type ReActAgent

type ReActAgent struct {

	// Modern patterns
	Reflector *SelfReflector
	Planner   *TaskPlanner
	Optimizer *MemoryOptimizer
	// contains filtered or unexported fields
}

ReActAgent implements a generic ReAct-based agent with modern patterns.

func NewReActAgent

func NewReActAgent(id, name string, opts ...Option) *ReActAgent

NewReActAgent creates a new ReAct agent with modern patterns.

func (*ReActAgent) ClearInterceptors

func (r *ReActAgent) ClearInterceptors()

ClearInterceptors removes all interceptors.

func (*ReActAgent) EnableNativeFunctionCalling

func (r *ReActAgent) EnableNativeFunctionCalling(config *interceptors.FunctionCallingConfig) error

EnableNativeFunctionCalling enables native LLM function calling on an already initialized agent. This allows enabling function calling after agent creation. If config is nil, uses the default configuration with the agent's tool registry.

func (*ReActAgent) EnableXMLParsing

func (r *ReActAgent) EnableXMLParsing(config interceptors.XMLConfig) error

EnableXMLParsing enables XML interceptor-based parsing on an already initialized agent. This allows enabling XML parsing after agent creation.

func (*ReActAgent) Execute

func (r *ReActAgent) Execute(ctx context.Context, input map[string]interface{}) (map[string]interface{}, error)

Execute runs the agent's task with given input.

func (*ReActAgent) ExecuteWithInterceptors

func (r *ReActAgent) ExecuteWithInterceptors(ctx context.Context, input map[string]interface{}, interceptors []core.AgentInterceptor) (map[string]interface{}, error)

ExecuteWithInterceptors runs the agent with interceptor support.

func (*ReActAgent) GetAgentID

func (r *ReActAgent) GetAgentID() string

GetAgentID returns the unique identifier for this agent.

func (*ReActAgent) GetAgentType

func (r *ReActAgent) GetAgentType() string

GetAgentType returns the type of this agent.

func (*ReActAgent) GetCapabilities

func (r *ReActAgent) GetCapabilities() []core.Tool

GetCapabilities returns the tools/capabilities available to this agent.

func (*ReActAgent) GetContextHealthStatus

func (r *ReActAgent) GetContextHealthStatus() map[string]interface{}

GetContextHealthStatus returns health status of context management systems.

func (*ReActAgent) GetContextPerformanceMetrics

func (r *ReActAgent) GetContextPerformanceMetrics() map[string]interface{}

GetContextPerformanceMetrics returns comprehensive context management metrics.

func (*ReActAgent) GetExecutionHistory

func (r *ReActAgent) GetExecutionHistory() []ExecutionRecord

GetExecutionHistory returns the execution history for analysis.

func (*ReActAgent) GetInterceptors

func (r *ReActAgent) GetInterceptors() []core.AgentInterceptor

GetInterceptors returns the current interceptors.

func (*ReActAgent) GetMemory

func (r *ReActAgent) GetMemory() agents.Memory

GetMemory returns the agent's memory store.

func (*ReActAgent) Initialize

func (r *ReActAgent) Initialize(llm core.LLM, signature core.Signature) error

Initialize sets up the agent with an LLM and creates the ReAct module.

func (*ReActAgent) RegisterTool

func (r *ReActAgent) RegisterTool(tool core.Tool) error

RegisterTool adds a tool to the agent's registry.

func (*ReActAgent) SetInterceptors

func (r *ReActAgent) SetInterceptors(interceptors []core.AgentInterceptor)

SetInterceptors sets the default interceptors for this agent.

type ReActAgentConfig

type ReActAgentConfig struct {
	// Core settings
	MaxIterations int
	ExecutionMode ExecutionMode
	Timeout       time.Duration

	// Memory settings
	MemoryRetention time.Duration
	ForgetThreshold float64
	EnableMemoryOpt bool

	// Reflection settings
	EnableReflection bool
	ReflectionDepth  int
	ReflectionDelay  time.Duration

	// Planning settings
	PlanningStrategy PlanningStrategy
	MaxPlanDepth     int
	EnablePlanning   bool

	// Tool settings
	ToolTimeout    time.Duration
	ParallelTools  bool
	MaxToolRetries int

	// Interceptor settings
	EnableInterceptors bool

	// XML parsing settings
	EnableXMLParsing bool
	XMLConfig        *interceptors.XMLConfig

	// Native function calling settings
	EnableNativeFunctionCalling bool
	FunctionCallingConfig       *interceptors.FunctionCallingConfig

	// Context Engineering settings (Manus-inspired patterns)
	EnableContextEngineering bool                            `json:"enable_context_engineering"`
	ContextConfig            contextmgmt.Config              `json:"context_config,omitempty"`
	ContextBaseDir           string                          `json:"context_base_dir"`
	AutoTodoManagement       bool                            `json:"auto_todo_management"`
	AutoErrorLearning        bool                            `json:"auto_error_learning"`
	ContextOptLevel          contextmgmt.CompressionPriority `json:"context_optimization_level"`
	MaxContextTokens         int                             `json:"max_context_tokens"`
	CacheEfficiencyTarget    float64                         `json:"cache_efficiency_target"`
}

ReActAgentConfig configures the ReAct agent behavior.

func DefaultReActAgentConfig

func DefaultReActAgentConfig() ReActAgentConfig

DefaultReActAgentConfig returns sensible defaults.

func ProductionReActAgentConfig

func ProductionReActAgentConfig() ReActAgentConfig

ProductionReActAgentConfig returns a configuration optimized for production cost efficiency.

type Reflection

type Reflection struct {
	Type           ReflectionType
	Insight        string
	Confidence     float64
	Recommendation string
	Evidence       []string
	Timestamp      time.Time
}

Reflection represents an insight gained from analyzing past executions.

type ReflectionType

type ReflectionType int

ReflectionType categorizes different types of reflections.

const (
	// ReflectionTypeStrategy reflects on overall strategy effectiveness.
	ReflectionTypeStrategy ReflectionType = iota
	// ReflectionTypePerformance reflects on performance metrics.
	ReflectionTypePerformance
	// ReflectionTypeLearning reflects on learned patterns.
	ReflectionTypeLearning
	// ReflectionTypeError reflects on errors and failures.
	ReflectionTypeError
)

type SelfReflector

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

SelfReflector implements self-reflection capabilities for agents.

func NewSelfReflector

func NewSelfReflector(depth int, delay time.Duration) *SelfReflector

NewSelfReflector creates a new self-reflection module.

func NewSelfReflectorWithThreshold

func NewSelfReflectorWithThreshold(depth int, delay time.Duration, successRateThreshold float64) *SelfReflector

NewSelfReflectorWithThreshold creates a new self-reflection module with configurable success rate threshold.

func (*SelfReflector) CalculateImprovement

func (sr *SelfReflector) CalculateImprovement(windowSize int) float64

CalculateImprovement compares metrics over time windows (thread-safe).

func (*SelfReflector) GetMetrics

func (sr *SelfReflector) GetMetrics() *PerformanceMetrics

GetMetrics returns current performance metrics.

func (*SelfReflector) GetPatterns

func (sr *SelfReflector) GetPatterns() map[string]*Pattern

GetPatterns returns identified patterns (thread-safe).

func (*SelfReflector) GetTopReflections

func (sr *SelfReflector) GetTopReflections(n int) []Reflection

GetTopReflections returns the most confident reflections (thread-safe).

func (*SelfReflector) Reflect

func (sr *SelfReflector) Reflect(ctx context.Context, record ExecutionRecord) []Reflection

Reflect analyzes an execution record and generates reflections.

func (*SelfReflector) Reset

func (sr *SelfReflector) Reset()

Reset clears all reflection data (thread-safe).

type TaskDecomposer

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

TaskDecomposer breaks down complex tasks into subtasks.

func NewTaskDecomposer

func NewTaskDecomposer(maxDepth int) *TaskDecomposer

NewTaskDecomposer creates a new task decomposer.

func (*TaskDecomposer) Decompose

func (td *TaskDecomposer) Decompose(task string, currentDepth int) []string

Decompose breaks down a task into subtasks.

type TaskPlanner

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

TaskPlanner implements task planning and decomposition.

func NewTaskPlanner

func NewTaskPlanner(strategy PlanningStrategy, maxDepth int) *TaskPlanner

NewTaskPlanner creates a new task planner.

func (*TaskPlanner) CreatePlan

func (tp *TaskPlanner) CreatePlan(ctx context.Context, input map[string]interface{}, tools []core.Tool) (*Plan, error)

CreatePlan creates an execution plan for a task.

func (*TaskPlanner) GetPlanMetrics

func (tp *TaskPlanner) GetPlanMetrics(plan *Plan) map[string]interface{}

GetPlanMetrics returns metrics about a plan.

func (*TaskPlanner) ValidatePlan

func (tp *TaskPlanner) ValidatePlan(plan *Plan) error

ValidatePlan checks if a plan is valid and executable.

type ToolStats

type ToolStats struct {
	UsageCount  int
	SuccessRate float64
	AvgDuration time.Duration
	LastUsed    time.Time
}

ToolStats tracks statistics for individual tool usage.

Jump to

Keyboard shortcuts

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