Skip to main content

ContextManager

Struct ContextManager 

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

Context manager: maintains full conversation history and automatically triggers compression when tokens exceed the limit.

§Typical usage

use echo_core::error::Result;
use echo_core::llm::types::Message;
use echo_state::compression::compressor::SlidingWindowCompressor;
use echo_state::compression::{ContextCompressor, ContextManager};

let mut ctx = ContextManager::builder(4096)
    .compressor(SlidingWindowCompressor::new(20))
    .build();

ctx.push(Message::system("You are an assistant".to_string()));
ctx.push(Message::user("Hello".to_string()));

// Call prepare() before each LLM call to auto-compress over-limit messages
let result = ctx.prepare(None).await?;
let messages = result.messages;

§Hybrid pipeline example

use echo_core::error::Result;
use echo_core::llm::LlmClient;
use echo_state::compression::compressor::{
    HybridCompressor, SlidingWindowCompressor, SummaryCompressor,
};
use echo_state::compression::{ContextCompressor, ContextManager};
use std::sync::Arc;

let compressor = HybridCompressor::builder()
    .stage(SlidingWindowCompressor::new(30))
    .stage(SummaryCompressor::new(llm, 8))
    .build();

let mut ctx = ContextManager::builder(8192)
    .compressor(compressor)
    .build();

Implementations§

Source§

impl ContextManager

Source

pub fn builder(token_limit: usize) -> ContextManagerBuilder

Source

pub fn push(&mut self, message: Message)

Append a message to the context buffer.

When the message count exceeds the max_messages hard cap, automatically applies sliding window degradation: preserves system messages and recent messages, discards the earliest conversation messages in the middle. This is the last line of defense; even if no compressor is configured or compression fails, OOM will not occur.

Source

pub fn push_many(&mut self, messages: impl IntoIterator<Item = Message>)

Batch-append messages

Source

pub fn messages(&self) -> &[Message]

Return all messages currently in the buffer (no compression)

Source

pub fn set_messages(&mut self, messages: Vec<Message>)

Replace the internal message buffer (used to restore conversation from persistent storage)

Messages should include the system prompt as the first entry (if needed).

Source

pub fn token_estimate(&self) -> usize

Estimate the token count of the current context

Uses the configured Tokenizer implementation (default HeuristicTokenizer, distinguishes ASCII/CJK).

Source

pub fn tokenizer(&self) -> &dyn Tokenizer

获取当前 Tokenizer

Source

pub fn set_tokenizer(&mut self, tokenizer: Arc<dyn Tokenizer>)

Dynamically replace the Tokenizer

Source

pub fn clear(&mut self)

Clear the context buffer (preserves configured compressor and protection markers)

Source

pub fn add_protected_marker(&mut self, marker: String)

Register a content marker that protects messages from compression.

Any message whose content contains this marker string will be excluded from compression passes. This is used by the skill system to protect activated skill instructions from being evicted during context compaction.

§Example
let mut ctx = ContextManager::builder(4096).build();
ctx.add_protected_marker("<skill_content".to_string());
Source

pub fn set_compressor(&mut self, compressor: impl ContextCompressor + 'static)

Dynamically replace the compressor without affecting the existing message buffer

Source

pub fn remove_compressor(&mut self)

Remove the compressor, reverting to unlimited mode

Source

pub fn has_compressor(&self) -> bool

Whether a compressor is configured

Source

pub async fn force_compress( &mut self, fallback_window: usize, ) -> Result<ForceCompressStats, ReactError>

Force-compress the context, regardless of whether the current token count exceeds the limit.

  • If a compressor is configured, use it;
  • Otherwise, temporarily use SlidingWindowCompressor::new(fallback_window).

Protected messages are excluded from compression and preserved.

Source

pub async fn force_compress_with( &mut self, compressor: &dyn ContextCompressor, ) -> Result<ForceCompressStats, ReactError>

Force-compress using a specific compressor, without affecting the currently installed compressor config.

Suitable for temporary strategy overrides like /compress sliding 10.

Source

pub fn update_system(&mut self, new_system_prompt: String)

Update the system message content

Typically called when add_skill() injects extra system prompts: finds the first message with role == “system” and replaces its content; if no system message exists, inserts one at the head of the queue.

Source

pub async fn prepare( &mut self, current_query: Option<&str>, ) -> Result<PrepareResult, ReactError>

Prepare the list of messages to send to the LLM.

When the estimated token count exceeds token_limit and a compressor is configured, automatically trigger compression and update the internal buffer. The compressed messages replace the original buffer.

Protected messages (containing registered markers, e.g. <skill_content>) are excluded from compression and re-inserted after system messages.

current_query is a reserved field; pass None.

Returns a PrepareResult containing the prepared messages and optional compression stats (populated only when auto-compression was triggered).

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> FutureExt for T

Source§

fn with_context(self, otel_cx: Context) -> WithContext<Self>

Attaches the provided Context to this type, returning a WithContext wrapper. Read more
Source§

fn with_current_context(self) -> WithContext<Self>

Attaches the current Context to this type, returning a WithContext wrapper. Read more
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> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> IntoRequest<T> for T

Source§

fn into_request(self) -> Request<T>

Wrap the input message T in a tonic::Request
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

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

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
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<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

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