config

package
v1.5.4 Latest Latest
Warning

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

Go to latest
Published: Feb 25, 2026 License: MIT Imports: 10 Imported by: 0

Documentation

Overview

Package config provides configuration management for Celeste CLI.

Package config provides configuration management for Celeste CLI. This file handles session persistence (conversation history).

Package config provides configuration management for Celeste CLI. This file handles token estimation and context window management.

Index

Constants

This section is empty.

Variables

View Source
var ModelLimits = map[string]int{
	"gpt-4":             8192,
	"gpt-4-turbo":       128000,
	"gpt-4o":            128000,
	"gpt-4o-mini":       128000,
	"gpt-3.5-turbo":     16385,
	"claude-3-opus":     200000,
	"claude-3-sonnet":   200000,
	"claude-3-haiku":    200000,
	"claude-sonnet-4":   200000,
	"claude-opus-4.5":   200000,
	"venice-uncensored": 8192,
	"llama-3.3-70b":     8192,
	"grok-4-1":          128000,
	"grok-4-1-fast":     128000,
	"default":           8192,
}

Model token limits (approximate context windows)

View Source
var ModelPricing = map[string]PricingTier{

	"gpt-4o":            {2.50, 10.00},
	"gpt-4o-mini":       {0.15, 0.60},
	"gpt-4o-2024-11-20": {2.50, 10.00},
	"gpt-4-turbo":       {10.00, 30.00},
	"gpt-4":             {30.00, 60.00},
	"gpt-3.5-turbo":     {0.50, 1.50},
	"gpt-3.5-turbo-16k": {3.00, 4.00},

	"claude-opus-4.5":            {15.00, 75.00},
	"claude-sonnet-4":            {3.00, 15.00},
	"claude-3-5-sonnet-20241022": {3.00, 15.00},
	"claude-3-5-sonnet-20240620": {3.00, 15.00},
	"claude-3-opus-20240229":     {15.00, 75.00},
	"claude-3-sonnet-20240229":   {3.00, 15.00},
	"claude-3-haiku-20240307":    {0.80, 4.00},
	"claude-haiku":               {0.80, 4.00},

	"grok-4-1-fast": {5.00, 25.00},
	"grok-4-1":      {3.00, 15.00},
	"grok-4":        {3.00, 15.00},
	"grok-3":        {2.00, 10.00},
	"grok-2":        {1.00, 5.00},

	"gemini-2.0-flash-exp": {0.00, 0.00},
	"gemini-1.5-pro":       {1.25, 5.00},
	"gemini-1.5-flash":     {0.075, 0.30},
	"gemini-1.0-pro":       {0.50, 1.50},

	"venice-uncensored": {0.00, 0.00},
	"llama-3.3-70b":     {0.50, 0.50},

	"meta-llama/llama-3.3-70b-instruct": {0.60, 0.60},
	"anthropic/claude-3-opus":           {15.00, 75.00},
	"anthropic/claude-3-sonnet":         {3.00, 15.00},
	"openai/gpt-4o":                     {2.50, 10.00},
}

ModelPricing contains pricing information for various LLM models (2025 rates)

Functions

func CalculateCost

func CalculateCost(model string, inputTokens, outputTokens int) float64

CalculateCost calculates the estimated cost based on token usage and model pricing

func EstimateMessageTokens

func EstimateMessageTokens(msg SessionMessage) int

EstimateMessageTokens counts tokens in a message

func EstimateSessionTokens

func EstimateSessionTokens(session *Session) int

EstimateSessionTokens counts total tokens in session

func EstimateSessionTokensByRole

func EstimateSessionTokensByRole(session *Session) (int, int, int)

EstimateSessionTokensByRole calculates separate input/output token counts from message history. Returns (promptTokens, completionTokens, totalTokens) - promptTokens: tokens in user messages + system messages - completionTokens: tokens in assistant messages This is useful for calculating historical sessions or when API doesn't provide breakdown.

func EstimateTokens

func EstimateTokens(text string) int

EstimateTokens approximates token count (rough: 4 chars = 1 token) This is a simple estimation. For production, consider using tiktoken library.

func ExportSession

func ExportSession(sessionID int64, format string) (string, error)

ExportSession is a helper function to export a session by ID

func FormatCost

func FormatCost(cost float64) string

