llm-batch-accelerator 0.1.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.
Files changed (54) hide show
  1. llm_batch_accelerator-0.1.0/.github/workflows/ci.yml +38 -0
  2. llm_batch_accelerator-0.1.0/.github/workflows/publish.yml +38 -0
  3. llm_batch_accelerator-0.1.0/.gitignore +32 -0
  4. llm_batch_accelerator-0.1.0/.python-version +1 -0
  5. llm_batch_accelerator-0.1.0/CHANGELOG.md +28 -0
  6. llm_batch_accelerator-0.1.0/CONTRIBUTING.md +35 -0
  7. llm_batch_accelerator-0.1.0/LICENSE +21 -0
  8. llm_batch_accelerator-0.1.0/PKG-INFO +173 -0
  9. llm_batch_accelerator-0.1.0/README.md +145 -0
  10. llm_batch_accelerator-0.1.0/docs/architecture.md +111 -0
  11. llm_batch_accelerator-0.1.0/docs/positioning.md +43 -0
  12. llm_batch_accelerator-0.1.0/pyproject.toml +64 -0
  13. llm_batch_accelerator-0.1.0/src/llm_batch_accelerator/__init__.py +49 -0
  14. llm_batch_accelerator-0.1.0/src/llm_batch_accelerator/cli.py +732 -0
  15. llm_batch_accelerator-0.1.0/src/llm_batch_accelerator/engine/__init__.py +41 -0
  16. llm_batch_accelerator-0.1.0/src/llm_batch_accelerator/engine/auditor.py +571 -0
  17. llm_batch_accelerator-0.1.0/src/llm_batch_accelerator/engine/identity.py +44 -0
  18. llm_batch_accelerator-0.1.0/src/llm_batch_accelerator/engine/journal.py +279 -0
  19. llm_batch_accelerator-0.1.0/src/llm_batch_accelerator/engine/orchestrator.py +725 -0
  20. llm_batch_accelerator-0.1.0/src/llm_batch_accelerator/engine/packer.py +107 -0
  21. llm_batch_accelerator-0.1.0/src/llm_batch_accelerator/engine/reconciler.py +362 -0
  22. llm_batch_accelerator-0.1.0/src/llm_batch_accelerator/engine/reuse.py +122 -0
  23. llm_batch_accelerator-0.1.0/src/llm_batch_accelerator/engine/sync_router.py +204 -0
  24. llm_batch_accelerator-0.1.0/src/llm_batch_accelerator/engine/tail_cut.py +139 -0
  25. llm_batch_accelerator-0.1.0/src/llm_batch_accelerator/models/__init__.py +79 -0
  26. llm_batch_accelerator-0.1.0/src/llm_batch_accelerator/models/events.py +230 -0
  27. llm_batch_accelerator-0.1.0/src/llm_batch_accelerator/models/policies.py +236 -0
  28. llm_batch_accelerator-0.1.0/src/llm_batch_accelerator/models/requests.py +192 -0
  29. llm_batch_accelerator-0.1.0/src/llm_batch_accelerator/models/state.py +128 -0
  30. llm_batch_accelerator-0.1.0/src/llm_batch_accelerator/providers/__init__.py +27 -0
  31. llm_batch_accelerator-0.1.0/src/llm_batch_accelerator/providers/base.py +116 -0
  32. llm_batch_accelerator-0.1.0/src/llm_batch_accelerator/providers/openai.py +619 -0
  33. llm_batch_accelerator-0.1.0/src/llm_batch_accelerator/providers/pacer.py +64 -0
  34. llm_batch_accelerator-0.1.0/src/llm_batch_accelerator/py.typed +0 -0
  35. llm_batch_accelerator-0.1.0/src/llm_batch_accelerator/reporting/__init__.py +13 -0
  36. llm_batch_accelerator-0.1.0/src/llm_batch_accelerator/reporting/_formatters.py +69 -0
  37. llm_batch_accelerator-0.1.0/src/llm_batch_accelerator/reporting/html.py +211 -0
  38. llm_batch_accelerator-0.1.0/src/llm_batch_accelerator/reporting/markdown.py +118 -0
  39. llm_batch_accelerator-0.1.0/src/llm_batch_accelerator/reporting/terminal.py +200 -0
  40. llm_batch_accelerator-0.1.0/src/llm_batch_accelerator/storage/__init__.py +15 -0
  41. llm_batch_accelerator-0.1.0/src/llm_batch_accelerator/storage/base.py +234 -0
  42. llm_batch_accelerator-0.1.0/src/llm_batch_accelerator/storage/local_fs.py +54 -0
  43. llm_batch_accelerator-0.1.0/src/llm_batch_accelerator/storage/sqlite.py +1023 -0
  44. llm_batch_accelerator-0.1.0/tests/test_auditor.py +300 -0
  45. llm_batch_accelerator-0.1.0/tests/test_cli_m2.py +277 -0
  46. llm_batch_accelerator-0.1.0/tests/test_engine_components.py +319 -0
  47. llm_batch_accelerator-0.1.0/tests/test_openai_adapter.py +199 -0
  48. llm_batch_accelerator-0.1.0/tests/test_orchestrator_e2e.py +414 -0
  49. llm_batch_accelerator-0.1.0/tests/test_pacer.py +54 -0
  50. llm_batch_accelerator-0.1.0/tests/test_reporting_and_cli.py +206 -0
  51. llm_batch_accelerator-0.1.0/tests/test_requests_and_identity.py +82 -0
  52. llm_batch_accelerator-0.1.0/tests/test_smoke.py +38 -0
  53. llm_batch_accelerator-0.1.0/tests/test_storage_sqlite.py +125 -0
  54. llm_batch_accelerator-0.1.0/uv.lock +437 -0
