manager

package
v1.7.1 Latest Latest
Warning

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

Go to latest
Published: Sep 28, 2026 License: Apache-2.0 Imports: 7 Imported by: 1 module, 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

View Source
const (
	// ContextModeCompress is the default mode: when the window exceeds
	// maxMessageRounds, the oldest rounds are summarized by the chatmodel and
	// atomically replaced by a single summary round (a blocking model call per
	// compression event).
	ContextModeCompress = "compress"
	// ContextModeTruncate keeps the window within maxMessageRounds by dropping
	// the oldest round(s) once the limit is reached. No model call is
	// involved. The cap is enforced at snapshot time (GetMessages), so the
	// history sent to the model can never exceed maxMessageRound rounds.
	ContextModeTruncate = "truncate"
	// ContextModeWindow drives overflow by the model's context window instead
	// of round count. The manager measures the context size from the prompt
	// tokens the model reports for each call (ReportUsage) and, once the
	// measurement reaches the configured threshold of the context window
	// (SetContextWindow), summarizes the oldest rounds into a single summary
	// round — the same mechanism as compress mode, but token-driven and
	// independent of maxMessageRounds. This suits models with large windows
	// where many short rounds fit comfortably but a single verbose round (e.g.
	// huge tool output) can exhaust the window.
	ContextModeWindow = "window"
)

Context overflow modes (chats.<name>.contextMode)

View Source
const (
	DefaultMaxMessageRound int = 10

	// DefaultTokenThresholdRatio is the fraction of the context window at
	// which window mode triggers compression. It is deliberately below 1: the
	// reserved headroom must cover the model's completion tokens for the
	// current round plus a safety margin for the estimate's error.
	DefaultTokenThresholdRatio = 0.8
)

Variables

This section is empty.

Functions

This section is empty.

Types

type CompressionCompleteCallback

type CompressionCompleteCallback func([]*schema.Message) error

CompressionCompleteCallback is a callback function that is called after compression completes This allows the caller to persist the modified messages (full overwrite mode)

type CompressionProgressCallback added in v1.6.0

type CompressionProgressCallback func(ctx context.Context)

CompressionProgressCallback is invoked right before the blocking summary model call so the caller can notify the user (e.g. print a hint on the CLI or push a message over WebSocket) that the request will pause while the history is compressed.

type Manager

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

Manager manages conversation context.

Append-only principle: once a message has been added (and therefore may have been sent to the model), it is never modified afterwards. The history only grows by appending at the tail. The only operations that rewrite the head are rare atomic events, both triggered when a new round starts:

  • compress mode (default): the oldest rounds are atomically replaced by a single summary round;
  • truncate mode: the oldest round(s) are dropped at snapshot time so the history sent to the model stays within maxMessageRound.

In compress mode this keeps the longest common prefix of consecutive requests stable, which is what provider prompt caches (OpenAI/DeepSeek/Ark/ Anthropic) match on: the head is rewritten only once per compression event instead of per model call. Truncate mode trades this away for simplicity.

func NewManager

func NewManager(maxMessageRound int, contextMode string) *Manager

NewManager creates a new Manager instance.

contextMode selects the overflow strategy (ContextModeCompress, default, or ContextModeTruncate); any unrecognized value falls back to compress.

func (*Manager) AddMessage

func (m *Manager) AddMessage(_ context.Context, message *schema.Message)

AddMessage adds a message to the context.

Messages are only appended: compression is never triggered here, because the current round is still in progress. It is triggered from IncRound, when a new round starts and every existing round is complete.

func (*Manager) Clear

func (m *Manager) Clear()

Clear clears the context (preserves system messages)

func (*Manager) GetChatModel

func (m *Manager) GetChatModel() model.ToolCallingChatModel

func (*Manager) GetFullMessages

func (m *Manager) GetFullMessages() []*schema.Message

GetFullMessages retrieves all full messages in the current context This includes all original messages without any simplification. The returned messages are guaranteed to have proper tool_call / tool_result pairing.

func (*Manager) GetLastUserMessage

func (m *Manager) GetLastUserMessage() string

GetLastUserMessage returns the content of the last user message in the conversation. Returns empty string if no user message is found.

func (*Manager) GetMessageCount

func (m *Manager) GetMessageCount() int

GetMessageCount returns the total number of messages in the context

func (*Manager) GetMessages

func (m *Manager) GetMessages() []*schema.Message

GetMessages retrieves the messages in the current context. All rounds are returned in full (append-only: no simplification of older rounds), so the sequence of consecutive requests shares a stable, growing prefix that provider prompt caches can match. The returned messages are guaranteed to have proper tool_call / tool_result pairing.

func (*Manager) GetSummary

func (m *Manager) GetSummary() string

GetSummary generates a summary of the conversation

func (*Manager) GetTokenUsage added in v1.6.4