FormatCost formats a cost value as a currency string

func FormatNumber

func FormatNumber(n int) string

FormatNumber formats a number with thousand separators

func FormatTokenCount

func FormatTokenCount(tokens int) string

FormatTokenCount formats token count with K/M suffix

func GenerateNameFromMessage

func GenerateNameFromMessage(content string) string

GenerateNameFromMessage creates a session name from first user message. Extracts first 40-50 chars, intelligently truncates at word boundary.

func GetAnalyticsPath

func GetAnalyticsPath() string

GetAnalyticsPath returns the path to the analytics file

func GetExportDir

func GetExportDir() string

GetExportDir returns the path to the exports directory

func GetMessagesForLLM

func GetMessagesForLLM(session *Session) []map[string]string

GetMessagesForLLM converts session messages to a format suitable for LLM.

func GetModelLimit

func GetModelLimit(model string) int

GetModelLimit returns token limit for a model

func GetModelLimitWithOverride

func GetModelLimitWithOverride(model string, configOverride int) int

GetModelLimitWithOverride returns token limit for a model, with optional config override

func ListConfigs

func ListConfigs() ([]string, error)

ListConfigs returns all available config names.

func NamedConfigPath

func NamedConfigPath(name string) string

NamedConfigPath returns the path for a named config file. If name is empty, returns the default config path.

func Paths

func Paths() (configDir, configFile, secretsFile, skillsFile string)

Paths returns the configuration directory and file paths.

func Save

func Save(config *Config) error

Save saves configuration to file.

func SaveSecrets

func SaveSecrets(config *Config) error

SaveSecrets saves API key to secrets file (backward compatibility).

func SaveSkillsConfig

func SaveSkillsConfig(skillsConfig *Config) error

SaveSkillsConfig saves skill-specific configuration to skills.json.

Types

type CollectionsConfig

type CollectionsConfig struct {
	Enabled           bool     `json:"enabled"`
	ActiveCollections []string `json:"active_collections"`
	AutoEnable        bool     `json:"auto_enable"`
}

CollectionsConfig holds collections settings

type Config

