memory

package
v0.0.0-...-6deb405 Latest Latest
Warning

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

Go to latest
Published: Apr 12, 2026 License: MIT Imports: 10 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func CreateKnowledgeContext

func CreateKnowledgeContext(data interface{}) ([]byte, error)

Helper function to create context JSON

func CreatePolicyActions

func CreatePolicyActions(data interface{}) ([]byte, error)

CreatePolicyActions creates JSONB actions for a policy

func CreatePolicyConditions

func CreatePolicyConditions(data interface{}) ([]byte, error)

CreatePolicyConditions creates JSONB conditions for a policy

func CreatePolicyParameters

func CreatePolicyParameters(data interface{}) ([]byte, error)

CreatePolicyParameters creates JSONB parameters for a policy

func CreateSkillImplementation

func CreateSkillImplementation(data interface{}) ([]byte, error)

CreateSkillImplementation creates JSONB implementation for a skill

Types

type AgentFilter

type AgentFilter struct {
	AgentName string
}

AgentFilter filters by agent name

func (AgentFilter) SQL

func (f AgentFilter) SQL(argIndex int) (string, []interface{})

type EmbeddingFunc

type EmbeddingFunc func(ctx context.Context, text string) ([]float32, error)

EmbeddingFunc is a function that generates embeddings for text

type Experience

type Experience struct {
	Description string
	SuccessRate float64
	AvgPnL      float64
	Occurrences int
	Symbol      string
}

type ExtractionConfig

type ExtractionConfig struct {
	MinConfidence  float64 // Minimum confidence to store knowledge (default: 0.5)
	MinOccurrences int     // Minimum pattern occurrences to extract (default: 3)
	EmbeddingFunc  EmbeddingFunc
}

ExtractionConfig configures the knowledge extraction process

func DefaultExtractionConfig

func DefaultExtractionConfig() ExtractionConfig

DefaultExtractionConfig returns sensible defaults

type Fact

type Fact struct {
	Statement  string
	Confidence float64
	Source     string
}

type Filter

type Filter interface {
	SQL(argIndex int) (clause string, args []interface{})
}

Filter represents a query filter for semantic memory

type KnowledgeExtractor

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

KnowledgeExtractor extracts knowledge from historical data and stores it in semantic memory

func NewKnowledgeExtractor

func NewKnowledgeExtractor(pool *pgxpool.Pool, config ExtractionConfig) *KnowledgeExtractor

NewKnowledgeExtractor creates a new knowledge extractor

func NewKnowledgeExtractorFromDB

func NewKnowledgeExtractorFromDB(database *db.DB, config ExtractionConfig) *KnowledgeExtractor

NewKnowledgeExtractorFromDB creates an extractor from existing DB connection

func (*KnowledgeExtractor) ExtractFactsFromMarketData

func (ke *KnowledgeExtractor) ExtractFactsFromMarketData(ctx context.Context, symbol string, since time.Time) (int, error)

ExtractFactsFromMarketData analyzes market data to extract factual knowledge

func (*KnowledgeExtractor) ExtractFromLLMDecisions

func (ke *KnowledgeExtractor) ExtractFromLLMDecisions(ctx context.Context, agentName string, since time.Time) (int, error)

ExtractFromLLMDecisions analyzes LLM decisions and extracts patterns

func (*KnowledgeExtractor) ExtractFromTradingResults

func (ke *KnowledgeExtractor) ExtractFromTradingResults(ctx context.Context, agentName string, since time.Time) (int, error)

ExtractFromTradingResults analyzes trading results and extracts experiences

type KnowledgeItem

