Documentation
¶
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Session ¶
type Session interface {
chat.Chat // a session is a chat that has been enhanced with context window management.
// SessionID returns the unique identifier for this session.
SessionID() string
// LiveRecords returns all records marked as live (in active context window).
LiveRecords() []persistence.Record
// TotalRecords returns all records (both live and dead).
TotalRecords() []persistence.Record
// CompactNow manually triggers context compaction.
CompactNow() error
// SetCompactionThreshold sets the threshold for automatic compaction (0.0-1.0).
// A value of 0.8 means compact when 80% of the context window is used.
// A value of 0.0 means never compact automatically.
SetCompactionThreshold(float64)
// Metrics returns usage statistics for the session.
Metrics() SessionMetrics
}
Session manages the conversation lifecycle with automatic context compaction. It embeds chat.Chat for full compatibility while adding persistence and automatic summarization capabilities. When the context window approaches capacity (default 80%), older messages are automatically compacted into summaries to maintain conversation continuity.
Example (Resumption) ¶
package main
import (
"context"
"fmt"
"log"
"os"
"strings"
agent "github.com/bpowers/go-agent"
"github.com/bpowers/go-agent/chat"
"github.com/bpowers/go-agent/llm/openai"
"github.com/bpowers/go-agent/persistence/sqlitestore"
)
func main() {
// Skip if no API key available
if os.Getenv("OPENAI_API_KEY") == "" {
fmt.Println("Session created")
fmt.Println("Conversation established")
fmt.Println("Session resumed")
fmt.Println("Context preserved: true")
return
}
ctx := context.Background()
dbPath := "/tmp/example_session.db"
// Clean up any existing database for this example
os.Remove(dbPath)
defer os.Remove(dbPath)
// Phase 1: Start a new conversation
sessionID := func() string {
// Create persistent storage
store, err := sqlitestore.New(dbPath)
if err != nil {
log.Fatal(err)
}
defer store.Close()
// Create OpenAI client
client, err := openai.NewClient(
openai.OpenAIURL,
os.Getenv("OPENAI_API_KEY"),
openai.WithModel("gpt-4o-mini"),
)
if err != nil {
log.Fatal(err)
}
// Create a new session with persistence
session := agent.NewSession(
client,
"You are a helpful assistant. Remember details about our conversation.",
agent.WithStore(store),
// We could specify a session ID, but letting it auto-generate is typical
)
sessionID := session.SessionID()
fmt.Println("Session created")
// Have a conversation
_, err = session.Message(ctx, chat.UserMessage("Hi! My name is Bobby and I'm learning Go programming."))
if err != nil {
log.Fatal(err)
}
response, err := session.Message(ctx, chat.UserMessage("What are some good resources for learning Go concurrency?"))
if err != nil {
log.Fatal(err)
}
// The assistant will provide helpful resources
if len(response.GetText()) > 0 {
fmt.Println("Conversation established")
}
return sessionID
}()
// Phase 2: Resume the conversation later
func() {
// Open the existing database
store, err := sqlitestore.New(dbPath)
if err != nil {
log.Fatal(err)
}
defer store.Close()
// Create the same client configuration
client, err := openai.NewClient(
openai.OpenAIURL,
os.Getenv("OPENAI_API_KEY"),
openai.WithModel("gpt-4o-mini"),
)
if err != nil {
log.Fatal(err)
}
// Resume the previous session
session := agent.NewSession(
client,
"This will be ignored - original prompt is preserved",
agent.WithStore(store),
agent.WithRestoreSession(sessionID), // Key: restore with the same ID
)
fmt.Println("Session resumed")
// The assistant should remember our previous conversation
response, err := session.Message(ctx, chat.UserMessage("What was my name again?"))
if err != nil {
log.Fatal(err)
}
// Check if the assistant remembers Bobby from the earlier conversation
if strings.Contains(strings.ToLower(response.GetText()), "bobby") {
fmt.Println("Context preserved: true")
}
}()
}
Output: Session created Conversation established Session resumed Context preserved: true
func NewSession ¶
func NewSession(client chat.Client, systemPrompt string, opts ...SessionOption) Session
NewSession creates a new Session with the given client, system prompt, and options.
type SessionMetrics ¶
type SessionMetrics struct {
CumulativeTokens int `json:"cumulative_tokens"` // Total tokens used across all messages
LiveTokens int `json:"live_tokens"` // Tokens in active context window
MaxTokens int `json:"max_tokens"` // Model's max context size
CompactionCount int `json:"compaction_count"` // Number of compactions performed
LastCompaction time.Time `json:"last_compaction"` // When last compacted
RecordsLive int `json:"records_live"` // Number of live records
RecordsTotal int `json:"records_total"` // Total records (live + dead)
PercentFull float64 `json:"percent_full"` // LiveTokens/MaxTokens ratio
}
SessionMetrics provides usage statistics for the session.
type SessionOption ¶
type SessionOption func(*sessionOptions)
SessionOption configures a Session.
func WithInitialMessages ¶
func WithInitialMessages(msgs ...chat.Message) SessionOption
WithInitialMessages sets the initial messages for the session.
func WithRestoreSession ¶
func WithRestoreSession(id string) SessionOption
WithRestoreSession restores a session with the given ID. This allows resuming a previous conversation by loading its history and state from the configured persistence store. If not provided, a new UUID will be generated for a fresh session.
func WithStore ¶
func WithStore(store persistence.Store) SessionOption
WithStore sets a custom persistence store for the session. If not provided, an in-memory store is used.
func WithSummarizer ¶
func WithSummarizer(summarizer Summarizer) SessionOption
WithSummarizer sets a custom summarizer for context compaction. If not provided, a default LLM-based summarizer is used.
type SimpleSummarizer ¶
type SimpleSummarizer struct {
// contains filtered or unexported fields
}
SimpleSummarizer provides a basic extractive summarization strategy. It keeps the first and last N messages without compression.
func NewSimpleSummarizer ¶
func NewSimpleSummarizer(keepFirst, keepLast int) *SimpleSummarizer
NewSimpleSummarizer creates a basic summarizer that keeps first and last messages.
func (*SimpleSummarizer) SetPrompt ¶
func (s *SimpleSummarizer) SetPrompt(prompt string)
SetPrompt is a no-op for SimpleSummarizer.
func (*SimpleSummarizer) Summarize ¶
func (s *SimpleSummarizer) Summarize(ctx context.Context, records []persistence.Record) (string, error)
Summarize returns a simple extraction of first and last messages.
type Summarizer ¶
type Summarizer interface {
// Summarize compresses a list of records into a concise summary.
// The summary should preserve key information, decisions made, and important context.
Summarize(ctx context.Context, records []persistence.Record) (string, error)
// SetPrompt allows customization of the summarization prompt for LLM-based summarizers.
SetPrompt(prompt string)
}
Summarizer defines the interface for conversation summarization strategies. Implementations can use LLMs, extractive summarization, or other techniques to compress conversation history while preserving important context.
func NewSummarizer ¶
func NewSummarizer(client chat.Client) Summarizer
NewSummarizer creates a new LLM-based summarizer. The client should be configured with the desired model for summarization (often a cheaper model). If nil, a default client will be used when the summarizer is needed.
Directories
¶
| Path | Synopsis |
|---|---|
|
cmd
|
|
|
build/funcschema
command
|
|
|
build/jsonschema
command
|
|
|
sessionview
command
Command sessionview is a CLI tool for viewing session data stored in SQLite.
|
Command sessionview is a CLI tool for viewing session data stored in SQLite. |
|
examples
|
|
|
agent-cli
command
|
|
|
internal
|
|
|
logging
Package logging provides centralized structured logging for the go-agent library.
|
Package logging provides centralized structured logging for the go-agent library. |
|
Package persistence provides storage interfaces for Session records.
|
Package persistence provides storage interfaces for Session records. |
|
sqlitestore
Package sqlitestore provides SQLite-based persistence for Session records.
|
Package sqlitestore provides SQLite-based persistence for Session records. |