Your agent's memory file and a month of session logs do not fit in a local model's context window. So what does a memory tool do when the input is ten times bigger than one call?
agentdream is an open source Python tool that "dreams" over an agent's memory: it reads the notes and the session transcripts, then proposes merges, corrections and new insights for you to review. With an LLM backend, each phase is a model call. When the input is too big for one call, agentdream splits the work into chunks and merges the answers. This post walks through how that works, using the code in src/agentdream/chunking.py and src/agentdream/engine/llm.py.
The analogy: a jigsaw sorted onto trays
Think of a 5,000 piece jigsaw and a table that only holds 500 pieces. You cannot lay it all out. So you sort pieces onto trays, work one tray at a time, and join the finished sections at the end.
Two things decide whether that works: how you sort (pieces that fit together must share a tray) and how you join (overlapping sections need a fixed rule for which one stays).
agentdream has the same two problems. The table is max_chunk_tokens. The sorting is the planner. The joining is the reduce step.
The budget
Three settings control chunking. These are the defaults from docs/CONFIG.md:
max_chunk_tokens = 60000 # LLM backends: token budget per call
chunk_overlap = 400 # transcript tokens repeated between consecutive chunks of a session
max_chunks = 64 # max model calls per phase
For a small local model you shrink the budget. The README shows this exact command:
agentdream dream -m ./memory -s ./logs --backend ollama --model llama3.1:8b --max-chunk-tokens 6000
Token counts are an estimate, not a real tokenizer. The whole function in util.py is one line:
def estimate_tokens(text: str) -> int:
return (len(text) + 3) // 4
That is about 4 characters per token, which the README lists as a limitation. The trade is on purpose: the core has zero dependencies (dependencies = [] in pyproject.toml), so there is no tokenizer to import.
Sorting the trays: three different plans
plan_calls(ctx, phase) turns a phase into model calls that fit the budget. It first subtracts the prompt scaffolding (system prompt, task text, your instructions). If what is left is under 256 tokens, it stops with a clear error instead of sending a useless prompt:
if budget < 256:
raise DreamLimitError(f"max_chunk_tokens={cfg.max_chunk_tokens} is too small: the prompt scaffolding alone "
f"needs ~{overhead} tokens (use at least {overhead + 1024})")
Then the plan depends on the phase.
Consolidate only looks at memory. If the store fits, it is one call. If not, a naive split would put duplicate notes in different chunks, and no single call would ever see both. So the entries are reordered first:
def similarity_order(entries: list[MemoryEntry]) -> list[MemoryEntry]:
"""Store order, but with likely duplicates / same-subject notes moved next to each other so
consolidation chunks see them together."""
sets = [token_set(e.content) for e in entries]
claims = claims_in_entries(entries)
subjects = [c.subject if c else frozenset() for c in claims]
pairs = [(i, j) for i, j in similar_pairs(sets, 0.3) if jaccard(sets[i], sets[j]) >= 0.3]
pairs += [(i, j) for i, j in similar_pairs(subjects, 0.5) if jaccard(subjects[i], subjects[j]) >= 0.5]
return [entries[i] for i in cluster_order(len(entries), pairs)]
Notes whose token sets overlap (Jaccard 0.3 or more), or whose subjects overlap (0.5 or more), are pulled next to each other with a union-find, then packed in order. All of this is cheap string math, done before any model is called.
Verify and insights read memory and transcripts together. Here there are three cases:
- Everything fits: one call.
- Memory fits in half the budget: every transcript chunk is sent along with the whole store.
- Memory is too big for that: each transcript chunk is paired only with the entries it is relevant to.
Case 3 is the interesting one. "Relevant" means sharing a distinctive token, and the code comment says what that is:
# Relevance = sharing a *distinctive* token (rare across the store: names, ids, numbers),
# not "service" or "port". Entries without any distinctive token need two shared tokens.
df = TokenIndex(sets)
cap = max(3, len(entries) // 50)
rare_sets = [frozenset(t for t in s if df.df(t) <= cap) for s in sets]
A token is rare if it appears in at most max(3, entries // 50) entries. If a transcript chunk mentions nothing in memory, verify skips it. No call, no tokens spent.
Cutting without losing things
The packer in chunking.py follows a few strict rules, listed in its module docstring:
- Items are packed greedily and in order. An entry or message is never split unless it alone is over budget.
- An oversized item is cut at paragraph, line, sentence, word or, last, character boundaries. Each piece keeps its original id or citation plus a
(part k/n)marker. - Transcript chunks overlap, but only inside one session. The overlap is capped at a quarter of the budget "so every chunk makes progress".
- Same input and same budget always give the same chunks.
The overlap matters for a real reason. docs/ARCHITECTURE.md explains it: a failure and its fix can sit on both sides of a chunk boundary, and the overlap lets one call see both.
There is one more guard. If a model only saw part of an entry, it must not rewrite it. The split_entry docstring puts it plainly: "The LLM engine never lets a model rewrite an entry it only saw part of." Excerpted entries are read-only.
Joining the sections: a reduce step with no model
After the map calls, reduce_operations merges the per-chunk proposals. No LLM is involved. The rules, from its docstring:
- Identical proposals collapse into one. Their evidence is unioned and the highest confidence is kept.
- Merges whose targets overlap become one merge, because duplication is transitive. If chunk 1 says A equals B and chunk 2 says B equals C, you get one merge of A, B and C.
- Other operations that touch the same entry are in conflict. One wins.
- Flags that change nothing are kept and deduplicated.
The winner in rule 3 is picked by a single sort key:
_TYPE_RANK = {"correct": 5, "replace": 4, "merge": 3, "contradiction": 2, "insight": 1}
_win_pos, win = max(members, key=lambda m: (len(m[1].evidence), m[1].confidence,
_TYPE_RANK.get(m[1].type, 0), -m[0][0], -m[0][1]))
Most verified evidence first, then confidence, then type, then whichever was seen first. The losers are not thrown away silently. They are written into the winner's history as "alternative proposal from part N" with their citations, and a warning names the conflict.
Same proposal, same id
Operation ids come from content, not from position:
def make_id(type_: str, targets: Iterable[str], after: Iterable[str]) -> str:
return f"{type_}-{stable_hash(type_, sorted(targets), list(after), length=8)}"
So the same proposal gets the same id whether the run used 1 call or 12. The repo tests this in test_chunked_and_unchunked_runs_give_same_op_ids, which runs the same input at budgets of 1,500 and 200,000 tokens and compares the ids.
This matters in practice because you accept operations by id. Changing the chunk budget should not change what you are approving.
When the plan is too big, or a call fails
If a phase needs more than max_chunks calls, there are two outcomes. With --on-limit fail the job stops with a DreamLimitError. Otherwise agentdream sends the first max_chunks calls for consolidate, or the most recent ones for verify and insights, and the notice says it "covered the rest with deterministic heuristics".
The same fallback covers failed calls. Per docs/ARCHITECTURE.md, if every call in a phase fails, the heuristics run for that phase. If only some fail, the valid LLM operations are applied first and the heuristics fill in.
What chunking cannot do
The README is honest about the limit: "Chunked runs see one part of the input per call: duplicates or evidence split across chunks are reconciled by the reduce step only if each chunk proposes them." Similarity ordering lowers that risk. It does not remove it.
It also costs more: the architecture doc says chunking adds overlap plus about 700 to 750 tokens of scaffolding per call.
Takeaways
- A context window is a table size. Plan how you sort work onto it before you call a model.
- Group related items before chunking. agentdream uses Jaccard overlap and a union-find so duplicates share a chunk.
- Overlap transcript chunks inside a session, never across sessions.
- Never let a model rewrite something it only saw part of.
- Make the reduce step plain code with a fixed tie-break, and keep the losers in a history.
- Derive ids from content so chunk size does not change what a reviewer approves.
Try it: pip install agentdream (Python 3.10 or newer, no dependencies), then read the code at github.com/mvplab-ai/agentdream.
Top comments (0)