type Config struct {
	// API settings
	APIKey       string `json:"api_key"`
	BaseURL      string `json:"base_url"`
	Model        string `json:"model"`
	Timeout      int    `json:"timeout"`                 // seconds
	ContextLimit int    `json:"context_limit,omitempty"` // Optional: Override context window size

	// Google Cloud authentication (for Gemini/Vertex AI)
	GoogleCredentialsFile string `json:"google_credentials_file,omitempty"` // Path to service account JSON file
	GoogleUseADC          bool   `json:"google_use_adc,omitempty"`          // Use Application Default Credentials

	// Runtime-detected provider (not persisted to config file)
	Provider string `json:"-"` // Detected from BaseURL at runtime

	// Persona settings
	SkipPersonaPrompt bool `json:"skip_persona_prompt"`

	// Streaming settings
	SimulateTyping bool `json:"simulate_typing"`
	TypingSpeed    int  `json:"typing_speed"` // chars per second

	// Venice.ai settings (for NSFW mode)
	VeniceAPIKey     string `json:"venice_api_key,omitempty"`
	VeniceBaseURL    string `json:"venice_base_url,omitempty"`
	VeniceModel      string `json:"venice_model,omitempty"`       // Chat model (venice-uncensored)
	VeniceImageModel string `json:"venice_image_model,omitempty"` // Image model (lustify-sdxl)

	// Tarot settings
	TarotFunctionURL string `json:"tarot_function_url,omitempty"`
	TarotAuthToken   string `json:"tarot_auth_token,omitempty"`

	// Twitter settings
	TwitterBearerToken       string `json:"twitter_bearer_token,omitempty"`
	TwitterAPIKey            string `json:"twitter_api_key,omitempty"`
	TwitterAPISecret         string `json:"twitter_api_secret,omitempty"`
	TwitterAccessToken       string `json:"twitter_access_token,omitempty"`
	TwitterAccessTokenSecret string `json:"twitter_access_token_secret,omitempty"`

	// Weather settings
	WeatherDefaultZipCode string `json:"weather_default_zip_code,omitempty"`

	// Twitch settings
	TwitchClientID        string `json:"twitch_client_id,omitempty"`
	TwitchClientSecret    string `json:"twitch_client_secret,omitempty"`
	TwitchDefaultStreamer string `json:"twitch_default_streamer,omitempty"`

	// YouTube settings
	YouTubeAPIKey         string `json:"youtube_api_key,omitempty"`
	YouTubeDefaultChannel string `json:"youtube_default_channel,omitempty"`

	// IPFS settings
	IPFSProvider       string `json:"ipfs_provider,omitempty"` // "infura", "pinata", "custom"
	IPFSAPIKey         string `json:"ipfs_api_key,omitempty"`
	IPFSAPISecret      string `json:"ipfs_api_secret,omitempty"`
	IPFSProjectID      string `json:"ipfs_project_id,omitempty"` // Infura specific
	IPFSGatewayURL     string `json:"ipfs_gateway_url,omitempty"`
	IPFSTimeoutSeconds int    `json:"ipfs_timeout_seconds,omitempty"`

	// Alchemy settings
	AlchemyAPIKey         string `json:"alchemy_api_key,omitempty"`
	AlchemyDefaultNetwork string `json:"alchemy_default_network,omitempty"`
	AlchemyTimeoutSeconds int    `json:"alchemy_timeout_seconds,omitempty"`

	// Blockchain monitoring settings
	BlockmonAlchemyAPIKey       string `json:"blockmon_alchemy_api_key,omitempty"`
	BlockmonWebhookURL          string `json:"blockmon_webhook_url,omitempty"`
	BlockmonDefaultNetwork      string `json:"blockmon_default_network,omitempty"`
	BlockmonPollIntervalSeconds int    `json:"blockmon_poll_interval_seconds,omitempty"`

	// Wallet security settings
	WalletSecurityEnabled      bool   `json:"wallet_security_enabled,omitempty"`
	WalletSecurityPollInterval int    `json:"wallet_security_poll_interval,omitempty"` // seconds
	WalletSecurityAlertLevel   string `json:"wallet_security_alert_level,omitempty"`   // "low", "medium", "high", "critical"

	// Collections configuration (xAI only)
	XAIManagementAPIKey string             `json:"xai_management_api_key,omitempty"`
	Collections         *CollectionsConfig `json:"collections,omitempty"`
	XAIFeatures         *XAIFeaturesConfig `json:"xai_features,omitempty"`
}

Config holds all configuration for Celeste CLI.

func DefaultConfig

func DefaultConfig() *Config

DefaultConfig returns a config with default values.

func Load

func Load() (*Config, error)

Load loads configuration from file and environment.

func LoadNamed

func LoadNamed(name string) (*Config, error)

LoadNamed loads configuration from a named config file. If name is empty, loads the default config.

func LoadSkillsConfig

func LoadSkillsConfig() (*Config, error)

LoadSkillsConfig loads skill-specific configuration from skills.json.

func (*Config) GetTimeout

func (c *Config) GetTimeout() time.Duration

GetTimeout returns the configured timeout as a duration.

type ConfigLoader

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

ConfigLoader implements skills.ConfigLoader interface.

func NewConfigLoader

func NewConfigLoader(config *Config) *ConfigLoader

NewConfigLoader creates a new config loader.

func (*ConfigLoader) GetAlchemyConfig

func (l *ConfigLoader) GetAlchemyConfig() (skills.AlchemyConfig, error)

GetAlchemyConfig returns Alchemy API configuration.

func (*ConfigLoader) GetBlockmonConfig

func (l *ConfigLoader) GetBlockmonConfig() (skills.BlockmonConfig, error)

GetBlockmonConfig returns blockchain monitoring configuration.

func (*ConfigLoader) GetIPFSConfig

func (l *ConfigLoader) GetIPFSConfig() (skills.IPFSConfig, error)

GetIPFSConfig returns IPFS configuration.

func (*ConfigLoader) GetTarotConfig

func (l *ConfigLoader) GetTarotConfig() (skills.TarotConfig, error)

GetTarotConfig returns tarot configuration.

func (*ConfigLoader) GetTwitchConfig

func (l *ConfigLoader) GetTwitchConfig() (skills.TwitchConfig, error)

GetTwitchConfig returns Twitch API configuration.

func (*ConfigLoader) GetVeniceConfig

