conversation

package
v0.0.0-...-d80aada Latest Latest
Warning

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

Go to latest
Published: Nov 20, 2025 License: MIT Imports: 15 Imported by: 0

Documentation

Overview

Package conversation provides conversation management functionality.

This package follows Go standard library design principles:

  • No global state - all functionality requires explicit dependencies
  • Interface-based design for testability
  • Clear separation between types and behavior
  • Consistent error handling with context

Basic usage:

db, err := pgxpool.New(ctx, databaseURL)
if err != nil {
    return err
}

store := conversation.NewStore(db, conversation.WithLogger(logger))

// Create a conversation
conv, err := store.Create(ctx, userID)
if err != nil {
    return err
}

// Add messages
err = store.AddMessage(ctx, conv.ID, conversation.Message{
    Role:    conversation.RoleUser,
    Content: "Hello, assistant!",
})

The package is designed to work with PostgreSQL through sqlc-generated queries, providing type safety and performance.

Package conversation provides enhanced conversation management.

Package conversation provides conversation management functionality. It follows Go standard library patterns for clean, testable design.

Index

Constants

View Source
const (
	RoleUser      = "user"
	RoleAssistant = "assistant"
	RoleSystem    = "system"
)

Role constants define valid message roles.

Variables

This section is empty.

Functions

func IsValidRole

func IsValidRole(role string) bool

IsValidRole checks if a role string is valid.

Types

type Conversation

type Conversation struct {
	ID            uuid.UUID
	Title         string
	Summary       string
	Metadata      Metadata
	LastMessageAt *time.Time
	CreatedAt     time.Time
	UpdatedAt     time.Time
}

Conversation represents a conversation session. It follows the pattern of standard library types - simple, focused structs.

type Manager

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

Manager provides enhanced conversation management with local caching. Inspired by Mods' approach to conversation handling.

func NewManager

func NewManager(store Store, opts ...ManagerOption) (*Manager, error)

NewManager creates a new conversation manager with enhanced features.

func (*Manager) AddMessage

func (m *Manager) AddMessage(ctx context.Context, msg Message) error

AddMessage adds a message to the current conversation.

func (*Manager) Close

func (m *Manager) Close(ctx context.Context) error

Close gracefully shuts down the manager.

func (*Manager) Continue

func (m *Manager) Continue(ctx context.Context, id uuid.UUID) (*Conversation, error)

Continue loads and continues a previous conversation.

func (*Manager) ContinueLast

func (m *Manager) ContinueLast(ctx context.Context) (*Conversation, error)

ContinueLast continues the most recent conversation.

func (*Manager) Current

func (m *Manager) Current(ctx context.Context) (*Conversation, error)

Current returns the current conversation, creating one if needed.

func (*Manager) GetMessages

func (m *Manager) GetMessages(ctx context.Context, limit int) ([]*Message, error)

GetMessages retrieves messages for the current conversation.

func (*Manager) List

func (m *Manager) List(ctx context.Context, limit int) ([]*Summary, error)

List returns recent conversations with enhanced metadata.

func (*Manager) ListConversations

func (m *Manager) ListConversations(ctx context.Context, limit int) ([]*Conversation, error)

ListConversations returns raw conversations for UI display.

func (*Manager) Save

func (m *Manager) Save(ctx context.Context) error

Save immediately saves pending messages.

func (*Manager) StartNew

func (m *Manager) StartNew(ctx context.Context) (*Conversation, error)

StartNew starts a new conversation.

func (*Manager) Store

func (m *Manager) Store() Store

Store returns the underlying store (for advanced operations)

type ManagerOption

type ManagerOption func(*Manager)

ManagerOption configures the conversation manager.

func WithAutoSave

func WithAutoSave(enabled bool, delay time.Duration) ManagerOption

WithAutoSave enables automatic conversation saving.

func WithCacheDir

func WithCacheDir(dir string) ManagerOption

WithCacheDir sets the local cache directory.

func WithManagerLogger

func WithManagerLogger(log logger.Logger) ManagerOption