type KnowledgeItem struct {
	ID uuid.UUID `json:"id"`

	// Knowledge metadata
	Type        KnowledgeType `json:"type"`
	Content     string        `json:"content"`      // Natural language description
	Embedding   []float32     `json:"embedding"`    // 1536-dim vector for similarity search
	Confidence  float64       `json:"confidence"`   // 0.0 to 1.0
	Importance  float64       `json:"importance"`   // 0.0 to 1.0, affects retrieval priority
	AccessCount int           `json:"access_count"` // How many times this knowledge was accessed

	// Provenance (where did this knowledge come from?)
	Source    string     `json:"source"`     // "llm_decision", "manual", "backtest", "pattern_extraction"
	SourceID  *uuid.UUID `json:"source_id"`  // ID of source (decision ID, backtest ID, etc.)
	AgentName string     `json:"agent_name"` // Which agent learned/created this knowledge
	Symbol    *string    `json:"symbol"`     // Associated symbol (if applicable)
	Context   []byte     `json:"context"`    // JSONB - additional context (market conditions, etc.)

	// Validation
	ValidationCount int       `json:"validation_count"` // How many times this knowledge was validated
	SuccessCount    int       `json:"success_count"`    // How many times applying this knowledge succeeded
	FailureCount    int       `json:"failure_count"`    // How many times it failed
	LastValidated   time.Time `json:"last_validated"`

	// Temporal
	CreatedAt time.Time  `json:"created_at"`
	UpdatedAt time.Time  `json:"updated_at"`
	ExpiresAt *time.Time `json:"expires_at"` // Optional expiration for time-sensitive knowledge
}

KnowledgeItem represents a piece of knowledge in semantic memory

func (*KnowledgeItem) Age

func (k *KnowledgeItem) Age() time.Duration

Age returns how old this knowledge is

func (*KnowledgeItem) IsValid

func (k *KnowledgeItem) IsValid() bool

IsValid checks if the knowledge is still valid (not expired, has good success rate)

func (*KnowledgeItem) Recency

func (k *KnowledgeItem) Recency() float64

Recency returns a score (0.0 to 1.0) based on how recent the knowledge is Newer knowledge gets higher scores

func (*KnowledgeItem) RelevanceScore

func (k *KnowledgeItem) RelevanceScore() float64

RelevanceScore combines multiple factors into a single relevance score

func (*KnowledgeItem) SuccessRate

func (k *KnowledgeItem) SuccessRate() float64

SuccessRate returns the success rate of this knowledge (0.0 to 1.0)

type KnowledgeType

type KnowledgeType string

KnowledgeType represents the type of knowledge stored in semantic memory

const (
	// KnowledgeFact represents factual information (e.g., "BTC price tends to rise after halving events")
	KnowledgeFact KnowledgeType = "fact"

	// KnowledgePattern represents observed patterns (e.g., "When RSI > 70 and volume decreases, price often corrects")
	KnowledgePattern KnowledgeType = "pattern"

	// KnowledgeExperience represents learned experiences (e.g., "Stop losses at 2% work better than 5% for volatile assets")
	KnowledgeExperience KnowledgeType = "experience"

	// KnowledgeStrategy represents strategic knowledge (e.g., "Mean reversion works better in ranging markets")
	KnowledgeStrategy KnowledgeType = "strategy"

	// KnowledgeRisk represents risk-related knowledge (e.g., "Drawdowns > 15% indicate strategy failure")
	KnowledgeRisk KnowledgeType = "risk"
)

type MinConfidenceFilter

type MinConfidenceFilter struct {
	MinConfidence float64
}

MinConfidenceFilter filters by minimum confidence

func (MinConfidenceFilter) SQL

func (f MinConfidenceFilter) SQL(argIndex int) (string, []interface{})

type PatternCandidate

type PatternCandidate struct {
	Condition    string
	Outcome      string
	Occurrences  int
	SuccessCount int
	FailureCount int
	AvgPnL       float64
	Symbols      []string
	AgentNames   []string
	DecisionIDs  []uuid.UUID
}

PatternCandidate represents a potential pattern to extract

func (*PatternCandidate) Confidence

func (pc *PatternCandidate) Confidence() float64

Confidence returns confidence score based on occurrences and success rate

func (*PatternCandidate) SuccessRate

func (pc *PatternCandidate) SuccessRate() float64

