llm-batch-accelerator 0.1.0__py3-none-any.whl
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.
- llm_batch_accelerator/__init__.py +49 -0
- llm_batch_accelerator/cli.py +732 -0
- llm_batch_accelerator/engine/__init__.py +41 -0
- llm_batch_accelerator/engine/auditor.py +571 -0
- llm_batch_accelerator/engine/identity.py +44 -0
- llm_batch_accelerator/engine/journal.py +279 -0
- llm_batch_accelerator/engine/orchestrator.py +725 -0
- llm_batch_accelerator/engine/packer.py +107 -0
- llm_batch_accelerator/engine/reconciler.py +362 -0
- llm_batch_accelerator/engine/reuse.py +122 -0
- llm_batch_accelerator/engine/sync_router.py +204 -0
- llm_batch_accelerator/engine/tail_cut.py +139 -0
- llm_batch_accelerator/models/__init__.py +79 -0
- llm_batch_accelerator/models/events.py +230 -0
- llm_batch_accelerator/models/policies.py +236 -0
- llm_batch_accelerator/models/requests.py +192 -0
- llm_batch_accelerator/models/state.py +128 -0
- llm_batch_accelerator/providers/__init__.py +27 -0
- llm_batch_accelerator/providers/base.py +116 -0
- llm_batch_accelerator/providers/openai.py +619 -0
- llm_batch_accelerator/providers/pacer.py +64 -0
- llm_batch_accelerator/py.typed +0 -0
- llm_batch_accelerator/reporting/__init__.py +13 -0
- llm_batch_accelerator/reporting/_formatters.py +69 -0
- llm_batch_accelerator/reporting/html.py +211 -0
- llm_batch_accelerator/reporting/markdown.py +118 -0
- llm_batch_accelerator/reporting/terminal.py +200 -0
- llm_batch_accelerator/storage/__init__.py +15 -0
- llm_batch_accelerator/storage/base.py +234 -0
- llm_batch_accelerator/storage/local_fs.py +54 -0
- llm_batch_accelerator/storage/sqlite.py +1023 -0
- llm_batch_accelerator-0.1.0.dist-info/METADATA +173 -0
- llm_batch_accelerator-0.1.0.dist-info/RECORD +36 -0
- llm_batch_accelerator-0.1.0.dist-info/WHEEL +4 -0
- llm_batch_accelerator-0.1.0.dist-info/entry_points.txt +3 -0
- llm_batch_accelerator-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,732 @@
|
|
|
1
|
+
"""Typer-based command-line interface for llm-batch-accelerator."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import json
|
|
7
|
+
from collections.abc import Sequence
|
|
8
|
+
from datetime import UTC, datetime
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
from typing import Annotated
|
|
11
|
+
|
|
12
|
+
import typer
|
|
13
|
+
from rich import box
|
|
14
|
+
from rich.console import Console
|
|
15
|
+
from rich.table import Table
|
|
16
|
+
|
|
17
|
+
from llm_batch_accelerator import __version__
|
|
18
|
+
from llm_batch_accelerator.engine.auditor import BatchAuditor
|
|
19
|
+
from llm_batch_accelerator.engine.orchestrator import BatchAccelerator
|
|
20
|
+
from llm_batch_accelerator.models.events import AuditReport, RunReport, TickResult
|
|
21
|
+
from llm_batch_accelerator.models.policies import ReuseMode, SyncBudget, TailCutPolicy
|
|
22
|
+
from llm_batch_accelerator.models.requests import BatchItemResult, load_requests_jsonl
|
|
23
|
+
from llm_batch_accelerator.providers.base import (
|
|
24
|
+
ExecutionBatchAdapter,
|
|
25
|
+
ProviderBatchAdapter,
|
|
26
|
+
ProviderError,
|
|
27
|
+
)
|
|
28
|
+
from llm_batch_accelerator.providers.openai import OpenAIAdapter
|
|
29
|
+
from llm_batch_accelerator.reporting import (
|
|
30
|
+
render_audit_html,
|
|
31
|
+
render_audit_markdown,
|
|
32
|
+
render_audit_terminal,
|
|
33
|
+
)
|
|
34
|
+
from llm_batch_accelerator.storage.sqlite import SQLiteStateStore
|
|
35
|
+
|
|
36
|
+
app = typer.Typer(
|
|
37
|
+
name="lba",
|
|
38
|
+
help="Production LLM Batch API accelerator — half the price, none of the 24-hour tail.",
|
|
39
|
+
no_args_is_help=True,
|
|
40
|
+
add_completion=False,
|
|
41
|
+
)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _version_callback(value: bool) -> None:
|
|
45
|
+
if value:
|
|
46
|
+
typer.echo(f"llm-batch-accelerator {__version__}")
|
|
47
|
+
raise typer.Exit(code=0)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
@app.callback()
|
|
51
|
+
def root(
|
|
52
|
+
version: Annotated[
|
|
53
|
+
bool | None,
|
|
54
|
+
typer.Option(
|
|
55
|
+
"--version",
|
|
56
|
+
callback=_version_callback,
|
|
57
|
+
is_eager=True,
|
|
58
|
+
help="Show package version and exit.",
|
|
59
|
+
),
|
|
60
|
+
] = None,
|
|
61
|
+
) -> None:
|
|
62
|
+
"""Top-level CLI callback."""
|
|
63
|
+
_ = version
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _parse_since_ts(since: str | None) -> int | None:
|
|
67
|
+
if since is None:
|
|
68
|
+
return None
|
|
69
|
+
raw = since.strip()
|
|
70
|
+
if not raw:
|
|
71
|
+
return None
|
|
72
|
+
if raw.endswith("Z"):
|
|
73
|
+
raw = raw[:-1] + "+00:00"
|
|
74
|
+
try:
|
|
75
|
+
dt = datetime.fromisoformat(raw)
|
|
76
|
+
except ValueError as exc:
|
|
77
|
+
raise ValueError(
|
|
78
|
+
f"Invalid --since timestamp {since!r}. Expected ISO-8601 date or datetime."
|
|
79
|
+
) from exc
|
|
80
|
+
if dt.tzinfo is None:
|
|
81
|
+
dt = dt.replace(tzinfo=UTC)
|
|
82
|
+
return int(dt.timestamp())
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _build_adapter(provider: str) -> ProviderBatchAdapter:
|
|
86
|
+
normalized = provider.strip().lower()
|
|
87
|
+
if normalized == "openai":
|
|
88
|
+
return OpenAIAdapter()
|
|
89
|
+
raise ValueError(
|
|
90
|
+
f"Unsupported provider {provider!r}. Currently supported: openai."
|
|
91
|
+
)
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def _build_exec_adapter(provider: str) -> ExecutionBatchAdapter:
|
|
95
|
+
normalized = provider.strip().lower()
|
|
96
|
+
if normalized == "openai":
|
|
97
|
+
return OpenAIAdapter()
|
|
98
|
+
raise ValueError(
|
|
99
|
+
f"Unsupported provider {provider!r}. Currently supported: openai."
|
|
100
|
+
)
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def _resolve_tail_cut_policy(tail_cut_mode: str, preset: str) -> TailCutPolicy:
|
|
104
|
+
mode_norm = tail_cut_mode.strip().lower()
|
|
105
|
+
if mode_norm not in {"off", "shadow", "active"}:
|
|
106
|
+
raise ValueError(
|
|
107
|
+
f"Invalid --tail-cut {tail_cut_mode!r}. Expected off, shadow, or active."
|
|
108
|
+
)
|
|
109
|
+
if mode_norm == "off":
|
|
110
|
+
return TailCutPolicy.off()
|
|
111
|
+
base = TailCutPolicy.from_preset(preset)
|
|
112
|
+
if base.mode == "off":
|
|
113
|
+
raise ValueError("Cannot combine --policy off with --tail-cut active/shadow.")
|
|
114
|
+
return base.model_copy(
|
|
115
|
+
update={
|
|
116
|
+
"mode": mode_norm,
|
|
117
|
+
"preset_name": f"{base.preset_name}:{mode_norm}" if mode_norm == "shadow" else base.preset_name,
|
|
118
|
+
}
|
|
119
|
+
)
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def _resolve_reuse_mode(reuse: str) -> ReuseMode:
|
|
123
|
+
norm = reuse.strip().lower()
|
|
124
|
+
if norm == "off":
|
|
125
|
+
return "off"
|
|
126
|
+
if norm == "completed":
|
|
127
|
+
return "completed"
|
|
128
|
+
if norm == "inflight":
|
|
129
|
+
return "inflight"
|
|
130
|
+
raise ValueError(f"Invalid --reuse {reuse!r}. Expected off, completed, or inflight.")
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def _write_exported_results(
|
|
134
|
+
results: Sequence[BatchItemResult],
|
|
135
|
+
*,
|
|
136
|
+
output_path: Path | None,
|
|
137
|
+
errors_path: Path | None,
|
|
138
|
+
output_format: str,
|
|
139
|
+
) -> tuple[int, int]:
|
|
140
|
+
fmt = output_format.strip().lower()
|
|
141
|
+
if fmt not in {"openai", "enriched"}:
|
|
142
|
+
raise ValueError(f"Invalid --output-format {output_format!r}. Expected openai or enriched.")
|
|
143
|
+
enriched = fmt == "enriched"
|
|
144
|
+
|
|
145
|
+
completed_lines: list[str] = []
|
|
146
|
+
error_lines: list[str] = []
|
|
147
|
+
for item in results:
|
|
148
|
+
line = json.dumps(
|
|
149
|
+
item.to_openai_output_dict(enriched=enriched),
|
|
150
|
+
separators=(",", ":"),
|
|
151
|
+
ensure_ascii=False,
|
|
152
|
+
)
|
|
153
|
+
if item.status == "completed":
|
|
154
|
+
completed_lines.append(line)
|
|
155
|
+
else:
|
|
156
|
+
error_lines.append(line)
|
|
157
|
+
|
|
158
|
+
if output_path is not None:
|
|
159
|
+
output_path.parent.mkdir(parents=True, exist_ok=True)
|
|
160
|
+
output_path.write_text(
|
|
161
|
+
("\n".join(completed_lines) + "\n") if completed_lines else "",
|
|
162
|
+
encoding="utf-8",
|
|
163
|
+
)
|
|
164
|
+
if errors_path is not None:
|
|
165
|
+
errors_path.parent.mkdir(parents=True, exist_ok=True)
|
|
166
|
+
errors_path.write_text(
|
|
167
|
+
("\n".join(error_lines) + "\n") if error_lines else "",
|
|
168
|
+
encoding="utf-8",
|
|
169
|
+
)
|
|
170
|
+
return len(completed_lines), len(error_lines)
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def _print_run_report(
|
|
174
|
+
report: RunReport,
|
|
175
|
+
*,
|
|
176
|
+
output_path: Path | None,
|
|
177
|
+
errors_path: Path | None,
|
|
178
|
+
no_tui: bool,
|
|
179
|
+
) -> None:
|
|
180
|
+
c = report.counts
|
|
181
|
+
if no_tui:
|
|
182
|
+
typer.echo(
|
|
183
|
+
f"Run {report.run_id} [{report.state}] · total={c.total} completed={c.completed} "
|
|
184
|
+
f"failed={c.failed} cancelled={c.cancelled} · batch={c.batch_completed} "
|
|
185
|
+
f"sync={c.sync_completed} cache={c.cached_hits} adopted={c.adopted_hits} · "
|
|
186
|
+
f"waves={report.batch_waves} tail_cuts={report.tail_cuts} duration={report.duration_seconds:.2f}s"
|
|
187
|
+
)
|
|
188
|
+
else:
|
|
189
|
+
table = Table(title=f"Run Summary · {report.run_id}", box=box.ROUNDED)
|
|
190
|
+
table.add_column("Metric", style="bold")
|
|
191
|
+
table.add_column("Value")
|
|
192
|
+
table.add_row("State", report.state)
|
|
193
|
+
table.add_row("Total / Completed / Failed / Cancelled", f"{c.total} / {c.completed} / {c.failed} / {c.cancelled}")
|
|
194
|
+
table.add_row(
|
|
195
|
+
"Breakdown",
|
|
196
|
+
f"batch={c.batch_completed}, sync={c.sync_completed}, cache={c.cached_hits}, adopted={c.adopted_hits}",
|
|
197
|
+
)
|
|
198
|
+
table.add_row("Waves / Tail-Cuts", f"{report.batch_waves} / {report.tail_cuts}")
|
|
199
|
+
table.add_row("Duration", f"{report.duration_seconds:.2f}s")
|
|
200
|
+
Console().print(table)
|
|
201
|
+
if output_path is not None:
|
|
202
|
+
typer.echo(f"Results written to {output_path}")
|
|
203
|
+
if errors_path is not None:
|
|
204
|
+
typer.echo(f"Errors written to {errors_path}")
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
@app.command()
|
|
208
|
+
def audit(
|
|
209
|
+
provider: Annotated[
|
|
210
|
+
str,
|
|
211
|
+
typer.Option("--provider", help="Batch API provider to inspect."),
|
|
212
|
+
] = "openai",
|
|
213
|
+
days: Annotated[
|
|
214
|
+
int,
|
|
215
|
+
typer.Option("--days", min=1, help="Lookback window in days (ignored if --since is set)."),
|
|
216
|
+
] = 30,
|
|
217
|
+
since: Annotated[
|
|
218
|
+
str | None,
|
|
219
|
+
typer.Option("--since", help="Explicit ISO-8601 start date/datetime (UTC if naive)."),
|
|
220
|
+
] = None,
|
|
221
|
+
limit: Annotated[
|
|
222
|
+
int,
|
|
223
|
+
typer.Option("--limit", min=1, help="Maximum number of batches to fetch."),
|
|
224
|
+
] = 500,
|
|
225
|
+
endpoint: Annotated[
|
|
226
|
+
str | None,
|
|
227
|
+
typer.Option("--endpoint", help="Filter batches by API endpoint (e.g. /v1/chat/completions)."),
|
|
228
|
+
] = None,
|
|
229
|
+
model: Annotated[
|
|
230
|
+
str | None,
|
|
231
|
+
typer.Option("--model", help="Filter batches by model name (requires metadata or --inspect-archives)."),
|
|
232
|
+
] = None,
|
|
233
|
+
policy: Annotated[
|
|
234
|
+
str,
|
|
235
|
+
typer.Option("--policy", help="Tail-cut preset: conservative | balanced | aggressive."),
|
|
236
|
+
] = "balanced",
|
|
237
|
+
sync_budget: Annotated[
|
|
238
|
+
str,
|
|
239
|
+
typer.Option("--sync-budget", help="Real-time tail finishing cap (e.g. 1%, 0, $5, 250req)."),
|
|
240
|
+
] = "1%",
|
|
241
|
+
inspect_archives: Annotated[
|
|
242
|
+
int,
|
|
243
|
+
typer.Option("--inspect-archives", min=0, help="Sample up to N error/output archives for dirty-line diagnostics."),
|
|
244
|
+
] = 0,
|
|
245
|
+
output_format: Annotated[
|
|
246
|
+
str,
|
|
247
|
+
typer.Option("--format", help="Report format: table | json | markdown | html."),
|
|
248
|
+
] = "table",
|
|
249
|
+
out: Annotated[
|
|
250
|
+
Path | None,
|
|
251
|
+
typer.Option("--out", help="Write rendered report to file instead of stdout."),
|
|
252
|
+
] = None,
|
|
253
|
+
no_tui: Annotated[
|
|
254
|
+
bool,
|
|
255
|
+
typer.Option("--no-tui", help="Disable Rich colors and box drawing in table output."),
|
|
256
|
+
] = False,
|
|
257
|
+
) -> None:
|
|
258
|
+
"""Read-only historical batch audit and Tail-Cut + Sync projection."""
|
|
259
|
+
fmt = output_format.strip().lower()
|
|
260
|
+
if fmt not in {"table", "json", "markdown", "html"}:
|
|
261
|
+
typer.echo(
|
|
262
|
+
f"Error: Unknown --format {output_format!r}. Choose table, json, markdown, or html.",
|
|
263
|
+
err=True,
|
|
264
|
+
)
|
|
265
|
+
raise typer.Exit(code=1)
|
|
266
|
+
|
|
267
|
+
try:
|
|
268
|
+
parsed_policy = TailCutPolicy.from_preset(policy)
|
|
269
|
+
if parsed_policy.preset_name in {"off", "balanced:shadow"} or parsed_policy.mode == "shadow":
|
|
270
|
+
raise ValueError(
|
|
271
|
+
f"Policy preset {policy!r} is not valid for audit simulation; use conservative, balanced, or aggressive."
|
|
272
|
+
)
|
|
273
|
+
parsed_budget = SyncBudget.parse(sync_budget)
|
|
274
|
+
since_ts = _parse_since_ts(since)
|
|
275
|
+
|
|
276
|
+
adapter = _build_adapter(provider)
|
|
277
|
+
|
|
278
|
+
async def _run() -> AuditReport:
|
|
279
|
+
try:
|
|
280
|
+
auditor = BatchAuditor(adapter)
|
|
281
|
+
return await auditor.audit(
|
|
282
|
+
days=days,
|
|
283
|
+
since_ts=since_ts,
|
|
284
|
+
limit=limit,
|
|
285
|
+
endpoint_filter=endpoint,
|
|
286
|
+
model_filter=model,
|
|
287
|
+
policy=parsed_policy,
|
|
288
|
+
sync_budget=parsed_budget,
|
|
289
|
+
inspect_archives=inspect_archives,
|
|
290
|
+
)
|
|
291
|
+
finally:
|
|
292
|
+
await adapter.aclose()
|
|
293
|
+
|
|
294
|
+
report = asyncio.run(_run())
|
|
295
|
+
except (ValueError, TypeError, ProviderError) as exc:
|
|
296
|
+
typer.echo(f"Error: {exc}", err=True)
|
|
297
|
+
raise typer.Exit(code=1) from exc
|
|
298
|
+
|
|
299
|
+
if out is not None:
|
|
300
|
+
if fmt == "json":
|
|
301
|
+
rendered = report.model_dump_json(indent=2) + "\n"
|
|
302
|
+
elif fmt == "markdown":
|
|
303
|
+
rendered = render_audit_markdown(report)
|
|
304
|
+
elif fmt == "html":
|
|
305
|
+
rendered = render_audit_html(report)
|
|
306
|
+
else:
|
|
307
|
+
rendered = render_audit_terminal(report, no_tui=no_tui)
|
|
308
|
+
out.parent.mkdir(parents=True, exist_ok=True)
|
|
309
|
+
out.write_text(rendered, encoding="utf-8")
|
|
310
|
+
typer.echo(f"Audit report written to {out}")
|
|
311
|
+
return
|
|
312
|
+
|
|
313
|
+
if fmt == "json":
|
|
314
|
+
typer.echo(report.model_dump_json(indent=2))
|
|
315
|
+
elif fmt == "markdown":
|
|
316
|
+
typer.echo(render_audit_markdown(report), nl=False)
|
|
317
|
+
elif fmt == "html":
|
|
318
|
+
typer.echo(render_audit_html(report), nl=False)
|
|
319
|
+
elif no_tui:
|
|
320
|
+
typer.echo(render_audit_terminal(report, no_tui=True), nl=False)
|
|
321
|
+
else:
|
|
322
|
+
render_audit_terminal(report, console=Console(), no_tui=False)
|
|
323
|
+
|
|
324
|
+
|
|
325
|
+
@app.command()
|
|
326
|
+
def run(
|
|
327
|
+
input_file: Annotated[
|
|
328
|
+
Path,
|
|
329
|
+
typer.Argument(exists=True, dir_okay=False, readable=True, help="Input JSONL file."),
|
|
330
|
+
],
|
|
331
|
+
output: Annotated[
|
|
332
|
+
Path | None,
|
|
333
|
+
typer.Option("-o", "--output", help="Write completed results JSONL to path."),
|
|
334
|
+
] = None,
|
|
335
|
+
errors: Annotated[
|
|
336
|
+
Path | None,
|
|
337
|
+
typer.Option("--errors", help="Write failed/cancelled items JSONL to path."),
|
|
338
|
+
] = None,
|
|
339
|
+
provider: Annotated[
|
|
340
|
+
str,
|
|
341
|
+
typer.Option("--provider", help="Batch API provider."),
|
|
342
|
+
] = "openai",
|
|
343
|
+
run_id: Annotated[
|
|
344
|
+
str | None,
|
|
345
|
+
typer.Option("--run-id", help="Explicit deterministic run ID for resume/idempotency."),
|
|
346
|
+
] = None,
|
|
347
|
+
endpoint: Annotated[
|
|
348
|
+
str | None,
|
|
349
|
+
typer.Option("--endpoint", help="Required for simplified raw-body JSONL (e.g. /v1/chat/completions)."),
|
|
350
|
+
] = None,
|
|
351
|
+
model: Annotated[
|
|
352
|
+
str | None,
|
|
353
|
+
typer.Option("--model", help="Default model injected when omitted in request bodies."),
|
|
354
|
+
] = None,
|
|
355
|
+
tail_cut: Annotated[
|
|
356
|
+
str,
|
|
357
|
+
typer.Option("--tail-cut", help="Tail-cut mode: off | shadow | active."),
|
|
358
|
+
] = "active",
|
|
359
|
+
policy: Annotated[
|
|
360
|
+
str,
|
|
361
|
+
typer.Option("--policy", help="Tail-cut preset: conservative | balanced | aggressive."),
|
|
362
|
+
] = "balanced",
|
|
363
|
+
sync_budget: Annotated[
|
|
364
|
+
str,
|
|
365
|
+
typer.Option("--sync-budget", help="Real-time sync guardrail (e.g. 1%, 0, $5, 250req)."),
|
|
366
|
+
] = "1%",
|
|
367
|
+
reuse: Annotated[
|
|
368
|
+
str,
|
|
369
|
+
typer.Option("--reuse", help="Reuse mode: off | completed | inflight."),
|
|
370
|
+
] = "inflight",
|
|
371
|
+
store: Annotated[
|
|
372
|
+
str,
|
|
373
|
+
typer.Option("--store", help="State store DSN (default: sqlite:///.lba/state.db)."),
|
|
374
|
+
] = "sqlite:///.lba/state.db",
|
|
375
|
+
artifacts: Annotated[
|
|
376
|
+
Path,
|
|
377
|
+
typer.Option("--artifacts", help="Local artifact directory."),
|
|
378
|
+
] = Path(".lba/artifacts"),
|
|
379
|
+
output_format: Annotated[
|
|
380
|
+
str,
|
|
381
|
+
typer.Option("--output-format", help="Output JSONL schema: openai | enriched."),
|
|
382
|
+
] = "openai",
|
|
383
|
+
resume_existing: Annotated[
|
|
384
|
+
bool,
|
|
385
|
+
typer.Option("--resume/--no-resume", help="Resume if --run-id already exists."),
|
|
386
|
+
] = True,
|
|
387
|
+
no_tui: Annotated[
|
|
388
|
+
bool,
|
|
389
|
+
typer.Option("--no-tui", help="Disable Rich panels/tables."),
|
|
390
|
+
] = False,
|
|
391
|
+
json_events: Annotated[
|
|
392
|
+
bool,
|
|
393
|
+
typer.Option("--json-events", help="Emit structured JSON lines for every tick event."),
|
|
394
|
+
] = False,
|
|
395
|
+
) -> None:
|
|
396
|
+
"""Execute a batch workload with adaptive tail-cutting, sync finishing, and reuse."""
|
|
397
|
+
try:
|
|
398
|
+
requests = load_requests_jsonl(input_file, endpoint=endpoint, model=model)
|
|
399
|
+
tc_policy = _resolve_tail_cut_policy(tail_cut, policy)
|
|
400
|
+
budget = SyncBudget.parse(sync_budget)
|
|
401
|
+
reuse_mode = _resolve_reuse_mode(reuse)
|
|
402
|
+
if output_format.strip().lower() not in {"openai", "enriched"}:
|
|
403
|
+
raise ValueError(
|
|
404
|
+
f"Invalid --output-format {output_format!r}. Expected openai or enriched."
|
|
405
|
+
)
|
|
406
|
+
|
|
407
|
+
state_store = SQLiteStateStore(store)
|
|
408
|
+
try:
|
|
409
|
+
if run_id and not resume_existing and state_store.get_run(run_id) is not None:
|
|
410
|
+
raise ValueError(
|
|
411
|
+
f"Run {run_id!r} already exists and --no-resume was specified."
|
|
412
|
+
)
|
|
413
|
+
|
|
414
|
+
adapter = _build_exec_adapter(provider)
|
|
415
|
+
if not json_events:
|
|
416
|
+
typer.echo(
|
|
417
|
+
f"[lba] Guardrails: provider={provider} requests={len(requests)} "
|
|
418
|
+
f"tail_cut={tc_policy.preset_name} ({tc_policy.mode}) "
|
|
419
|
+
f"sync_budget={budget.spec} reuse={reuse_mode}",
|
|
420
|
+
err=True,
|
|
421
|
+
)
|
|
422
|
+
|
|
423
|
+
emitted_event_ids: set[int] = set()
|
|
424
|
+
|
|
425
|
+
def _on_tick(t: TickResult) -> None:
|
|
426
|
+
if not json_events:
|
|
427
|
+
return
|
|
428
|
+
for ev in t.events:
|
|
429
|
+
if ev.event_id is not None and ev.event_id in emitted_event_ids:
|
|
430
|
+
continue
|
|
431
|
+
if ev.event_id is not None:
|
|
432
|
+
emitted_event_ids.add(ev.event_id)
|
|
433
|
+
typer.echo(ev.model_dump_json())
|
|
434
|
+
|
|
435
|
+
async def _exec() -> RunReport:
|
|
436
|
+
async with BatchAccelerator(
|
|
437
|
+
provider=adapter,
|
|
438
|
+
store=state_store,
|
|
439
|
+
artifacts=artifacts,
|
|
440
|
+
tail_cut=tc_policy,
|
|
441
|
+
sync_budget=budget,
|
|
442
|
+
reuse=reuse_mode,
|
|
443
|
+
) as acc:
|
|
444
|
+
try:
|
|
445
|
+
return await acc.run(requests, run_id=run_id, on_tick=_on_tick)
|
|
446
|
+
finally:
|
|
447
|
+
await adapter.aclose()
|
|
448
|
+
|
|
449
|
+
report = asyncio.run(_exec())
|
|
450
|
+
finally:
|
|
451
|
+
state_store.close()
|
|
452
|
+
except (ValueError, TypeError, ProviderError) as exc:
|
|
453
|
+
typer.echo(f"Error: {exc}", err=True)
|
|
454
|
+
raise typer.Exit(code=1) from exc
|
|
455
|
+
|
|
456
|
+
_write_exported_results(
|
|
457
|
+
report.results,
|
|
458
|
+
output_path=output,
|
|
459
|
+
errors_path=errors,
|
|
460
|
+
output_format=output_format,
|
|
461
|
+
)
|
|
462
|
+
if json_events:
|
|
463
|
+
typer.echo(json.dumps({"event_type": "run_report", **report.summary}))
|
|
464
|
+
else:
|
|
465
|
+
_print_run_report(report, output_path=output, errors_path=errors, no_tui=no_tui)
|
|
466
|
+
|
|
467
|
+
|
|
468
|
+
@app.command()
|
|
469
|
+
def status(
|
|
470
|
+
run_id: Annotated[
|
|
471
|
+
str | None,
|
|
472
|
+
typer.Argument(help="Optional run_id to inspect (lists recent runs if omitted)."),
|
|
473
|
+
] = None,
|
|
474
|
+
store: Annotated[
|
|
475
|
+
str,
|
|
476
|
+
typer.Option("--store", help="State store DSN."),
|
|
477
|
+
] = "sqlite:///.lba/state.db",
|
|
478
|
+
output_format: Annotated[
|
|
479
|
+
str,
|
|
480
|
+
typer.Option("--format", help="Output format: table | json."),
|
|
481
|
+
] = "table",
|
|
482
|
+
no_tui: Annotated[
|
|
483
|
+
bool,
|
|
484
|
+
typer.Option("--no-tui", help="Disable Rich formatting."),
|
|
485
|
+
] = False,
|
|
486
|
+
) -> None:
|
|
487
|
+
"""Inspect active or completed runs, in-flight batches, and counts."""
|
|
488
|
+
fmt = output_format.strip().lower()
|
|
489
|
+
if fmt not in {"table", "json"}:
|
|
490
|
+
typer.echo(f"Error: Unknown --format {output_format!r}. Choose table or json.", err=True)
|
|
491
|
+
raise typer.Exit(code=1)
|
|
492
|
+
|
|
493
|
+
state_store = SQLiteStateStore(store)
|
|
494
|
+
try:
|
|
495
|
+
if run_id is None:
|
|
496
|
+
runs = state_store.list_runs(limit=20)
|
|
497
|
+
if fmt == "json":
|
|
498
|
+
payload = [
|
|
499
|
+
{
|
|
500
|
+
"run_id": r.run_id,
|
|
501
|
+
"provider": r.provider,
|
|
502
|
+
"state": r.state,
|
|
503
|
+
"counts": state_store.get_progress_counts(r.run_id).model_dump(),
|
|
504
|
+
"created_at": r.created_at.isoformat(),
|
|
505
|
+
}
|
|
506
|
+
for r in runs
|
|
507
|
+
]
|
|
508
|
+
typer.echo(json.dumps(payload, indent=2))
|
|
509
|
+
return
|
|
510
|
+
if not runs:
|
|
511
|
+
typer.echo("No runs found.")
|
|
512
|
+
return
|
|
513
|
+
if no_tui:
|
|
514
|
+
for r in runs:
|
|
515
|
+
c = state_store.get_progress_counts(r.run_id)
|
|
516
|
+
typer.echo(
|
|
517
|
+
f"{r.run_id}\t{r.state}\ttotal={c.total}\tcompleted={c.completed}\t"
|
|
518
|
+
f"failed={c.failed}\tin_flight={c.in_flight}\tpending={c.pending}"
|
|
519
|
+
)
|
|
520
|
+
return
|
|
521
|
+
tbl = Table(title="Recent Runs", box=box.SIMPLE_HEAD)
|
|
522
|
+
tbl.add_column("Run ID", style="cyan")
|
|
523
|
+
tbl.add_column("State")
|
|
524
|
+
tbl.add_column("Total", justify="right")
|
|
525
|
+
tbl.add_column("Completed", justify="right")
|
|
526
|
+
tbl.add_column("In Flight", justify="right")
|
|
527
|
+
tbl.add_column("Failed", justify="right")
|
|
528
|
+
for r in runs:
|
|
529
|
+
c = state_store.get_progress_counts(r.run_id)
|
|
530
|
+
tbl.add_row(r.run_id, r.state, str(c.total), str(c.completed), str(c.in_flight), str(c.failed))
|
|
531
|
+
Console().print(tbl)
|
|
532
|
+
return
|
|
533
|
+
|
|
534
|
+
run_rec = state_store.get_run(run_id)
|
|
535
|
+
if run_rec is None:
|
|
536
|
+
typer.echo(f"Error: Run {run_id!r} not found.", err=True)
|
|
537
|
+
raise typer.Exit(code=1)
|
|
538
|
+
|
|
539
|
+
counts = state_store.get_progress_counts(run_id)
|
|
540
|
+
events = state_store.list_events(run_id, limit=50)
|
|
541
|
+
if fmt == "json":
|
|
542
|
+
typer.echo(
|
|
543
|
+
json.dumps(
|
|
544
|
+
{
|
|
545
|
+
"run_id": run_rec.run_id,
|
|
546
|
+
"provider": run_rec.provider,
|
|
547
|
+
"state": run_rec.state,
|
|
548
|
+
"counts": counts.model_dump(),
|
|
549
|
+
"events": [e.model_dump(mode="json") for e in events],
|
|
550
|
+
},
|
|
551
|
+
indent=2,
|
|
552
|
+
)
|
|
553
|
+
)
|
|
554
|
+
return
|
|
555
|
+
|
|
556
|
+
typer.echo(
|
|
557
|
+
f"Run {run_rec.run_id} [{run_rec.state}] · provider={run_rec.provider} · "
|
|
558
|
+
f"total={counts.total} completed={counts.completed} in_flight={counts.in_flight} "
|
|
559
|
+
f"pending={counts.pending} failed={counts.failed} cancelled={counts.cancelled}"
|
|
560
|
+
)
|
|
561
|
+
if not no_tui and events:
|
|
562
|
+
for ev in events[-10:]:
|
|
563
|
+
typer.echo(f" - [{ev.event_type}] {ev.message}")
|
|
564
|
+
finally:
|
|
565
|
+
state_store.close()
|
|
566
|
+
|
|
567
|
+
|
|
568
|
+
@app.command()
|
|
569
|
+
def resume(
|
|
570
|
+
run_id: Annotated[str, typer.Argument(help="Run ID to resume.")],
|
|
571
|
+
output: Annotated[Path | None, typer.Option("-o", "--output", help="Write completed results JSONL.")] = None,
|
|
572
|
+
errors: Annotated[Path | None, typer.Option("--errors", help="Write failed/cancelled JSONL.")] = None,
|
|
573
|
+
provider: Annotated[str, typer.Option("--provider", help="Batch API provider.")] = "openai",
|
|
574
|
+
store: Annotated[str, typer.Option("--store", help="State store DSN.")] = "sqlite:///.lba/state.db",
|
|
575
|
+
artifacts: Annotated[Path, typer.Option("--artifacts", help="Artifact directory.")] = Path(".lba/artifacts"),
|
|
576
|
+
output_format: Annotated[str, typer.Option("--output-format", help="openai | enriched")] = "openai",
|
|
577
|
+
no_tui: Annotated[bool, typer.Option("--no-tui")] = False,
|
|
578
|
+
json_events: Annotated[bool, typer.Option("--json-events")] = False,
|
|
579
|
+
) -> None:
|
|
580
|
+
"""Resume an interrupted run by run_id."""
|
|
581
|
+
try:
|
|
582
|
+
state_store = SQLiteStateStore(store)
|
|
583
|
+
try:
|
|
584
|
+
run_rec = state_store.get_run(run_id)
|
|
585
|
+
if run_rec is None:
|
|
586
|
+
raise ValueError(f"Run {run_id!r} does not exist.")
|
|
587
|
+
tc_policy = TailCutPolicy.model_validate_json(run_rec.tail_cut_policy_json)
|
|
588
|
+
budget = SyncBudget.model_validate_json(run_rec.sync_budget_json)
|
|
589
|
+
reuse_mode = _resolve_reuse_mode(run_rec.reuse_mode)
|
|
590
|
+
adapter = _build_exec_adapter(provider)
|
|
591
|
+
|
|
592
|
+
def _on_tick(t: TickResult) -> None:
|
|
593
|
+
if json_events:
|
|
594
|
+
for ev in t.events:
|
|
595
|
+
typer.echo(ev.model_dump_json())
|
|
596
|
+
|
|
597
|
+
async def _exec() -> RunReport:
|
|
598
|
+
async with BatchAccelerator(
|
|
599
|
+
provider=adapter,
|
|
600
|
+
store=state_store,
|
|
601
|
+
artifacts=artifacts,
|
|
602
|
+
tail_cut=tc_policy,
|
|
603
|
+
sync_budget=budget,
|
|
604
|
+
reuse=reuse_mode,
|
|
605
|
+
) as acc:
|
|
606
|
+
try:
|
|
607
|
+
return await acc.resume(run_id, on_tick=_on_tick)
|
|
608
|
+
finally:
|
|
609
|
+
await adapter.aclose()
|
|
610
|
+
|
|
611
|
+
report = asyncio.run(_exec())
|
|
612
|
+
finally:
|
|
613
|
+
state_store.close()
|
|
614
|
+
except (ValueError, TypeError, ProviderError) as exc:
|
|
615
|
+
typer.echo(f"Error: {exc}", err=True)
|
|
616
|
+
raise typer.Exit(code=1) from exc
|
|
617
|
+
|
|
618
|
+
_write_exported_results(
|
|
619
|
+
report.results,
|
|
620
|
+
output_path=output,
|
|
621
|
+
errors_path=errors,
|
|
622
|
+
output_format=output_format,
|
|
623
|
+
)
|
|
624
|
+
if json_events:
|
|
625
|
+
typer.echo(json.dumps({"event_type": "run_report", **report.summary}))
|
|
626
|
+
else:
|
|
627
|
+
_print_run_report(report, output_path=output, errors_path=errors, no_tui=no_tui)
|
|
628
|
+
|
|
629
|
+
|
|
630
|
+
@app.command()
|
|
631
|
+
def cancel(
|
|
632
|
+
run_id: Annotated[str, typer.Argument(help="Run ID to cancel.")],
|
|
633
|
+
drain: Annotated[bool, typer.Option("--drain/--no-drain", help="Reconcile available partial archives.")] = True,
|
|
634
|
+
provider: Annotated[str, typer.Option("--provider", help="Batch API provider.")] = "openai",
|
|
635
|
+
store: Annotated[str, typer.Option("--store", help="State store DSN.")] = "sqlite:///.lba/state.db",
|
|
636
|
+
artifacts: Annotated[Path, typer.Option("--artifacts", help="Artifact directory.")] = Path(".lba/artifacts"),
|
|
637
|
+
) -> None:
|
|
638
|
+
"""Cancel in-flight batches and optionally drain/reconcile partial archives."""
|
|
639
|
+
try:
|
|
640
|
+
state_store = SQLiteStateStore(store)
|
|
641
|
+
try:
|
|
642
|
+
adapter = _build_exec_adapter(provider)
|
|
643
|
+
|
|
644
|
+
async def _exec() -> TickResult:
|
|
645
|
+
async with BatchAccelerator(
|
|
646
|
+
provider=adapter,
|
|
647
|
+
store=state_store,
|
|
648
|
+
artifacts=artifacts,
|
|
649
|
+
) as acc:
|
|
650
|
+
try:
|
|
651
|
+
return await acc.cancel(run_id, drain=drain)
|
|
652
|
+
finally:
|
|
653
|
+
await adapter.aclose()
|
|
654
|
+
|
|
655
|
+
res = asyncio.run(_exec())
|
|
656
|
+
finally:
|
|
657
|
+
state_store.close()
|
|
658
|
+
except (ValueError, TypeError, ProviderError) as exc:
|
|
659
|
+
typer.echo(f"Error: {exc}", err=True)
|
|
660
|
+
raise typer.Exit(code=1) from exc
|
|
661
|
+
|
|
662
|
+
typer.echo(
|
|
663
|
+
f"Cancelled {res.run_id}: completed={res.counts.completed}, "
|
|
664
|
+
f"failed={res.counts.failed}, cancelled={res.counts.cancelled}."
|
|
665
|
+
)
|
|
666
|
+
|
|
667
|
+
|
|
668
|
+
@app.command()
|
|
669
|
+
def export(
|
|
670
|
+
run_id: Annotated[str, typer.Argument(help="Run ID to export.")],
|
|
671
|
+
output: Annotated[Path, typer.Option("-o", "--output", help="Output JSONL path.")],
|
|
672
|
+
errors: Annotated[Path | None, typer.Option("--errors", help="Optional error JSONL path.")] = None,
|
|
673
|
+
output_format: Annotated[str, typer.Option("--output-format", help="openai | enriched")] = "openai",
|
|
674
|
+
store: Annotated[str, typer.Option("--store", help="State store DSN.")] = "sqlite:///.lba/state.db",
|
|
675
|
+
) -> None:
|
|
676
|
+
"""Re-export reconciled results/errors from the local state store."""
|
|
677
|
+
try:
|
|
678
|
+
state_store = SQLiteStateStore(store)
|
|
679
|
+
try:
|
|
680
|
+
if state_store.get_run(run_id) is None:
|
|
681
|
+
raise ValueError(f"Run {run_id!r} does not exist.")
|
|
682
|
+
results: list[BatchItemResult] = []
|
|
683
|
+
cursor: int | None = None
|
|
684
|
+
while True:
|
|
685
|
+
page = state_store.collect_results(run_id, after_cursor=cursor, limit=1000)
|
|
686
|
+
results.extend(page.items)
|
|
687
|
+
cursor = page.next_cursor
|
|
688
|
+
if not page.has_more:
|
|
689
|
+
break
|
|
690
|
+
finally:
|
|
691
|
+
state_store.close()
|
|
692
|
+
|
|
693
|
+
completed_cnt, error_cnt = _write_exported_results(
|
|
694
|
+
results,
|
|
695
|
+
output_path=output,
|
|
696
|
+
errors_path=errors,
|
|
697
|
+
output_format=output_format,
|
|
698
|
+
)
|
|
699
|
+
except ValueError as exc:
|
|
700
|
+
typer.echo(f"Error: {exc}", err=True)
|
|
701
|
+
raise typer.Exit(code=1) from exc
|
|
702
|
+
|
|
703
|
+
typer.echo(f"Exported {completed_cnt} completed results to {output} ({error_cnt} errors).")
|
|
704
|
+
|
|
705
|
+
|
|
706
|
+
def main(argv: Sequence[str] | None = None) -> int:
|
|
707
|
+
"""CLI entrypoint compatible with console scripts and programmatic calls."""
|
|
708
|
+
try:
|
|
709
|
+
app(
|
|
710
|
+
args=list(argv) if argv is not None else None,
|
|
711
|
+
prog_name="lba",
|
|
712
|
+
standalone_mode=False,
|
|
713
|
+
)
|
|
714
|
+
except typer.Exit as exc:
|
|
715
|
+
return int(exc.exit_code)
|
|
716
|
+
except typer.Abort:
|
|
717
|
+
return 1
|
|
718
|
+
except typer.exceptions.TyperException as exc:
|
|
719
|
+
show = getattr(exc, "show", None)
|
|
720
|
+
if callable(show):
|
|
721
|
+
show()
|
|
722
|
+
else:
|
|
723
|
+
typer.echo(f"Error: {exc}", err=True)
|
|
724
|
+
return int(getattr(exc, "exit_code", 2))
|
|
725
|
+
except SystemExit as exc:
|
|
726
|
+
code = exc.code
|
|
727
|
+
return int(code) if isinstance(code, int) else (0 if code is None else 1)
|
|
728
|
+
return 0
|
|
729
|
+
|
|
730
|
+
|
|
731
|
+
if __name__ == "__main__":
|
|
732
|
+
raise SystemExit(main())
|