Skip to main content

Compactor

Struct Compactor 

Source
pub struct Compactor { /* private fields */ }
Expand description

Applies 5-layer context compaction when context nears the model token limit.

The compactor is stateless except for the circuit breaker counter, which tracks consecutive failures across invocations.

§Example

use talos_agent::compaction::Compactor;
use talos_agent::token::TokenEstimator;
use talos_core::message::Message;
let estimator = TokenEstimator::new();
let mut compactor = Compactor::new(estimator, 128_000);

let messages = vec![Message::User { content: "Hello!".into() }];
if compactor.should_compact(&messages) {
    let provider: &dyn LanguageModel = &MyModel;
    let compacted = compactor.compact(messages, provider).await.unwrap();
}

Implementations§

Source§

impl Compactor

Source

pub fn new(token_estimator: TokenEstimator, model_limit: u32) -> Self

Creates a new compactor with the given token estimator and model limit.

The trigger threshold defaults to 0.8 (80% of model_limit).

§Arguments
  • token_estimator — The token estimator for measuring context size.
  • model_limit — Maximum token limit of the target language model.
Source

pub fn with_threshold(self, threshold: f32) -> Self

Sets the trigger threshold (fraction of model_limit that triggers compaction).

§Arguments
  • threshold — A value between 0.0 and 1.0. Default is 0.8.
Source

pub fn should_compact(&self, messages: &[Message]) -> bool

Checks whether compaction should be triggered for the given messages.

Returns true if the estimated token usage exceeds model_limit * trigger_threshold.

§Arguments
  • messages — The current conversation messages.
Source

pub async fn compact( &mut self, messages: Vec<Message>, provider: &dyn LanguageModel, ) -> CompactionResult<Vec<Message>>

Applies compaction layers to reduce context size.

Layers are applied in order (budget → trim → microcompact → collapse → autocompact), stopping as soon as the context fits within the model limit.

The last 10 turns are always preserved verbatim.

§Arguments
  • messages — The current conversation messages (consumed).
  • provider — The language model provider for LLM-based summarization.
§Errors

Returns CompactionError::CircuitBreakerTripped if the circuit breaker has tripped due to repeated failures.

Returns CompactionError::CompactionFailed if all layers were applied but the context still exceeds the limit.

Returns CompactionError::ProviderError if the LLM provider fails during summarization.

Source

pub fn apply_budget(&self, messages: Vec<Message>) -> Vec<Message>

Layer 1: Cap tool result sizes to max 4000 chars each.

Truncates tool results exceeding [MAX_TOOL_RESULT_CHARS] characters, appending [TRUNCATION_SUFFIX].

Source

pub fn apply_trim(&self, messages: Vec<Message>) -> Vec<Message>

Layer 2: Remove tool results from turns older than 20.

Counts turns from the start of the conversation. Tool results belonging to turns beyond [TRIM_TURN_THRESHOLD] are removed (replaced with empty content).

Source

pub fn apply_microcompact(&self, messages: Vec<Message>) -> Vec<Message>

Layer 3: Keep only the last tool result for each tool call ID.

Iterates through messages and for each tool_use_id, only preserves the most recent (last occurring) tool result. Earlier duplicates are replaced with empty content.

Source

pub async fn apply_collapse( &self, messages: Vec<Message>, provider: &dyn LanguageModel, ) -> CompactionResult<Vec<Message>>

Layer 4: Summarize turns older than 10 into a single summary message.

Uses the LLM to generate a concise summary of old turns. The last [PRESERVED_TURNS] turns are preserved verbatim.

§Errors

Returns CompactionError::ProviderError if the LLM provider fails.

Source

pub async fn apply_autocompact( &self, messages: Vec<Message>, provider: &dyn LanguageModel, ) -> CompactionResult<Vec<Message>>

Layer 5: Use LLM to summarize the entire conversation history.

Preserves the last [PRESERVED_TURNS] turns verbatim and summarizes everything before them.

§Errors

Returns CompactionError::ProviderError if the LLM provider fails.

Source

pub fn compact_deterministic( &self, messages: Vec<Message>, ) -> (Vec<Message>, CompactionStatus)

Apply deterministic layers 1-3 (budget, trim, microcompact) and return status.

Safe at any boundary (pre-turn, manual) because it does not invoke the LLM. If deterministic layers are insufficient, the status reports Skipped with the reason — the caller can then decide whether to escalate to compact (which uses LLM layers 4-5).

Source

pub async fn manual_compact( &mut self, messages: Vec<Message>, provider: &dyn LanguageModel, ) -> (Vec<Message>, CompactionStatus)

Manual compaction trigger that returns status without exposing hidden output.

Checks the trigger threshold first. If the context fits, returns Skipped. If the circuit breaker is tripped, returns Failed. Otherwise delegates to compact and wraps the result.

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more