WithManagerLogger sets the logger for the manager.

type Message

type Message struct {
	ID             uuid.UUID
	ConversationID uuid.UUID
	Role           string // "user", "assistant", "system"
	Content        string
	Metadata       MessageMetadata
	TokensUsed     int32
	CreatedAt      time.Time
}

Message represents a single message within a conversation. Each message is immutable once created.

type MessageMatch

type MessageMatch struct {
	Message           *Message
	HighlightedText   string
	ConversationTitle string
}

MessageMatch represents a matched message in search

type MessageMetadata

type MessageMetadata struct {
	Model        string            `json:"model,omitempty"`
	Provider     string            `json:"provider,omitempty"`
	Temperature  float32           `json:"temperature,omitempty"`
	ToolCalls    []ToolCall        `json:"tool_calls,omitempty"`
	Custom       map[string]string `json:"custom,omitempty"`
	ProcessingMS int64             `json:"processing_ms,omitempty"`
}

MessageMetadata stores additional message properties. This separation allows the core Message to remain stable while metadata evolves.

type Metadata

type Metadata struct {
	PreferredModel    string            `json:"preferred_model,omitempty"`
	PreferredProvider string            `json:"preferred_provider,omitempty"`
	Topic             string            `json:"topic,omitempty"`
	Tags              []string          `json:"tags,omitempty"`
	Custom            map[string]string `json:"custom,omitempty"`

	// Enhanced metadata for better management
	MessageCount  int       `json:"message_count,omitempty"`
	LastActivity  time.Time `json:"last_activity,omitempty"`
	AutoGenerated bool      `json:"auto_generated,omitempty"` // If title was auto-generated
}

Metadata stores additional conversation properties. Using a dedicated type provides type safety and documentation.

type SearchResult

type SearchResult struct {
	Conversation       *Conversation
	HighlightedTitle   string
	HighlightedSummary string
	Rank               float32
	MatchedMessages    []*MessageMatch
}

SearchResult represents a search result with highlights

type Store

type Store interface {
	// Create creates a new conversation
	Create(ctx context.Context) (*Conversation, error)
	// Get retrieves a conversation by ID
	Get(ctx context.Context, id uuid.UUID) (*Conversation, error)
	// List retrieves recent conversations
	List(ctx context.Context, limit int) ([]*Conversation, error)
	// Search performs full-text search on conversations
	Search(ctx context.Context, query string, limit int) ([]*SearchResult, error)
	// AddMessage adds a message to a conversation
	AddMessage(ctx context.Context, conversationID uuid.UUID, msg Message) error
	// GetMessages retrieves messages from a conversation
	GetMessages(ctx context.Context, conversationID uuid.UUID, limit int) ([]*Message, error)
}

Store defines the interface for conversation persistence. This allows for easy testing and alternative implementations.

func NewStore

func NewStore(db *pgxpool.Pool, opts ...StoreOption) Store

NewStore creates a new conversation store with the given database connection. It follows the pattern of sql.Open, pgx.Connect, etc.

type StoreOption

type StoreOption func(*store)

StoreOption configures a Store instance.

func WithDefaultLimit

func WithDefaultLimit(limit int) StoreOption

WithDefaultLimit sets the default limit for queries.

func WithLogger

func WithLogger(log logger.Logger) StoreOption

WithLogger sets a custom logger for the store.

func WithMaxMessageLimit

func WithMaxMessageLimit(limit int) StoreOption

WithMaxMessageLimit sets the maximum message limit.

type Summary

type Summary struct {
	*Conversation
	Fingerprint  string `json:"fingerprint"`
	MessageCount int    `json:"message_count"`
}

Summary provides enhanced conversation information.

type ToolCall

type ToolCall struct {
	ID     string          `json:"id"`
	Name   string          `json:"name"`
	Input  json.RawMessage `json:"input"`
	Output json.RawMessage `json:"output,omitempty"`
}

ToolCall represents a tool invocation within a message. Using json.RawMessage defers parsing until needed.

Jump to

Keyboard shortcuts

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