CompressContextTool is a LangChain BaseTool that reduces prompt size without any external LLM call. It collapses whitespace, removes common English stop words, and optionally truncates to a maximum character length. It is compatible with LangChain tool runners and can be passed directly to an ExecutionAgent.
Tool name: compress_context
Import
Extends
langchain_core.tools.BaseTool
Constructor
Default truncation limit in characters. Applied when
_run is called without an explicit max_length override. Set to None to disable truncation entirely.Methods
_run
Synchronously compresses the input text.
The raw text to compress.
Per-call character limit override. When provided, takes precedence over the instance-level
max_length. When omitted, the instance default is used.The compressed string. If truncation occurred, the string ends with
"... [TRUNCATED]".Compression pipeline
- Collapse all whitespace sequences (including newlines) to a single space and strip leading/trailing whitespace.
- Remove the following stop words (case-insensitive):
a,an,the,is,are,was,were,and,or,but. - Collapse any double spaces introduced by stop-word removal.
- Truncate to
max_lengthcharacters and append"... [TRUNCATED]"if the result exceeds the limit.
Stop words are matched with surrounding spaces (e.g.,
" the ") to avoid partial-word removal. A word like "theater" is not affected._arun
Async version. Delegates directly to _run.
The raw text to compress.
Per-call character limit override.
Same output as
_run.Utility Function
A standalone helper is also exported for use without instantiating the fullBaseTool:
CompressContextTool(max_length=max_length) and calls _run.