compact

package
v0.8.1 Latest Latest
Warning

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

Go to latest
Published: Apr 19, 2026 License: Apache-2.0 Imports: 5 Imported by: 0

Documentation

Overview

Package compact summarizes older messages of a running ChatHistory when it approaches the model's context window, replacing them with one synthetic user message of the form:

<compact-summary>
  ...summary text...
</compact-summary>

Designed to be invoked at the head of a chat_completion task — i.e. between tool rounds in an agentic loop — so an executor that has just appended large tool results does not blow context on the next assistant turn.

Compaction is conservative:

  • The most recent KeepRecent messages are preserved verbatim.
  • A single non-agentic LLM call produces the summary; it must not recurse.
  • On consecutive failures the State circuit-breaks and Maybe becomes a no-op for the rest of the step, letting Shift / hard truncation take over.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Caller

type Caller func(ctx context.Context, model, systemInstruction, prompt string) (string, error)

Caller invokes a single non-streaming LLM call and returns the assistant text. The compact package does not import any provider package; the wiring code (taskexec.go) supplies a closure that bridges to llmrepo and llmretry.

type Message

type Message struct {
	Role    string
	Content string
	// HasToolCalls is true when the message originated from an assistant turn
	// that requested tool calls. Such messages cannot safely be elided in
	// isolation because the following tool-result message references them.
	HasToolCalls bool
	// ToolCallID is non-empty for tool-result messages.
	ToolCallID string
}

Message is the minimal shape compact needs from a chat history. It mirrors the relevant fields of taskengine.Message without importing taskengine, so this package stays a leaf utility.

type Policy

type Policy struct {
	// TriggerFraction is the fraction of token_limit that triggers compaction.
	// Defaults to 0.85 when zero.
	TriggerFraction float64 `yaml:"trigger_fraction,omitempty" json:"trigger_fraction,omitempty"`
	// KeepRecent is the number of trailing messages preserved verbatim.
	// Defaults to 10 when zero.
	KeepRecent int `yaml:"keep_recent,omitempty" json:"keep_recent,omitempty"`
	// Model is the LLM used for compaction. Empty means the caller's default.
	Model string `yaml:"model,omitempty" json:"model,omitempty"`
	// Provider, if non-empty, restricts the compaction call to a provider type.
	Provider string `yaml:"provider,omitempty" json:"provider,omitempty"`
	// MaxFailures is the consecutive-failure threshold that disables compaction
	// for the remainder of the step. Defaults to 3 when zero.
	MaxFailures int `yaml:"max_failures,omitempty" json:"max_failures,omitempty"`
	// MinReplacedMessages requires at least this many messages to be replaced
	// for a compaction to be considered worthwhile. Defaults to 4.
	MinReplacedMessages int `yaml:"min_replaced_messages,omitempty" json:"min_replaced_messages,omitempty"`
}

Policy controls when and how Maybe summarizes history.

type Result

type Result struct {
	Compacted        bool
	Replaced         int
	ReplaceFrom      int
	ReplaceTo        int
	SyntheticContent string
	UsageBefore      int
	UsageAfter       int
	SummaryChars     int
	Skipped          string // human-readable reason when Compacted is false
}

Result reports what Maybe did. Compacted is true only when messages were actually replaced; UsageBefore/After are the totalled token counts when a counter was supplied.

When Compacted is true the caller must apply the splice on its own typed message slice as:

out := append([]M{}, msgs[:ReplaceFrom]...)
out = append(out, syntheticUserMessage(SyntheticContent))
out = append(out, msgs[ReplaceTo:]...)

SyntheticContent is the user-visible content for the replacement message (already wrapped in <compact-summary> tags).

func Maybe

func Maybe(
	ctx context.Context,
	p Policy,
	st *State,
	msgs []Message,
	tokenLimit int,
	count TokenCounter,
	call Caller,
) (Result, error)

Maybe inspects msgs and decides whether to compact. When triggered it calls the LLM, builds the synthetic <compact-summary> content, and returns a splice plan (ReplaceFrom..ReplaceTo, SyntheticContent) for the caller to apply on its own typed message slice.

Maybe never mutates msgs. The caller owns the typed slice (e.g. taskengine.Message with CallTools, Timestamps, etc.) and applies the splice while preserving any per-message metadata on the kept tail.

type State

type State struct {
	ConsecutiveFailures int
	Disabled            bool
	LastCompactedAt     time.Time
	Compactions         int
	// contains filtered or unexported fields
}

State carries circuit-breaker counters across Maybe calls within one step. Safe for concurrent reads via the embedded mutex.

func (*State) Snapshot

func (s *State) Snapshot() (failures, compactions int, disabled bool, lastAt time.Time)

Snapshot returns a shallow copy for inspection. Safe for concurrent use.

type TokenCounter

type TokenCounter func(ctx context.Context, model, s string) (int, error)

TokenCounter returns the token count for s under model. Used to estimate pre/post-compaction usage. May return (0, nil) if no counter is available.

Jump to

Keyboard shortcuts

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