specbench-cli 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.
@@ -0,0 +1,479 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import statistics
5
+ from dataclasses import dataclass, field
6
+ from datetime import datetime, timezone
7
+ from pathlib import Path
8
+ from typing import Any, Callable
9
+
10
+ from rich.console import Console
11
+ from rich.table import Table
12
+
13
+ from speculation_benchmark.backends.base import SpeculationBackend
14
+ from speculation_benchmark.backends.llamacpp import (
15
+ LlamaCppServerBackend,
16
+ detect_hardware_tag,
17
+ discover_hf_sidecar_file,
18
+ )
19
+ from speculation_benchmark.config import BenchmarkConfig, is_quantized_label
20
+ from speculation_benchmark.publisher import publish_results
21
+ from speculation_benchmark.suites.base import BenchmarkSample
22
+ from speculation_benchmark.suites.loaders import load_all_suites
23
+
24
+
25
+ @dataclass
26
+ class BenchmarkRunResult:
27
+ """In-memory and on-disk result bundle for a completed sweep."""
28
+
29
+ run_id: str
30
+ summary_rows: list[dict[str, Any]]
31
+ sample_rows: list[dict[str, Any]]
32
+ output_dir: Path
33
+ hub_urls: dict[str, str] = field(default_factory=dict)
34
+
35
+
36
+ def _resolve_speculator_fields(
37
+ config: BenchmarkConfig,
38
+ detected_speculator_file: str | None = None,
39
+ ) -> tuple[str, str, bool | None]:
40
+ """Resolve `(speculator_file, speculator_quant, speculator_is_quantized)` for dataset rows."""
41
+ spec_file = config.model.resolve_speculator_file(detected_speculator_file)
42
+ spec_quant = config.model.resolve_speculator_quant(detected_speculator_file)
43
+ return spec_file, spec_quant or "", is_quantized_label(spec_quant)
44
+
45
+
46
+ def _backfill_speculator_metadata(
47
+ rows: list[dict[str, Any]],
48
+ spec_file: str,
49
+ spec_quant: str,
50
+ spec_is_quantized: bool | None,
51
+ ) -> None:
52
+ """Update earlier rows (e.g. baseline draft_n_max=0) once runtime logs confirm the draft file."""
53
+ for row in rows:
54
+ row["speculator_file"] = spec_file
55
+ row["speculator_quant"] = spec_quant
56
+ row["speculator_is_quantized"] = spec_is_quantized
57
+
58
+
59
+ def aggregate_summary_row(
60
+ *,
61
+ sample_rows: list[dict[str, Any]],
62
+ config: BenchmarkConfig,
63
+ capability: str,
64
+ draft_n_max: int,
65
+ effective_draft_n_max: int | None = None,
66
+ detected_speculator_file: str | None = None,
67
+ timestamp_utc: str,
68
+ hardware: str,
69
+ llama_version: str,
70
+ gpu_memory_peak_mib: float | None = None,
71
+ ) -> dict[str, Any]:
72
+ """Aggregate per-sample records for one (capability, draft_n_max) slice."""
73
+ ok_rows = [row for row in sample_rows if row["ok"]]
74
+ total_prompt = sum(int(row["prompt_tokens"]) for row in ok_rows)
75
+ total_predicted = sum(int(row["predicted_tokens"]) for row in ok_rows)
76
+ total_draft_n = sum(int(row["draft_n"]) for row in ok_rows)
77
+ total_accepted = sum(int(row["draft_n_accepted"]) for row in ok_rows)
78
+
79
+ pooled_accept = (total_accepted / total_draft_n) if total_draft_n > 0 else None
80
+ sample_rates = [
81
+ float(row["acceptance_rate"])
82
+ for row in ok_rows
83
+ if row["acceptance_rate"] is not None
84
+ ]
85
+ prompt_speeds = [
86
+ float(row["prompt_per_second"])
87
+ for row in ok_rows
88
+ if row["prompt_per_second"] is not None
89
+ ]
90
+ pred_speeds = [
91
+ float(row["predicted_per_second"])
92
+ for row in ok_rows
93
+ if row["predicted_per_second"] is not None
94
+ ]
95
+ latencies = [float(row["latency_s"]) for row in ok_rows]
96
+
97
+ source_datasets = sorted({str(row["source_dataset"]) for row in sample_rows})
98
+ spec_type = "none" if draft_n_max == 0 else config.model.resolved_spec_type
99
+ spec_file, spec_quant, spec_is_quantized = _resolve_speculator_fields(
100
+ config,
101
+ detected_speculator_file,
102
+ )
103
+
104
+ return {
105
+ "run_id": config.run_id,
106
+ "timestamp_utc": timestamp_utc,
107
+ "backend": config.backend_name,
108
+ "llama_version": llama_version,
109
+ "hardware": hardware,
110
+ "model_repo": config.model.model_repo,
111
+ "model_file": config.model.model_file or "",
112
+ "model_quant": config.model.resolved_model_quant or "",
113
+ "is_quantized": config.model.is_quantized,
114
+ "speculator_repo": config.model.effective_speculator_repo,
115
+ "speculator_file": spec_file,
116
+ "speculator_quant": spec_quant,
117
+ "speculator_is_quantized": spec_is_quantized,
118
+ "speculator_mode": config.model.speculator_mode,
119
+ "spec_type": spec_type,
120
+ "draft_n_max": int(draft_n_max),
121
+ "effective_draft_n_max": int(
122
+ effective_draft_n_max if effective_draft_n_max is not None else draft_n_max
123
+ ),
124
+ "capability": capability,
125
+ "source_datasets": ", ".join(source_datasets),
126
+ "samples_total": len(sample_rows),
127
+ "samples_ok": len(ok_rows),
128
+ "samples_failed": len(sample_rows) - len(ok_rows),
129
+ "total_prompt_tokens": total_prompt,
130
+ "total_predicted_tokens": total_predicted,
131
+ "total_draft_n": total_draft_n,
132
+ "total_draft_n_accepted": total_accepted,
133
+ "acceptance_rate": pooled_accept,
134
+ "mean_sample_acceptance_rate": statistics.mean(sample_rates) if sample_rates else None,
135
+ "avg_prompt_per_second": statistics.mean(prompt_speeds) if prompt_speeds else None,
136
+ "avg_predicted_per_second": statistics.mean(pred_speeds) if pred_speeds else None,
137
+ "avg_latency_s": statistics.mean(latencies) if latencies else None,
138
+ "speedup_vs_baseline": None,
139
+ "gpu_memory_peak_mib": gpu_memory_peak_mib,
140
+ "speculator_extra_gpu_memory_mib": None,
141
+ "max_tokens": config.generation.max_tokens,
142
+ "temperature": config.generation.temperature,
143
+ }
144
+
145
+
146
+ def attach_baseline_metrics(summary_rows: list[dict[str, Any]]) -> None:
147
+ """Populate `speedup_vs_baseline` and `speculator_extra_gpu_memory_mib` vs draft_n_max == 0."""
148
+ baseline_tps_by_cap: dict[str, float] = {}
149
+ baseline_gpu_mib: float | None = None
150
+ for row in summary_rows:
151
+ if row["draft_n_max"] == 0:
152
+ if row.get("avg_predicted_per_second"):
153
+ baseline_tps_by_cap[str(row["capability"])] = float(row["avg_predicted_per_second"])
154
+ if row.get("gpu_memory_peak_mib") is not None:
155
+ mem = float(row["gpu_memory_peak_mib"])
156
+ baseline_gpu_mib = mem if baseline_gpu_mib is None else max(baseline_gpu_mib, mem)
157
+
158
+ for row in summary_rows:
159
+ cap = str(row["capability"])
160
+ base_tps = baseline_tps_by_cap.get(cap)
161
+ tps = row.get("avg_predicted_per_second")
162
+ if base_tps and base_tps > 0 and isinstance(tps, (int, float)):
163
+ row["speedup_vs_baseline"] = float(tps) / base_tps
164
+
165
+ mem = row.get("gpu_memory_peak_mib")
166
+ if baseline_gpu_mib is not None and isinstance(mem, (int, float)):
167
+ row["speculator_extra_gpu_memory_mib"] = float(mem) - baseline_gpu_mib
168
+
169
+
170
+ # Backwards-compatible alias
171
+ attach_baseline_speedups = attach_baseline_metrics
172
+
173
+
174
+ def _write_checkpoint(
175
+ run_dir: Path,
176
+ summary_rows: list[dict[str, Any]],
177
+ sample_rows: list[dict[str, Any]],
178
+ config: BenchmarkConfig,
179
+ ) -> None:
180
+ run_dir.mkdir(parents=True, exist_ok=True)
181
+ (run_dir / "config.json").write_text(
182
+ json.dumps(config.model_dump(mode="json"), indent=2),
183
+ encoding="utf-8",
184
+ )
185
+ (run_dir / "summary.json").write_text(
186
+ json.dumps(summary_rows, indent=2),
187
+ encoding="utf-8",
188
+ )
189
+ (run_dir / "samples.json").write_text(
190
+ json.dumps(sample_rows, indent=2),
191
+ encoding="utf-8",
192
+ )
193
+
194
+
195
+ def render_summary_table(summary_rows: list[dict[str, Any]], console: Console) -> None:
196
+ table = Table(title="Speculative Decoding Acceptance Benchmark Summary")
197
+ table.add_column("Capability", style="cyan")
198
+ table.add_column("Draft N", justify="right")
199
+ table.add_column("Spec Type")
200
+ table.add_column("OK/Total", justify="right")
201
+ table.add_column("Accept Rate", justify="right", style="green")
202
+ table.add_column("Accepted / Drafted", justify="right")
203
+ table.add_column("Pred tok/s", justify="right")
204
+ table.add_column("Speedup", justify="right")
205
+ table.add_column("Peak GPU (MiB)", justify="right")
206
+ table.add_column("Extra GPU (MiB)", justify="right")
207
+
208
+ for row in summary_rows:
209
+ acc = f"{row['acceptance_rate']:.4f}" if row["acceptance_rate"] is not None else "n/a"
210
+ tps = f"{row['avg_predicted_per_second']:.2f}" if row["avg_predicted_per_second"] is not None else "n/a"
211
+ spd = f"{row['speedup_vs_baseline']:.2f}x" if row["speedup_vs_baseline"] is not None else "n/a"
212
+ peak_gpu = f"{row['gpu_memory_peak_mib']:.0f}" if row.get("gpu_memory_peak_mib") is not None else "n/a"
213
+ extra_gpu = (
214
+ f"{row['speculator_extra_gpu_memory_mib']:+.0f}"
215
+ if row.get("speculator_extra_gpu_memory_mib") is not None
216
+ else "n/a"
217
+ )
218
+ draft_label = str(row["draft_n_max"])
219
+ eff_n = row.get("effective_draft_n_max")
220
+ if eff_n is not None and eff_n != row["draft_n_max"]:
221
+ draft_label = f"{row['draft_n_max']} (eff {eff_n})"
222
+ table.add_row(
223
+ str(row["capability"]),
224
+ draft_label,
225
+ str(row["spec_type"]),
226
+ f"{row['samples_ok']}/{row['samples_total']}",
227
+ acc,
228
+ f"{row['total_draft_n_accepted']}/{row['total_draft_n']}",
229
+ tps,
230
+ spd,
231
+ peak_gpu,
232
+ extra_gpu,
233
+ )
234
+ console.print(table)
235
+
236
+
237
+ def run_benchmark(
238
+ config: BenchmarkConfig,
239
+ *,
240
+ backend: SpeculationBackend | None = None,
241
+ suites_override: dict[str, list[BenchmarkSample]] | None = None,
242
+ console: Console | None = None,
243
+ on_step_complete: Callable[[int, list[dict[str, Any]]], None] | None = None,
244
+ ) -> BenchmarkRunResult:
245
+ """Execute the full draft-token sweep across capabilities and export/push results."""
246
+ console = console or Console()
247
+ timestamp_utc = datetime.now(timezone.utc).isoformat()
248
+ hardware = config.hardware_tag or detect_hardware_tag()
249
+ run_dir = Path(config.output.output_dir) / config.run_id
250
+ run_dir.mkdir(parents=True, exist_ok=True)
251
+
252
+ suites_by_cap = suites_override if suites_override is not None else load_all_suites(config.suites)
253
+ any_images = any(
254
+ sample.has_images
255
+ for samples in suites_by_cap.values()
256
+ for sample in samples
257
+ )
258
+ if any_images and config.model.no_mmproj:
259
+ console.print(
260
+ "[yellow]Warning:[/yellow] multimodal samples with images are configured, "
261
+ "but `model.no_mmproj=True` is set. Multimodal requests may fail."
262
+ )
263
+
264
+ owns_backend = backend is None
265
+ if backend is None:
266
+ backend = LlamaCppServerBackend(
267
+ model=config.model,
268
+ server=config.server,
269
+ log_dir=run_dir / "logs",
270
+ )
271
+
272
+ detected_speculator_file: str | None = None
273
+ if owns_backend:
274
+ detected_speculator_file = discover_hf_sidecar_file(
275
+ config.model,
276
+ hf_token=config.server.hf_token,
277
+ )
278
+ if detected_speculator_file:
279
+ _, pre_quant, _ = _resolve_speculator_fields(config, detected_speculator_file)
280
+ console.print(
281
+ f"[dim]Auto-discovered speculator sidecar:[/dim] {detected_speculator_file}"
282
+ + (f" (quant={pre_quant})" if pre_quant else "")
283
+ )
284
+
285
+ meta = backend.runtime_metadata()
286
+ llama_version = str(meta.get("llama_version") or "")
287
+
288
+ all_sample_rows: list[dict[str, Any]] = []
289
+ all_summary_rows: list[dict[str, Any]] = []
290
+
291
+ try:
292
+ for draft_n_max in config.draft_tokens:
293
+ spec_type = "none" if draft_n_max == 0 else config.model.resolved_spec_type
294
+ console.print(
295
+ f"\n[bold]Starting sweep step:[/bold] draft_n_max={draft_n_max} "
296
+ f"(spec_type={spec_type}, model={config.model.model_repo}, "
297
+ f"speculator={config.model.effective_speculator_repo})"
298
+ )
299
+ backend.start(draft_n_max=draft_n_max)
300
+ if draft_n_max > 0:
301
+ get_detected = getattr(backend, "detected_speculator_file", None)
302
+ runtime_spec_file = get_detected() if callable(get_detected) else None
303
+ if runtime_spec_file and runtime_spec_file != detected_speculator_file:
304
+ detected_speculator_file = runtime_spec_file
305
+ spec_file, spec_quant, spec_is_quantized = _resolve_speculator_fields(
306
+ config,
307
+ detected_speculator_file,
308
+ )
309
+ _backfill_speculator_metadata(
310
+ all_summary_rows,
311
+ spec_file,
312
+ spec_quant,
313
+ spec_is_quantized,
314
+ )
315
+ _backfill_speculator_metadata(
316
+ all_sample_rows,
317
+ spec_file,
318
+ spec_quant,
319
+ spec_is_quantized,
320
+ )
321
+ console.print(
322
+ f" [dim]Detected loaded speculator:[/dim] {spec_file}"
323
+ + (f" (quant={spec_quant})" if spec_quant else "")
324
+ )
325
+
326
+ spec_file, spec_quant, spec_is_quantized = _resolve_speculator_fields(
327
+ config,
328
+ detected_speculator_file,
329
+ )
330
+ effective_draft_n = backend.effective_draft_n_max()
331
+ if effective_draft_n is None:
332
+ effective_draft_n = draft_n_max
333
+ if effective_draft_n != draft_n_max:
334
+ console.print(
335
+ f" [yellow]Warning:[/yellow] requested draft_n_max={draft_n_max} was clamped "
336
+ f"by llama.cpp to effective_draft_n_max={effective_draft_n}."
337
+ )
338
+ step_summary_rows: list[dict[str, Any]] = []
339
+
340
+ try:
341
+ for capability, samples in suites_by_cap.items():
342
+ console.print(f" Running capability=[cyan]{capability}[/cyan] ({len(samples)} samples)...")
343
+ cap_sample_rows: list[dict[str, Any]] = []
344
+
345
+ for sample in samples:
346
+ try:
347
+ resp = backend.complete(sample.messages, config.generation)
348
+ timings = resp.timings
349
+ row = {
350
+ "run_id": config.run_id,
351
+ "timestamp_utc": timestamp_utc,
352
+ "backend": config.backend_name,
353
+ "llama_version": llama_version,
354
+ "hardware": hardware,
355
+ "model_repo": config.model.model_repo,
356
+ "model_file": config.model.model_file or "",
357
+ "model_quant": config.model.resolved_model_quant or "",
358
+ "is_quantized": config.model.is_quantized,
359
+ "speculator_repo": config.model.effective_speculator_repo,
360
+ "speculator_file": spec_file,
361
+ "speculator_quant": spec_quant,
362
+ "speculator_is_quantized": spec_is_quantized,
363
+ "speculator_mode": config.model.speculator_mode,
364
+ "spec_type": spec_type,
365
+ "draft_n_max": int(draft_n_max),
366
+ "effective_draft_n_max": int(effective_draft_n),
367
+ "capability": capability,
368
+ "source_dataset": sample.source_dataset,
369
+ "sample_id": sample.sample_id,
370
+ "has_images": bool(sample.has_images),
371
+ "ok": True,
372
+ "error": "",
373
+ "finish_reason": resp.finish_reason or "",
374
+ "prompt_tokens": int(timings.prompt_n),
375
+ "predicted_tokens": int(timings.predicted_n),
376
+ "draft_n": int(timings.draft_n),
377
+ "draft_n_accepted": int(timings.draft_n_accepted),
378
+ "acceptance_rate": timings.acceptance_rate,
379
+ "prompt_ms": timings.prompt_ms,
380
+ "predicted_ms": timings.predicted_ms,
381
+ "prompt_per_second": timings.prompt_per_second,
382
+ "predicted_per_second": timings.predicted_per_second,
383
+ "latency_s": float(resp.latency_s),
384
+ "max_tokens": config.generation.max_tokens,
385
+ "temperature": config.generation.temperature,
386
+ }
387
+ except Exception as exc:
388
+ row = {
389
+ "run_id": config.run_id,
390
+ "timestamp_utc": timestamp_utc,
391
+ "backend": config.backend_name,
392
+ "llama_version": llama_version,
393
+ "hardware": hardware,
394
+ "model_repo": config.model.model_repo,
395
+ "model_file": config.model.model_file or "",
396
+ "model_quant": config.model.resolved_model_quant or "",
397
+ "is_quantized": config.model.is_quantized,
398
+ "speculator_repo": config.model.effective_speculator_repo,
399
+ "speculator_file": spec_file,
400
+ "speculator_quant": spec_quant,
401
+ "speculator_is_quantized": spec_is_quantized,
402
+ "speculator_mode": config.model.speculator_mode,
403
+ "spec_type": spec_type,
404
+ "draft_n_max": int(draft_n_max),
405
+ "effective_draft_n_max": int(effective_draft_n),
406
+ "capability": capability,
407
+ "source_dataset": sample.source_dataset,
408
+ "sample_id": sample.sample_id,
409
+ "has_images": bool(sample.has_images),
410
+ "ok": False,
411
+ "error": str(exc),
412
+ "finish_reason": "",
413
+ "prompt_tokens": 0,
414
+ "predicted_tokens": 0,
415
+ "draft_n": 0,
416
+ "draft_n_accepted": 0,
417
+ "acceptance_rate": None,
418
+ "prompt_ms": None,
419
+ "predicted_ms": None,
420
+ "prompt_per_second": None,
421
+ "predicted_per_second": None,
422
+ "latency_s": 0.0,
423
+ "max_tokens": config.generation.max_tokens,
424
+ "temperature": config.generation.temperature,
425
+ }
426
+ cap_sample_rows.append(row)
427
+
428
+ all_sample_rows.extend(cap_sample_rows)
429
+ summary_row = aggregate_summary_row(
430
+ sample_rows=cap_sample_rows,
431
+ config=config,
432
+ capability=capability,
433
+ draft_n_max=draft_n_max,
434
+ effective_draft_n_max=effective_draft_n,
435
+ detected_speculator_file=detected_speculator_file,
436
+ timestamp_utc=timestamp_utc,
437
+ hardware=hardware,
438
+ llama_version=llama_version,
439
+ )
440
+ if draft_n_max > 0 and summary_row["samples_ok"] > 0 and summary_row["total_draft_n"] == 0:
441
+ console.print(
442
+ f" [yellow]Warning:[/yellow] draft_n == 0 for capability={capability} "
443
+ f"at draft_n_max={draft_n_max}. Check that --spec-type ({spec_type}) "
444
+ f"matches your speculator architecture."
445
+ )
446
+ step_summary_rows.append(summary_row)
447
+ all_summary_rows.append(summary_row)
448
+ finally:
449
+ backend.stop()
450
+
451
+ step_peak_gpu = backend.gpu_memory_peak_mib()
452
+ for srow in step_summary_rows:
453
+ srow["gpu_memory_peak_mib"] = step_peak_gpu
454
+
455
+ attach_baseline_metrics(all_summary_rows)
456
+ _write_checkpoint(run_dir, all_summary_rows, all_sample_rows, config)
457
+ if on_step_complete is not None:
458
+ on_step_complete(draft_n_max, step_summary_rows)
459
+ finally:
460
+ if owns_backend:
461
+ backend.stop()
462
+
463
+ render_summary_table(all_summary_rows, console)
464
+
465
+ hub_urls = publish_results(
466
+ summary_rows=all_summary_rows,
467
+ sample_rows=all_sample_rows,
468
+ output=config.output,
469
+ run_dir=run_dir,
470
+ console=console,
471
+ )
472
+
473
+ return BenchmarkRunResult(
474
+ run_id=config.run_id,
475
+ summary_rows=all_summary_rows,
476
+ sample_rows=all_sample_rows,
477
+ output_dir=run_dir,
478
+ hub_urls=hub_urls,
479
+ )
@@ -0,0 +1,19 @@
1
+ from speculation_benchmark.suites.base import (
2
+ BenchmarkSample,
3
+ build_chat_messages,
4
+ encode_image_to_data_url,
5
+ )
6
+ from speculation_benchmark.suites.loaders import (
7
+ SUITE_PRESETS,
8
+ load_all_suites,
9
+ load_suite,
10
+ )
11
+
12
+ __all__ = [
13
+ "BenchmarkSample",
14
+ "SUITE_PRESETS",
15
+ "build_chat_messages",
16
+ "encode_image_to_data_url",
17
+ "load_all_suites",
18
+ "load_suite",
19
+ ]
@@ -0,0 +1,96 @@
1
+ from __future__ import annotations
2
+
3
+ import base64
4
+ import io
5
+ from dataclasses import dataclass, field
6
+ from pathlib import Path
7
+ from typing import Any
8
+
9
+ from PIL import Image
10
+
11
+
12
+ @dataclass
13
+ class BenchmarkSample:
14
+ """Normalized prompt sample passed to a speculative decoding backend."""
15
+
16
+ sample_id: str
17
+ capability: str
18
+ source_dataset: str
19
+ messages: list[dict[str, Any]]
20
+ has_images: bool = False
21
+ metadata: dict[str, Any] = field(default_factory=dict)
22
+
23
+
24
+ def encode_image_to_data_url(
25
+ image: Image.Image | str | Path | bytes | dict[str, Any],
26
+ base_dir: Path | None = None,
27
+ max_side: int | None = 1536,
28
+ ) -> str:
29
+ """Convert a PIL image, file path, bytes, HF image dict, or URL into an OpenAI image_url value."""
30
+ if isinstance(image, str):
31
+ if image.startswith(("data:image/", "http://", "https://")):
32
+ return image
33
+ path = Path(image)
34
+ if not path.is_absolute() and base_dir is not None:
35
+ path = base_dir / path
36
+ with Image.open(path) as pil_img:
37
+ return _pil_to_data_url(pil_img, max_side=max_side)
38
+
39
+ if isinstance(image, Path):
40
+ path = image if image.is_absolute() or base_dir is None else base_dir / image
41
+ with Image.open(path) as pil_img:
42
+ return _pil_to_data_url(pil_img, max_side=max_side)
43
+
44
+ if isinstance(image, bytes):
45
+ with Image.open(io.BytesIO(image)) as pil_img:
46
+ return _pil_to_data_url(pil_img, max_side=max_side)
47
+
48
+ if isinstance(image, dict):
49
+ if image.get("bytes"):
50
+ with Image.open(io.BytesIO(image["bytes"])) as pil_img:
51
+ return _pil_to_data_url(pil_img, max_side=max_side)
52
+ if image.get("path"):
53
+ return encode_image_to_data_url(image["path"], base_dir=base_dir, max_side=max_side)
54
+ raise ValueError(f"Unsupported image dict payload keys: {list(image.keys())}")
55
+
56
+ if isinstance(image, Image.Image):
57
+ return _pil_to_data_url(image, max_side=max_side)
58
+
59
+ raise TypeError(f"Unsupported image type: {type(image)!r}")
60
+
61
+
62
+ def _pil_to_data_url(img: Image.Image, max_side: int | None = 1536) -> str:
63
+ working = img.convert("RGB")
64
+ if max_side is not None and max(working.size) > max_side:
65
+ working = working.copy()
66
+ working.thumbnail((max_side, max_side), Image.Resampling.LANCZOS)
67
+
68
+ buf = io.BytesIO()
69
+ working.save(buf, format="PNG")
70
+ b64 = base64.b64encode(buf.getvalue()).decode("ascii")
71
+ return f"data:image/png;base64,{b64}"
72
+
73
+
74
+ def build_chat_messages(
75
+ prompt: str,
76
+ images: list[Any] | None = None,
77
+ system_prompt: str | None = None,
78
+ base_dir: Path | None = None,
79
+ ) -> tuple[list[dict[str, Any]], bool]:
80
+ """Build OpenAI-compatible chat messages (with multimodal image_url blocks when images exist)."""
81
+ messages: list[dict[str, Any]] = []
82
+ if system_prompt:
83
+ messages.append({"role": "system", "content": system_prompt})
84
+
85
+ valid_images = [img for img in (images or []) if img is not None]
86
+ if valid_images:
87
+ content: list[dict[str, Any]] = []
88
+ for img in valid_images:
89
+ data_url = encode_image_to_data_url(img, base_dir=base_dir)
90
+ content.append({"type": "image_url", "image_url": {"url": data_url}})
91
+ content.append({"type": "text", "text": prompt})
92
+ messages.append({"role": "user", "content": content})
93
+ return messages, True
94
+
95
+ messages.append({"role": "user", "content": prompt})
96
+ return messages, False
@@ -0,0 +1,5 @@
1
+ {"id": "code_lru_cache", "capability": "coding", "prompt": "Implement a thread-safe LRU cache in Python 3.12 with O(1) get and put operations, supporting an optional per-entry TTL in seconds. Include type annotations and brief unit tests."}
2
+ {"id": "code_sql_window", "capability": "coding", "prompt": "Write a PostgreSQL query that computes a 7-day rolling revenue average per customer segment from a table `orders(order_id, customer_id, segment, created_at, amount_cents)` while filling missing calendar days with 0. Explain any indexing recommendations."}
3
+ {"id": "code_rust_parser", "capability": "coding", "prompt": "Write a zero-copy Rust parser function `parse_kv_pairs(input: &str) -> Result<Vec<(&str, &str)>, ParseError>` that parses `key=value` pairs separated by commas, supporting quoted values containing commas and escaped quotes."}
4
+ {"id": "code_ts_retry", "capability": "coding", "prompt": "Implement a generic TypeScript function `withRetry<T>(fn: (signal: AbortSignal) => Promise<T>, opts: RetryOptions): Promise<T>` supporting exponential backoff with jitter, max attempts, abort signal propagation, and a predicate to classify retryable errors."}
5
+ {"id": "code_debug_async", "capability": "coding", "prompt": "Explain why calling `asyncio.gather` on 10,000 coroutines that each open an unthrottled HTTP connection can exhaust file descriptors and stall an event loop, then write a clean Python `asyncio` worker pool with bounded concurrency, per-task timeouts, and graceful cancellation."}
@@ -0,0 +1,2 @@
1
+ {"id": "mm_bar_chart", "capability": "multimodal", "images": ["assets/sample_bar_chart.png"], "prompt": "Read the bar chart in the image. List the four quarterly values shown, identify the highest and lowest quarters, and compute the percentage increase from Q1 to Q4."}
2
+ {"id": "mm_diagram", "capability": "multimodal", "images": ["assets/sample_architecture.png"], "prompt": "Describe the data flow shown in this system diagram step by step, naming each box and arrow direction."}