func (l *ConfigLoader) GetVeniceConfig() (skills.VeniceConfig, error)

GetVeniceConfig returns Venice.ai configuration.

func (*ConfigLoader) GetWalletSecurityConfig

func (l *ConfigLoader) GetWalletSecurityConfig() (skills.WalletSecuritySettingsConfig, error)

GetWalletSecurityConfig returns wallet security monitoring configuration.

func (*ConfigLoader) GetWeatherConfig

func (l *ConfigLoader) GetWeatherConfig() (skills.WeatherConfig, error)

GetWeatherConfig returns weather skill configuration.

func (*ConfigLoader) GetYouTubeConfig

func (l *ConfigLoader) GetYouTubeConfig() (skills.YouTubeConfig, error)

GetYouTubeConfig returns YouTube API configuration.

type ContextTracker

type ContextTracker struct {
	Session          *Session
	Model            string
	MaxTokens        int
	CurrentTokens    int
	PromptTokens     int
	CompletionTokens int

	// Thresholds
	WarnThreshold     float64 // 0.75
	CautionThreshold  float64 // 0.85
	CriticalThreshold float64 // 0.95

	// Tracking
	LastWarningLevel string
	CompactionCount  int
	TruncationCount  int
}

ContextTracker monitors token usage and context window status for a session

func NewContextTracker

func NewContextTracker(session *Session, model string, contextLimitOverride ...int) *ContextTracker

NewContextTracker creates a new context tracker for a session

func (*ContextTracker) EstimateMessagesUntilLimit

func (ct *ContextTracker) EstimateMessagesUntilLimit(avgTokensPerMsg int) int

EstimateMessagesUntilLimit estimates how many messages can be sent before hitting limit

func (*ContextTracker) GetContextSummary

func (ct *ContextTracker) GetContextSummary() string

GetContextSummary returns a formatted summary of context usage

func (*ContextTracker) GetRemainingTokens

func (ct *ContextTracker) GetRemainingTokens() int

GetRemainingTokens returns the number of tokens remaining before limit

func (*ContextTracker) GetStatusEmoji

func (ct *ContextTracker) GetStatusEmoji() string

GetStatusEmoji returns an emoji representing the current status

func (*ContextTracker) GetUsagePercentage

func (ct *ContextTracker) GetUsagePercentage() float64

GetUsagePercentage returns the percentage of context window used (0.0 to 1.0)

func (*ContextTracker) GetWarningLevel

func (ct *ContextTracker) GetWarningLevel() string

GetWarningLevel returns the current warning level based on usage percentage Possible values: "ok", "warn", "caution", "critical"

func (*ContextTracker) GetWarningMessage

func (ct *ContextTracker) GetWarningMessage() string

GetWarningMessage returns a user-friendly warning message

func (*ContextTracker) IncrementCompactionCount

func (ct *ContextTracker) IncrementCompactionCount()

IncrementCompactionCount increments the compaction counter

func (*ContextTracker) IncrementTruncationCount

func (ct *ContextTracker) IncrementTruncationCount()

IncrementTruncationCount increments the truncation counter

func (*ContextTracker) MarkWarningShown

func (ct *ContextTracker) MarkWarningShown()

MarkWarningShown updates the last warning level after displaying a warning

func (*ContextTracker) ShouldCompact

func (ct *ContextTracker) ShouldCompact() bool

ShouldCompact returns true if auto-compaction should be triggered

func (*ContextTracker) ShouldWarn

func (ct *ContextTracker) ShouldWarn() bool

ShouldWarn returns true if a warning should be displayed

func (*ContextTracker) UpdateFromEstimate

func (ct *ContextTracker) UpdateFromEstimate()

UpdateFromEstimate updates tokens using character-based estimation

func (*ContextTracker) UpdateTokens

func (ct *ContextTracker) UpdateTokens(prompt, completion, total int)

UpdateTokens updates token counts from API response

type DailyStats

type DailyStats struct {
	Date         string  `json:"date"`
	SessionCount int     `json:"session_count"`
	MessageCount int     `json:"message_count"`
	TokenCount   int     `json:"token_count"`
	Cost         float64 `json:"cost"`
}

DailyStats tracks usage for a specific day

type Exporter

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

Exporter handles session export to various formats

func NewExporter

func NewExporter(session *Session) *Exporter

