Metadata-Version: 2.5
Name: agentfold
Version: 0.2.0
Summary: Cut your LLM/agent bill two ways: route (an OpenAI-compatible gateway) and compile (fold a LangGraph workflow into one cached conversation) — measured, not promised.
Project-URL: Homepage, https://github.com/agentfold/agentfold
Project-URL: Repository, https://github.com/agentfold/agentfold
Project-URL: Issues, https://github.com/agentfold/agentfold/issues
Author: agentfold contributors
License: Apache-2.0
License-File: LICENSE
Keywords: agents,cost,gateway,langgraph,llm,model-routing,openai-compatible,prompt-cache,proxy,routing
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Topic :: Software Development :: Libraries
Requires-Python: >=3.11
Provides-Extra: anthropic
Requires-Dist: anthropic>=0.39; extra == 'anthropic'
Provides-Extra: crewai
Requires-Dist: crewai>=1.0; extra == 'crewai'
Provides-Extra: dev
Requires-Dist: fastapi>=0.110; extra == 'dev'
Requires-Dist: httpx>=0.27; extra == 'dev'
Requires-Dist: langgraph>=0.2; extra == 'dev'
Requires-Dist: mypy>=1.11; extra == 'dev'
Requires-Dist: pytest>=8.0; extra == 'dev'
Requires-Dist: ruff>=0.6; extra == 'dev'
Provides-Extra: eval
Requires-Dist: datasets>=2.19; extra == 'eval'
Provides-Extra: gateway
Requires-Dist: fastapi>=0.110; extra == 'gateway'
Requires-Dist: uvicorn>=0.30; extra == 'gateway'
Provides-Extra: langgraph
Requires-Dist: langgraph>=0.2; extra == 'langgraph'
Provides-Extra: openai
Requires-Dist: openai>=1.40; extra == 'openai'
Description-Content-Type: text/markdown

# 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_url` at 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`](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:

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

```bash
# 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`](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.

```bash
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`](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

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

[Apache-2.0](LICENSE).