func (m *Manager) GetTokenUsage() (prompt, completion, total, contextTokens, window int)

GetTokenUsage returns the session's cumulative token usage across all model calls (prompt/completion/total), plus the current context-size measurement (total tokens of the most recent call — the estimate of the context size the next call will have) and the configured context window size (0 when window mode is not configured).

func (*Manager) IncRound

func (m *Manager) IncRound(ctx context.Context)

IncRound starts a new round.

This is the only place where compression is triggered: the just-finished round is complete and the new round is empty, so any summary model call here does not interfere with in-flight messages of the current round. Compression is skipped while restoring from persistence.

func (*Manager) RemoveLastRound

func (m *Manager) RemoveLastRound()

RemoveLastRound removes the last round of messages from the context. This is used for regenerating a response - the last assistant response is removed so the user message can be re-processed.

func (*Manager) ReportUsage added in v1.6.4

func (m *Manager) ReportUsage(u *schema.TokenUsage)

ReportUsage feeds the token usage of one completed model call back into the manager. The caller takes it from the response message's ResponseMeta.Usage; providers attach it to the final chunk of each call (including intermediate tool-calling outputs). Call it for every assistant model output.

It updates the current context-size measurement (the call's TOTAL tokens — the next request's prompt will carry the history plus this call's completion, so the total reflects the size the next request will have) and the session's cumulative usage counters.

func (*Manager) SetChatModel

func (m *Manager) SetChatModel(chatmodel model.ToolCallingChatModel)

SetChatModel sets the chat model for message compression

func (*Manager) SetCompressionCompleteCallback

func (m *Manager) SetCompressionCompleteCallback(cb CompressionCompleteCallback)

SetCompressionCompleteCallback sets the callback that is called after compression completes

func (*Manager) SetCompressionProgressCallback added in v1.6.0

func (m *Manager) SetCompressionProgressCallback(cb CompressionProgressCallback)

SetCompressionProgressCallback sets the callback that is invoked before the blocking summary model call (to notify the user that compression is starting)

func (*Manager) SetContextWindow added in v1.6.4

func (m *Manager) SetContextWindow(maxContextTokens int, thresholdRatio float64)

SetContextWindow configures the token-based (window) overflow mode.

maxContextTokens is the model's context window size in tokens and thresholdRatio the fraction of it that triggers compression (a value <= 0 or >= 1 selects DefaultTokenThresholdRatio). Call it before the first round when using ContextModeWindow; a non-positive maxContextTokens keeps the manager in measurement-only state — usage is tracked and reportable but no compression ever runs (there is no window to measure against).

func (*Manager) SetLoading added in v1.6.0

func (m *Manager) SetLoading(loading bool)

SetLoading toggles the loading (restore-from-persistence) state. While loading, IncRound skips compression.

func (*Manager) SetPersistenceCallback

func (m *Manager) SetPersistenceCallback(cb PersistenceCallback)

SetPersistenceCallback sets the callback for auto-saving messages

func (*Manager) SetSystemPrompt added in v1.6.1

func (m *Manager) SetSystemPrompt(prompt string, renderer func(string) (string, error))

SetSystemPrompt shares the runner's system prompt with the manager.

prompt is the same template passed to the agent's Instruction and renderer the same function the agent's GenModelInput uses to expand it, so the compression summary request leads with the exact same system message the runner sends — keeping its prefix prompt-cache friendly. An empty prompt or a nil renderer is a no-op: the summary call is then sent without a system message (as before).

func (*Manager) SetTokenUsage added in v1.6.4

func (m *Manager) SetTokenUsage(prompt, completion, total, lastPrompt int)

SetTokenUsage restores the session's token usage, e.g. from persistence after a restart: the cumulative counters plus the last measured prompt token count (lastPrompt). Restoring lastPrompt keeps the window-mode overflow check working across restarts: the restored history was the one the model last saw, so if its measurement was over the threshold the next IncRound compresses it instead of waiting for a fresh (possibly window-exceeding) model call.

func (*Manager) SetUsageUpdateCallback added in v1.6.4

func (m *Manager) SetUsageUpdateCallback(cb UsageUpdateCallback)

SetUsageUpdateCallback sets the callback invoked after the session's cumulative token usage changes (ReportUsage or SetTokenUsage), so the caller can persist the counters. It is invoked outside the manager lock.

type PersistenceCallback

type PersistenceCallback func(*schema.Message) error

PersistenceCallback is a callback function for single message persistence Each time a new message is added, this callback is invoked with that single message

type UsageUpdateCallback added in v1.6.4

type UsageUpdateCallback func(promptTokens, completionTokens, totalTokens, lastPromptTokens int)

UsageUpdateCallback is invoked (outside the manager lock) after the session's cumulative token usage changes, so the caller can persist it.

Jump to

Keyboard shortcuts

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