SuccessRate returns the success rate of this pattern

type Policy

type Policy struct {
	ID uuid.UUID `json:"id"`

	// Policy metadata
	Type        PolicyType `json:"type"`
	Name        string     `json:"name"`        // Human-readable name
	Description string     `json:"description"` // What this policy does

	// Policy definition
	Conditions []byte `json:"conditions"` // JSONB - when to apply this policy
	Actions    []byte `json:"actions"`    // JSONB - what actions to take
	Parameters []byte `json:"parameters"` // JSONB - configurable parameters

	// Performance tracking
	TimesApplied int     `json:"times_applied"` // How many times this policy was used
	SuccessCount int     `json:"success_count"` // How many times it succeeded
	FailureCount int     `json:"failure_count"` // How many times it failed
	AvgPnL       float64 `json:"avg_pnl"`       // Average P&L when applied
	TotalPnL     float64 `json:"total_pnl"`     // Cumulative P&L
	Sharpe       float64 `json:"sharpe"`        // Sharpe ratio
	MaxDrawdown  float64 `json:"max_drawdown"`  // Maximum drawdown
	WinRate      float64 `json:"win_rate"`      // Win rate (0.0 to 1.0)

	// Learning metadata
	AgentName   string     `json:"agent_name"`   // Which agent learned this policy
	Symbol      *string    `json:"symbol"`       // Associated symbol (if specific)
	LearnedFrom string     `json:"learned_from"` // Source: "backtest", "live_trading", "manual"
	SourceID    *uuid.UUID `json:"source_id"`    // ID of source (backtest ID, session ID, etc.)
	Confidence  float64    `json:"confidence"`   // Confidence in this policy (0.0 to 1.0)
	IsActive    bool       `json:"is_active"`    // Whether this policy is currently active
	Priority    int        `json:"priority"`     // Priority when multiple policies match (higher = more priority)

	// Temporal
	CreatedAt    time.Time  `json:"created_at"`
	UpdatedAt    time.Time  `json:"updated_at"`
	LastApplied  *time.Time `json:"last_applied"`
	LastModified *time.Time `json:"last_modified"`
}

Policy represents a learned trading policy or rule

func (*Policy) IsPerforming

func (p *Policy) IsPerforming() bool

IsPerforming checks if the policy is performing well

func (*Policy) SuccessRate

func (p *Policy) SuccessRate() float64

SuccessRate returns the success rate of this policy

type PolicyType

type PolicyType string

PolicyType represents the type of policy stored in procedural memory

const (
	// PolicyEntry defines when and how to enter a position
	PolicyEntry PolicyType = "entry"

	// PolicyExit defines when and how to exit a position
	PolicyExit PolicyType = "exit"

	// PolicySizing defines how to size positions
	PolicySizing PolicyType = "sizing"

	// PolicyRisk defines risk management rules
	PolicyRisk PolicyType = "risk"

	// PolicyHedging defines hedging strategies
	PolicyHedging PolicyType = "hedging"

	// PolicyRebalancing defines portfolio rebalancing rules
	PolicyRebalancing PolicyType = "rebalancing"
)

type ProceduralMemory

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

ProceduralMemory manages policies and skills

func NewProceduralMemory

func NewProceduralMemory(pool *pgxpool.Pool) *ProceduralMemory

NewProceduralMemory creates a new procedural memory instance

func (*ProceduralMemory) DeactivatePolicy

func (pm *ProceduralMemory) DeactivatePolicy(ctx context.Context, id uuid.UUID) error

DeactivatePolicy deactivates a policy

func (*ProceduralMemory) GetBestPolicies

func (pm *ProceduralMemory) GetBestPolicies(ctx context.Context, limit int) ([]*Policy, error)

GetBestPolicies retrieves the best performing policies

func (*ProceduralMemory) GetPoliciesByAgent

func (pm *ProceduralMemory) GetPoliciesByAgent(ctx context.Context, agentName string, activeOnly bool) ([]*Policy, error)

