Memory Consolidation Patterns
The Problem: Memory Bloat
Agent memory grows faster than retrieval slows, creating bloat:
- Retrieval noise: Searching "customer sentiment" returns 100+ results. Top 10 have low signal. Wastes tokens scoring irrelevant memories.
- Storage cost: 50K memories × 50/month per agent. With consolidation: 5K summaries = $5/month.
- Latency creep: Searching 50K memories is slower than 5K. BM25 and semantic search degrade.
Example: Customer support agent
- Day 1–30: 100 interactions, 500 memories (5 per interaction)
- Month 3: 300 interactions, 1,500 memories
- Month 6: 600 interactions, 3,000 memories
Retrieval "customer sentiment" now searches 3,000 items. Many are duplicates:
- "Customer angry about shipping" (Day 1)
- "Customer still angry about shipping" (Day 2)
- "Customer angry about shipping and billing" (Day 3)
Consolidation: Collapse these 3 into one summary: "Customer upset about shipping delays and billing errors; prefers email contact."
Results:
- 3,000 memories → 1,000 consolidated summaries (66% reduction)
- Retrieval latency improves 3x
- Storage cost drops from 1
- Retrieval quality improves (less noise, more relevant summaries)
Pattern 1: Summarize Similar Memories
Idea: Group similar memories by topic, summarize the group, replace with one consolidated memory.
When to use:
- Agent stores detailed logs that are repetitive (trading logs, chat turns)
- You want to reduce noise while preserving facts
- Long-term memory is more important than detailed history
How it works:
import os
import json
from brain_db_sdk import Auth, BrainClient, EncodeBuilder, RecallBuilder, ForgetBuilder
from anthropic import Anthropic
client = BrainClient.connect(
"127.0.0.1", 9090, Auth.token(os.environ["BRAIN_API_KEY"].encode())
)
claude = Anthropic(api_key="...")
def consolidate_by_topic(topic: str, original_ids: list) -> dict:
"""
Consolidate memories matching a topic into a single summary.
Recall the memories for the topic, summarize them with Claude, encode the
summary as a new memory, then forget the originals (ids you kept from the
encode() calls that created them).
"""
# 1. Recall memories matching the topic
answer = client.recall(RecallBuilder(topic).limit(100).build())
memory_texts = [hit.text for hit in answer.memories]
if len(memory_texts) < 2:
return {"consolidated": False, "reason": "Less than 2 memories"}
# 2. Summarize using Claude
summary = claude.messages.create(
model="claude-opus-4-1",
max_tokens=500,
messages=[
{
"role": "user",
"content": f"""Consolidate these {len(memory_texts)} memories about {topic} into a single summary.
Focus on patterns, key facts, and trends. Preserve specifics.
Memories:
{json.dumps(memory_texts, indent=2)}
Return a single consolidated memory (2-3 sentences max)."""
}
]
).content[0].text
# 3. Encode the consolidated summary as a new memory
stored = client.encode(EncodeBuilder(summary).build())
# 4. Forget the original memories
for memory_id in original_ids:
client.forget(ForgetBuilder(memory_id).build())
return {
"consolidated": True,
"consolidated_id": stored.memory_id,
"memories_merged": len(memory_texts),
"summary": summary,
}
# Usage
result = consolidate_by_topic("trading_losses", original_ids=[...])
print(f"Consolidated {result['memories_merged']} losses into 1 summary")Example execution:
Input (5 trading loss memories):
1. "Sold AAPL too early, lost 1.2% on recovery"
2. "Held MSFT too long, got stopped at -2.5%"
3. "TSLA bad entry, exited at -1.8%"
4. "Missed NVDA dip, entered at peak, -2.1%"
5. "Tech sector rotation caught me unprepared, -3.2% total"
Output (1 consolidated summary):
"Lost 10.8% across 5 trades in tech sector (AAPL, MSFT, TSLA, NVDA).
Errors: premature exit, overholding, bad entry, missed dips.
Pattern: Sector rotation without position rotation."Pattern 2: Filter Duplicates
Idea: Detect and remove near-duplicate memories (same content, slightly different wording).
When to use:
- Agent stores redundant information (chat bots storing every message + summary)
- You want to deduplicate without manual review
- Exact deduplication isn't needed (near-duplicate is fine)
How it works:
import { BrainClient, ForgetBuilder } from "@brain-db/sdk";
const auth = { kind: "token", token: new TextEncoder().encode(process.env.BRAIN_API_KEY!) };
const client = await BrainClient.connect("127.0.0.1", 9090, { auth });
// Brain deduplicates near-identical memories for you. The write path runs
// extraction + supersession + predicate consolidation on every shard, so a
// re-statement of an existing fact supersedes the older one instead of piling
// up a second near-duplicate vector — you rarely need a client-side dedup pass.
//
// When you do want to drop a specific memory you know is redundant, forget it
// by id (the id you kept from the encode() call that created it):
async function forgetDuplicate(memoryId: bigint): Promise<void> {
await client.forget(new ForgetBuilder(memoryId).build());
}Pattern 3: Archive Cold Data
Idea: Move rarely-retrieved memories to cold storage (separate table, S3, etc.). Keep hot data in Brain.
When to use:
- You must keep long history (compliance, audit)
- But most queries only need recent data
- Cold storage is much cheaper than active memory
How it works:
import os
import json
import boto3
from datetime import datetime
from brain_db_sdk import Auth, BrainClient, ForgetBuilder
client = BrainClient.connect(
"127.0.0.1", 9090, Auth.token(os.environ["BRAIN_API_KEY"].encode())
)
s3_client = boto3.client("s3")
S3_BUCKET = "agent_memory_archive"
def archive_cold_memories(cold_memories: list) -> dict:
"""
Move a set of cold memory records to S3, then forget them in Brain.
`cold_memories` is the list of records your app has decided are cold—each
with at least an `id` and `content` (track these as you encode). Brain's
per-shard decay + retention workers also age out stale memories server-side,
so this pass is only for data you want in your own cold store.
"""
if not cold_memories:
return {"archived": 0, "reason": "No cold memories"}
# 1. Create archive file
archive = {
"archived_at": datetime.utcnow().isoformat(),
"count": len(cold_memories),
"memories": cold_memories,
}
# 2. Upload to S3
archive_key = f"archives/{datetime.utcnow().strftime('%Y-%m-%d')}.json"
s3_client.put_object(
Bucket=S3_BUCKET,
Key=archive_key,
Body=json.dumps(archive),
ContentType="application/json",
)
# 3. Forget from Brain
forgotten = 0
for memory in cold_memories:
client.forget(ForgetBuilder(memory["id"]).build())
forgotten += 1
return {
"archived": len(cold_memories),
"archive_key": archive_key,
"forgotten_from_brain": forgotten,
}Retrieval from archive (when needed):
def retrieve_from_archive(date: str) -> list:
"""Read archived memories back from S3 if needed"""
archive_key = f"archives/{date}.json"
obj = s3_client.get_object(Bucket=S3_BUCKET, Key=archive_key)
archive = json.loads(obj["Body"].read())
return archive["memories"]Consolidation Triggers
When should you consolidate?
| Trigger | Condition | Action |
|---|---|---|
| Size-based | Memories > 1,000 | Consolidate oldest 500 by topic |
| Time-based | Weekly cron job | Consolidate duplicates, archive >30 days |
| Quality-based | Low retrieval score | Summarize 10 low-scoring memories into 1 |
| Manual | User request | Run consolidation on demand |
Implementation (size-based trigger):
// Brain doesn't expose a client-side memory count, so track how many memories
// you've encoded and trigger consolidation when your own counter crosses a
// threshold.
let encodedCount = 0;
function onEncoded() {
encodedCount++;
if (encodedCount > 1000) {
console.log(`Reached ${encodedCount} memories. Triggering consolidation...`);
consolidateByTopic("observed_pattern"); // your consolidation routine
encodedCount = 0;
}
}
// Call onEncoded() after each encode(), or run a periodic pass:
setInterval(onEncoded, 1000 * 60 * 60);Consolidation Patterns: Cost Impact
Consolidate 5 memories into 1; how much do you save?
| Before | After | Savings |
|---|---|---|
| 5 memories @ 500 bytes each | 1 summary @ 200 bytes | 80% storage, 72% retrieval tokens |
| 50K memories, BM25 search | 10K summaries, BM25 search | 80% search time, 80% retrieval cost |
| 3,000 vectors @ $0.001 ea | 600 summaries @ $0.001 ea | $2.40/month per agent |
At scale (100 agents, 3K memories each):
- Before: 300K memories = 150/month retrieval = $450/month
- After: 60K summaries = 30/month retrieval = $90/month
- Savings: $360/month (80%)
Implementation Checklist
- Choose consolidation pattern: summarize similar (topic-based), deduplicate (near-exact), or archive (cold)
- If summarizing: identify topics (trading_losses, customer_complaints, decisions)
- If deduplicating: lean on Brain's server-side supersession + consolidation (re-stated facts supersede older near-duplicates); forget specific redundant ids when needed
- If archiving: define hot/cold boundaries (30 days hot, >365 days cold)
- Implement consolidation function with error handling
- Add consolidation trigger: size-based (>1K), time-based (weekly), or quality-based (low score)
- Test consolidation on a staging agent before production
- Monitor: measure token reduction, retrieval latency, cost per agent
- Document: when consolidation runs, what gets consolidated, where archives live
Next Steps
- Temporal management: See Temporal Context Windows for time-based memory cleanup
- Cost optimization: Check Cost Optimization for Agent Memory for the full picture
- Long-term memory: Read Longterm Memory for strategies that last months/years