Metadata-Version: 2.5
Name: llm-batch-accelerator
Version: 0.1.1
Summary: Half the price, none of the 24-hour tail: production LLM Batch API accelerator with adaptive tail-cutting, hybrid real-time fallback, crash-safe reconciliation, and deterministic reuse.
Project-URL: Homepage, https://github.com/YuehaoDai/llm-batch-accelerator
Project-URL: Repository, https://github.com/YuehaoDai/llm-batch-accelerator
Project-URL: Issues, https://github.com/YuehaoDai/llm-batch-accelerator/issues
Project-URL: Changelog, https://github.com/YuehaoDai/llm-batch-accelerator/blob/main/CHANGELOG.md
Author: YuehaoDai
License-Expression: MIT
License-File: LICENSE
Keywords: async,batch-api,llm,openai,reliability,tail-cutting
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Typing :: Typed
Requires-Python: >=3.11
Requires-Dist: httpx>=0.27
Requires-Dist: pydantic>=2.7
Requires-Dist: rich>=13.7
Requires-Dist: typer>=0.12
Description-Content-Type: text/markdown

# llm-batch-accelerator

[![PyPI version](https://img.shields.io/pypi/v/llm-batch-accelerator.svg)](https://pypi.org/project/llm-batch-accelerator/)
[![CI](https://github.com/YuehaoDai/llm-batch-accelerator/actions/workflows/ci.yml/badge.svg)](https://github.com/YuehaoDai/llm-batch-accelerator/actions/workflows/ci.yml)
[![Python 3.11+](https://img.shields.io/badge/python-3.11%2B-blue.svg)](https://www.python.org/downloads/)
[![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](LICENSE)
[![Ruff](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json)](https://github.com/astral-sh/ruff)

**Half the price. None of the 24-hour tail.**

`llm-batch-accelerator` (`lba`) is an open-source accelerator and reliability engine for LLM Batch APIs (OpenAI first, with Anthropic and Gemini adapters planned). It preserves the 50% batch discount while eliminating multi-hour straggler lock-in, broken partial-archive recovery, and duplicate billing across restarts.

![Native Batch vs llm-batch-accelerator](docs/assets/tail-cut-comparison.svg)

---

## Why It Exists

Native LLM Batch APIs cut token spend by 50%, but running large workloads in production exposes three recurring bottlenecks:

1. **Straggler Tail Lock-In**: Large batches frequently complete 95%–99% of requests quickly, then stall on the remaining tail until hitting the 24-hour expiration window.
2. **Double-Billing on Retries & Restarts**: Re-submitting an input file after an interruption, timeout, or pipeline upgrade replays requests that already completed or are still in flight.
3. **Dirty Partial Archives**: Cancelled and expired batch outputs can arrive with unordered records, hidden `503` error lines, truncated payloads, or stale progress counters.

## Core Capabilities

- **Adaptive 3-Tier Tail-Cutting & Bounded Hybrid Sync**: Detect stalled batches across calibrated `Ultra / Standard / High-Age` tiers (`off` / `shadow` / `active`), cancel early to release completed results, and finish bounded tails through real-time APIs under an explicit `SyncBudget` guardrail (with automatic fallback to Batch on `429`).
- **Zero Double-Billing & In-Flight Adoption**: Deterministic SHA-256 hashing over the canonical wire payload and provider contract enables cross-run caching, adoption of still-running batches, and intent-journaled submissions (`max_retries=0` on creation).
- **Crash-Safe Dirty Archive Reconciliation**: Safely unpack and reconcile `completed`, `cancelled`, `expired`, and `failed` batch artifacts by `custom_id` before rescheduling only the verified unfinished delta.

---

## See Your Tail in 30 Seconds (`lba audit`)

Zero code changes, strictly read-only (`GET /v1/batches` only):

```bash
OPENAI_API_KEY="sk-..." uvx llm-batch-accelerator audit --days 30 --limit 1000 --inspect-archives 5 --share
```

Example output (illustrative synthetic dataset):

```text
╭──────────────────────────────────────────────────────────────────────────────────────╮
│ OPENAI Batch Audit · Last 30 days (observed span: 72.4h) · 500 batches · 720,000 req │
╰──────────────────────────────────────────────────────────────────────────────────────╯

   Status Mix                      cancelled: 28, completed: 312, expired: 85, in_progress: 75
   Turnaround                      P50: 11.2h   P90: 24.0h   P99: 24.0h   (slow >6h completed: 142)
   Expired Tail                    85 expired (17.0%) · median completion: 99.5% · >=95% at expiry: 76 · locked wait: ~1088.0h
   In-Flight Radar                 75 active (24 >=95% complete, 19 match tail-cut tiers now) · cancelled >=95%: 26
   Small-Batch Sync                48 batches (<=25 reqs, 512 reqs) waited avg 9.4h — ideal for instant Sync
   Projection (balanced · sync 1%) Avoidable expired: 79/85 · Est. speedup: 1.32× – 1.74× · Hours saved: 948.0h – 1738.0h · Sync tail: 740 reqs (+0.10%, within cap)

                              Worst / Slowest Batches
  Batch ID              Status    Duration           Completed   Remaining   Endpoint
 ──────────────────────────────────────────────────────────────────────────────────────
  batch_demo_001        expired      24.0h   4982/5000 (99.6%)          18   /v1/responses
  batch_demo_002        expired      24.0h   4371/4375 (99.9%)           4   /v1/responses
  batch_demo_003        expired      24.0h   3585/3597 (99.7%)          12   /v1/responses
```

Use `--share` to print a redacted summary card (no batch IDs or endpoints) you can safely paste into team Slack, GitHub Discussions, or X.

---

## Installation

```bash
# Run directly without installing
uvx llm-batch-accelerator --help

# Or install into a project / environment
uv add llm-batch-accelerator
# or: pip install llm-batch-accelerator
```

---

## Quickstart CLI

```bash
# 1. Read-only audit + exportable Markdown / single-file HTML report
lba audit --days 30 --inspect-archives 5 --format html --out audit-report.html

# 2. Run a standard OpenAI Batch JSONL workload (tail-cut active, 1% sync cap, inflight reuse)
lba run requests.jsonl -o results.jsonl --errors errors.jsonl --run-id batch-dec04

# 3. Run simplified body-only JSONL by passing --endpoint explicitly
lba run prompts.jsonl -o results.jsonl --endpoint /v1/chat/completions --model gpt-4o-mini

# 4. Inspect, resume, cancel+drain, or re-export locally
lba status
lba resume batch-dec04 -o results.jsonl
lba cancel batch-dec04 --drain
lba export batch-dec04 -o results.jsonl --output-format enriched
```

---

## Python Async SDK

### Managed Mode ([`examples/eval_pipeline.py`](examples/eval_pipeline.py))

```python
import asyncio
from llm_batch_accelerator import BatchAccelerator, BatchRequest, SyncBudget, TailCutPolicy

async def main() -> None:
    requests = [
        BatchRequest(
            custom_id="doc-1",
            endpoint="/v1/chat/completions",
            body={"model": "gpt-4o-mini", "messages": [{"role": "user", "content": "Summarize."}]},
        )
    ]
    async with BatchAccelerator(
        provider="openai",
        store="sqlite:///.lba/state.db",
        tail_cut=TailCutPolicy.balanced(),
        sync_budget=SyncBudget.parse("1%"),
        reuse="inflight",
    ) as acc:
        report = await acc.run(requests, run_id="demo-run")
        print(report.summary)

asyncio.run(main())
```

### Step / Pulse Mode ([`examples/airflow_tick_dag.py`](examples/airflow_tick_dag.py))

```python
async with BatchAccelerator(store="sqlite:///.lba/state.db") as acc:
    run = await acc.enqueue(requests, run_id="daily-2026-12-04")
    tick = await acc.tick(run.run_id)
    page = acc.collect(run.run_id, after_cursor=None, limit=1000)
```

---

## Documentation

- [Architecture & Public Contract](docs/architecture.md)
- [Product Positioning & Roadmap](docs/positioning.md)
- [Changelog](CHANGELOG.md)
- [Contributing Guide](CONTRIBUTING.md)

## License

MIT License — see [LICENSE](LICENSE).