@@ -0,0 +1,38 @@
1
+ name: CI
2
+
3
+ on:
4
+ push:
5
+ branches: [main]
6
+ pull_request:
7
+
8
+ jobs:
9
+ test:
10
+ name: Test (Python ${{ matrix.python-version }})
11
+ runs-on: ubuntu-latest
12
+ strategy:
13
+ fail-fast: false
14
+ matrix:
15
+ python-version: ["3.11", "3.12", "3.13"]
16
+
17
+ steps:
18
+ - name: Checkout repository
19
+ uses: actions/checkout@v4
20
+
21
+ - name: Set up uv
22
+ uses: astral-sh/setup-uv@v5
23
+
24
+ - name: Install dependencies
25
+ run: uv sync --python ${{ matrix.python-version }}
26
+
27
+ - name: Lint with ruff
28
+ run: uv run ruff check src tests
29
+
30
+ - name: Run unit and E2E tests
31
+ run: uv run pytest -v
32
+
33
+ - name: Build distributions
34
+ if: matrix.python-version == '3.12'
35
+ run: |
36
+ uv build
37
+ test -n "$(find dist -maxdepth 1 -name '*.whl' -print -quit)"
38
+ test -n "$(find dist -maxdepth 1 -name '*.tar.gz' -print -quit)"
@@ -0,0 +1,38 @@
1
+ name: Publish to PyPI
2
+
3
+ on:
4
+ release:
5
+ types: [published]
6
+ workflow_dispatch:
7
+
8
+ jobs:
9
+ build-and-publish:
10
+ name: Verify, build, and publish
11
+ runs-on: ubuntu-latest
12
+ environment:
13
+ name: pypi
14
+ url: https://pypi.org/p/llm-batch-accelerator
15
+ permissions:
16
+ id-token: write
17
+ contents: read
18
+
19
+ steps:
20
+ - name: Checkout repository
21
+ uses: actions/checkout@v4
22
+
23
+ - name: Set up uv
24
+ uses: astral-sh/setup-uv@v5
25
+
26
+ - name: Install dependencies
27
+ run: uv sync --python 3.12
28
+
29
+ - name: Run verification gate
30
+ run: |
31
+ uv run ruff check src tests
32
+ uv run pytest -v
33
+
34
+ - name: Build wheel and sdist
35
+ run: uv build
36
+
37
+ - name: Publish package to PyPI via Trusted Publishing
38
+ uses: pypa/gh-action-pypi-publish@release/v1
@@ -0,0 +1,32 @@
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+ *.egg-info/
6
+
7
+ # Virtual environments
8
+ .venv/
9
+ venv/
10
+
11
+ # Distribution / packaging
12
+ build/
13
+ dist/
14
+ wheels/
15
+
16
+ # Test, lint, and coverage caches
17
+ .pytest_cache/
18
+ .ruff_cache/
19
+ .coverage
20
+ htmlcov/
21
+
22
+ # Local environment & secrets
23
+ .env
24
+ .env.*
25
+
26
+ # Local state & SQLite files
27
+ *.db
28
+ *.sqlite
29
+ *.sqlite3
30
+
31
+ # macOS
32
+ .DS_Store
@@ -0,0 +1 @@
1
+ 3.12
@@ -0,0 +1,28 @@
1
+ # Changelog
2
+
3
+ All notable changes to `llm-batch-accelerator` will be documented in this file.
4
+
5
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
6
+ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
+
8
+ ## [0.1.0] - 2026-12-04
9
+
10
+ ### Added
11
+
12
+ - **Read-Only Batch Auditor (`lba audit`)**:
13
+ - Analyzes historical OpenAI Batch jobs (`/v1/batches`) across configurable lookback windows with `--days`, `--since`, `--limit`, `--endpoint`, and `--model` filters.
14
+ - Reports turnaround P50/P90/P99 latencies, expired-tail completion ratios, live In-Flight & Tail Radar, Small-Batch Sync latency opportunities, and transparent `TailCutPolicy` + `SyncBudget` projections.
15
+ - Supports `--inspect-archives N` read-only sampling (with 5 MiB byte-cap truncation handling) to surface hidden `503` error lines and stale `request_counts`.
16
+ - Exports terminal (Rich / `--no-tui`), JSON, GitHub-flavored Markdown, and zero-dependency HTML reports.
17
+ - **Core Optimization Engine & Python Async SDK (`BatchAccelerator`)**:
18
+ - Dual execution modes built on one deterministic 8-step state machine: Managed (`run`, `stream`, `resume`) and Step/Pulse (`enqueue`, `tick`, `collect`, `status`, `cancel`).
19
+ - Adaptive 3-tier `TailCutPolicy` (`Ultra`, `Standard`, `High-Age`) with `off`, `shadow`, and `active` modes and lineage caps.
20
+ - Budgeted `HybridSyncRouter` with explicit `SyncBudget` guardrails (`1%`, `0`, `$5`, `250req`) and automatic `429` cooldown fallback to Batch.
21
+ - `DirtyArchiveReconciler` handling unordered records, hidden `503`s, malformed/truncated lines, and stale provider counts.
22
+ - Canonical wire-payload SHA-256 `ReuseResolver` with cross-run completed caching (`completed`) and in-flight batch adoption (`inflight`) plus revocation guards.
23
+ - Crash-safe `DispatchJournal` (`intent_created` + `metadata.lba_intent_id`) preventing duplicate billing on timeouts or restarts.
24
+ - **Local-First Persistence & Full CLI**:
25
+ - `SQLiteStateStore` (WAL mode) and `LocalArtifactStore` (atomic temp-file + `os.replace` writes).
26
+ - Full `lba` CLI surface: `audit`, `run`, `status`, `resume`, `cancel`, and `export` (supporting standard OpenAI Batch JSONL and explicit `--endpoint` simplified JSONL).
27
+ - **Packaging & CI**:
28
+ - MIT License, PEP 561 `py.typed` marker, GitHub Actions CI across Python 3.11–3.13, and OIDC PyPI Trusted Publishing workflow.
@@ -0,0 +1,35 @@
1
+ # Contributing to `llm-batch-accelerator`
2
+
3
+ Thank you for your interest in contributing! This repository is built as a **clean-room**, protocol-focused engine with zero business or domain coupling.
4
+
5
+ ## Local Setup
6
+
7
+ Requires Python 3.11+ and [`uv`](https://docs.astral.sh/uv/):
8
+
9
+ ```bash
10
+ git clone https://github.com/YuehaoDai/llm-batch-accelerator.git
11
+ cd llm-batch-accelerator
12
+ uv sync --python 3.12
13
+ ```
14
+
15
+ ## Running Lint, Tests, and Packaging Checks
16
+
17
+ ```bash
18
+ uv run ruff check src tests
19
+ uv run pytest -v
20
+ uv build
21
+ ```
22
+
23
+ All tests run deterministically offline using `httpx.MockTransport`, fake clocks/sleepers, and `:memory:` or temp-dir SQLite databases — no real API keys or network calls are required.
24
+
25
+ ## Clean-Room & Code Guidelines
26
+
27
+ 1. **Keep the core protocol-pure**: Do not introduce domain-specific prompt templates, schemas, or orchestrator-specific dependencies into `engine/`, `providers/`, or `storage/`.
28
+ 2. **Never auto-retry non-idempotent creations blindly**: Any submission/retry logic must preserve `DispatchJournal` intent guarantees and explicit `SyncBudget` cost caps.
29
+ 3. **Preserve clean-room boundaries**: All contributions must be original work or properly licensed under compatible open-source terms. Never include proprietary keys, internal IDs, or private datasets in issues, PRs, or fixtures.
30
+
31
+ ## High-Impact Areas (Phase 2 Roadmap)
32
+
33
+ - **Provider Adapters**: Anthropic Message Batches API and Google Gemini Batch Mode implementing `ExecutionBatchAdapter`.
34
+ - **Distributed Storage Backends**: `PostgresStateStore` and `S3ArtifactStore` implementing `StateStore` and `ArtifactStore`.
35
+ - **Observability**: Lightweight local web dashboard (`lba ui`) reading from `StateStore`.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 YuehaoDai
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,173 @@
1
+ Metadata-Version: 2.5
2
+ Name: llm-batch-accelerator
3
+ Version: 0.1.0
4
+ 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.
5
+ Project-URL: Homepage, https://github.com/YuehaoDai/llm-batch-accelerator
6
+ Project-URL: Repository, https://github.com/YuehaoDai/llm-batch-accelerator
7
+ Project-URL: Issues, https://github.com/YuehaoDai/llm-batch-accelerator/issues
8
+ Project-URL: Changelog, https://github.com/YuehaoDai/llm-batch-accelerator/blob/main/CHANGELOG.md
9
+ Author: YuehaoDai
10
+ License-Expression: MIT
11
+ License-File: LICENSE
12
+ Keywords: async,batch-api,llm,openai,reliability,tail-cutting
13
+ Classifier: Development Status :: 3 - Alpha
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: License :: OSI Approved :: MIT License
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
21
+ Classifier: Typing :: Typed
22
+ Requires-Python: >=3.11
23
+ Requires-Dist: httpx>=0.27
24
+ Requires-Dist: pydantic>=2.7
25
+ Requires-Dist: rich>=13.7
26
+ Requires-Dist: typer>=0.12
27
+ Description-Content-Type: text/markdown
28
+
29
+ # llm-batch-accelerator
30
+
31
+ [![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)
32
+ [![Python 3.11+](https://img.shields.io/badge/python-3.11%2B-blue.svg)](https://www.python.org/downloads/)
33
+ [![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](LICENSE)
34
+ [![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)
35
+
36
+ **Half the price. None of the 24-hour tail.**
37
+
38
+ `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.
39
+
40
+ ---
41
+
42
+ ## Why It Exists
43
+
44
+ Native LLM Batch APIs cut token spend by 50%, but running large workloads in production exposes three recurring bottlenecks:
45
+
46
+ 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.
47
+ 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.
48
+ 3. **Dirty Partial Archives**: Cancelled and expired batch outputs can arrive with unordered records, hidden `503` error lines, truncated payloads, or stale progress counters.
49
+
50
+ ## Core Capabilities
51
+
52
+ - **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`).
53
+ - **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).
54
+ - **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.
55
+
56
+ ---
57
+
58
+ ## See Your Tail in 30 Seconds (`lba audit`)
59
+
60
+ Zero code changes, strictly read-only (`GET /v1/batches` only):
61
+
62
+ ```bash
63
+ OPENAI_API_KEY="sk-..." uvx llm-batch-accelerator audit --days 30 --limit 1000 --inspect-archives 5
64
+ ```
65
+
66
+ Example output (illustrative synthetic dataset):
67
+
68
+ ```text
69
+ ╭──────────────────────────────────────────────────────────────────────────────────────╮
70
+ │ OPENAI Batch Audit · Last 30 days (observed span: 72.4h) · 500 batches · 720,000 req │
71
+ ╰──────────────────────────────────────────────────────────────────────────────────────╯
72
+
73
+ Status Mix cancelled: 28, completed: 312, expired: 85, in_progress: 75
74
+ Turnaround P50: 11.2h P90: 24.0h P99: 24.0h (slow >6h completed: 142)
75
+ Expired Tail 85 expired (17.0%) · median completion: 99.5% · >=95% at expiry: 76 · locked wait: ~1088.0h
76
+ In-Flight Radar 75 active (24 >=95% complete, 19 match tail-cut tiers now) · cancelled >=95%: 26
77
+ Small-Batch Sync 48 batches (<=25 reqs, 512 reqs) waited avg 9.4h — ideal for instant Sync
78
+ 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)
79
+
80
+ Worst / Slowest Batches
81
+ Batch ID Status Duration Completed Remaining Endpoint
82
+ ──────────────────────────────────────────────────────────────────────────────────────
83
+ batch_demo_001 expired 24.0h 4982/5000 (99.6%) 18 /v1/responses
84
+ batch_demo_002 expired 24.0h 4371/4375 (99.9%) 4 /v1/responses
85
+ batch_demo_003 expired 24.0h 3585/3597 (99.7%) 12 /v1/responses
86
+ ```
87
+
88
+ ---
89
+
90
+ ## Installation
91
+
92
+ ```bash
93
+ # Run directly without installing
94
+ uvx llm-batch-accelerator --help
95
+
96
+ # Or install into a project / environment
97
+ uv add llm-batch-accelerator
98
+ # or: pip install llm-batch-accelerator
99
+ ```
100
+
101
+ ---
102
+
103
+ ## Quickstart CLI
104
+
105
+ ```bash
106
+ # 1. Read-only audit + exportable Markdown / single-file HTML report
107
+ lba audit --days 30 --inspect-archives 5 --format html --out audit-report.html
108
+
109
+ # 2. Run a standard OpenAI Batch JSONL workload (tail-cut active, 1% sync cap, inflight reuse)
110
+ lba run requests.jsonl -o results.jsonl --errors errors.jsonl --run-id batch-dec04
111
+
112
+ # 3. Run simplified body-only JSONL by passing --endpoint explicitly
113
+ lba run prompts.jsonl -o results.jsonl --endpoint /v1/chat/completions --model gpt-4o-mini
114
+
115
+ # 4. Inspect, resume, cancel+drain, or re-export locally
116
+ lba status
117
+ lba resume batch-dec04 -o results.jsonl
118
+ lba cancel batch-dec04 --drain
119
+ lba export batch-dec04 -o results.jsonl --output-format enriched
120
+ ```
121
+
122
+ ---
123
+
124
+ ## Python Async SDK
125
+
126
+ ### Managed Mode
127
+
128
+ ```python
129
+ import asyncio
130
+ from llm_batch_accelerator import BatchAccelerator, BatchRequest, SyncBudget, TailCutPolicy
131
+
132
+ async def main() -> None:
133
+ requests = [
134
+ BatchRequest(
135
+ custom_id="doc-1",
136
+ endpoint="/v1/chat/completions",
137
+ body={"model": "gpt-4o-mini", "messages": [{"role": "user", "content": "Summarize."}]},
138
+ )
139
+ ]
140
+ async with BatchAccelerator(
141
+ provider="openai",
142
+ store="sqlite:///.lba/state.db",
143
+ tail_cut=TailCutPolicy.balanced(),
144
+ sync_budget=SyncBudget.parse("1%"),
145
+ reuse="inflight",
146
+ ) as acc:
147
+ report = await acc.run(requests, run_id="demo-run")
148
+ print(report.summary)
149
+
150
+ asyncio.run(main())
151
+ ```
152
+
153
+ ### Step / Pulse Mode (Airflow, Temporal, K8s CronJobs)
154
+
155
+ ```python
156
+ async with BatchAccelerator(store="sqlite:///.lba/state.db") as acc:
157
+ run = await acc.enqueue(requests, run_id="daily-2026-12-04")
158
+ tick = await acc.tick(run.run_id)
159
+ page = acc.collect(run.run_id, after_cursor=None, limit=1000)
160
+ ```
161
+
162
+ ---
163
+
164
+ ## Documentation
165
+
166
+ - [Architecture & Public Contract](docs/architecture.md)
167
+ - [Product Positioning & Roadmap](docs/positioning.md)
168
+ - [Changelog](CHANGELOG.md)
169
+ - [Contributing Guide](CONTRIBUTING.md)
170
+
171
+ ## License
172
+
173
+ MIT License — see [LICENSE](LICENSE).
@@ -0,0 +1,145 @@
1
+ # llm-batch-accelerator
2
+
3
+ [![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)
4
+ [![Python 3.11+](https://img.shields.io/badge/python-3.11%2B-blue.svg)](https://www.python.org/downloads/)
5
+ [![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](LICENSE)
6
+ [![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)
7
+
8
+ **Half the price. None of the 24-hour tail.**
9
+
10
+ `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.
11
+
12
+ ---
13
+
14
+ ## Why It Exists
15
+
16
+ Native LLM Batch APIs cut token spend by 50%, but running large workloads in production exposes three recurring bottlenecks:
17
+
18
+ 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.
19
+ 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.
20
+ 3. **Dirty Partial Archives**: Cancelled and expired batch outputs can arrive with unordered records, hidden `503` error lines, truncated payloads, or stale progress counters.
21
+
22
+ ## Core Capabilities
23
+
24
+ - **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`).
25
+ - **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).
26
+ - **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.
27
+
28
+ ---
29
+
30
+ ## See Your Tail in 30 Seconds (`lba audit`)
31
+
32
+ Zero code changes, strictly read-only (`GET /v1/batches` only):
33
+
34
+ ```bash
35
+ OPENAI_API_KEY="sk-..." uvx llm-batch-accelerator audit --days 30 --limit 1000 --inspect-archives 5
36
+ ```
37
+
38
+ Example output (illustrative synthetic dataset):
39
+
40
+ ```text
41
+ ╭──────────────────────────────────────────────────────────────────────────────────────╮
42
+ │ OPENAI Batch Audit · Last 30 days (observed span: 72.4h) · 500 batches · 720,000 req │
43
+ ╰──────────────────────────────────────────────────────────────────────────────────────╯
44
+
45
+ Status Mix cancelled: 28, completed: 312, expired: 85, in_progress: 75
46
+ Turnaround P50: 11.2h P90: 24.0h P99: 24.0h (slow >6h completed: 142)
47
+ Expired Tail 85 expired (17.0%) · median completion: 99.5% · >=95% at expiry: 76 · locked wait: ~1088.0h
48
+ In-Flight Radar 75 active (24 >=95% complete, 19 match tail-cut tiers now) · cancelled >=95%: 26
49
+ Small-Batch Sync 48 batches (<=25 reqs, 512 reqs) waited avg 9.4h — ideal for instant Sync
50
+ 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)
51
+
52
+ Worst / Slowest Batches
53
+ Batch ID Status Duration Completed Remaining Endpoint
54
+ ──────────────────────────────────────────────────────────────────────────────────────
55
+ batch_demo_001 expired 24.0h 4982/5000 (99.6%) 18 /v1/responses
56
+ batch_demo_002 expired 24.0h 4371/4375 (99.9%) 4 /v1/responses
57
+ batch_demo_003 expired 24.0h 3585/3597 (99.7%) 12 /v1/responses
58
+ ```
59
+
60
+ ---
61
+
62
+ ## Installation
63
+
64
+ ```bash
65
+ # Run directly without installing
66
+ uvx llm-batch-accelerator --help
67
+
68
+ # Or install into a project / environment
69
+ uv add llm-batch-accelerator
70
+ # or: pip install llm-batch-accelerator
71
+ ```
72
+
73
+ ---
74
+
75
+ ## Quickstart CLI
76
+
77
+ ```bash
78
+ # 1. Read-only audit + exportable Markdown / single-file HTML report
79
+ lba audit --days 30 --inspect-archives 5 --format html --out audit-report.html
80
+
81
+ # 2. Run a standard OpenAI Batch JSONL workload (tail-cut active, 1% sync cap, inflight reuse)
82
+ lba run requests.jsonl -o results.jsonl --errors errors.jsonl --run-id batch-dec04
83
+
84
+ # 3. Run simplified body-only JSONL by passing --endpoint explicitly
85
+ lba run prompts.jsonl -o results.jsonl --endpoint /v1/chat/completions --model gpt-4o-mini
86
+
87
+ # 4. Inspect, resume, cancel+drain, or re-export locally
88
+ lba status
89
+ lba resume batch-dec04 -o results.jsonl
90
+ lba cancel batch-dec04 --drain
91
+ lba export batch-dec04 -o results.jsonl --output-format enriched
92
+ ```
93
+
94
+ ---
95
+
96
+ ## Python Async SDK
97
+
98
+ ### Managed Mode
99
+
100
+ ```python
101
+ import asyncio
102
+ from llm_batch_accelerator import BatchAccelerator, BatchRequest, SyncBudget, TailCutPolicy
103
+
104
+ async def main() -> None:
105
+ requests = [
106
+ BatchRequest(
107
+ custom_id="doc-1",
108
+ endpoint="/v1/chat/completions",
109
+ body={"model": "gpt-4o-mini", "messages": [{"role": "user", "content": "Summarize."}]},
110
+ )
111
+ ]
112
+ async with BatchAccelerator(
113
+ provider="openai",
114
+ store="sqlite:///.lba/state.db",
115
+ tail_cut=TailCutPolicy.balanced(),
116
+ sync_budget=SyncBudget.parse("1%"),
117
+ reuse="inflight",
118
+ ) as acc:
119
+ report = await acc.run(requests, run_id="demo-run")
120
+ print(report.summary)
121
+
122
+ asyncio.run(main())
123
+ ```
124
+
125
+ ### Step / Pulse Mode (Airflow, Temporal, K8s CronJobs)
126
+
127
+ ```python
128
+ async with BatchAccelerator(store="sqlite:///.lba/state.db") as acc:
129
+ run = await acc.enqueue(requests, run_id="daily-2026-12-04")
130
+ tick = await acc.tick(run.run_id)
131
+ page = acc.collect(run.run_id, after_cursor=None, limit=1000)
132
+ ```
133
+
134
+ ---
135
+
136
+ ## Documentation
137
+
138
+ - [Architecture & Public Contract](docs/architecture.md)
139
+ - [Product Positioning & Roadmap](docs/positioning.md)
140
+ - [Changelog](CHANGELOG.md)
141
+ - [Contributing Guide](CONTRIBUTING.md)
142
+
143
+ ## License
144
+
145
+ MIT License — see [LICENSE](LICENSE).
@@ -0,0 +1,111 @@
1
+ # Architecture & Public Contract
2
+
3
+ `llm-batch-accelerator` (`lba`) is a clean-room, wire-level reliability and latency optimization engine for asynchronous LLM Batch APIs.
4
+
5
+ ## 1. Design Principles
6
+
7
+ 1. **Zero Business Coupling**: Core components operate strictly on wire-level HTTP envelopes (`method`, `endpoint`, `body`, `custom_id`) and provider responses. No prompt templates, domain schemas, or orchestrator-specific hooks exist in the core.
8
+ 2. **Native Provider Wire Payloads**: Each `ProviderBatchAdapter` consumes its provider's native payload structure (`endpoint + body`) with zero lossy parameter translation.
9
+ 3. **Explicit Cost Guardrails**: Every transition to real-time synchronous execution is gated by an explicit `SyncBudget` (e.g., `1%` extra spend, `0` for batch-only re-dispatch), displayed upfront in CLI runs and recorded per item.
10
+ 4. **Crash-Safe & Re-entrant**: Submission intents are journaled before network dispatch, archives are reconciled defensively by `custom_id`, and managed runs share the exact same state machine as step-based orchestrator ticks.
11
+
12
+ ---
13
+
14
+ ## 2. Public CLI Surface (`lba`)
15
+
16
+ | Command | Status | Purpose |
17
+ |---|---|---|
18
+ | `lba audit` | Milestone 1 | Read-only analysis of historical batches, expired-tail diagnosis, and Tail-Cut + Sync projection |
19
+ | `lba run` | Milestone 2 | Managed execution of a JSONL workload with adaptive Tail-Cut, Sync finishing, and reuse |
20
+ | `lba status` | Milestone 2 | Inspect active or completed runs, in-flight batches, tail-cut events, and cost breakdown |
21
+ | `lba resume` | Milestone 2 | Resume an interrupted run by `run_id` |
22
+ | `lba cancel` | Milestone 2 | Cancel in-flight remote batches and optionally drain/reconcile partial archives (`--drain`) |
23
+ | `lba export` | Milestone 2 | Re-export cleanly reconciled `results.jsonl` / `errors.jsonl` from the state store |
24
+
25
+ ### Locked `lba run` Defaults & Input Contract
26
+
27
+ - **Defaults**: `--tail-cut active`, `--policy balanced`, `--sync-budget 1%`, `--reuse inflight`, `--store sqlite:///.lba/state.db`, `--output-format openai`.
28
+ - **Standard Input**: Native OpenAI Batch JSONL (`{"custom_id", "method", "url", "body"}`) works out of the box with no extra flags.
29
+ - **Simplified Input**: When `--endpoint` (and optional `--model`) is explicitly provided, `lba run` accepts raw request-body lines and deterministically assigns `custom_id` values. Mixed formats in a single file fail fast rather than silently guessing.
30
+
31
+ ---
32
+
33
+ ## 3. Python Async SDK Contract
34
+
35
+ The SDK exposes two execution styles backed by the exact same engine:
36
+
37
+ - **Managed mode** (`await acc.run(requests, run_id=...)` / `async for item in acc.stream(...)`): convenience loop driving `enqueue` -> `tick` -> `collect`.
38
+ - **Step / Pulse mode** (`enqueue`, `tick`, `collect`): stateless, re-entrant primitives designed for Airflow, Temporal, Dagster, or Kubernetes CronJobs.
39
+
40
+ ```python
41
+ async with BatchAccelerator(
42
+ provider="openai",
43
+ store="sqlite:///.lba/state.db",
44
+ tail_cut=TailCutPolicy.balanced(),
45
+ sync_budget=SyncBudget.parse("1%"),
46
+ reuse="inflight",
47
+ ) as acc:
48
+ run = await acc.enqueue(run_id="daily-2026-12-04", requests=requests)
49
+ tick = await acc.tick(run.run_id)
50
+ page = await acc.collect(run.run_id, after_cursor=None, limit=1000)
51
+ ```
52
+
53
+ ---
54
+
55
+ ## 4. Module Layout
56
+
57
+ ```text
58
+ src/llm_batch_accelerator/
59
+ ├── models/ # Pydantic v2 contracts: policies, state records, events, audit reports
60
+ ├── providers/ # ProviderBatchAdapter protocol, AsyncRequestPacer, OpenAIAdapter
61
+ ├── storage/ # StateStore & ArtifactStore protocols (Phase 1: SQLite + LocalFS; Phase 2: Postgres + S3)
62
+ ├── engine/ # Pure protocol logic: auditor, identity, journal, packer, tail_cut, sync_router, reconciler, reuse, orchestrator
63
+ └── reporting/ # Terminal (Rich), Markdown, and self-contained HTML report renderers
64
+ ```
65
+
66
+ ---
67
+
68
+ ## 5. Dual-Layer State Machines
69
+
70
+ Logical items and remote batches are modeled separately and linked via memberships so a single logical item can survive multi-wave tail-cuts and a single remote batch can be adopted across runs.
71
+
72
+ ### Logical Item State (`(run_id, custom_id)`)
73
+
74
+ ```text
75
+ pending ──▶ cached (matched completed wire-hash artifact)
76
+ ──▶ adopted_inflight (attached to an existing in-flight remote batch)
77
+ ──▶ dispatched_batch (packed into a newly submitted remote batch wave)
78
+ ──▶ dispatched_sync (routed to real-time sync fallback inside SyncBudget)
79
+ ──▶ completed | failed | cancelled
80
+ ```
81
+
82
+ Items in `adopted_inflight`, `dispatched_batch`, or `dispatched_sync` return to `pending` automatically if their batch is cancelled/expired without producing that item or if real-time fallback hits rate limits.
83
+
84
+ ### Global Remote Batch State (`(provider, provider_batch_id)`)
85
+
86
+ ```text
87
+ intent_created ──▶ submitted ──▶ in_progress ──▶ finalizing
88
+ │ │
89
+ ▼ ▼
90
+ cancelling ──▶ reconciling ──▶ reconciled
91
+ ```
92
+
93
+ ---
94
+
95
+ ## 6. Deterministic 8-Step `tick(run_id)` Pipeline
96
+
97
+ 1. **Intent Recovery (`DispatchJournal`)**: Reconcile any `intent_created` records by checking `metadata.lba_intent_id` against the provider before clearing or retrying (`max_retries=0` on creation).
98
+ 2. **In-Flight Polling (`AsyncRequestPacer`)**: Poll remote status under the management RPM token bucket and record `ProgressSample` points for stall detection and `audit --from-store` replay.
99
+ 3. **Dirty Archive Reconciliation (`DirtyArchiveReconciler`)**: Download `output_file` and `error_file` after terminal visibility grace period; tolerate malformed/truncated JSON lines, hidden `503` error lines, and stale `request_counts`; write verified outputs to the wire-hash cache and return unfinished items to `pending`.
100
+ 4. **Three-Tier Tail-Cut Evaluation (`TailCutEvaluator`)**: Evaluate `Ultra`, `Standard`, and `High-Age` stall tiers and `max_tail_cuts` caps (`shadow` logs events only; `active` issues remote cancellation).
101
+ 5. **Cross-Run Reuse Check (`ReuseResolver`)**: Match newly returned `pending` items against completed cache or adoptable in-flight batches.
102
+ 6. **Budgeted Hybrid Sync (`HybridSyncRouter`)**: Drain bounded remainders (`max_tail_ratio`, `max_tail_items`, `SyncBudget`) via real-time API with automatic fallback to Batch on 429/transient errors.
103
+ 7. **Dynamic Packaging (`DynamicPacker`)**: Pack remaining `pending` items under count/byte/token ceilings and cold/steady/backlog linger rules, write WAL intent, and submit.
104
+ 8. **Result & Next Poll (`TickResult`)**: Emit updated `ProgressCounts`, structured `EngineEvent` list, and adaptive `next_poll_after_seconds`.
105
+
106
+ ---
107
+
108
+ ## 7. Phase 1 vs Phase 2 Storage Boundary
109
+
110
+ - **Phase 1 (Local-First MIT)**: `SQLiteStateStore` (WAL mode, transactional state transitions) + `LocalArtifactStore` (atomic temp-file + rename).
111
+ - **Phase 2 (Distributed)**: `PostgresStateStore` + `S3ArtifactStore` implementing the exact same `StateStore` (with optional `lease_owner` / optimistic version guards) and `ArtifactStore` (URI-addressed blobs) protocols, requiring zero engine changes.