NewExporter creates a new exporter for a session

func (*Exporter) ExportToFile

func (e *Exporter) ExportToFile(format string) (string, error)

ExportToFile is a convenience method that exports and saves in one call

func (*Exporter) SaveToFile

func (e *Exporter) SaveToFile(content string, format string) (string, error)

SaveToFile saves the exported content to a file

func (*Exporter) ToCSV

func (e *Exporter) ToCSV() (string, error)

ToCSV exports the session as CSV (one row per message) Format: timestamp,role,content,tokens,model,cost

func (*Exporter) ToJSON

func (e *Exporter) ToJSON() (string, error)

ToJSON exports the session as pretty-printed JSON

func (*Exporter) ToMarkdown

func (e *Exporter) ToMarkdown() (string, error)

ToMarkdown exports the session as Markdown with frontmatter

type GlobalAnalytics

type GlobalAnalytics struct {
	TotalSessions int     `json:"total_sessions"`
	TotalMessages int     `json:"total_messages"`
	TotalTokens   int     `json:"total_tokens"`
	TotalCost     float64 `json:"total_cost"`

	// Per-provider breakdown
	ProviderUsage map[string]*ProviderStats `json:"provider_usage"`

	// Per-model breakdown
	ModelUsage map[string]*ModelStats `json:"model_usage"`

	// Time-based tracking (YYYY-MM-DD -> stats)
	DailyUsage map[string]*DailyStats `json:"daily_usage"`

	LastUpdated time.Time `json:"last_updated"`
}

GlobalAnalytics tracks cumulative usage across all sessions

func LoadGlobalAnalytics

func LoadGlobalAnalytics() (*GlobalAnalytics, error)

LoadGlobalAnalytics loads analytics from ~/.celeste/analytics.json

func NewGlobalAnalytics

func NewGlobalAnalytics() *GlobalAnalytics

NewGlobalAnalytics creates a new empty analytics tracker

func (*GlobalAnalytics) GetTopModelNames

func (ga *GlobalAnalytics) GetTopModelNames(n int) []struct {
	Name  string
	Stats ModelStats
}

GetTopModelNames returns the top N model names with their stats

func (*GlobalAnalytics) GetTopModels

func (ga *GlobalAnalytics) GetTopModels(n int) []ModelStats

GetTopModels returns the top N models by usage

func (*GlobalAnalytics) GetTopProviders

func (ga *GlobalAnalytics) GetTopProviders() []struct {
	Name  string
	Stats ProviderStats
}

GetTopProviders returns providers sorted by usage

func (*GlobalAnalytics) GetWeeklyUsage

func (ga *GlobalAnalytics) GetWeeklyUsage() []DailyStats

GetWeeklyUsage returns usage stats for the last 7 days

func (*GlobalAnalytics) Save

func (ga *GlobalAnalytics) Save() error

Save persists analytics to ~/.celeste/analytics.json

func (*GlobalAnalytics) UpdateFromSession

func (ga *GlobalAnalytics) UpdateFromSession(session *Session)

UpdateFromSession updates analytics with data from a session

type ModelStats

type ModelStats struct {
	SessionCount int     `json:"session_count"`
	MessageCount int     `json:"message_count"`
	InputTokens  int     `json:"input_tokens"`
	OutputTokens int     `json:"output_tokens"`
	Cost         float64 `json:"cost"`
}

ModelStats tracks usage for a specific model

type PricingTier

type PricingTier struct {
	InputCostPerMillion  float64
	OutputCostPerMillion float64
}

PricingTier represents the cost per million tokens for input and output

func GetModelPricing

func GetModelPricing(model string) (PricingTier, bool)

GetModelPricing returns the pricing tier for a model, if available

type ProviderStats

type ProviderStats struct {
	SessionCount int     `json:"session_count"`
	MessageCount int     `json:"message_count"`
	TokenCount   int     `json:"token_count"`
	Cost         float64 `json:"cost"`
}

ProviderStats tracks usage for a specific provider

type Session

