Skip to content

mnesis.context

context

Context window assembly.

BuiltContext dataclass

BuiltContext(
    messages: list[LLMMessage],
    system_prompt: str,
    token_estimate: int,
    budget: ContextBudget,
    has_summary: bool,
    oldest_included_message_id: str | None = None,
    summary_token_count: int = 0,
    raw_message_tokens: int = 0,
    tool_output_tokens: int = 0,
)

The assembled context window ready for an LLM call.

raw_message_tokens class-attribute instance-attribute

raw_message_tokens: int = 0

Tokens consumed by raw (non-summary) messages included in context.

tool_output_tokens class-attribute instance-attribute

tool_output_tokens: int = 0

Subset of raw_message_tokens attributable to tool call parts.

ContextBuilder

ContextBuilder(
    store: ImmutableStore,
    dag_store: SummaryDAGStore,
    token_estimator: TokenEstimator,
)

Assembles the exact message list sent to the LLM on each turn.

Invariants: 1. The most recent raw messages are always included. 2. Messages before the most recent summary are excluded (replaced by the summary). 3. Tool parts with compacted_at set have output replaced by tombstone strings. 4. FileRefPart objects are rendered as structured [FILE: ...] blocks. 5. Total assembled token count fits within ContextBudget.usable. 6. The system prompt is counted against the token budget.

Context assembly is O(1) via the context_items table: a single ordered SELECT returns the current context snapshot, and each item is loaded by ID. This replaces the previous O(n) backward scan that inferred context from message timestamps and summary span IDs.

build async

build(
    session_id: str,
    model: ModelInfo,
    system_prompt: str,
    config: MnesisConfig,
) -> BuiltContext

Build the context window for the next LLM call.

Uses the context_items table to determine what is currently in context (O(1) lookup), then loads each item by ID and assembles the LLM message list in position order, respecting the token budget.

Parameters:

Name Type Description Default
session_id str

The session to build context for.

required
model ModelInfo

Model metadata for budget calculations and tokenisation.

required
system_prompt str

The system prompt to include (counted against budget).

required
config MnesisConfig

Mnesis configuration providing the compaction buffer value.

required

Returns:

Type Description
BuiltContext

BuiltContext with the assembled messages, budget, and token estimate.

LLMMessage dataclass

LLMMessage(role: str, content: str | list[dict[str, Any]])

A single message formatted for the LLM provider API.