learning

package
v1.9.0 Latest Latest
Warning

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

Go to latest
Published: Mar 27, 2026 License: MIT Imports: 14 Imported by: 0

Documentation

Overview

Package learning provides LLM-based extraction of behavioral patterns from session transcripts.

Package learning provides self-learning utilities for engram.

Package learning provides self-learning utilities for engram.

Index

Constants

View Source
const (
	// DefaultMaxMessages is the maximum number of messages to include in LLM input.
	DefaultMaxMessages = 20
	// DefaultMaxMessageLen is the maximum length of a single message.
	DefaultMaxMessageLen = 2000
)

Variables

View Source
var ValidOutcomes = map[Outcome]struct{}{
	OutcomeSuccess:   {},
	OutcomePartial:   {},
	OutcomeFailure:   {},
	OutcomeAbandoned: {},
}

ValidOutcomes is the set of valid outcome values.

Functions

func FormatTranscriptForExtraction

func FormatTranscriptForExtraction(messages []Message) string

FormatTranscriptForExtraction builds the user prompt from sanitized messages.

func GeneratePatternInsight added in v1.8.0

func GeneratePatternInsight(ctx context.Context, llm LLMClient, observations []*models.Observation) (string, error)

GeneratePatternInsight generates a 2-3 sentence LLM summary for a pattern from its source observations. Returns an empty string (not an error) when the LLM is unavailable or returns nothing.

func IsEnabled

func IsEnabled() bool

IsEnabled returns true if learning extraction is enabled and configured.

func IsGenericDescription added in v1.8.0

func IsGenericDescription(desc string) bool

IsGenericDescription reports whether desc is the auto-generated placeholder set when a pattern is first detected (before any LLM summarisation).

func IsValidOutcome added in v1.9.0

func IsValidOutcome(o Outcome) bool

IsValidOutcome reports whether o is a recognised outcome value.

func PropagateOutcome added in v1.9.0

func PropagateOutcome(
	ctx context.Context,
	injStore InjectionSource,
	obsStore EffectivenessUpdater,
	sessionID string,
	outcome Outcome,
) (int, error)

PropagateOutcome propagates a session outcome to the utility scores of all injected observations. For abandoned outcomes it is a no-op (returns 0, nil).

Types

type EffectivenessUpdater added in v1.9.0

type EffectivenessUpdater interface {
	// GetUtilityScore returns the current utility_score for an observation.
	GetUtilityScore(ctx context.Context, id int64) (float64, error)
	// UpdateEffectivenessStats atomically increments effectiveness counters and sets utility_score.
	UpdateEffectivenessStats(ctx context.Context, id int64, addInjections, addSuccesses int, newUtilityScore float64) error
}

EffectivenessUpdater applies effectiveness stats to a single observation.

type ExtractedLearning

type ExtractedLearning struct {
	Title     string   `json:"title"`
	Narrative string   `json:"narrative"`
	Concepts  []string `json:"concepts"`
	Type      string   `json:"type"`   // "guidance", "decision", "bugfix", "discovery", etc.
	Signal    string   `json:"signal"` // legacy: "correction", "preference", "pattern"
}

ExtractedLearning represents a single learning extracted by the LLM.

type ExtractionResult

type ExtractionResult struct {
	Learnings []ExtractedLearning `json:"learnings"`
}

ExtractionResult is the LLM response structure.

type Extractor

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

Extractor handles LLM-based extraction of behavioral patterns from transcripts.

func NewExtractor

func NewExtractor(llm LLMClient) *Extractor

NewExtractor creates a new learning extractor.

func (*Extractor) ExtractGuidance

func (e *Extractor) ExtractGuidance(ctx context.Context, messages []Message, project string) ([]*models.ParsedObservation, error)

ExtractGuidance analyzes a session transcript and returns guidance observations.

type InjectionRecord added in v1.9.0

type InjectionRecord struct {
	ObservationID    int64
	InjectionSection string
}

InjectionRecord represents a single observation injection event for propagation.

type InjectionSource added in v1.9.0

type InjectionSource interface {
	GetInjectionsBySession(ctx context.Context, sessionID string) ([]InjectionRecord, error)
}

InjectionSource provides injection records for a session.

type LLMClient

type LLMClient interface {
	Complete(ctx context.Context, systemPrompt, userPrompt string) (string, error)
}

LLMClient defines the interface for LLM completion calls.

type Message

type Message struct {
	Role string `json:"role"` // "user" or "assistant"
	Text string `json:"text"`
}

Message represents a transcript message for LLM processing.

func SanitizeTranscript

func SanitizeTranscript(messages []Message, maxMessages, maxMsgLen int) []Message

SanitizeTranscript prepares transcript messages for LLM input. It strips potentially adversarial content, limits length, and keeps only recent messages.

type OpenAIClient

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

OpenAIClient implements LLMClient using an OpenAI-compatible API.

func NewOpenAIClient

func NewOpenAIClient(cfg OpenAIConfig) *OpenAIClient

NewOpenAIClient creates a new OpenAI-compatible LLM client.

func (*OpenAIClient) Complete

func (c *OpenAIClient) Complete(ctx context.Context, systemPrompt, userPrompt string) (string, error)

Complete sends a chat completion request and returns the response text.

func (*OpenAIClient) IsConfigured

func (c *OpenAIClient) IsConfigured() bool

IsConfigured returns true if the LLM client has a URL configured.

type OpenAIConfig

type OpenAIConfig struct {
	BaseURL   string        // ENGRAM_LLM_URL (default: reuse ENGRAM_EMBEDDING_URL base)
	APIKey    string        // ENGRAM_LLM_API_KEY
	Model     string        // ENGRAM_LLM_MODEL (default: gpt-4o-mini)
	MaxTokens int           // ENGRAM_LLM_MAX_TOKENS (default: 4096)
	Timeout   time.Duration // HTTP client timeout (default: 120s)
}

OpenAIConfig holds configuration for the OpenAI-compatible client.

func DefaultOpenAIConfig

func DefaultOpenAIConfig() OpenAIConfig

DefaultOpenAIConfig returns config from environment variables.

type Outcome added in v1.9.0

type Outcome string

Outcome represents the result of a session.

const (
	OutcomeSuccess   Outcome = "success"
	OutcomePartial   Outcome = "partial"
	OutcomeFailure   Outcome = "failure"
	OutcomeAbandoned Outcome = "abandoned"
)

func DetermineSessionOutcome added in v1.9.0

func DetermineSessionOutcome(ctx context.Context, store SessionOutcomeStore, sessionID string) (Outcome, string)

DetermineSessionOutcome heuristically determines the outcome of a session. Rules (from spec FR-1, clarification C1):

  • success: session has ≥1 observation with type bugfix or feature
  • partial: session has observations but none are bugfix/feature type
  • failure: (reserved for hook-detected consecutive errors — not determinable server-side)
  • abandoned: session has no observations

type SessionOutcomeStore added in v1.9.0

type SessionOutcomeStore interface {
	GetObservationsBySession(ctx context.Context, sessionID string) ([]*models.Observation, error)
}

SessionOutcomeStore provides session data for outcome determination.

Jump to

Keyboard shortcuts

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