ExAgent.Compaction behaviour (ExAgent v3.0.0)

View Source

Behaviour for reducing the conversation context sent to a model.

Stability — Candidate.

A compactor takes the current request projection [Message.t()] and returns a compacted list, {:no_change}, {:no_change, :protected_prefix}, or an error. The built-in ExAgent.Compaction.Summary replaces older messages with an LLM-generated summary while keeping the most recent ones verbatim.

Compaction is wired into a run as a capability built with capability/2. It acts in ExAgent.Capability.before_model_request/3 and changes only the request's :messages: the authoritative history remains append-only and new_messages remains its real suffix. Compaction is opt-in and does not guarantee that pinned context fits a provider's context window.

compaction =
  ExAgent.Compaction.capability(ExAgent.Compaction.Summary,
    threshold_tokens: 6000,
    summarize: &MyApp.summarize/2
  )

ExAgent.new(model: model, capabilities: [compaction])

Custom compactors

compact/3 receives the projection, the options given to capability/2 and a context %{deadline, params, run_id, step}: the run's absolute monotonic deadline in milliseconds (or nil), the request's ExAgent.ModelRequestParameters (offered and output tools, native output schema), the run ID and the step. Its output must preserve the original instructions, the latest user request and complete, unmodified tool exchanges, and must not insert new System instructions; an invalid projection is treated as an error. The optional validate/1 checks the options when the capability is built.

Failures and telemetry

A compaction error never fails the run: the request keeps the incoming projection. Every attempt emits [:exagent, :compaction, :stop] with measurements %{duration, input_messages, output_messages, estimated_tokens_saved} (duration in native units) and metadata %{run_id, step, compactor, reason, status, error}, where reason is :before_model_request or :context_overflow, status is :compacted, :no_change or :error and error is a projected class such as %{type: "invalid_summary"} (nil otherwise). Summary adds skip_reason: :protected_prefix when the prefix is the reason it kept the original projection. The metadata never contains messages or summaries. Stream cancellation is propagated.

Summary

Callbacks

Optional: check the options at construction. Return :ok or {:error, reason}, or raise ArgumentError.

Functions

Build the capability that compacts each request with compactor.

A rough context estimate using content bytes / 4 plus message/part overhead.

Types

context()

@type context() :: %{
  deadline: integer() | nil,
  params: ExAgent.ModelRequestParameters.t(),
  run_id: String.t() | nil,
  step: non_neg_integer()
}

messages()

@type messages() :: [ExAgent.Message.t()]

opts()

@type opts() :: keyword()

Callbacks

compact(messages, opts, context)

@callback compact(messages(), opts(), context()) ::
  {:ok, messages()}
  | {:no_change}
  | {:no_change, :protected_prefix}
  | {:error, term()}

validate(opts)

(optional)
@callback validate(opts()) :: :ok | {:error, term()}

Optional: check the options at construction. Return :ok or {:error, reason}, or raise ArgumentError.

Functions

capability(compactor, opts \\ [])

@spec capability(module(), opts()) :: ExAgent.Capability.t()

Build the capability that compacts each request with compactor.

compactor must be a loaded module implementing compact/3, and opts a keyword list, checked by the compactor's validate/1 when it exports one (ExAgent.Compaction.Summary does). Invalid values raise ArgumentError before any run.

estimate_tokens(messages)

@spec estimate_tokens(messages()) :: non_neg_integer()

A rough context estimate using content bytes / 4 plus message/part overhead.

Includes instructions, text, thinking/signatures, tool names, arguments, returns and retries. It can under- or over-estimate model tokens, especially for different tokenizers, languages and multimodal content; it is not a usage or billing counter. The built-in capability also includes advertised tool definitions and the native output schema when using this default estimate. Supply :token_counter for a model-specific estimate.