tokenslim-langgraph
TokenSlim × LangGraph/LangChain — trim agent tool outputs before they re-enter the context, without breaking the tool-calling protocol.
Tool results are the silent budget-killer in agent loops: one log dump, one search result, one file read gets re-sent to the model on every later turn. TokenSlim shrinks that content — duplicate collapse, signal-aware truncation that keeps error lines and identifiers — and this package wires it into LangGraph and LangChain with the protocol left exactly intact:
- every trimmed message keeps its
id,tool_call_id,nameand status (trimming is amodel_copywith new content, nothing else); - human, system and AI messages are never rewritten;
- message count and order never change.
Install
pip install tokenslim-langgraph
Requires Python ≥ 3.10, tokenslim-py >= 0.1.0, langgraph >= 1.0,
langchain-core >= 1.0, and langchain >= 1.0 (the middleware uses the
langchain 1.x AgentMiddleware API, which does not exist in 0.3 — see
Caveats below). Developed and tested against langgraph 1.2.24,
langchain 1.5.2, langchain-core 1.8.5.
Option 1 — a LangGraph node
Put the trim node between your tools node and your model node:
from langgraph.graph import StateGraph, MessagesState
from langgraph.prebuilt import ToolNode
from tokenslim_langgraph import trim_tool_messages
graph = StateGraph(MessagesState)
graph.add_node("model", call_model)
graph.add_node("tools", ToolNode(tools))
graph.add_node("trim", trim_tool_messages) # <-- here
graph.add_edge("tools", "trim")
graph.add_edge("trim", "model")
The node returns a minimal {"messages": [...]} update containing only the
messages that changed. Since each carries its original id, the
add_messages reducer swaps the fat original for the trimmed copy in
place.
Configure it with the factory (LangGraph nodes take only state):
from tokenslim_langgraph import make_trim_tool_messages_node
graph.add_node("trim", make_trim_tool_messages_node(
tool_max_tokens=200, # per-tool-message token cap
query="why did the deploy fail", # lines mentioning the task score higher
))
Option 2 — LangChain agent middleware
With create_agent (langchain ≥ 1.0), the middleware trims each tool
result at the moment it is produced — the fat original never enters the
agent's state at all:
from langchain.agents import create_agent
from tokenslim_langgraph import TokenSlimMiddleware
agent = create_agent(
model,
tools=[...],
middleware=[TokenSlimMiddleware(tool_max_tokens=400)],
)
Both sync (wrap_tool_call) and async (awrap_tool_call) agents are
supported, including tools that return a Command with messages in its
update.
See it run
examples/mini_graph.py is a complete offline demo — a stub chat model
(no API keys), one tool that returns a 6,487-token redundant log, the
graph run with and without the trim node:
tool output tokens : 6,487 -> 400 (93.8% saved)
total state tokens : 6,534 -> 447 (93.2% saved)
python examples/mini_graph.py
Honest numbers
TokenSlim's savings depend entirely on how redundant your tool outputs are. On redundant log-style content, the core library's published benchmark keeps 55/55 tracked facts at ~98% fewer tokens; on unique prose the same pipeline saves far less, and on accuracy it is at parity with untrimmed context — it does not "beat" it. Full methodology and reproduction: the benchmark page and the main TokenSlim repo.
When NOT to use it
See docs/INTEGRATION.md — the short version: prose-heavy contexts (long documents you actually need verbatim), non-text tool results, and any setting where a trimmed excerpt cannot stand in for the full output. Trimming is lossy by design; the facts are scored to survive, but no trimmer is a substitute for the source when the source itself is the deliverable.
Caveats
- Trim, not compact. TokenSlim's full pipeline can also compact
history (summarise old turns). This integration deliberately runs the
pipeline in its structure-preserving configuration: history compaction
rewrites the message list, and LangGraph state is keyed by message id —
merging the two would risk orphaning a
ToolMessagefrom its tool call. Per-message trimming is always safe; if you want compaction, run TokenSlim on an exported history outside the live graph. - String content only. Tool messages whose content is not plain text (image/file blocks) are passed through untouched.
- langchain ≥ 1.0 is a hard floor for the middleware. The LangGraph node itself only needs langgraph + langchain-core.
License
MIT © Kamal Mosadegh
Metadata
Release files for tokenslim-langgraph 0.1.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| tokenslim_langgraph-0.1.0.tar.gz | 13.8 kB | With provenance | Details for tokenslim_langgraph-0.1.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| tokenslim_langgraph-0.1.0-py3-none-any.whl | Python 3 | none | any | Details for tokenslim_langgraph-0.1.0-py3-none-any.whl |
Total release size: 24.1 kB
Release files / tokenslim_langgraph-0.1.0.tar.gz
| Download URL | tokenslim_langgraph-0.1.0.tar.gz |
|---|---|
| Size | 13.8 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
df8171d7983e5c73c98371a449cb7c97ca36d2855e9bdee5b7e8d2c01b0b98cc
|
|
BLAKE2b-256 checksum How to use checksums |
33470d269bae251443a6cb558499b6042e109ccc3c94ab7b21604e0ff1906df9
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 28, 2026.
Transparency logRelease files / tokenslim_langgraph-0.1.0-py3-none-any.whl
| Download URL | tokenslim_langgraph-0.1.0-py3-none-any.whl |
|---|---|
| Size | 10.3 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
3c79998b4ef35b7000000dc3f7520ddc1433b6642a1a919b9f9dba074da3f38a
|
|
BLAKE2b-256 checksum How to use checksums |
ddbd4f58fe11a06abbd2913b1106b9345c0efac836ab0d33bc409aab4e146d2e
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 28, 2026.
Transparency logSecurity for tokenslim-langgraph 0.1.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
Full provenance
Both files in this release have been uploaded with provenance metadata.
Attestation for tokenslim_langgraph-0.1.0.tar.gz
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 28, 2026.
Transparency logA note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.