agentfold
Cut your LLM/agent bill two ways — and measure both. agentfold is
cost-cutting middleware for AI agents, built on one principle: remove compute you
don't need, and prove it's safe before doing it.
Two independent levers, which stack:
- Route — per call, run a cheap model and escalate to the full model
only when a verifier is unsure. Delivered as a gateway (an OpenAI-compatible
proxy): point any harness's
base_urlat it and get routing for free, on any model, across providers. Measured ~27% cheaper at full-model quality. - Compile — fold a multi-node LangGraph workflow into one cached
conversation so the provider's prompt cache is reused across steps. Delivered
as a library + CLI (
analyze/bench). Measured ~30% input-cost saving on foldable graphs — but only safe on some, so it's selective.
Status. Engine + routing gateway are complete and (mostly) live-proven on real providers; 390+ tests, offline by default. No production users yet — all numbers below are measured on benchmarks, not promised on your traffic. New here? Read
docs/OVERVIEW.md— the one-page product map.
The gateway (route, universal) — the fastest way to try it
Any OpenAI-compatible client works unchanged except two lines:
from openai import OpenAI
client = OpenAI(base_url="http://your-gateway:8000/v1", api_key="<a gateway key>")
client.chat.completions.create(model="agentfold-auto", messages=[...])
That's the whole integration — no importer, no SDK swap. Works with LangChain, LlamaIndex, CrewAI, n8n, Langflow, raw code… anything that lets you set a base URL.
Trust before you flip it on. Run a key in shadow mode: the gateway always returns the full model (zero quality risk) while measuring, on your traffic, what routing would have saved and how often the cheap answer agrees with the full one. When you're convinced, flip to active — optionally with a quality floor that auto-tightens routing if live agreement drops.
# run it (see docs/gateway_deploy.md for Docker, config, TLS, scaling)
AGENTFOLD_MAX_USD=100 python -m agentfold.gateway mygateway.json --host 0.0.0.0
# read the savings + measured quality off the event log
python -m agentfold.gateway.dashboard events.jsonl --by-key
Capabilities: streaming, tool / multi-turn tool calls, cross-provider routing
(e.g. Haiku → GPT-4o), per-key budgets + rate limits, hashed keys, a savings
dashboard. Full guide: docs/gateway_deploy.md.
On a 119-item mixed reasoning set the cascade held full-model quality at 26.9%
lower cost and beats a naive length heuristic (docs/route_results.md); it is
honest about where it stops (the verifier over-escalates, leaving most of the
oracle's ceiling on the table).
The library (compile, graph-specific)
Many multi-agent workflows are, under the right conditions, equivalent to one LLM conversation that plays each agent's role in turn — so the provider can cache the shared prefix. This is the Section 3.2 "single-LLM simulator" from Rethinking the Value of Multi-Agent Workflow: A Strong Single Agent Baseline (ICLR 2026 submission) — not the paper's OneFlow workflow designer.
Compilation is faithful only when (Proposition 1): tools are deterministic;
routing depends only on visible history + tool outputs; decoding is deterministic;
and every agent uses the same base model. agentfold detects these and
refuses — or falls back per node — when they don't hold.
pip install -e ".[dev]"
# Will this graph compile? Reasons mapped to Proposition 1 + a cost estimate.
agentfold analyze examples.graphs.plan_execute:graph
# Measure separate vs compiled on your golden set; non-zero exit if quality drops.
agentfold bench examples.graphs.linear:graph --dataset golden.jsonl \
--metric exact --max-quality-drop 0.05
# Both levers at once on one QA set.
agentfold route examples.graphs.linear:graph --dataset qa.jsonl \
--cheap-model claude-haiku-5-5 --full-model claude-sonnet-5-5 --provider anthropic
Measured results (compile, Phase 1)
Ten workflow patterns, run separate vs compiled on Haiku 5.5, quality
judged on identical captured outputs by an independent Sonnet 5.5 judge over 30
examples each. Method + caveats in
docs/phase1_final_verdict.md.
| Workflow | Input-cost saved | Compiled no-loss (judge) | Verdict |
|---|---|---|---|
| research_report | +45% | 83% | ✅ compile helps |
| self_correct_extraction | +15% | 70% | ✅ compile helps |
| reflection | +42% | 60% | ✅ compile helps |
| debate_resolve | +30% | 33% | ➖ mixed |
| rag_answer | +39% | 27% | ➖ leans worse |
| map_reduce_summarize | +21% | 27% | ➖ leans worse |
| code_review_fix | +34% | 13% | ❌ compile hurts |
| plan_execute | +47% | 7% | ❌ compile hurts |
| collaboration | +35% | 7% | ❌ compile hurts |
| router_solver | −3% | 0% | ❌ hurts (no cost win) |
Takeaway. Compiling cut input-token cost in 9 of 10 workflows (~30% avg), but
applying it unconditionally degrades quality on most. The right product is
selective compilation: compile only where equivalence is expected to hold —
which is what analyze decides and bench verifies.
Worked examples: python -m examples.run_examples (see examples/README.md).
How it fits together
┌─ gateway/ (OpenAI-compatible proxy) ──▶ ROUTE: cheap→verify→escalate
harness / caller ──▶┤ + shadow measurement + quality floor
└─ importers → ir.py → analyze → compile → runtime ──▶ COMPILE: fold to one
+ bench cached conversation
every LLM call ──▶ llm/client (budgeted + logged)
- Route (
agentfold/route/,agentfold/gateway/): the cascade + the proxy. - Compile (
agentfold/{ir,analyze,compile,runtime}.py,importers/): the library; refuses what it can't represent rather than guessing. - Shared (
agentfold/llm/): one budgeted, logged client; providers for Anthropic and OpenAI; a configurable price table. agentfold/budget/: a documented null result — a budget-aware orchestrator spike that honestly did not beat a one-line baseline (docs/budget_phase1.md). Kept for integrity, not shipped.
Cost safety
Every LLM call goes through agentfold.llm.client, which logs
input/cached/output tokens and USD and enforces AGENTFOLD_MAX_USD (default 5.00).
API keys are read from environment variables only — never committed.
Development
python -m venv .venv && source .venv/bin/activate
pip install -e ".[dev]"
ruff check . && mypy agentfold && pytest # unit tests use a FakeLLM (offline)
pytest --live # also runs real-provider tests (costs money)
License
Metadata
Release files for agentfold 0.2.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 |
|---|---|---|---|---|
| agentfold-0.2.0.tar.gz | 281.9 kB | Without provenance | Details for agentfold-0.2.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| agentfold-0.2.0-py3-none-any.whl | Python 3 | none | any | Details for agentfold-0.2.0-py3-none-any.whl |
Total release size: 423.7 kB
Release files / agentfold-0.2.0.tar.gz
| Download URL | agentfold-0.2.0.tar.gz |
|---|---|
| Size | 281.9 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
118942362f66d4b93c396af3a6d5ac06884df334fa37895ec6ff35167ab61209
|
|
BLAKE2b-256 checksum How to use checksums |
f27309067b58d5b8543f01778026fcc1746151a8a59c7dfbcd75365632a3d951
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.14.2
|
Release files / agentfold-0.2.0-py3-none-any.whl
| Download URL | agentfold-0.2.0-py3-none-any.whl |
|---|---|
| Size | 141.7 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
109aca6cd81f5b5b25a13541aef872f81ffab5df3b55172d27dcad604695e283
|
|
BLAKE2b-256 checksum How to use checksums |
8bd6e2a64804fbdb22a41326c27d2ec1b5bc0719117b6159d193ed4c13fb7287
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.14.2
|
Security for agentfold 0.2.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.
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.