learning

package
v1.0.2 Latest Latest
Warning

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

Go to latest
Published: Jan 15, 2026 License: Apache-2.0 Imports: 19 Imported by: 0

Documentation

Overview

Copyright 2026 Teradata

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func FindPatternYAMLFile

func FindPatternYAMLFile(libraryPath, patternName string) (string, error)

FindPatternYAMLFile searches for a YAML file containing the specified pattern. It searches all .yaml and .yml files in the given directory (non-recursive).

func GetCurrentPriority

func GetCurrentPriority(yamlPath, patternName string) (int32, error)

GetCurrentPriority reads the current priority value for a pattern from a YAML file

func InitSelfImprovementSchema

func InitSelfImprovementSchema(ctx context.Context, db *sql.DB, tracer observability.Tracer) error

InitSelfImprovementSchema creates database tables for self-improvement tracking. This extends the existing metaagent_deployments table with runtime metrics and improvement history tracking.

func LoadLearningAgentConfig

func LoadLearningAgentConfig(path string) (*loomv1.LearningAgentConfig, []string, error)

LoadLearningAgentConfig loads a learning agent configuration from a YAML file

func LoadLearningAgentConfigs

func LoadLearningAgentConfigs(dir string) ([]*loomv1.LearningAgentConfig, error)

LoadLearningAgentConfigs loads all learning agent configurations from a directory

func ParseAnalysisInterval

func ParseAnalysisInterval(config *loomv1.LearningAgentConfig) (time.Duration, error)

ParseAnalysisInterval parses the analysis interval from config to time.Duration

func ParseCooldownPeriod

func ParseCooldownPeriod(config *loomv1.LearningAgentConfig) (time.Duration, error)

ParseCooldownPeriod parses the circuit breaker cooldown from config to time.Duration

func ToLearningAgentOptions

func ToLearningAgentOptions(config *loomv1.LearningAgentConfig) (AutonomyLevel, time.Duration, *CircuitBreaker, error)

ToLearningAgentOptions converts proto config to LearningAgent constructor options

func UpdatePatternPriority

func UpdatePatternPriority(yamlPath, patternName string, newPriority int32) error

UpdatePatternPriority updates the priority field for a specific pattern in a YAML file. This function preserves comments, formatting, and structure of the YAML file.

Types

type AutonomyLevel

type AutonomyLevel int

AutonomyLevel defines how autonomous the learning agent is

const (
	// AutonomyManual requires human approval for all improvements
	AutonomyManual AutonomyLevel = 0

	// AutonomyHumanApproval applies improvements after human approval
	AutonomyHumanApproval AutonomyLevel = 1

	// AutonomyFull applies improvements automatically (with circuit breaker)
	AutonomyFull AutonomyLevel = 2
)

type CircuitBreaker

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

CircuitBreaker prevents runaway improvements

type CircuitBreakerConfigYAML

type CircuitBreakerConfigYAML struct {
	Enabled          bool   `yaml:"enabled"`
	FailureThreshold int32  `yaml:"failure_threshold"`
	CooldownPeriod   string `yaml:"cooldown_period"`
	SuccessThreshold int32  `yaml:"success_threshold"`
}

CircuitBreakerConfigYAML configures the circuit breaker

type DeploymentMetric

type DeploymentMetric struct {
	AgentID          string
	Domain           DomainType
	Templates        []string // Which templates were considered
	SelectedTemplate string   // Which template was chosen
	Patterns         []string // Which patterns were selected
	Success          bool     // Did deployment succeed?
	ErrorMessage     string   // If failed, why?
	CostUSD          float64  // Generation cost
	TurnsUsed        int      // How many conversation turns
	CreatedAt        time.Time
	Metadata         map[string]string // Additional metadata
}

DeploymentMetric represents metrics for a single agent deployment

type DomainInsights

type DomainInsights struct {
	Domain       DomainType
	SuccessRate  float64
	BestPatterns []PatternScore
	Improvements []Improvement
}

DomainInsights contains comprehensive insights for a domain

type DomainType

type DomainType string

DomainType represents the domain of an agent

const (
	DomainSQL      DomainType = "sql"
	DomainREST     DomainType = "rest"
	DomainFile     DomainType = "file"
	DomainDocument DomainType = "document"
	DomainETL      DomainType = "etl"
	DomainUnknown  DomainType = "unknown"
)

type Improvement