GetPoliciesByAgent retrieves policies for a specific agent

func (*ProceduralMemory) GetPoliciesByType

func (pm *ProceduralMemory) GetPoliciesByType(ctx context.Context, policyType PolicyType, activeOnly bool) ([]*Policy, error)

GetPoliciesByType retrieves policies of a specific type

func (*ProceduralMemory) GetSkillsByAgent

func (pm *ProceduralMemory) GetSkillsByAgent(ctx context.Context, agentName string, activeOnly bool) ([]*Skill, error)

GetSkillsByAgent retrieves skills for a specific agent

func (*ProceduralMemory) RecordPolicyApplication

func (pm *ProceduralMemory) RecordPolicyApplication(ctx context.Context, id uuid.UUID, success bool, pnl float64) error

RecordPolicyApplication records that a policy was applied

func (*ProceduralMemory) RecordSkillUsage

func (pm *ProceduralMemory) RecordSkillUsage(ctx context.Context, id uuid.UUID, success bool, duration float64, accuracy float64) error

RecordSkillUsage records that a skill was used

func (*ProceduralMemory) StorePolicy

func (pm *ProceduralMemory) StorePolicy(ctx context.Context, policy *Policy) error

StorePolicy stores a policy in procedural memory

func (*ProceduralMemory) StoreSkill

func (pm *ProceduralMemory) StoreSkill(ctx context.Context, skill *Skill) error

StoreSkill stores a skill in procedural memory

type SemanticMemory

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

SemanticMemory manages knowledge storage and retrieval using vector embeddings

func NewSemanticMemory

func NewSemanticMemory(pool *pgxpool.Pool) *SemanticMemory

NewSemanticMemory creates a new semantic memory instance

func NewSemanticMemoryFromDB

func NewSemanticMemoryFromDB(database *db.DB) *SemanticMemory

NewSemanticMemoryFromDB creates a semantic memory instance from existing DB connection

func (*SemanticMemory) Delete

func (sm *SemanticMemory) Delete(ctx context.Context, id uuid.UUID) error

Delete removes a knowledge item from semantic memory

func (*SemanticMemory) FindByAgent

func (sm *SemanticMemory) FindByAgent(ctx context.Context, agentName string, limit int) ([]*KnowledgeItem, error)

FindByAgent retrieves knowledge learned by a specific agent

func (*SemanticMemory) FindByType

func (sm *SemanticMemory) FindByType(ctx context.Context, knowledgeType KnowledgeType, limit int) ([]*KnowledgeItem, error)

FindByType retrieves knowledge items of a specific type

func (*SemanticMemory) FindSimilar

func (sm *SemanticMemory) FindSimilar(ctx context.Context, embedding []float32, limit int, filters ...Filter) ([]*KnowledgeItem, error)

FindSimilar finds knowledge items similar to the given embedding

func (*SemanticMemory) GetMostRelevant

func (sm *SemanticMemory) GetMostRelevant(ctx context.Context, limit int, filters ...Filter) ([]*KnowledgeItem, error)

GetMostRelevant retrieves the most relevant knowledge items based on multiple criteria

func (*SemanticMemory) GetStats

func (sm *SemanticMemory) GetStats(ctx context.Context) (map[string]interface{}, error)

GetStats returns statistics about semantic memory

func (*SemanticMemory) PruneExpired

func (sm *SemanticMemory) PruneExpired(ctx context.Context) (int, error)

PruneExpired removes expired knowledge items

func (*SemanticMemory) PruneLowQuality

func (sm *SemanticMemory) PruneLowQuality(ctx context.Context, minValidations int, minSuccessRate float64) (int, error)

PruneLowQuality removes knowledge items with low success rates

func (*SemanticMemory) RecordAccess

func (sm *SemanticMemory) RecordAccess(ctx context.Context, id uuid.UUID) error

RecordAccess increments the access count for a knowledge item

func (*SemanticMemory) RecordValidation

