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 ¶
- Variables
- func CalculateCost(model string, inputTokens, outputTokens int) float64
- func EstimateMessageTokens(msg SessionMessage) int
- func EstimateSessionTokens(session *Session) int
- func EstimateSessionTokensByRole(session *Session) (int, int, int)
- func EstimateTokens(text string) int
- func ExportSession(sessionID int64, format string) (string, error)
- func FormatCost(cost float64) string
- func FormatNumber(n int) string
- func FormatTokenCount(tokens int) string
- func GenerateNameFromMessage(content string) string
- func GetAnalyticsPath() string
- func GetExportDir() string
- func GetMessagesForLLM(session *Session) []map[string]string
- func GetModelLimit(model string) int
- func GetModelLimitWithOverride(model string, configOverride int) int
- func ListConfigs() ([]string, error)
- func NamedConfigPath(name string) string
- func Paths() (configDir, configFile, secretsFile, skillsFile string)
- func Save(config *Config) error
- func SaveSecrets(config *Config) error
- func SaveSkillsConfig(skillsConfig *Config) error
- type CollectionsConfig
- type Config
- type ConfigLoader
- func (l *ConfigLoader) GetAlchemyConfig() (skills.AlchemyConfig, error)
- func (l *ConfigLoader) GetBlockmonConfig() (skills.BlockmonConfig, error)
- func (l *ConfigLoader) GetIPFSConfig() (skills.IPFSConfig, error)
- func (l *ConfigLoader) GetTarotConfig() (skills.TarotConfig, error)
- func (l *ConfigLoader) GetTwitchConfig() (skills.TwitchConfig, error)
- func (l *ConfigLoader) GetVeniceConfig() (skills.VeniceConfig, error)
- func (l *ConfigLoader) GetWalletSecurityConfig() (skills.WalletSecuritySettingsConfig, error)
- func (l *ConfigLoader) GetWeatherConfig() (skills.WeatherConfig, error)
- func (l *ConfigLoader) GetYouTubeConfig() (skills.YouTubeConfig, error)
- type ContextTracker
- func (ct *ContextTracker) EstimateMessagesUntilLimit(avgTokensPerMsg int) int
- func (ct *ContextTracker) GetContextSummary() string
- func (ct *ContextTracker) GetRemainingTokens() int
- func (ct *ContextTracker) GetStatusEmoji() string
- func (ct *ContextTracker) GetUsagePercentage() float64
- func (ct *ContextTracker) GetWarningLevel() string
- func (ct *ContextTracker) GetWarningMessage() string
- func (ct *ContextTracker) IncrementCompactionCount()
- func (ct *ContextTracker) IncrementTruncationCount()
- func (ct *ContextTracker) MarkWarningShown()
- func (ct *ContextTracker) ShouldCompact() bool
- func (ct *ContextTracker) ShouldWarn() bool
- func (ct *ContextTracker) UpdateFromEstimate()
- func (ct *ContextTracker) UpdateTokens(prompt, completion, total int)
- type DailyStats
- type Exporter
- type GlobalAnalytics
- func (ga *GlobalAnalytics) GetTopModelNames(n int) []struct{ ... }
- func (ga *GlobalAnalytics) GetTopModels(n int) []ModelStats
- func (ga *GlobalAnalytics) GetTopProviders() []struct{ ... }
- func (ga *GlobalAnalytics) GetWeeklyUsage() []DailyStats
- func (ga *GlobalAnalytics) Save() error
- func (ga *GlobalAnalytics) UpdateFromSession(session *Session)
- type ModelStats
- type PricingTier
- type ProviderStats
- type Session
- func (s *Session) ClearMessages()
- func (s *Session) GetEndpoint() string
- func (s *Session) GetMessages() []SessionMessage
- func (s *Session) GetMessagesRaw() interface{}
- func (s *Session) GetMessagesWithLimit(systemPromptTokens int) []SessionMessage
- func (s *Session) GetModel() string
- func (s *Session) GetNSFWMode() bool
- func (s *Session) GetProvider() string
- func (s *Session) InitializeUsageMetrics()
- func (s *Session) SetEndpoint(endpoint string)
- func (s *Session) SetMessagesRaw(msgs interface{})
- func (s *Session) SetModel(model string)
- func (s *Session) SetNSFWMode(enabled bool)
- func (s *Session) SetName(name string)
- func (s *Session) SetProvider(provider string)
- func (s *Session) Summarize() SessionSummary
- func (s *Session) SummarizeRaw() interface{}
- func (s *Session) UpdateUsageMetrics(inputTokens, outputTokens int)
- type SessionManager
- func (m *SessionManager) AddMessage(session *Session, role, content string)
- func (m *SessionManager) AddMessageWithTokens(session *Session, role, content string, inputTokens, outputTokens int)
- func (m *SessionManager) Clear() error
- func (m *SessionManager) Delete(id string) error
- func (m *SessionManager) GetCurrentID() string
- func (m *SessionManager) List() ([]Session, error)
- func (m *SessionManager) ListRaw() ([]interface{}, error)
- func (m *SessionManager) Load(id string) (*Session, error)
- func (m *SessionManager) LoadLatest() (*Session, error)
- func (m *SessionManager) LoadRaw(id string) (interface{}, error)
- func (m *SessionManager) MergeSessions(session1, session2 *Session) *Session
- func (m *SessionManager) MergeSessionsRaw(session1, session2 interface{}) interface{}
- func (m *SessionManager) NewSession() *Session
- func (m *SessionManager) NewSessionRaw() interface{}
- func (m *SessionManager) Save(session *Session) error
- func (m *SessionManager) SaveRaw(session interface{}) error
- type SessionMessage
- type SessionSummary
- type UsageMetrics
- type XAIFeaturesConfig
Constants ¶
This section is empty.
Variables ¶
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)
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 ¶
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 ¶
EstimateSessionTokens counts total tokens in session
func EstimateSessionTokensByRole ¶
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 ¶
EstimateTokens approximates token count (rough: 4 chars = 1 token) This is a simple estimation. For production, consider using tiktoken library.
func ExportSession ¶
ExportSession is a helper function to export a session by ID
func FormatCost ¶
FormatCost formats a cost value as a currency string
func FormatNumber ¶
FormatNumber formats a number with thousand separators
func FormatTokenCount ¶
FormatTokenCount formats token count with K/M suffix
func GenerateNameFromMessage ¶
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 ¶
GetMessagesForLLM converts session messages to a format suitable for LLM.
func GetModelLimit ¶
GetModelLimit returns token limit for a model
func GetModelLimitWithOverride ¶
GetModelLimitWithOverride returns token limit for a model, with optional config override
func ListConfigs ¶
ListConfigs returns all available config names.
func NamedConfigPath ¶
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 SaveSecrets ¶
SaveSecrets saves API key to secrets file (backward compatibility).
func SaveSkillsConfig ¶
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 LoadNamed ¶
LoadNamed loads configuration from a named config file. If name is empty, loads the default config.
func LoadSkillsConfig ¶
LoadSkillsConfig loads skill-specific configuration from skills.json.
func (*Config) GetTimeout ¶
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 ¶
NewExporter creates a new exporter for a session
func (*Exporter) ExportToFile ¶
ExportToFile is a convenience method that exports and saves in one call
func (*Exporter) SaveToFile ¶
SaveToFile saves the exported content to a file
func (*Exporter) ToCSV ¶
ToCSV exports the session as CSV (one row per message) Format: timestamp,role,content,tokens,model,cost
func (*Exporter) ToMarkdown ¶
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 ¶
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 ¶
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 ¶
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) GetNSFWMode ¶
GetNSFWMode retrieves the NSFW mode from session.
func (*Session) GetProvider ¶
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 ¶
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) SetNSFWMode ¶
SetNSFWMode stores the NSFW mode in session.
func (*Session) SetProvider ¶
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 ¶
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) 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