type Improvement struct {
	Type        string // "pattern_add", "pattern_remove", "template_adjust"
	Description string
	Confidence  float64
	Impact      string // "high", "medium", "low"
	Details     map[string]interface{}
}

Improvement represents a suggested improvement

type ImprovementPolicyYAML

type ImprovementPolicyYAML struct {
	AutoApplyMinConfidence float64  `yaml:"auto_apply_min_confidence"`
	MaxDailyChanges        int32    `yaml:"max_daily_changes"`
	ProtectedAgents        []string `yaml:"protected_agents"`
	AllowedChangeTypes     []string `yaml:"allowed_change_types"`
	MaxAutoApplyImpact     string   `yaml:"max_auto_apply_impact"`
}

ImprovementPolicyYAML defines improvement application rules

type LearningAgent

type LearningAgent struct {
	loomv1.UnimplementedLearningAgentServiceServer
	// contains filtered or unexported fields
}

LearningAgent implements the LearningAgentService proto interface. It provides autonomous self-improvement capabilities by monitoring pattern effectiveness and generating/applying improvements.

func NewLearningAgent

func NewLearningAgent(
	db *sql.DB,
	tracer observability.Tracer,
	engine *LearningEngine,
	tracker *PatternEffectivenessTracker,
	autonomyLevel AutonomyLevel,
	analysisInterval time.Duration,
) (*LearningAgent, error)

NewLearningAgent creates a new learning agent with validation

func NewLearningAgentFromConfig

func NewLearningAgentFromConfig(
	db *sql.DB,
	tracer observability.Tracer,
	engine *LearningEngine,
	tracker *PatternEffectivenessTracker,
	config *loomv1.LearningAgentConfig,
) (*LearningAgent, error)

NewLearningAgentFromConfig creates a learning agent from proto configuration. This enables declarative YAML-based configuration.

func (*LearningAgent) AnalyzePatternEffectiveness

AnalyzePatternEffectiveness analyzes runtime pattern performance

func (*LearningAgent) ApplyImprovement

ApplyImprovement applies an improvement proposal (respects autonomy level)

func (*LearningAgent) GenerateImprovements

GenerateImprovements generates improvement proposals based on pattern analysis

func (*LearningAgent) GetConfig

func (la *LearningAgent) GetConfig() *loomv1.LearningAgentConfig

GetConfig returns the declarative configuration if set via NewLearningAgentFromConfig. Returns nil if the agent was created with NewLearningAgent (legacy constructor).

func (*LearningAgent) GetExecutionCount

func (la *LearningAgent) GetExecutionCount() int64

GetExecutionCount returns the current execution count. This is useful for monitoring and testing.

func (*LearningAgent) GetImprovementHistory

GetImprovementHistory retrieves improvement history

func (*LearningAgent) IsAgentProtected

func (la *LearningAgent) IsAgentProtected(agentID string) bool

IsAgentProtected checks if an agent is protected from auto-apply. Protected agents always require human approval regardless of autonomy level.

func (*LearningAgent) IsEnabled

func (la *LearningAgent) IsEnabled() bool

IsEnabled returns whether this learning agent is enabled. If no config is set (legacy constructor), returns true by default.

func (*LearningAgent) RecordExecution

func (la *LearningAgent) RecordExecution(ctx context.Context) error

RecordExecution increments the execution counter and triggers learning if threshold is reached. This should be called by the agent after each pattern execution. If executionTrigger > 0 and executionCount % executionTrigger == 0, sends SignalLearningAnalyze.

func (*LearningAgent) ResetExecutionCount

func (la *LearningAgent) ResetExecutionCount()

ResetExecutionCount resets the execution counter to zero. This is useful for testing or when starting a new learning cycle.

func (*LearningAgent) RollbackImprovement

RollbackImprovement rolls back a failed improvement

func (*LearningAgent) SetInterruptChannel

func (la *LearningAgent) SetInterruptChannel(ic *interrupt.InterruptChannel, agentID string, executionTrigger int64) error

SetInterruptChannel sets the interrupt channel for this learning agent. Optional - if set, enables interrupt-driven learning triggers. The agentID is used to register interrupt handlers for learning signals. The executionTrigger specifies how many executions before auto-triggering learning (0 = disabled).

func (*LearningAgent) SetPatternReloader

func (la *LearningAgent) SetPatternReloader(reloader PatternReloader)

SetPatternReloader sets the pattern reloader for this learning agent. Optional - if not set, improvements will be applied without automatic pattern reload. Accepts any type that implements PatternReloader interface (e.g., *patterns.HotReloader).

