Class: Agentic::Learning::PatternRecognizer

Inherits:
Object
  • Object
show all
Defined in:
lib/agentic/learning/pattern_recognizer.rb

Overview

PatternRecognizer identifies patterns and optimization opportunities from execution history. It analyzes historical task and plan executions to detect recurring patterns, success/failure correlations, and potential optimization points.

Examples:

Analyzing patterns in task executions

history_store = Agentic::Learning::ExecutionHistoryStore.new
recognizer = Agentic::Learning::PatternRecognizer.new(history_store: history_store)
patterns = recognizer.analyze_agent_performance("research_agent")

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ PatternRecognizer

Initialize a new PatternRecognizer

Parameters:

  • options (Hash) (defaults to: {})

    Configuration options

Options Hash (options):

  • :logger (Logger)

    Custom logger (defaults to Agentic.logger)

  • :history_store (ExecutionHistoryStore)

    The history store to analyze

  • :min_sample_size (Integer)

    Minimum sample size for pattern detection (defaults to 10)

  • :significance_threshold (Float)

    Statistical significance threshold (defaults to 0.05)

  • :time_window_days (Integer)

    Time window in days for analysis (defaults to 30)



23
24
25
26
27
28
29
30
31
# File 'lib/agentic/learning/pattern_recognizer.rb', line 23

def initialize(options = {})
  @logger = options[:logger] || Agentic.logger
  @history_store = options[:history_store] || raise(ArgumentError, "history_store is required")
  @min_sample_size = options[:min_sample_size] || 10
  @significance_threshold = options[:significance_threshold] || 0.05
  @time_window_days = options[:time_window_days] || 30
  @pattern_cache = {}
  @cache_expiry = {}
end

Instance Method Details

#analyze_agent_performance(agent_type, options = {}) ⇒ Hash

Analyze performance patterns for a specific agent type

Parameters:

  • agent_type (String)

    The agent type to analyze

  • options (Hash) (defaults to: {})

    Analysis options

Options Hash (options):

  • :metrics (Array<Symbol>)

    Specific metrics to analyze (defaults to all)

  • :force_refresh (Boolean)

    Force a fresh analysis even if cached (defaults to false)

Returns:

  • (Hash)

    Analysis results with identified patterns



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/agentic/learning/pattern_recognizer.rb', line 40

def analyze_agent_performance(agent_type, options = {})
  cache_key = "agent_perf:#{agent_type}:#{options[:metrics]}"

  # Check cache first if not forcing refresh
  if !options[:force_refresh] && @pattern_cache[cache_key] && @cache_expiry[cache_key] && @cache_expiry[cache_key] > Time.now
    return @pattern_cache[cache_key]
  end

  # Fetch relevant history
  history = fetch_agent_history(agent_type)

  if history.size < @min_sample_size
    @logger.info("Insufficient data to analyze patterns for #{agent_type} (#{history.size} < #{@min_sample_size})")
    return {insufficient_data: true, sample_size: history.size, required_size: @min_sample_size}
  end

  # Perform analysis
  patterns = {
    success_rate: calculate_success_rate(history),
    performance_trends: analyze_performance_trends(history, options[:metrics]),
    failure_patterns: identify_failure_patterns(history),
    optimization_opportunities: identify_optimization_opportunities(history)
  }

  # Cache results
  @pattern_cache[cache_key] = patterns
  @cache_expiry[cache_key] = Time.now + 3600 # Cache for 1 hour

  patterns
end

#analyze_correlation(task_property, performance_metric) ⇒ Hash

Identify correlation between task properties and success/performance

Parameters:

  • task_property (Symbol)

    The property to analyze correlation for

  • performance_metric (Symbol)

    The performance metric to correlate with

Returns:

  • (Hash)

    Correlation analysis results



76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
# File 'lib/agentic/learning/pattern_recognizer.rb', line 76

def analyze_correlation(task_property, performance_metric)
  # Fetch all history within time window
  end_time = Time.now
  start_time = end_time - (@time_window_days * 24 * 60 * 60)

  history = @history_store.get_history(start_time: start_time, end_time: end_time)

  if history.size < @min_sample_size
    return {insufficient_data: true, sample_size: history.size}
  end

  # Extract property and metric values
  data_points = history.map do |record|
    property_value = extract_property_value(record, task_property)
    metric_value = extract_metric_value(record, performance_metric)

    {property: property_value, metric: metric_value} if property_value && metric_value
  end.compact

  # Calculate correlation
  if data_points.size < @min_sample_size
    return {insufficient_data: true, sample_size: data_points.size}
  end

  correlation = calculate_correlation(data_points)

  {
    correlation_coefficient: correlation[:coefficient],
    statistical_significance: correlation[:significance],
    sample_size: data_points.size,
    significant: correlation[:significance] < @significance_threshold
  }
end

#recommend_optimizations(agent_type) ⇒ Array<Hash>

Recommend optimization strategies based on recognized patterns

Parameters:

  • agent_type (String)

    The agent type to generate recommendations for

Returns:

  • (Array<Hash>)

    List of recommended optimization strategies



114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
# File 'lib/agentic/learning/pattern_recognizer.rb', line 114

def recommend_optimizations(agent_type)
  # Start with performance analysis
  performance = analyze_agent_performance(agent_type, force_refresh: true)

  if performance[:insufficient_data]
    return [{type: :insufficient_data, message: "Need more execution data to make recommendations"}]
  end

  recommendations = []

  # Check success rate
  if performance[:success_rate][:overall] < 0.8
    recommendations << {
      type: :success_rate,
      priority: :high,
      message: "Improve success rate (currently #{(performance[:success_rate][:overall] * 100).round(1)}%)",
      suggestions: generate_success_rate_suggestions(performance)
    }
  end

  # Check performance trends
  slow_metrics = performance[:performance_trends].select { |_, v| v[:trend] == :increasing && v[:significant] }
  if slow_metrics.any?
    recommendations << {
      type: :performance,
      priority: :medium,
      message: "Performance degradation detected in #{slow_metrics.keys.join(", ")}",
      suggestions: generate_performance_suggestions(slow_metrics)
    }
  end

  # Check failure patterns
  if performance[:failure_patterns]&.any?
    recommendations << {
      type: :failures,
      priority: :high,
      message: "Address common failure patterns",
      patterns: performance[:failure_patterns].first(3),
      suggestions: generate_failure_suggestions(performance[:failure_patterns])
    }
  end

  # Check optimization opportunities
  if performance[:optimization_opportunities]&.any?
    recommendations << {
      type: :optimization,
      priority: :medium,
      message: "Potential optimization opportunities identified",
      opportunities: performance[:optimization_opportunities],
      suggestions: performance[:optimization_opportunities].map { |o| o[:suggestion] }
    }
  end

  recommendations
end