func (sm *SemanticMemory) RecordValidation(ctx context.Context, id uuid.UUID, success bool) error

RecordValidation records a validation attempt (success or failure)

func (*SemanticMemory) Store

func (sm *SemanticMemory) Store(ctx context.Context, item *KnowledgeItem) error

Store stores a knowledge item in semantic memory

func (*SemanticMemory) UpdateConfidence

func (sm *SemanticMemory) UpdateConfidence(ctx context.Context, id uuid.UUID, confidence float64) error

UpdateConfidence updates the confidence level of a knowledge item

type Skill

type Skill struct {
	ID uuid.UUID `json:"id"`

	// Skill metadata
	Type        SkillType `json:"type"`
	Name        string    `json:"name"`
	Description string    `json:"description"`

	// Skill definition
	Implementation []byte `json:"implementation"` // JSONB - how to execute this skill
	Parameters     []byte `json:"parameters"`     // JSONB - configurable parameters
	Prerequisites  []byte `json:"prerequisites"`  // JSONB - required conditions/resources

	// Performance tracking
	TimesUsed    int     `json:"times_used"`    // How many times this skill was used
	SuccessCount int     `json:"success_count"` // Successful executions
	FailureCount int     `json:"failure_count"` // Failed executions
	AvgDuration  float64 `json:"avg_duration"`  // Average execution duration (ms)
	AvgAccuracy  float64 `json:"avg_accuracy"`  // Average accuracy (0.0 to 1.0)

	// Learning metadata
	AgentName   string     `json:"agent_name"`   // Which agent has this skill
	LearnedFrom string     `json:"learned_from"` // Source: "training", "observation", "manual"
	SourceID    *uuid.UUID `json:"source_id"`    // ID of source
	Proficiency float64    `json:"proficiency"`  // Proficiency level (0.0 to 1.0)
	IsActive    bool       `json:"is_active"`    // Whether this skill is active

	// Temporal
	CreatedAt time.Time  `json:"created_at"`
	UpdatedAt time.Time  `json:"updated_at"`
	LastUsed  *time.Time `json:"last_used"`
}

Skill represents an agent's learned capability or skill

func (*Skill) IsProficient

func (s *Skill) IsProficient() bool

IsProficient checks if the agent is proficient in this skill

func (*Skill) SkillSuccessRate

func (s *Skill) SkillSuccessRate() float64

SkillSuccessRate returns the success rate of this skill

type SkillType

type SkillType string

SkillType represents types of agent skills

const (
	// SkillTechnicalAnalysis represents technical analysis capability
	SkillTechnicalAnalysis SkillType = "technical_analysis"

	// SkillOrderBookAnalysis represents order book analysis capability
	SkillOrderBookAnalysis SkillType = "orderbook_analysis"

	// SkillSentimentAnalysis represents sentiment analysis capability
	SkillSentimentAnalysis SkillType = "sentiment_analysis"

	// SkillTrendFollowing represents trend following strategy
	SkillTrendFollowing SkillType = "trend_following"

	// SkillMeanReversion represents mean reversion strategy
	SkillMeanReversion SkillType = "mean_reversion"

	// SkillRiskManagement represents risk management capability
	SkillRiskManagement SkillType = "risk_management"
)

type SymbolFilter

type SymbolFilter struct {
	Symbol string
}

SymbolFilter filters by symbol

func (SymbolFilter) SQL

func (f SymbolFilter) SQL(argIndex int) (string, []interface{})

type TypeFilter

type TypeFilter struct {
	Type KnowledgeType
}

TypeFilter filters by knowledge type

func (TypeFilter) SQL

func (f TypeFilter) SQL(argIndex int) (string, []interface{})

type ValidOnlyFilter

type ValidOnlyFilter struct{}

ValidOnlyFilter filters to only valid knowledge (not expired, good success rate)

func (ValidOnlyFilter) SQL

func (f ValidOnlyFilter) SQL(argIndex int) (string, []interface{})

Jump to

Keyboard shortcuts

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