carpool-agents 0.2.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 carpool contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,52 @@
1
+ Metadata-Version: 2.4
2
+ Name: carpool-agents
3
+ Version: 0.2.0
4
+ Summary: Many agent tasks, one ride. Batch independent LLM tasks into one verified request — same answers, a fraction of the tokens.
5
+ License-Expression: MIT
6
+ Project-URL: Homepage, https://github.com/nmayp/carpool
7
+ Project-URL: Source, https://github.com/nmayp/carpool
8
+ Project-URL: Results, https://github.com/nmayp/carpool/blob/main/docs/RESULTS.md
9
+ Project-URL: Issues, https://github.com/nmayp/carpool/issues
10
+ Project-URL: Changelog, https://github.com/nmayp/carpool/blob/main/CHANGELOG.md
11
+ Keywords: llm,agents,tokens,cost,claude,codex,batching,prompt-compression
12
+ Requires-Python: >=3.10
13
+ Description-Content-Type: text/markdown
14
+ License-File: LICENSE
15
+ Provides-Extra: anthropic
16
+ Requires-Dist: anthropic; extra == "anthropic"
17
+ Provides-Extra: dev
18
+ Requires-Dist: pytest; extra == "dev"
19
+ Dynamic: license-file
20
+
21
+ # carpool
22
+
23
+ **Why make 24 trips when one carpool do trick.**
24
+
25
+ Many independent LLM tasks, one verified request: about 80% cheaper per accepted answer than one lean call per
26
+ task, 93–96% cheaper than one Claude Code agent call per task, with 0 regressions (measured on Claude).
27
+
28
+ ![carpool stats on real Claude Code results](https://raw.githubusercontent.com/nmayp/carpool/main/docs/assets/demo.svg)
29
+
30
+ If your script, pipeline or agent makes a separate model call for every item, each call pays for the whole
31
+ harness again: system prompt, tool schemas, instructions. In Claude Code that's about 26,000 input tokens before
32
+ your task starts. carpool puts independent tasks in one request, checks every answer against the source it cites,
33
+ and redoes only the ones that fail.
34
+
35
+ ```bash
36
+ pip install carpool-agents
37
+ carpool bench # offline demo with a mock model, no API key
38
+ ```
39
+
40
+ - **Library and CLI** with no dependencies, and backends that report real usage: Claude Code, Codex, Gemini CLI,
41
+ Anthropic (including the Message Batches API), any OpenAI-compatible endpoint, Gemini API, Ollama.
42
+ - **MCP server** (`carpool-mcp`) for Claude Code, Cursor, Windsurf, Cline, Codex, Gemini CLI and Claude Desktop.
43
+ - **Claude Code plugin** with a skill, a `/carpool` command and hooks.
44
+
45
+ | set | one call per task | carpool | cost per accepted answer | regressions |
46
+ |---|---|---|---|---|
47
+ | 24 ops tasks, 3 repeats | 24 calls · 24/24 · $1.159 | 1 call · 24/24 · $0.052–0.065 | −94% to −96% | 0 |
48
+ | 48 SQuAD questions, 2 repeats | 48 calls · 40/48 · $2.449 | 2 calls · 44–45/48 · $0.106–0.178 | −93% to −96% | 0 |
49
+
50
+ On a small local model the savings were small and grouping cost some quality. Every result, failures included,
51
+ is in [RESULTS.md](https://github.com/nmayp/carpool/blob/main/docs/RESULTS.md). Documentation and install options are on
52
+ [GitHub](https://github.com/nmayp/carpool).
@@ -0,0 +1,274 @@
1
+ <div align="center">
2
+
3
+ # carpool
4
+
5
+ **Why make 24 trips when one carpool do trick.**
6
+
7
+ Many independent LLM tasks, one verified request.
8
+
9
+ [![CI](https://img.shields.io/github/actions/workflow/status/nmayp/carpool/ci.yml?style=flat-square&label=ci&labelColor=000000&color=1840ff)](https://github.com/nmayp/carpool/actions/workflows/ci.yml)
10
+ ![Python 3.10+](https://img.shields.io/badge/python-3.10%2B-1840ff?style=flat-square&labelColor=000000)
11
+ ![No dependencies](https://img.shields.io/badge/dependencies-none-1840ff?style=flat-square&labelColor=000000)
12
+ ![MIT](https://img.shields.io/badge/license-MIT-1840ff?style=flat-square&labelColor=000000)
13
+
14
+ <img alt="Terminal running carpool stats on 48 SQuAD questions with lean Claude calls: carpool uses 3 calls instead of 48, accepts 46 of 48 answers against 42, and costs 78 percent less per accepted answer on the first run, with 0 regressions." src="docs/assets/demo.svg" width="733">
15
+
16
+ </div>
17
+
18
+ If your script, pipeline or agent makes a separate model call for every item, each call pays for its fixed
19
+ setup again: system prompt, tool schemas, instructions. carpool puts independent tasks in one request, checks
20
+ every answer against the source it cites, and redoes only the ones that fail. In our tests on Claude, that cut
21
+ the cost per accepted answer by about 80% against one lean call per task, and by 93–96% against one Claude Code
22
+ agent call per task, with no regressions.[^1]
23
+
24
+ ## 1. Quick start
25
+
26
+ In Claude Code:
27
+
28
+ ```bash
29
+ claude plugin marketplace add nmayp/carpool
30
+ ```
31
+
32
+ ```bash
33
+ claude plugin install carpool@carpool
34
+ ```
35
+
36
+ Or try the library offline, no API key needed:
37
+
38
+ ```bash
39
+ pip install carpool-agents
40
+ ```
41
+
42
+ ```bash
43
+ carpool bench
44
+ ```
45
+
46
+ `carpool bench` uses a mock model with a fixed cost per call, so it shows how carpool works rather than what it
47
+ saves. For real numbers run `carpool bench --backend claude-lean` (or `claude-code`, `codex`, `ollama:<model>`, …).
48
+
49
+ ## 2. Results
50
+
51
+ | set | baseline | one call per task | carpool, first run | cost per accepted answer | regressions |
52
+ |---|---|---|---|---|---|
53
+ | 24 ops tasks | lean call | 24 calls · 24/24 · $0.281 | 1 call · 24/24 · $0.047 | −83% | 0 |
54
+ | 48 SQuAD questions | lean call | 48 calls · 42/48 · $0.817 | 3 calls · 46/48 · $0.195 | −78% | 0 |
55
+ | 24 ops tasks | agent call | 24 calls · 24/24 · $1.159 | 1 call · 24/24 · $0.065 | −94% | 0 |
56
+ | 48 SQuAD questions | agent call | 48 calls · 40/48 · $2.449 | 2 calls · 44/48 · $0.178 | −93% | 0 |
57
+
58
+ A *lean call* is Claude through Claude Code with no tools and a one-line system prompt (about 1,100 tokens of
59
+ fixed setup); an *agent call* is a full Claude Code session (about 26,000). Repeat runs came out cheaper still
60
+ because the provider cached the grouped prompt, so the table quotes first runs.
61
+
62
+ <img alt="Cost per accepted answer in US cents. 24 ops tasks: 4.83 with one agent call per task, 1.17 with one lean call per task, 0.20 with carpool. 48 SQuAD questions: 6.12, 1.94 and 0.42." src="docs/assets/cost-per-answer.svg" width="760">
63
+
64
+ <img alt="Cost per accepted answer by tasks per request on 48 SQuAD questions with agent calls: 8.56 cents at 1, 2.99 at 4, 2.06 at 12, 1.77 at 24 and 1.42 at 48, against 9.41 cents for one call per task." src="docs/assets/group-size.svg" width="760">
65
+
66
+ Every raw JSON file, the ablation, the group-size sweep and the agent experiments are in
67
+ [docs/RESULTS.md](docs/RESULTS.md).
68
+
69
+ What we measured:
70
+ - The saving comes from sharing the request. Shortening evidence with one call per task saved 2.5% on the ops
71
+ tasks and cost 5.7% more on SQuAD.
72
+ - The bigger each call's fixed setup is compared with one task's own text, the more carpool saves. On a small
73
+ local model with almost no fixed setup, savings were 8–51% and grouping cost some quality.
74
+ - A well-behaved interactive agent (Claude Code triaging 20 tickets) showed no measurable change, because it
75
+ already reads everything in one go. When agents did spawn one subagent per file, it cost 4–6× more.
76
+
77
+ ## 3. How it works
78
+
79
+ <img alt="One call per task pays the fixed part H 24 times; carpool sends one request with 24 labelled tasks and pays H once, then checks each answer and redoes only the failures." src="docs/assets/how-it-works.svg" width="760">
80
+
81
+ The four rules:
82
+
83
+ 1. Run exact work as code. Lookups, counts and filters don't need a model: in the original study, 1,000 of 1,000 order lookups were correct with no model calls.
84
+ 2. Put independent reasoning tasks in one request. Every task and source gets a stable ID, and the model returns one JSON answer and source ID per task.
85
+ 3. Send compact evidence only when it's clearly safe: when the best source leads the runner-up by at least 40% (BM25) and isn't a draft. Otherwise send the full evidence straight away.
86
+ 4. Check every answer and retry only the failures. An answer that is missing, duplicated, cites another task's source or a draft, doesn't appear in its source, sits in an unrelated passage, is an ambiguous number or a name cut short ("London" for "London Exhibition") gets its own full-evidence call.
87
+
88
+ ### The cost model
89
+
90
+ Every call costs `H + E_i`: shared harness context `H` plus that task's evidence `E_i`.
91
+ With `b` separate calls you pay `b·H`. Carpooled, you pay `H` once:
92
+
93
+ ```
94
+ C_group = H + Σ E_i + J_b + V_b + Σ_{i∈F} C_retry,i
95
+ ```
96
+
97
+ `J_b` is the cost of grouping and formatting, `V_b` the checks, and `F` the
98
+ retried tasks. Compression on its own barely helped: when every task still
99
+ needed its own call, preflight-only compression saved 0.2%. The tokens are
100
+ saved by sharing the request.
101
+
102
+ ## 4. Other ways to use it
103
+
104
+ ### MCP server (Claude Code, Cursor, Windsurf, Cline, Codex, Gemini CLI, Claude Desktop)
105
+
106
+ ```bash
107
+ pip install carpool-agents
108
+ ```
109
+
110
+ ```bash
111
+ claude mcp add carpool -- carpool-mcp
112
+ ```
113
+
114
+ It adds four tools: `carpool_prompt`, `carpool_verify`, `carpool_run` and `carpool_lookup`, which does exact lookups with no model call. [integrations/MCP.md](integrations/MCP.md) has the config for each client.
115
+
116
+ ### Any other agent (Codex, Cursor, Gemini CLI, Windsurf, Aider…)
117
+
118
+ Paste the five rules in [`integrations/AGENTS.md`](integrations/AGENTS.md) into your `AGENTS.md`, `.cursorrules`, `GEMINI.md` or system prompt.
119
+
120
+ ### Python library / CLI (zero dependencies)
121
+
122
+ ```bash
123
+ pip install carpool-agents
124
+ ```
125
+
126
+ These backends report the provider's real usage: `claude-code`, `codex`, `gemini-cli`, `anthropic`,
127
+ `openai:<model>` (any OpenAI-compatible endpoint: OpenAI, OpenRouter, Groq, vLLM, LM Studio via `OPENAI_BASE_URL`),
128
+ `gemini:<model>`, `ollama:<model>`, plus `cmd:"<any cli>"` (estimated).
129
+
130
+ ### With a ChatGPT or Claude subscription, no API
131
+
132
+ ```bash
133
+ carpool prompt my_tasks.jsonl | pbcopy
134
+ ```
135
+
136
+ Paste into ChatGPT, Claude.ai or Gemini, then save the reply:
137
+
138
+ ```bash
139
+ carpool parse my_tasks.jsonl reply.txt
140
+ ```
141
+
142
+ It prints the accepted answers and lists which tasks need a retry, and why.
143
+
144
+ ### As a library
145
+
146
+ ```python
147
+ from carpool import Task, Source, run_carpool, AnthropicBackend
148
+
149
+ tasks = [
150
+ Task("T01", "Which team maintains the fire pump at Mirefield?", [
151
+ Source("T01-a", "The fire pump at Mirefield is maintained by the Halvard Controls Group."),
152
+ Source("T01-b", "The Mirefield canteen closes at 15:00 on Fridays."),
153
+ ]),
154
+ # ... more independent tasks
155
+ ]
156
+
157
+ res = run_carpool(tasks, AnthropicBackend()) # or CommandBackend("codex exec -")
158
+ for a in res.answers.values():
159
+ print(a.task_id, a.answer, a.source_id, a.route, a.fallback_reason)
160
+ print(res.ledger.n_calls, res.ledger.total_tokens, res.ledger.uncached_tokens)
161
+ ```
162
+
163
+ Exact operations with a contract check:
164
+
165
+ ```python
166
+ from carpool import Index
167
+ orders = Index(rows, key="order_id", required=("status",)) # raises if a key repeats or a status is missing
168
+ orders.get("W123", "status"); orders.count(status="pending")
169
+ ```
170
+
171
+ Tasks file format (`.jsonl`, one task per line; `answers` is optional and only used for scoring):
172
+
173
+ ```json
174
+ {"id": "T01", "question": "...", "sources": [{"id": "T01-a", "text": "...", "trusted": true}], "answers": ["..."]}
175
+ ```
176
+
177
+ ## 5. FAQ
178
+
179
+ **Isn't this the same as a batch API?** No. Batch APIs (like Anthropic's Message Batches) run many separate
180
+ requests later at a discount; each request still pays its full fixed part. carpool cuts the number of requests.
181
+ The two stack: `--backend anthropic-batch` sends carpool's grouped requests through the Batches API.
182
+
183
+ **Doesn't putting many tasks in one prompt hurt quality?** It can, so carpool checks every answer and redoes
184
+ failures one by one. On Claude Code we saw 0 regressions on both task sets, and more answers were exactly right
185
+ (44–45/48 vs 40/48). On a 1.5B local model, groups of 8 caused 4 regressions against 7 improvements. Measure
186
+ on your own tasks: `bench/real.py` reports regressions for you.
187
+
188
+ **Will it make my everyday Claude Code sessions cheaper?** Probably not by much. Claude Code already reads many
189
+ items in one go. The big savings are in code that calls a model once per item. When agents did spawn one
190
+ subagent per file in our tests, it cost 4–6 times more for the same result
191
+ ([details](docs/RESULTS.md#8-does-the-fan-out-hook-change-what-an-agent-does)).
192
+
193
+ **Doesn't prompt caching already solve this?** Partly. Caching makes the repeated fixed part cheaper but not
194
+ free, and it doesn't help output or uncached tokens. In our runs, uncached input plus output also fell by about 80–96%.
195
+
196
+ **How many tasks per request?** On Claude Code, cost kept falling up to 48. The best size
197
+ works out as b* = √(H / (φ(H+E))), where φ is how much each extra task raises the redo rate; `carpool run --adaptive` learns it from the retries it sees. Small local models need
198
+ small groups.
199
+
200
+ **Do I need an API key?** No. `carpool prompt` and `carpool parse` work with a chat subscription, the MCP tools
201
+ `carpool_prompt` and `carpool_verify` use the agent you're already talking to, and `--backend claude-code` uses
202
+ your Claude Code login.
203
+
204
+ **How is this different from caveman?** caveman makes the model write fewer words; carpool makes you pay for
205
+ fewer requests. They work on different costs, so you can use both.
206
+
207
+ ## 6. Caveats
208
+
209
+ - All Claude numbers are from Claude Sonnet 5.5 through Claude Code, on short extractive answers, 24 and 48 tasks per set. The fair comparison is against one lean call per task (about 80%); against one full agent call per task it's 93–96%. On a small local model (Ollama, Qwen2.5-1.5B) the savings were small, because a raw API call has almost no fixed part to share, and grouping in 8s cost 4 regressions on SQuAD against 7 improvements ([results](docs/RESULTS.md#7-a-small-local-model-ollama-qwen25-15b-on-4-cpu-cores)). Codex, Gemini and OpenAI-compatible backends exist but haven't been benchmarked.
210
+ - Prices are list prices from the CLI, not an invoice. Prompt-cache state changes the cost of a run (repeats are listed separately).
211
+ - Zero regressions in 48 tasks bounds the true regression rate at about 6% with 95% confidence, not 0%.
212
+ - The verifier fix was designed after inspecting the first SQuAD run, then evaluated on a fresh, disjoint holdout. Both runs are reported.
213
+ - Groups can fail together. Stable IDs, per-task source checks and individual fallback limit the damage but don't rule it out.
214
+ - The original idea and first results came from the working paper [*Lowering the Cost of Agent Work at a Fixed Quality Target*](docs/PAPER.md) (Codex CLI: −94.6% total tokens, 24/24). Our Claude Code numbers independently reproduce the same pattern.
215
+
216
+ ## 7. Roadmap / help wanted
217
+
218
+ - [x] Real results on Claude Code ([docs/RESULTS.md](docs/RESULTS.md))
219
+ - [x] Results on a local Ollama model ([docs/RESULTS.md](docs/RESULTS.md#7-a-small-local-model-ollama-qwen25-15b-on-4-cpu-cores))
220
+ - [ ] Results on Codex, Gemini CLI and larger local models (`python bench/real.py --backend codex`; send a PR with the JSON)
221
+ - [x] Message Batches backend: `--backend anthropic-batch` for another 50% off non-urgent work
222
+ - [x] `carpool stats results/<file>.json` summarises a saved benchmark
223
+ - [x] MCP server ([integrations/MCP.md](integrations/MCP.md))
224
+ - [x] Batching vs compact-evidence ablation (batching drives the savings)
225
+ - [x] Learning group sizes automatically from retry rates (`carpool run --adaptive`, [results](docs/RESULTS.md#5-adaptive-group-size-learned-during-the-run))
226
+ - [x] A hook that notices "N subagents for N tiny questions" and suggests a carpool (ships with the plugin)
227
+ - [x] Measure whether the hook's note changes agent behaviour: it doesn't, because agents launch subagents in one batch before the note arrives ([results](docs/RESULTS.md#8-does-the-fan-out-hook-change-what-an-agent-does))
228
+ - [x] A hook that acts before the first subagent launch, without overruling users who ask for subagents ([results](docs/RESULTS.md#9-a-hook-that-acts-before-the-first-launch))
229
+ - [ ] Find out why plugins with any hook on the subagent tool fanned out in 1 of 14 runs (against 6 of 8 without), even a hook that does nothing ([results](docs/RESULTS.md#10-is-it-just-having-a-hook-registered))
230
+
231
+ ## 8. Contributing
232
+
233
+ Benchmark results from other clients and models help most; failures are as welcome as successes. See
234
+ [CONTRIBUTING.md](CONTRIBUTING.md). Please follow the [code of conduct](CODE_OF_CONDUCT.md), and report
235
+ security problems privately ([SECURITY.md](SECURITY.md)).
236
+
237
+ To cite carpool, use the "Cite this repository" button (from [CITATION.cff](CITATION.cff)).
238
+
239
+ ## 9. Related work
240
+
241
+ carpool builds on earlier work; the core idea of several tasks in one request is not new.
242
+
243
+ - **Batch prompting.** [Cheng et al., 2023](https://arxiv.org/abs/2301.08721) ([code](https://github.com/hkunlp/batch-prompting))
244
+ put several samples in one prompt and reported cost falling almost in proportion to the batch size, with accuracy
245
+ dropping on larger batches. carpool uses the same idea and adds what a production pipeline needs
246
+ around it: an ID for every task and source, a check of every answer against the source it cites, a redo of
247
+ only the failed tasks, and a group size learned from the redo rate.
248
+ - **Many questions in one prompt.** Studies such as
249
+ [*Evaluating LLMs with Multiple Problems at once*](https://arxiv.org/abs/2406.10786) and
250
+ [*How Accurate Are LLMs at Multi-Question Answering*](https://arxiv.org/abs/2509.21732) measure how accuracy
251
+ changes as questions are added. That risk is why carpool checks every answer and reports regressions instead
252
+ of assuming grouping is free.
253
+ - **Provider batch APIs and parallel-call libraries.** Anthropic's Message Batches and similar APIs, and
254
+ libraries such as [LiteLLM](https://docs.litellm.ai/docs/completion/batching), still send one request per
255
+ task: they make each request cheaper or faster, not fewer. carpool can send its grouped requests through
256
+ the Batches API (`--backend anthropic-batch`).
257
+ - **Prompt caching** makes the repeated fixed part of each request cheaper but not free. Our Claude Code costs
258
+ are the CLI's own figures, cache discounts included (see the FAQ).
259
+ - **Prompt compression,** such as [LLMLingua](https://arxiv.org/abs/2310.05736), shortens the input of each
260
+ request. carpool's compact-evidence step is a simple version of that with a checked fallback; on its own it
261
+ changed cost by −2.5% to +5.7% in our ablation ([results](docs/RESULTS.md#2-squad-48-first-run-ablation-and-group-size-sweep)).
262
+ - **Answers with citations.** Checking that an answer is supported by the passage it cites follows work on
263
+ attributed answers such as [ALCE](https://arxiv.org/abs/2305.14627). carpool's checker is deliberately
264
+ simple and rule-based (exact text, numbers with units, names), so it costs no extra model calls.
265
+
266
+ ## 10. Credits
267
+
268
+ Inspired by [caveman](https://github.com/JuliusBrussee/caveman) (fewer output tokens), Pomerado (callable
269
+ operations), The Token Company (input compression) and Confident AI (agent evals). caveman reduces what the
270
+ model writes; carpool reduces how many requests you pay for.
271
+
272
+ MIT licensed.
273
+
274
+ [^1]: Claude Sonnet 5.5 via Claude Code at list prices; 24 fictional operations tasks and 48 public SQuAD questions, first runs. Details and every raw result: [docs/RESULTS.md](docs/RESULTS.md) §1–3 and §11.
@@ -0,0 +1,24 @@
1
+ """carpool — many agent tasks, one ride.
2
+
3
+ Lower the cost of agent work at a fixed quality target:
4
+ 1. exact operations run as code (zero model calls)
5
+ 2. independent reasoning tasks share ONE request, bound to stable IDs
6
+ 3. compact evidence only when a preflight says it is safe
7
+ 4. every answer is validated; failures fall back individually
8
+ """
9
+ from .backends import AnthropicBackend, CommandBackend, MockBackend, make_backend
10
+ from .batch import build_batch_prompt, build_single_prompt, parse_batch, parse_single
11
+ from .compact import normalize, preflight, verify
12
+ from .exact import ContractError, Index
13
+ from .ledger import Ledger, regressions, score
14
+ from .router import Result, run_carpool, run_compact_individual, run_individual
15
+ from .types import Answer, Completion, Source, Task
16
+
17
+ __version__ = "0.2.0"
18
+ __all__ = [
19
+ "AnthropicBackend", "CommandBackend", "MockBackend", "make_backend",
20
+ "build_batch_prompt", "build_single_prompt", "parse_batch", "parse_single",
21
+ "normalize", "preflight", "verify", "ContractError", "Index",
22
+ "Ledger", "regressions", "score", "Result", "run_carpool", "run_compact_individual", "run_individual",
23
+ "Answer", "Completion", "Source", "Task",
24
+ ]
@@ -0,0 +1,249 @@
1
+ """Backends that report REAL provider usage.
2
+
3
+ Agent CLIs (each call pays the full agent harness — the cost carpool removes):
4
+ * ClaudeCodeBackend `claude -p --output-format json` (tested)
5
+ * CodexBackend `codex exec --json -` (parser from documented event format)
6
+ * GeminiCLIBackend `gemini -p ... --output-format json` (parser from documented format)
7
+
8
+ Raw model APIs over HTTP, stdlib only:
9
+ * OpenAICompatBackend /v1/chat/completions — OpenAI, Groq, Together, vLLM, LM Studio, OpenRouter...
10
+ * GeminiAPIBackend generateContent
11
+ * OllamaBackend /api/generate (local)
12
+
13
+ Spec strings for `make_backend` / the CLI:
14
+ claude-code[:model] claude-lean[:model] codex[:model] gemini-cli[:model]
15
+ openai:<model> gemini:<model> ollama:<model>
16
+ """
17
+ from __future__ import annotations
18
+
19
+ import json
20
+ import os
21
+ import shlex
22
+ import subprocess
23
+ import tempfile
24
+ import time
25
+ import urllib.request
26
+ from typing import Optional
27
+
28
+ from .types import Completion
29
+
30
+
31
+ # ---------------------------------------------------------------- parsers
32
+ # Pure functions so they can be unit-tested against recorded payloads.
33
+
34
+ def parse_claude_code(stdout: str) -> Completion:
35
+ d = json.loads(stdout)
36
+ u = d.get("usage", {})
37
+ read = u.get("cache_read_input_tokens", 0) or 0
38
+ write = u.get("cache_creation_input_tokens", 0) or 0
39
+ return Completion(
40
+ text=d.get("result", "") or "",
41
+ input_tokens=(u.get("input_tokens", 0) or 0) + read + write,
42
+ cached_input_tokens=read,
43
+ output_tokens=u.get("output_tokens", 0) or 0,
44
+ cost_usd=float(d.get("total_cost_usd", 0) or 0),
45
+ )
46
+
47
+
48
+ def parse_codex_events(stdout: str) -> Completion:
49
+ text, inp, cached, out = "", 0, 0, 0
50
+ for line in stdout.splitlines():
51
+ line = line.strip()
52
+ if not line.startswith("{"):
53
+ continue
54
+ try:
55
+ ev = json.loads(line)
56
+ except json.JSONDecodeError:
57
+ continue
58
+ if ev.get("type") == "item.completed":
59
+ item = ev.get("item", {})
60
+ if item.get("type") in ("agent_message", "assistant_message"):
61
+ text = item.get("text", text)
62
+ elif ev.get("type") == "turn.completed":
63
+ u = ev.get("usage", {})
64
+ inp += u.get("input_tokens", 0) or 0
65
+ cached += u.get("cached_input_tokens", 0) or 0
66
+ out += u.get("output_tokens", 0) or 0
67
+ return Completion(text=text, input_tokens=inp, cached_input_tokens=cached, output_tokens=out)
68
+
69
+
70
+ def parse_gemini_cli(stdout: str) -> Completion:
71
+ d = json.loads(stdout[stdout.find("{"):])
72
+ inp = cached = out = 0
73
+ for m in d.get("stats", {}).get("models", {}).values():
74
+ t = m.get("tokens", {})
75
+ inp += t.get("prompt", 0) or 0
76
+ cached += t.get("cached", 0) or 0
77
+ out += (t.get("candidates", 0) or 0) + (t.get("thoughts", 0) or 0)
78
+ return Completion(text=d.get("response", "") or "", input_tokens=inp, cached_input_tokens=cached, output_tokens=out)
79
+
80
+
81
+ def parse_openai(d: dict) -> Completion:
82
+ u = d.get("usage") or {}
83
+ details = u.get("prompt_tokens_details") or {}
84
+ return Completion(
85
+ text=d["choices"][0]["message"].get("content") or "",
86
+ input_tokens=u.get("prompt_tokens", 0) or 0,
87
+ cached_input_tokens=details.get("cached_tokens", 0) or 0,
88
+ output_tokens=u.get("completion_tokens", 0) or 0,
89
+ )
90
+
91
+
92
+ def parse_gemini_api(d: dict) -> Completion:
93
+ u = d.get("usageMetadata") or {}
94
+ parts = (d.get("candidates") or [{}])[0].get("content", {}).get("parts", [])
95
+ return Completion(
96
+ text="".join(p.get("text", "") for p in parts if not p.get("thought")),
97
+ input_tokens=u.get("promptTokenCount", 0) or 0,
98
+ cached_input_tokens=u.get("cachedContentTokenCount", 0) or 0,
99
+ output_tokens=(u.get("candidatesTokenCount", 0) or 0) + (u.get("thoughtsTokenCount", 0) or 0),
100
+ )
101
+
102
+
103
+ def parse_ollama(d: dict) -> Completion:
104
+ return Completion(
105
+ text=d.get("response", "") or "",
106
+ input_tokens=d.get("prompt_eval_count", 0) or 0,
107
+ output_tokens=d.get("eval_count", 0) or 0,
108
+ )
109
+
110
+
111
+ # ---------------------------------------------------------------- CLI agents
112
+
113
+ class _CLI:
114
+ parse = staticmethod(lambda s: Completion(s))
115
+ timeout = 900
116
+
117
+ def argv(self) -> list[str]:
118
+ raise NotImplementedError
119
+
120
+ def __call__(self, prompt: str) -> Completion:
121
+ # empty working dir so the agent has nothing to go and read
122
+ with tempfile.TemporaryDirectory(prefix="carpool-") as cwd:
123
+ t0 = time.perf_counter()
124
+ p = subprocess.run(self.argv(), input=prompt, capture_output=True, text=True,
125
+ timeout=self.timeout, cwd=cwd)
126
+ dt = time.perf_counter() - t0
127
+ if p.returncode != 0:
128
+ raise RuntimeError(f"{self.argv()[0]} exited {p.returncode}: {(p.stderr or p.stdout)[-800:]}")
129
+ c = self.parse(p.stdout)
130
+ c.seconds = dt
131
+ return c
132
+
133
+
134
+ class ClaudeCodeBackend(_CLI):
135
+ parse = staticmethod(parse_claude_code)
136
+
137
+ def __init__(self, model: Optional[str] = None, extra: str = ""):
138
+ self.model, self.extra = model, extra
139
+
140
+ def argv(self):
141
+ a = ["claude", "-p", "--output-format", "json", "--no-session-persistence", "--strict-mcp-config"]
142
+ if self.model:
143
+ a += ["--model", self.model]
144
+ return a + shlex.split(self.extra)
145
+
146
+
147
+ class CodexBackend(_CLI):
148
+ parse = staticmethod(parse_codex_events)
149
+
150
+ def __init__(self, model: Optional[str] = None):
151
+ self.model = model
152
+
153
+ def argv(self):
154
+ a = ["codex", "exec", "--json", "--skip-git-repo-check"]
155
+ if self.model:
156
+ a += ["-m", self.model]
157
+ return a + ["-"]
158
+
159
+
160
+ class GeminiCLIBackend(_CLI):
161
+ parse = staticmethod(parse_gemini_cli)
162
+
163
+ def __init__(self, model: Optional[str] = None):
164
+ self.model = model
165
+
166
+ def argv(self):
167
+ a = ["gemini", "--output-format", "json"]
168
+ if self.model:
169
+ a += ["-m", self.model]
170
+ return a + ["-p", " "] # prompt arrives on stdin; -p enables headless mode
171
+
172
+
173
+ # ---------------------------------------------------------------- HTTP APIs
174
+
175
+ def _post(url: str, body: dict, headers: dict, timeout: float = 600) -> dict:
176
+ req = urllib.request.Request(url, data=json.dumps(body).encode(), method="POST",
177
+ headers={"content-type": "application/json", **headers})
178
+ with urllib.request.urlopen(req, timeout=timeout) as r:
179
+ return json.loads(r.read())
180
+
181
+
182
+ class _HTTP:
183
+ def __call__(self, prompt: str) -> Completion:
184
+ t0 = time.perf_counter()
185
+ c = self.call(prompt)
186
+ c.seconds = time.perf_counter() - t0
187
+ return c
188
+
189
+
190
+ class OpenAICompatBackend(_HTTP):
191
+ def __init__(self, model: str, base_url: Optional[str] = None, api_key_env: str = "OPENAI_API_KEY"):
192
+ self.model = model
193
+ self.base = (base_url or os.environ.get("OPENAI_BASE_URL") or "https://api.openai.com/v1").rstrip("/")
194
+ self.key = os.environ.get(api_key_env, "")
195
+
196
+ def call(self, prompt):
197
+ d = _post(f"{self.base}/chat/completions",
198
+ {"model": self.model, "messages": [{"role": "user", "content": prompt}]},
199
+ {"authorization": f"Bearer {self.key}"} if self.key else {})
200
+ return parse_openai(d)
201
+
202
+
203
+ class GeminiAPIBackend(_HTTP):
204
+ def __init__(self, model: str):
205
+ self.model, self.key = model, os.environ.get("GEMINI_API_KEY", "")
206
+
207
+ def call(self, prompt):
208
+ d = _post(f"https://generativelanguage.googleapis.com/v1beta/models/{self.model}:generateContent",
209
+ {"contents": [{"role": "user", "parts": [{"text": prompt}]}]},
210
+ {"x-goog-api-key": self.key})
211
+ return parse_gemini_api(d)
212
+
213
+
214
+ class OllamaBackend(_HTTP):
215
+ """Local models. `num_ctx` sets the context window: Ollama's default is small
216
+ and silently truncates long prompts, which would break grouped requests."""
217
+
218
+ def __init__(self, model: str, host: Optional[str] = None, num_ctx: int = 32768):
219
+ self.model, self.num_ctx = model, num_ctx
220
+ self.host = (host or os.environ.get("OLLAMA_HOST") or "http://localhost:11434").rstrip("/")
221
+ if not self.host.startswith("http"):
222
+ self.host = "http://" + self.host
223
+
224
+ def call(self, prompt):
225
+ return parse_ollama(_post(f"{self.host}/api/generate",
226
+ {"model": self.model, "prompt": prompt, "stream": False,
227
+ "options": {"num_ctx": self.num_ctx, "temperature": 0}}, {}, timeout=1800))
228
+
229
+
230
+ def make_agent_backend(spec: str):
231
+ name, _, arg = spec.partition(":")
232
+ arg = arg or None
233
+ if name == "claude-code":
234
+ return ClaudeCodeBackend(arg)
235
+ if name == "claude-lean":
236
+ # Same model through Claude Code, but no tools and a one-line system prompt:
237
+ # a strong baseline with a small fixed part per call (~1k tokens instead of ~26k).
238
+ return ClaudeCodeBackend(arg, extra='--tools "" --system-prompt "Answer the user\'s tasks exactly as instructed."')
239
+ if name == "codex":
240
+ return CodexBackend(arg)
241
+ if name == "gemini-cli":
242
+ return GeminiCLIBackend(arg)
243
+ if name == "openai" and arg:
244
+ return OpenAICompatBackend(arg)
245
+ if name == "gemini" and arg:
246
+ return GeminiAPIBackend(arg)
247
+ if name == "ollama" and arg:
248
+ return OllamaBackend(arg)
249
+ return None