Metadata-Version: 2.5
Name: tokenslim-langgraph
Version: 0.1.0
Summary: TokenSlim integration for LangGraph and LangChain: trim tool outputs before they re-enter the context, without breaking the tool-calling protocol.
Project-URL: Homepage, https://kamalmosadegh.github.io/tokenslim/
Project-URL: Repository, https://github.com/kamalmosadegh/tokenslim
Project-URL: Benchmark, https://kamalmosadegh.github.io/tokenslim/
Author: Kamal Mosadegh
License: MIT
License-File: LICENSE
Keywords: agents,context,langchain,langgraph,llm,tokens
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Requires-Python: >=3.10
Requires-Dist: langchain-core>=1.0
Requires-Dist: langchain>=1.0
Requires-Dist: langgraph>=1.0
Requires-Dist: tokenslim-py>=0.1.0
Provides-Extra: dev
Requires-Dist: pytest>=8; extra == 'dev'
Description-Content-Type: text/markdown

# 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](https://github.com/kamalmosadegh/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`**, **`name`**
  and **status** (trimming is a `model_copy` with new content, nothing else);
- human, system and AI messages are **never** rewritten;
- message count and order never change.

## Install

```bash
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:

```python
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`):

```python
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:

```python
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)
```

```bash
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](https://kamalmosadegh.github.io/tokenslim/)**
and the [main TokenSlim repo](https://github.com/kamalmosadegh/tokenslim).

## When NOT to use it

See [docs/INTEGRATION.md](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 `ToolMessage` from 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
