Fit an agent's message list into its token budget by structural compression: no LLM calls, no framework lock-in, same answer every run.
pip install ctxfit && ctxfit demo
Needs Python 3.10 or newer. demo runs on a built-in synthetic sample, not your data. Real output:
ctxfit demo: a synthetic 5-tool-call agent run, squeezed into a 6,000-token budget.
est. tokens: 51,765 → 1,126 (−97.8%) [heuristic]
system 11 → 11
retrieved 51,699 → 1,060
history 55 → 55
deduplicate: −28,113 est. tokens, 3 message(s)
compact_json: −4,304 est. tokens, 1 message(s)
truncate_tool_output: −18,222 est. tokens, 1 message(s)
prompt-cache prefix kept: messages 0..2 unchanged
within budget ✓
Next: ctxfit analyze your-convo.json (JSON array of messages; '-' reads stdin)
- Shrinks the biggest waste first. Exact-duplicate messages, bulky JSON and oversized tool output are cut down; pinned messages and tool-call arguments are never touched.
- Enforces a budget. Declare a total and a per-section split. Overruns become warnings, or errors with
strict=True. - Shows its work. Every figure is an estimate and says so, and the report lists savings per strategy.
Why
Attention cost scales quadratically: doubling context roughly quadruples compute, and every extra chunk makes the agent slower, more expensive, and less accurate. Fifty turns into a run you hit the limit, and each tool result sits uncompressed in context for the rest of the run. ctxfit packages the layer agent teams usually hand-roll as a standalone library. Read Limitations before relying on it.
import ctxfit
fitted, report = ctxfit.fit(messages, total_budget=128_000)
print(report.summary())
What it does
Structural compression (no API call, no latency, reproducible):
| Strategy | What it does |
|---|---|
Deduplicate |
Exact-duplicate message bodies → pointer to the first occurrence |
CompactJson |
JSON arrays → markdown tables; nested objects → flat key paths (only when it saves tokens) |
TruncateToolOutput |
Oversized tool results → head + tail with an explicit omission marker |
SlidingWindow |
Oldest turns dropped while history overflows (pinned + latest turn never dropped) |
MaskOldToolOutputs |
Opt-in (and in the aggressive preset, before dropping): all but the last keep_last (default 3) tool results become [ctxfit: tool output masked, N chars, sha256:…]; the calls and pairs stay, pinned results are skipped |
DropOldestUnpinned |
Aggressive-mode last resort: oldest-first dropping until the total fits |
Budget enforcement: declare a total budget and per-section split —
default system 10% / retrieved 55% / history 25% / scratchpad 10%.
Strategies compress toward the budgets; surviving overruns produce warnings
(strict=True raises BudgetOverflow instead).
Token estimation: heuristic by default (chars/4, CJK-adjusted, zero
dependencies); automatically upgrades to tiktoken's cl100k_base when
installed. Pluggable — implement count(text) for your own tokenizer.
Framework adapters: raw message-list dicts are first-class
(ctxfit.fit accepts them directly). OpenAI-shaped (also covers
OpenAI-compatible endpoints like Ollama/freellmapi), Anthropic block-shaped,
and duck-typed LangChain-shaped helpers convert at the boundary; the core
never sees framework shapes.
Install
pip install ctxfit
# optional: better estimates
pip install "ctxfit[tiktoken]"
CLI
# No file yet? See it work on a built-in synthetic sample (not your data)
ctxfit demo
cat convo.json | ctxfit analyze - # '-' reads the JSON from stdin
python -m ctxfit --version # also works without the console script
# Breakdown without changing anything (exit 2 if over budget — CI-friendly)
ctxfit analyze convo.json --budget 128000
ctxfit analyze convo.json --format json --top 20
# Which tools eat the context? (tool results grouped by tool name)
ctxfit analyze convo.json --by-tool
# Compress to fit, write fitted messages + report
ctxfit fit convo.json --out fitted.json --report report.json --aggressive
# Section overrides + strict mode
ctxfit --budget 64000 --budgets retrieved=0.6,history=0.2 --strict fit convo.json
# Quick estimate
ctxfit estimate "some text"
Shared options (--budget, --budgets, --estimator, --flavor, --aggressive,
--strict) work before or after the analyze / fit subcommand. ctxfit --version
prints the installed version.
convo.json is a JSON array of message dicts (generic {"role","content"} or
OpenAI-shaped; --flavor overrides auto-detection).
Python API
import ctxfit
from ctxfit import Budget, FitPipeline, TruncateToolOutput
# One call
fitted, report = ctxfit.fit(
messages,
total_budget=128_000,
budgets={"retrieved": 0.6, "history": 0.2}, # partial overrides OK
strategies="default", # or "aggressive", or [Strategy(...), ...]
estimator="auto", # "heuristic" | "tiktoken" | your own
strict=False, # True -> raise instead of warn
flavor="auto", # "openai" | "anthropic" | "langchain" | "generic"
)
# Full control
pipeline = FitPipeline(
strategies=[TruncateToolOutput(max_chars=8000, when="always")],
estimator="heuristic",
budget=Budget(total=64_000),
aggressive=True,
)
fitted, report = pipeline.fit(messages, flavor="openai")
# Measure-only
info = pipeline.analyze(messages) # section usage, warnings, top consumers
FitReport carries tokens_before/after per section, per-strategy savings,
warnings, over_budget, plus summary() and to_dict().
Custom strategies
from ctxfit import Strategy, Message
class RedactSecrets(Strategy):
name = "redact_secrets"
target_sections = ("retrieved", "history")
def _apply(self, messages, ctx, report):
out = []
for m in messages:
new = m.content.replace("sk-live-", "sk-live-[REDACTED]")
if new != m.content:
report.log("redacted secret-like token", 0)
out.append(Message(role=m.role, content=new, kind=m.kind,
name=m.name, call_id=m.call_id,
section=m.section, pinned=m.pinned, meta=m.meta))
return out, report
Contract: pure function (never mutate inputs — return new objects), preserve
message order, never modify tool_call content, never orphan half of a
tool_call/tool_result pair (the pipeline raises PairingBroken if you do),
and respect pinned.
Pinning
System messages are pinned automatically. Pin anything that must survive:
{"role": "user", "content": task_brief, "pinned": True}
Pinned messages are never dropped; truncated only with explicit opt-in
(TruncateToolOutput(truncate_pinned=True)).
Safety rules (load-bearing)
- Pair-atomicity. Tool calls and results are linked by ID and kept,
truncated, or dropped together.
validate_pairing()runs before and after the pipeline; violations raisePairingBroken. - Tool-call arguments are sacred. No strategy ever modifies
tool_callcontent — API validity is non-negotiable. - Soft enforcement by default. ctxfit degrades to warnings, never crashes
your agent loop. Opt into
strict=Trueif you want exceptions. - Honest numbers. Every figure is an estimate, labeled as such.
Limitations (read before trusting it blindly)
Limits up front, in plain words:
- Estimates, not tokens. The heuristic is roughly ±25% on mixed prose/code and worse on CJK/emoji-heavy text. Budget 80–90% of your model's true window as a safety margin. tiktoken (optional) narrows the error but no heuristic equals your model's actual tokenizer.
- Lossy by design. ctxfit deletes and rewrites content to fit budgets. Pin anything that must survive verbatim.
- Head+tail truncation assumes the middle matters least. If the critical line is item #500 of 1,000, it will be lost. Pin or pre-filter such payloads.
- JSON compaction is whole-message only (no substring extraction);
non-uniform object arrays are left alone; table cells truncate at 120 chars
(marked
…); only applied when it actually saves tokens. - Observation masking forgets old tool output. The model sees only the size and hash of masked results. The paper "The Complexity Trap" (Lindenbauer et al., arXiv:2508.21433) reports that simple observation masking matched LLM summarization for software-engineering agents; that is the paper's finding on its benchmarks, not something ctxfit has measured.
- Compression can cost prompt caching. Provider prompt caches match on an
unchanged message prefix. Any change early in the list invalidates the cache
from that point, which may cost more than the tokens saved. The FitReport
shows
first_changed_indexand the summary printsprompt-cache prefix kept: messages 0..N unchangedso you can check. - Exact-match dedup only. Near-duplicates are not merged — deliberate; fuzzy matching is unexplainable and risky.
- No LLM summarization, ever. Structural compression only. (Subclass
Strategywith your own summarizer if you want semantic compression — that's your API bill, not ours.) - Turn counting is user-message-led. Tool-heavy loops with few user turns
should use
aggressive=True. to_anthropicemits system messages as{"role": "system"}dicts — hoist them to the API's top-levelsystemparameter yourself.- Section overrides are a power tool. Mislabeling sections mostly hurts you (wrong protection, wrong truncation eligibility); assignment from role/kind is deterministic and never inferred from content length.
Development
python -m venv .venv && .venv/bin/pip install -e ".[dev]"
.venv/bin/python -m pytest
.venv/bin/ruff check src tests
.venv/bin/ruff format --check src tests
Links
License
MIT — Calas Automations Inc.
Metadata
Release files for ctxfit 0.1.3
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 |
|---|---|---|---|---|
| ctxfit-0.1.3.tar.gz | 44.7 kB | Without provenance | Details for ctxfit-0.1.3.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| ctxfit-0.1.3-py3-none-any.whl | Python 3 | none | any | Details for ctxfit-0.1.3-py3-none-any.whl |
Total release size: 79.5 kB
Release files / ctxfit-0.1.3.tar.gz
| Download URL | ctxfit-0.1.3.tar.gz |
|---|---|
| Size | 44.7 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
0f923289678918d5755567661e33df46cab63c25a30413b1d285abd078c16b7b
|
|
BLAKE2b-256 checksum How to use checksums |
58b8e12341a8ff6b3cba4b4023ce025a31c258db400fdac261f175f9aae0b530
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.12.10
|
Release files / ctxfit-0.1.3-py3-none-any.whl
| Download URL | ctxfit-0.1.3-py3-none-any.whl |
|---|---|
| Size | 34.8 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
5979c8875c17941e80cd3fdeb6cb788fcf063ccba5b550b1fbbe04699dac6444
|
|
BLAKE2b-256 checksum How to use checksums |
152402b9cc813b36b936bc4b12414eea9b1dbfbe0a84728f24e5db34f118fb5f
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.12.10
|
Security for ctxfit 0.1.3
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.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A 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.