func (*LearningAgent) ShouldAutoApply

func (la *LearningAgent) ShouldAutoApply(improvement *loomv1.Improvement) bool

ShouldAutoApply checks if an improvement should be auto-applied based on config. Returns false if: - Autonomy level is not FULL - Agent is protected - Confidence is below threshold - Impact level exceeds max auto-apply impact

func (*LearningAgent) ShouldProcessDomain

func (la *LearningAgent) ShouldProcessDomain(domain string) bool

ShouldProcessDomain checks if this learning agent should process the given domain. If no domains are configured, processes all domains.

func (*LearningAgent) Start

func (la *LearningAgent) Start(ctx context.Context) error

Start begins the autonomous analysis loop

func (*LearningAgent) Stop

func (la *LearningAgent) Stop(ctx context.Context) error

Stop gracefully stops the analysis loop

func (*LearningAgent) StreamPatternMetrics

StreamPatternMetrics streams real-time pattern effectiveness metrics

func (*LearningAgent) TunePatterns

TunePatterns automatically adjusts pattern parameters based on effectiveness analysis

type LearningAgentConfigSpecYAML

type LearningAgentConfigSpecYAML struct {
	Enabled           bool                     `yaml:"enabled"`
	AutonomyLevel     string                   `yaml:"autonomy_level"`
	AnalysisInterval  string                   `yaml:"analysis_interval"`
	WatchEvalSuites   []string                 `yaml:"watch_eval_suites"`
	Domains           []string                 `yaml:"domains"`
	CircuitBreaker    CircuitBreakerConfigYAML `yaml:"circuit_breaker"`
	ImprovementPolicy ImprovementPolicyYAML    `yaml:"improvement_policy"`
	Notifications     NotificationConfigYAML   `yaml:"notifications"`
}

LearningAgentConfigSpecYAML contains the learning agent specification

type LearningAgentConfigYAML

type LearningAgentConfigYAML struct {
	APIVersion string                      `yaml:"apiVersion"`
	Kind       string                      `yaml:"kind"`
	Metadata   LearningAgentMetadataYAML   `yaml:"metadata"`
	Spec       LearningAgentConfigSpecYAML `yaml:"spec"`
}

LearningAgentConfigYAML represents the YAML structure for learning agent configuration. This mirrors the proto LearningAgentConfig but uses YAML-friendly types.

type LearningAgentMetadataYAML

type LearningAgentMetadataYAML struct {
	Name        string            `yaml:"name"`
	Description string            `yaml:"description"`
	Labels      map[string]string `yaml:"labels"`
}

LearningAgentMetadataYAML contains metadata for the learning agent config

type LearningEngine

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

LearningEngine analyzes deployment metrics and provides insights

func NewLearningEngine

func NewLearningEngine(collector *MetricsCollector, tracer observability.Tracer) *LearningEngine

NewLearningEngine creates a new learning engine

func (*LearningEngine) GetBestPatterns

func (le *LearningEngine) GetBestPatterns(ctx context.Context, domain DomainType) ([]PatternScore, error)

GetBestPatterns returns the best performing patterns for a domain

func (*LearningEngine) GetDomainInsights

func (le *LearningEngine) GetDomainInsights(ctx context.Context, domain DomainType) (*DomainInsights, error)

GetDomainInsights provides comprehensive insights for a domain

func (*LearningEngine) SuggestImprovements

func (le *LearningEngine) SuggestImprovements(ctx context.Context, domain DomainType) ([]Improvement, error)

SuggestImprovements analyzes metrics and suggests improvements

type MetricsCollector

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

MetricsCollector collects and stores meta-agent deployment metrics All database operations are fully instrumented with observability tracing

func NewMetricsCollector

func NewMetricsCollector(dbPath string, tracer observability.Tracer) (*MetricsCollector, error)

NewMetricsCollector creates a new metrics collector with SQLite storage

func (*MetricsCollector) Close

func (mc *MetricsCollector) Close() error

Close closes the database connection

func (*MetricsCollector) GetPatternPerformance

func (mc *MetricsCollector) GetPatternPerformance(ctx context.Context, domain DomainType) (map[string]*PatternMetrics, error)

GetPatternPerformance returns performance metrics for patterns in a domain

func (*MetricsCollector) GetRecentFailures

func (mc *MetricsCollector) GetRecentFailures(ctx context.Context, domain DomainType, limit int) ([]*DeploymentMetric, error)

