Hi maintainers,
Ive been working on a context management layer for LangGraph and wanted to get some feedback before opening a PR. LangGraph already has tools like pre_model_hook, RemoveMessage, and trim_messages, but I couldn’t find a reusable way to combine context compaction with checkpointed state and provenance.
I’ve built a dependency free implementation, along with an optional integration with Brevitas Splice that edits the KV cache directly for self hosted Transformers models, avoiding a full prefill after compaction. I wanted to get your thoughts on whether this abstraction makes sense for LangGraph and how you’d prefer the cache integration to be structured.
What I’m proposing (dependency free core)
A ContextManager usable as a pre_model_hook that:
- Compacts older history under a pluggable policy while preserving recent, system, and pinned messages and never orphaning a tool result from its tool call.
- Produces a derived
llm_input_messagesview and never mutates canonical messages. - Records provenance (which message IDs → which revision/transformation → which context_version) in a context_ledger state channel that survives checkpointing.
- Is idempotent across retries and resumption (no double-compaction).
This is pure python, adds no dependencies, and works with any messages bearing graph.
For self hosted Transformers models, I have a working backend that mirrors a compaction onto the model’s KV cache via exact RoPE re-rotation (Brevitas Splice), so surviving tokens don’t have to be re-prefilled. It sits behind a small, provisional InferenceCacheAdapter protocol with a no-op default, imports lazily, and is not a dependency of any published package.
In one specific experiment (Qwen2.5-0.5B, CPU/fp32, dropping a single early turn), I measure next token top-1 agreement of 10/12 and KL ≈ 0.067 nats vs a recompute, at roughly 20-30x lower latency than re-prefilling. Those numbers are illustrative, not a general guarantee, and will vary by model, what’s dropped, and dtype. It’s opt in, defaults off, and always falls back to normal inference. Im presenting it as a measured approximation, not a drop in optimization.
Some questions I have for maintainers are: is the general context-management layer something you’d accept in principle? Should it live in langgraph core or langgraph-prebuilt? It uses only core primitives and returns a plain pre_model_hook dict, so either seems plausible.
Happy to share the branch and benchmark script. Thanks!