type Session struct {
	ID         string           `json:"id"`
	Name       string           `json:"name,omitempty"`
	CreatedAt  time.Time        `json:"created_at"`
	UpdatedAt  time.Time        `json:"updated_at"`
	Messages   []SessionMessage `json:"messages"`
	NSFWMode   bool             `json:"nsfw_mode,omitempty"`
	Metadata   map[string]any   `json:"metadata,omitempty"`
	TokenCount int              `json:"token_count,omitempty"` // Estimated token count
	Model      string           `json:"model,omitempty"`       // Track model for limits

	// NEW: Enhanced tracking
	UsageMetrics *UsageMetrics `json:"usage_metrics,omitempty"` // Detailed usage tracking
	Provider     string        `json:"provider,omitempty"`      // Provider (openai, venice, etc)
	MaxContext   int           `json:"max_context,omitempty"`   // Model's max context window
}

Session represents a saved conversation session.

func LoadSession

func LoadSession(sessionID int64) (*Session, error)

LoadSession is a global helper to load a session by numeric ID

func (*Session) ClearMessages

func (s *Session) ClearMessages()

ClearMessages clears all messages from the session.

func (*Session) GetEndpoint

func (s *Session) GetEndpoint() string

GetEndpoint retrieves the endpoint from session metadata.

func (*Session) GetMessages

func (s *Session) GetMessages() []SessionMessage

GetMessages returns all session messages.

func (*Session) GetMessagesRaw

func (s *Session) GetMessagesRaw() interface{}

GetMessagesRaw returns messages as interface{} (for TUI interface compatibility).

func (*Session) GetMessagesWithLimit

func (s *Session) GetMessagesWithLimit(systemPromptTokens int) []SessionMessage

GetMessagesWithLimit returns messages with token limit applied.

func (*Session) GetModel

func (s *Session) GetModel() string

GetModel retrieves the model from session metadata.

func (*Session) GetNSFWMode

func (s *Session) GetNSFWMode() bool

GetNSFWMode retrieves the NSFW mode from session.

func (*Session) GetProvider

func (s *Session) GetProvider() string

GetProvider retrieves the provider name from the session.

func (*Session) InitializeUsageMetrics

func (s *Session) InitializeUsageMetrics()

InitializeUsageMetrics ensures the session has usage metrics initialized.

func (*Session) SetEndpoint

func (s *Session) SetEndpoint(endpoint string)

SetEndpoint stores the current endpoint in session metadata.

func (*Session) SetMessagesRaw

func (s *Session) SetMessagesRaw(msgs interface{})

SetMessagesRaw sets messages from interface{} (for TUI interface compatibility).

func (*Session) SetModel

func (s *Session) SetModel(model string)

SetModel stores the current model in session metadata.

func (*Session) SetNSFWMode

func (s *Session) SetNSFWMode(enabled bool)

SetNSFWMode stores the NSFW mode in session.

func (*Session) SetName

func (s *Session) SetName(name string)

SetName updates the session name.

func (*Session) SetProvider

func (s *Session) SetProvider(provider string)

SetProvider stores the provider name in the session.

func (*Session) Summarize

func (s *Session) Summarize() SessionSummary

Summarize returns a summary of the session.

func (*Session) SummarizeRaw

func (s *Session) SummarizeRaw() interface{}

SummarizeRaw returns summary as interface{} (for TUI interface compatibility).

func (*Session) UpdateUsageMetrics

func (s *Session) UpdateUsageMetrics(inputTokens, outputTokens int)

UpdateUsageMetrics updates the session's usage metrics with new token data.

type SessionManager

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

SessionManager manages session persistence.

func NewSessionManager

func NewSessionManager() *SessionManager

NewSessionManager creates a new session manager.

func (*SessionManager) AddMessage

func (m *SessionManager) AddMessage(session *Session, role, content string)

AddMessage adds a message to the session and saves.

func (*SessionManager) AddMessageWithTokens

func (m *SessionManager) AddMessageWithTokens(session *Session, role, content string, inputTokens, outputTokens int)

AddMessageWithTokens adds a message to the session with token tracking.

func (*SessionManager) Clear

func (m *SessionManager) Clear() error

Clear deletes all sessions.

func (*SessionManager) Delete

func (m *SessionManager) Delete(id string) error

Delete deletes a session by ID.

func (*SessionManager) GetCurrentID

func (m *SessionManager) GetCurrentID() string

GetCurrentID returns the current session ID.

func (*SessionManager) List

func (m *SessionManager) List() ([]Session, error)

List returns all saved sessions.