GetRecentFailures returns recent failed deployments for analysis

func (*MetricsCollector) GetSuccessRate

func (mc *MetricsCollector) GetSuccessRate(ctx context.Context, domain DomainType) (float64, error)

GetSuccessRate returns the success rate for a given domain If domain is empty, returns success rate across all domains

func (*MetricsCollector) GetTemplatePerformance

func (mc *MetricsCollector) GetTemplatePerformance(ctx context.Context, domain DomainType) (map[string]*TemplateMetrics, error)

GetTemplatePerformance returns performance metrics for templates in a domain

func (*MetricsCollector) RecordDeployment

func (mc *MetricsCollector) RecordDeployment(ctx context.Context, metric *DeploymentMetric) error

RecordDeployment records a deployment metric to the database

func (*MetricsCollector) UpdateDeploymentFeedback

func (mc *MetricsCollector) UpdateDeploymentFeedback(ctx context.Context, agentID string, feedback interface{}) error

UpdateDeploymentFeedback updates a deployment record with post-deployment feedback

type NotificationConfigYAML

type NotificationConfigYAML struct {
	SlackWebhook   string   `yaml:"slack_webhook"`
	EmailAddresses []string `yaml:"email_addresses"`
	NotifyOn       []string `yaml:"notify_on"`
	IncludeDetails bool     `yaml:"include_details"`
}

NotificationConfigYAML defines notification settings

type PatternEffectivenessTracker

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

PatternEffectivenessTracker tracks pattern usage effectiveness in real-time. Runs as a background goroutine, aggregating metrics and flushing to database and MessageBus periodically.

Thread-safe for concurrent RecordUsage calls from multiple agents.

func NewPatternEffectivenessTracker

func NewPatternEffectivenessTracker(
	db *sql.DB,
	tracer observability.Tracer,
	bus *communication.MessageBus,
	windowSize time.Duration,
	flushInterval time.Duration,
) *PatternEffectivenessTracker

NewPatternEffectivenessTracker creates a new pattern effectiveness tracker.

Parameters:

  • db: SQLite database with pattern_effectiveness table (see schema.go)
  • tracer: Observability tracer for instrumentation
  • bus: MessageBus for publishing aggregated metrics (optional, can be nil)
  • windowSize: Aggregation window (e.g., 1 hour)
  • flushInterval: How often to batch-write to DB (e.g., 5 minutes)

func (*PatternEffectivenessTracker) GetMessageBus

GetMessageBus returns the MessageBus instance used by this tracker. Returns nil if no MessageBus was configured.

func (*PatternEffectivenessTracker) RecordUsage

func (t *PatternEffectivenessTracker) RecordUsage(
	ctx context.Context,
	patternName string,
	variant string,
	domain string,
	agentID string,
	success bool,
	costUSD float64,
	latency time.Duration,
	errorType string,
	llmProvider string,
	llmModel string,
	judgeResult *loomv1.EvaluateResponse,
)

RecordUsage records a single pattern usage event. Variant is extracted from context or defaults to "default". judgeResult is optional - if provided, judge evaluation metrics will be tracked.

Thread-safe for concurrent calls.

func (*PatternEffectivenessTracker) Start

Start begins the background goroutine for periodic flushing. Safe to call multiple times (subsequent calls are no-ops).

func (*PatternEffectivenessTracker) Stop

Stop gracefully stops the background goroutine and flushes remaining data. Blocks until all pending data is flushed to database.

type PatternMetrics

type PatternMetrics struct {
	Pattern      string
	UsageCount   int
	SuccessCount int
	SuccessRate  float64
	TotalCost    float64
	AvgCost      float64
}

PatternMetrics contains performance metrics for a pattern

type PatternReloader

type PatternReloader interface {
	ManualReload(patternName string) error
}

PatternReloader is an interface for pattern hot-reload functionality. This avoids circular dependency with pkg/patterns.

type PatternScore

type PatternScore struct {
	Pattern      string
	SuccessRate  float64
	UsageCount   int
	AvgCost      float64
	Confidence   float64 // Based on sample size
	RecommendUse bool    // Should this pattern be used?
}

PatternScore represents a pattern with its performance score

type TemplateMetrics

type TemplateMetrics struct {
	Template     string
	UsageCount   int
	SuccessCount int
	SuccessRate  float64
	AvgCost      float64
}

TemplateMetrics contains performance metrics for a template

Jump to

Keyboard shortcuts

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