Advanced Memory Providers¶
RoomKit's memory system controls what conversation context the AI sees. Beyond the default SlidingWindowMemory, two advanced providers handle long conversations: BudgetAwareMemory (token-budget trimming) and CompactingMemory (summarize + trim).
MemoryProvider ABC¶
from __future__ import annotations
from abc import ABC, abstractmethod
from roomkit.memory import MemoryResult
class MemoryProvider(ABC):
@abstractmethod
async def retrieve(self, room_id, current_event, context, *, channel_id=None) -> MemoryResult:
"""Retrieve context for AI generation."""
...
async def ingest(self, room_id, event, *, channel_id=None) -> None:
"""Ingest an event (optional, for stateful providers)."""
async def clear(self, room_id) -> None:
"""Clear memory for a room (optional)."""
async def close(self) -> None:
"""Release resources (optional)."""
MemoryResult¶
@dataclass
class MemoryResult:
messages: list[AIMessage] = field(default_factory=list) # Pre-built messages (summaries)
events: list[RoomEvent] = field(default_factory=list) # Raw events for conversion
notes: list[str] = field(default_factory=list) # Retrieved for this turn alone
- messages are prepended first in the AI context (e.g., conversation summaries)
- events are converted by AIChannel using its content extraction logic (preserves vision/images)
- notes is what the provider retrieved for the current turn only (knowledge passages): it rides the turn's notes, after the input, never the history, so a provider that caches a prefix keeps the history cached from turn to turn (RFC §20.2). A provider that wraps another and rebuilds its result carries the inner
notes(dataclasses.replace(inner_result, ...)keeps them) - All fields are optional — a provider may populate any of them
When to Use Each¶
| Provider | Conversation Length | Cost | Use Case |
|---|---|---|---|
SlidingWindowMemory |
< 50 messages | None | Simple chatbots, short conversations |
BudgetAwareMemory |
50-500 messages | None | Medium conversations, no AI cost for memory |
CompactingMemory |
500+ messages | LLM calls | Long conversations, full context retention |
SummarizingMemory |
Any length | LLM calls | Agentic workloads with large tool results and proactive budget management |
max_context_tokens is the model's window
BudgetAwareMemory, CompactingMemory and SummarizingMemory size the history to what the window leaves once the rest of the turn is in it: the system prompt, the tools, the channel's notes, the current message and the reply (RFC §20). With a 32,000-token window, a 12,000-token system prompt, 8,000 tokens of tools and a 6,000-token reply, the history, a summary included, gets under 6,000 tokens. Pass the model's window, not a budget for the history.
SlidingWindowMemory (Default)¶
Returns the most recent N events. Stateless and zero-cost.
from __future__ import annotations
from roomkit.channels import AIChannel
from roomkit.memory import SlidingWindowMemory
memory = SlidingWindowMemory(max_events=50)
ai = AIChannel(
"ai-assistant",
provider=provider,
memory=memory,
)
Note
When no memory provider is specified, AIChannel creates SlidingWindowMemory(max_events=max_context_events) by default.
# These are equivalent:
ai = AIChannel("ai", provider=provider, max_context_events=50)
ai = AIChannel("ai", provider=provider, memory=SlidingWindowMemory(max_events=50))
BudgetAwareMemory¶
Wraps any inner provider and trims events to fit a token budget. No LLM calls — pure algorithmic trimming.
from __future__ import annotations
from roomkit.channels import AIChannel
from roomkit.memory import BudgetAwareMemory, SlidingWindowMemory
memory = BudgetAwareMemory(
inner=SlidingWindowMemory(max_events=200),
max_context_tokens=8000, # The model's context window
safety_margin_ratio=0.15, # Reserve 15% of the window for the reply
min_events=3, # Never drop below 3 events
)
ai = AIChannel("ai-assistant", provider=provider, memory=memory)
| Parameter | Default | Description |
|---|---|---|
inner |
required | Wrapped memory provider |
max_context_tokens |
required | The model's context window |
safety_margin_ratio |
0.15 |
Reserve this fraction of the window for the reply (15%) |
min_events |
3 |
Minimum events to preserve |
reserved_tokens |
0 |
A floor on the turn's non-history input; the larger of it and the channel's measure is reserved, never their sum |
How it works:
- Calls
inner.retrieve()to get events - Effective budget = the window less the turn's footprint (RFC §20). Before it
reads its memory, the AI channel measures the rest of the turn, readable as
current_turn_footprint(), aTurnFootprint:input_tokens(system prompt with anAgent's identity, tools declared under Tool Search and the tool policy, the room's plan, the speaker attribution),reply_tokens(the turn'smax_tokens) andreplayed, each earlier round of tool calls and instruction the history replays as(index, turn, tokens). The memory reserves the larger ofinput_tokensandreserved_tokens, and for the reply the larger ofmax_context_tokens * safety_margin_ratioandreply_tokens, never both. What aBEFORE_AI_GENERATIONhook adds afterwards is not measured. - If total tokens exceed budget, trims oldest events first, each event with
what the history replays with it (
replayed, charged to its turn's first event after it, else the event before it): a turn is kept or cut whole, its rounds with it. A memory of your own that reservesinput_tokenscounts the rounds only if it readsreplayedtoo. - Never drops below
min_events - Preserves pre-built messages from inner provider unchanged
Token estimation: ~1 token per 4 characters (rough heuristic via estimate_tokens()).
CompactingMemory¶
Extends budget-aware trimming with AI-powered summarization of older events:
from __future__ import annotations
from roomkit.channels import AIChannel
from roomkit.memory import CompactingMemory, SlidingWindowMemory
from roomkit.providers.anthropic import AnthropicAIProvider, AnthropicConfig
# Use a fast, cheap model for summarization
summarizer = AnthropicAIProvider(AnthropicConfig(api_key="...", model="claude-haiku-5-5"))
memory = CompactingMemory(
inner=SlidingWindowMemory(max_events=200),
provider=summarizer,
max_context_tokens=8000, # The model's context window
summary_ratio=0.10, # 10% of the window for summaries
safety_margin_ratio=0.15, # 15% safety margin
min_events=5, # Keep at least 5 recent events
summary_cache_ttl_seconds=300.0, # Cache summaries for 5 minutes
)
ai = AIChannel("ai-assistant", provider=provider, memory=memory)
| Parameter | Default | Description |
|---|---|---|
inner |
required | Wrapped memory provider |
provider |
required | AI provider for summarization |
max_context_tokens |
required | The model's context window |
summary_ratio |
0.10 |
Fraction of the window allocated to summaries |
safety_margin_ratio |
0.15 |
Fraction of the window reserved for the reply |
min_events |
5 |
Minimum events before compacting |
summary_cache_ttl_seconds |
300.0 |
How long to cache summaries per room |
How it works:
- Calls
inner.retrieve()to get all events - Budget = the window less the turn's footprint, as
BudgetAwareMemoryreckons it (RFC §20): the input the AI channel measured (current_turn_footprint()), the current event, the inner provider's messages and notes, and for the reply the larger ofmax_context_tokens * safety_margin_ratioand the turn'smax_tokens. If the events fit in it → return as-is (no compacting) - If over budget, the latest events that fit the budget less the summary's share are kept:
- Split events into trimmed (old) and kept (recent)
- Summarize trimmed events via the AI provider, each quoted on one line after who said it:
[user]and[assistant]in a one-to-one conversation, the runtime's label (Alice: “…”,@sms1: “…”) when the turns retrieved, summarized or kept, hold several speakers,[assistant]naming only the agent the summary is for; the result'sspeakerslists the labels named, which the conversation counts - Inject summary as a pre-built message at the context start
- Return:
[summary_message] + [kept_events]
- Summaries are cached per-room with TTL to avoid regenerating on every call
Graceful degradation: If summarization fails (provider error), a placeholder message is injected instead.
Choosing a Summarizer
Use a fast, inexpensive model (e.g., Claude Haiku) for summarization. The summary prompt focuses on decisions made, key findings, tool results, and errors.
SummarizingMemory (Two-Tier)¶
SummarizingMemory proactively manages context budget with two tiers. Unlike CompactingMemory (which only fires when the budget is exceeded), SummarizingMemory starts truncating early and summarizes before hitting the limit. Designed for agentic workloads where tool results can be very large.
from roomkit.channels import AIChannel
from roomkit.memory import SlidingWindowMemory, SummarizingMemory
from roomkit.providers.anthropic import AnthropicAIProvider, AnthropicConfig
# Lightweight model for summaries
summarizer = AnthropicAIProvider(AnthropicConfig(
api_key="...", model="claude-haiku-5-5",
))
memory = SummarizingMemory(
inner=SlidingWindowMemory(max_events=100),
provider=summarizer,
max_context_tokens=128_000, # The model's context window
tier1_ratio=0.50, # Truncate old events at 50% of what the turn leaves
tier2_ratio=0.85, # Summarize at 85% of it
truncate_chars=2000, # Max chars per old event in tier 1
summary_max_tokens=1000, # Max tokens for summaries
min_events=5, # Always keep at least 5 recent events
summary_cache_ttl_seconds=300.0, # Cache summaries for 5 minutes
)
ai = AIChannel("ai-agent", provider=main_provider, memory=memory)
| Parameter | Default | Description |
|---|---|---|
inner |
required | Wrapped memory provider |
provider |
required | AI provider for summarization |
max_context_tokens |
required | The model's context window |
tier1_ratio |
0.50 |
Fraction of the history's budget that triggers tier-1 truncation |
tier2_ratio |
0.85 |
Fraction of the history's budget that triggers tier-2 summarization |
truncate_chars |
2000 |
Max characters per old event body in tier 1 |
summary_max_tokens |
1000 |
Max output tokens for the LLM summary |
min_events |
5 |
Minimum events to keep before summarizing |
summary_cache_ttl_seconds |
300.0 |
TTL for cached summaries |
How it works:
- Calls
inner.retrieve()to get events and pre-built messages - History's budget = the window less what the rest of the turn takes (RFC §20):
the input the AI channel measured (
current_turn_footprint()), the turn'smax_tokensand the current event - Estimates total tokens (events + prior messages and notes)
- Tier 1 (at ~50% of the budget): Truncates large text bodies in the older half of events to
truncate_chars. No LLM call — cheap and fast. - Tier 2 (at ~85% of the budget): Calls the summary provider to summarize older events into a concise paragraph. Keeps recent events at full fidelity. Supports chained summaries — if a prior summary exists, it is incorporated into the new one.
- Drops the oldest events until the result fits the budget, one event always kept
- Summaries are cached using a content-derived key with TTL
Graceful degradation: If tier-2 summarization fails (provider error), the events are returned un-summarized with a placeholder.
SummarizingMemory vs CompactingMemory
Use CompactingMemory for simple long conversations. Use SummarizingMemory for agentic workloads where tool results are large and you want proactive budget management before hitting the context limit.
RetrievalMemory (RAG)¶
RetrievalMemory enriches AI context with knowledge from external sources — vector stores, search engines, document indexes, or any system that can answer relevance queries.
from roomkit.channels import AIChannel
from roomkit.knowledge import KnowledgeSource, KnowledgeResult
from roomkit.memory import RetrievalMemory, SlidingWindowMemory
class FAQSource(KnowledgeSource):
"""Example: retrieve from a vector database."""
async def search(self, query, *, room_id=None, limit=5):
results = await my_vector_db.search(query, top_k=limit)
return [
KnowledgeResult(content=r.text, score=r.score, source="faq")
for r in results
]
async def index(self, content, metadata=None):
await my_vector_db.upsert(content, metadata=metadata)
memory = RetrievalMemory(
sources=[FAQSource()],
inner=SlidingWindowMemory(max_events=50),
max_results=5, # Max knowledge results in context
min_query_length=3, # Skip search for very short queries
)
ai = AIChannel("ai-agent", provider=provider, memory=memory)
| Parameter | Default | Description |
|---|---|---|
sources |
required | List of KnowledgeSource implementations |
inner |
required | Wrapped memory provider for conversation history |
max_results |
5 |
Maximum knowledge results to include in context |
min_query_length |
3 |
Minimum query length to trigger search |
How it works:
- Calls
inner.retrieve()for conversation history - Extracts query text from the current event
- Searches all sources concurrently (fault-tolerant — one failure doesn't break others)
- Deduplicates results by content (keeps highest score)
- Returns the passages as the turn's note (
MemoryResult.notes), each in a<knowledge>block set apart as data: they follow the turn's input, after the question, and leave the conversation history untouched, so its cache holds when the passages change at the next question (on a six-question benchmark, 30 % cheaper onclaude-sonnet-5)
Automatic indexing: When AIChannel calls ingest() on every inbound event, RetrievalMemory forwards to both the inner provider and all knowledge sources — enabling auto-indexing of conversation content.
Composing Providers
RetrievalMemory composes with other providers. For both RAG and summarization:
Custom Memory Provider¶
Implement MemoryProvider for custom logic (e.g., vector store retrieval):
from __future__ import annotations
from roomkit.memory import MemoryProvider, MemoryResult
from roomkit.providers.ai import AIMessage
class VectorStoreMemory(MemoryProvider):
"""Retrieve relevant context from a vector store."""
def __init__(self, vector_db, top_k: int = 5, recent_count: int = 10) -> None:
self._vector_db = vector_db
self._top_k = top_k
self._recent_count = recent_count
@property
def name(self) -> str:
return "VectorStoreMemory"
async def retrieve(self, room_id, current_event, context, *, channel_id=None):
# Get relevant past context via similarity search
query = current_event.content.body if hasattr(current_event.content, "body") else ""
relevant = await self._vector_db.search(query, top_k=self._top_k, room_id=room_id)
# Build a context summary from relevant results
summary = "\n".join(f"- {r.text}" for r in relevant)
summary_msg = AIMessage(
role="user",
content=f"[Relevant context from conversation history]\n{summary}",
)
# Also include the most recent events for immediate context
recent = context.recent_events[-self._recent_count:]
return MemoryResult(messages=[summary_msg], events=recent)
async def ingest(self, room_id, event, *, channel_id=None):
# Index new events in the vector store
text = event.content.body if hasattr(event.content, "body") else str(event.content)
await self._vector_db.index(text, room_id=room_id, event_id=event.id)
Multi-Channel Memory¶
The channel_id parameter enables different memory strategies per AI channel in the same room:
from __future__ import annotations
from roomkit.memory import MemoryProvider, MemoryResult
class PerChannelMemory(MemoryProvider):
@property
def name(self) -> str:
return "PerChannelMemory"
async def retrieve(self, room_id, current_event, context, *, channel_id=None):
if channel_id == "ai-summarizer":
# This channel sees the full history
return MemoryResult(events=context.recent_events[-200:])
else:
# Other channels see only recent events
return MemoryResult(events=context.recent_events[-20:])
Token Estimation Utilities¶
from roomkit.memory import (
estimate_context_tokens,
estimate_message_tokens,
estimate_tokens,
)
# Text estimation (~1 token per 4 chars)
tokens = estimate_tokens("Hello, how can I help?") # → 6
# Message estimation (includes role overhead)
tokens = estimate_message_tokens(AIMessage(role="user", content="Hello")) # → 5
# Full context estimation (system prompt + messages + tools)
tokens = estimate_context_tokens(ai_context)
Note
These are rough estimates. For exact token counting, use the provider's tokenizer (e.g., tiktoken for OpenAI). The built-in estimator is designed for budget allocation, not exact measurement.
Testing with MockMemoryProvider¶
from __future__ import annotations
from roomkit.memory import MockMemoryProvider
from roomkit.providers.ai import AIMessage
mock = MockMemoryProvider(
messages=[AIMessage(role="system", content="Previous conversation summary")],
events=[event1, event2],
)
# After usage:
assert len(mock.retrieve_calls) == 1
assert mock.retrieve_calls[0].room_id == "room-1"
assert mock.retrieve_calls[0].channel_id == "ai-assistant"
assert not mock.closed
The mock tracks all retrieve(), ingest(), and clear() calls for assertion.