func (*SessionManager) ListRaw

func (m *SessionManager) ListRaw() ([]interface{}, error)

ListRaw lists all sessions (returns []interface{}).

func (*SessionManager) Load

func (m *SessionManager) Load(id string) (*Session, error)

Load loads a session by ID.

func (*SessionManager) LoadLatest

func (m *SessionManager) LoadLatest() (*Session, error)

LoadLatest loads the most recent session.

func (*SessionManager) LoadRaw

func (m *SessionManager) LoadRaw(id string) (interface{}, error)

LoadRaw loads a session by ID (returns interface{}).

func (*SessionManager) MergeSessions

func (m *SessionManager) MergeSessions(session1, session2 *Session) *Session

MergeSessions combines messages from two sessions chronologically.

func (*SessionManager) MergeSessionsRaw

func (m *SessionManager) MergeSessionsRaw(session1, session2 interface{}) interface{}

MergeSessionsRaw merges two sessions (accepts and returns interface{}).

func (*SessionManager) NewSession

func (m *SessionManager) NewSession() *Session

NewSession creates a new session with a unique ID.

func (*SessionManager) NewSessionRaw

func (m *SessionManager) NewSessionRaw() interface{}

NewSessionRaw returns a new session as interface{}.

func (*SessionManager) Save

func (m *SessionManager) Save(session *Session) error

Save saves a session to disk.

func (*SessionManager) SaveRaw

func (m *SessionManager) SaveRaw(session interface{}) error

SaveRaw saves a session (accepts interface{}).

type SessionMessage

type SessionMessage struct {
	Role      string    `json:"role"`
	Content   string    `json:"content"`
	Timestamp time.Time `json:"timestamp"`
}

SessionMessage represents a message in a session.

func TruncateToLimit

func TruncateToLimit(messages []SessionMessage, model string, systemPromptTokens int) []SessionMessage

TruncateToLimit removes oldest messages to fit within token limit

type SessionSummary

type SessionSummary struct {
	ID           string         `json:"id"`
	Name         string         `json:"name,omitempty"`
	MessageCount int            `json:"message_count"`
	CreatedAt    time.Time      `json:"created_at"`
	UpdatedAt    time.Time      `json:"updated_at"`
	FirstMessage string         `json:"first_message,omitempty"`
	Metadata     map[string]any `json:"metadata,omitempty"`
}

SessionSummary provides a brief overview of a session.

type UsageMetrics

type UsageMetrics struct {
	TotalInputTokens  int       `json:"total_input_tokens"`
	TotalOutputTokens int       `json:"total_output_tokens"`
	TotalTokens       int       `json:"total_tokens"`
	EstimatedCost     float64   `json:"estimated_cost"`
	CompactionCount   int       `json:"compaction_count"`
	TruncationCount   int       `json:"truncation_count"`
	MessageCount      int       `json:"message_count"`
	ConversationStart time.Time `json:"conversation_start"`
	ConversationEnd   time.Time `json:"conversation_end"`
}

UsageMetrics tracks token usage and cost for a session

func NewUsageMetrics

func NewUsageMetrics() *UsageMetrics

NewUsageMetrics creates a new usage metrics instance

func (*UsageMetrics) GetAverageTokensPerMessage

func (um *UsageMetrics) GetAverageTokensPerMessage() float64

GetAverageTokensPerMessage returns the average tokens per message

func (*UsageMetrics) GetCostPerMessage

func (um *UsageMetrics) GetCostPerMessage() float64

GetCostPerMessage returns the average cost per message

func (*UsageMetrics) GetDuration

func (um *UsageMetrics) GetDuration() time.Duration

GetDuration returns the duration of the conversation

func (*UsageMetrics) IncrementMessageCount

func (um *UsageMetrics) IncrementMessageCount()

IncrementMessageCount increments the message counter

func (*UsageMetrics) Update

func (um *UsageMetrics) Update(inputTokens, outputTokens int, model string)

Update updates the usage metrics with new token counts

type XAIFeaturesConfig

type XAIFeaturesConfig struct {
	EnableWebSearch bool `json:"enable_web_search"`
	EnableXSearch   bool `json:"enable_x_search"`
}

XAIFeaturesConfig holds xAI-specific feature flags

Jump to

Keyboard shortcuts

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