-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathweb_app.py
More file actions
995 lines (898 loc) · 36.5 KB
/
Copy pathweb_app.py
File metadata and controls
995 lines (898 loc) · 36.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
"""Standard-library web interface for PureLLM."""
import html
import json
import queue
import sys
import threading
import time
import traceback
import urllib.parse
import urllib.request
import urllib.error
from dataclasses import dataclass, field
from datetime import datetime, timezone
from http import HTTPStatus
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from typing import Any, Optional
from reporter import BenchmarkReporter
from runner import BenchmarkRun, BenchmarkRunner, TestResult
from tests import ALL_TESTS
import web_db
ROOT = Path(__file__).resolve().parent
OUTPUT_DIR = ROOT / "outputs" / "web"
@dataclass
class WebJob:
id: str
run_id: int
mode: str
status: str = "running"
events: "queue.Queue[dict[str, Any]]" = field(default_factory=queue.Queue)
summary: Optional[dict[str, Any]] = None
error: Optional[str] = None
def emit(self, event: dict[str, Any]) -> None:
event.setdefault("timestamp", datetime.now(timezone.utc).isoformat())
self.events.put(event)
JOBS: dict[str, WebJob] = {}
JOBS_LOCK = threading.Lock()
def json_bytes(data: Any) -> bytes:
return json.dumps(data, ensure_ascii=False).encode("utf-8")
def parse_form(body: bytes) -> dict[str, str]:
parsed = urllib.parse.parse_qs(body.decode("utf-8"), keep_blank_values=True)
return {k: v[-1].strip() for k, v in parsed.items()}
def esc(value: Any) -> str:
return html.escape("" if value is None else str(value), quote=True)
def load_provider_config() -> dict[str, list[dict[str, str]]]:
path = ROOT / "providers.json"
with path.open("r", encoding="utf-8") as f:
data = json.load(f)
return {
"official": list(data.get("official", [])),
"routers": list(data.get("routers", [])),
}
def provider_buttons(providers: list[dict[str, str]], default_name: Optional[str] = None) -> str:
chunks = []
for index, provider in enumerate(providers):
active = provider.get("name") == default_name or (default_name is None and index == 0)
chunks.append(
'<button type="button" '
f'class="provider-option {"active" if active else ""}" '
f'data-provider-name="{esc(provider.get("name", ""))}" '
f'data-base-url="{esc(provider.get("baseurl", ""))}" '
f'data-provider-home="{esc(provider.get("home", ""))}" '
f'data-api-type="{esc(provider.get("type", "openai"))}">'
f'{esc(provider.get("name", ""))}</button>'
)
return "".join(chunks)
def baseline_ready_table(models: list[dict[str, Any]]) -> str:
ready = [m for m in models if m.get("latest_baseline_run_id")]
if not ready:
return '<p class="muted">No official baselines have been recorded yet.</p>'
rows = []
for model in ready:
score = model.get("baseline_score")
score_text = f"{score:.1%}" if isinstance(score, (int, float)) else "-"
rows.append(
"<tr>"
f"<td>{esc(model.get('name'))}</td>"
f"<td>{esc(model.get('model_name'))}</td>"
f"<td>{esc(model.get('base_url') or 'default endpoint')}</td>"
f"<td>{esc(model.get('baseline_started_at'))}</td>"
f"<td>{esc(score_text)}</td>"
"</tr>"
)
return (
'<table><thead><tr><th>Name</th><th>Model</th><th>Base URL</th>'
'<th>Baseline Run</th><th>Score</th></tr></thead><tbody>'
+ "".join(rows)
+ "</tbody></table>"
)
def page_shell(title: str, active: str, body: str) -> bytes:
nav = [
("/", "Baseline", "baseline"),
("/test", "Test Provider", "test"),
("/leaderboard", "Leaderboard", "leaderboard"),
]
links = "".join(
f'<a class="nav-link {"active" if key == active else ""}" href="{href}">{label}</a>'
for href, label, key in nav
)
html_doc = f"""<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{esc(title)} - PureLLM</title>
<style>
:root {{
--bg: #f7f8fa;
--panel: #ffffff;
--ink: #111827;
--muted: #5b6472;
--line: #d9dee7;
--accent: #0f766e;
--accent-dark: #115e59;
--danger: #b42318;
--ok: #067647;
--warn: #b54708;
}}
* {{ box-sizing: border-box; }}
body {{
margin: 0;
background: var(--bg);
color: var(--ink);
font: 14px/1.45 system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
}}
header {{
height: 58px;
border-bottom: 1px solid var(--line);
background: #fff;
display: flex;
align-items: center;
padding: 0 28px;
gap: 28px;
position: sticky;
top: 0;
z-index: 5;
}}
.brand {{ font-weight: 700; font-size: 18px; letter-spacing: 0; }}
nav {{ display: flex; gap: 6px; }}
.nav-link {{
color: var(--muted);
text-decoration: none;
padding: 8px 11px;
border-radius: 6px;
}}
.nav-link.active, .nav-link:hover {{
color: var(--ink);
background: #eef3f2;
}}
main {{ max-width: 1180px; margin: 0 auto; padding: 26px; }}
h1 {{ font-size: 24px; margin: 0 0 6px; }}
h2 {{ font-size: 16px; margin: 0 0 14px; }}
p.lede {{ color: var(--muted); margin: 0 0 22px; }}
.grid {{ display: grid; grid-template-columns: minmax(320px, 420px) 1fr; gap: 18px; align-items: start; }}
.panel {{
background: var(--panel);
border: 1px solid var(--line);
border-radius: 8px;
padding: 18px;
}}
label {{ display: block; font-weight: 600; margin: 13px 0 6px; }}
input, select {{
width: 100%;
min-height: 38px;
padding: 8px 10px;
border: 1px solid #cbd5e1;
border-radius: 6px;
background: #fff;
color: var(--ink);
}}
.row {{ display: grid; grid-template-columns: 1fr 1fr; gap: 12px; }}
.provider-group {{ display: flex; flex-wrap: wrap; gap: 8px; margin-top: 6px; }}
.provider-option {{
min-height: 34px;
margin: 0;
padding: 0 11px;
border: 1px solid #cbd5e1;
background: #fff;
color: var(--ink);
border-radius: 6px;
font-weight: 650;
}}
.provider-option.active {{ border-color: var(--accent); background: #e7f3f1; color: var(--accent-dark); }}
.label-row {{ display: flex; align-items: baseline; justify-content: space-between; gap: 10px; margin: 13px 0 6px; }}
.label-row label {{ margin: 0; }}
.provider-home-link {{ font-size: 13px; color: var(--accent-dark); text-decoration: none; }}
.provider-home-link:hover {{ text-decoration: underline; }}
.provider-home-link[hidden] {{ display: none; }}
.inline-action {{ display: flex; gap: 10px; align-items: end; }}
.inline-action > div {{ flex: 1; }}
.secondary-button {{ background: #334155; margin-top: 0; white-space: nowrap; }}
.secondary-button:hover {{ background: #1f2937; }}
.baseline-table {{ margin-bottom: 18px; }}
.model-picker {{ display: grid; gap: 8px; }}
.model-picker select {{ color: var(--ink); }}
button {{
margin-top: 16px;
min-height: 40px;
border: 0;
border-radius: 6px;
background: var(--accent);
color: white;
font-weight: 700;
padding: 0 14px;
cursor: pointer;
}}
button:hover {{ background: var(--accent-dark); }}
button:disabled {{ background: #94a3b8; cursor: default; }}
.muted {{ color: var(--muted); }}
.status-line {{
display: grid;
grid-template-columns: 96px 1fr 70px;
gap: 10px;
align-items: start;
border-bottom: 1px solid #eef1f5;
padding: 8px 0;
}}
.status-pass {{ color: var(--ok); font-weight: 700; }}
.status-fail {{ color: var(--danger); font-weight: 700; }}
.status-run {{ color: var(--warn); font-weight: 700; }}
.log {{
max-height: 560px;
overflow: auto;
border-top: 1px solid #eef1f5;
}}
.summary {{
display: grid;
grid-template-columns: repeat(4, minmax(120px, 1fr));
gap: 12px;
margin-bottom: 14px;
}}
.metric {{
border: 1px solid var(--line);
border-radius: 8px;
padding: 12px;
background: #fbfcfd;
}}
.metric strong {{ display: block; font-size: 20px; margin-top: 3px; }}
table {{ width: 100%; border-collapse: collapse; background: #fff; }}
th, td {{ text-align: left; border-bottom: 1px solid #e6eaf0; padding: 10px; vertical-align: top; }}
th {{ font-size: 12px; text-transform: uppercase; color: var(--muted); background: #f8fafc; }}
.filters {{ display: grid; grid-template-columns: 1fr 1fr auto; gap: 12px; align-items: end; margin-bottom: 16px; }}
.pill {{ display: inline-block; padding: 2px 7px; border-radius: 999px; background: #edf2f7; margin: 2px 4px 2px 0; font-size: 12px; white-space: nowrap; }}
@media (max-width: 880px) {{
main {{ padding: 18px; }}
.grid, .row, .summary, .filters {{ grid-template-columns: 1fr; }}
header {{ padding: 0 16px; gap: 14px; }}
nav {{ overflow-x: auto; }}
}}
</style>
</head>
<body>
<header><div class="brand">PureLLM</div><nav>{links}</nav></header>
<main>{body}</main>
</body>
</html>"""
return html_doc.encode("utf-8")
def options(rows: list[dict[str, Any]], selected: Optional[str] = None) -> str:
chunks = []
for row in rows:
value = str(row["id"])
label = row.get("name") or row.get("model_name") or value
suffix = ""
if row.get("latest_baseline_run_id"):
suffix = " - baseline ready"
chunks.append(
f'<option value="{esc(value)}" {"selected" if value == selected else ""}>{esc(label + suffix)}</option>'
)
return "".join(chunks)
def baseline_page() -> bytes:
models = web_db.get_official_models()
providers = load_provider_config()["official"]
default_provider = providers[0] if providers else {"name": "", "baseurl": "", "type": "openai"}
body = f"""
<h1>Establish Official Baseline</h1>
<p class="lede">Run the active authenticity suite against an official model and save its baseline for future provider comparisons.</p>
<section class="panel baseline-table">
<h2>Official Models With Baselines</h2>
{baseline_ready_table(models)}
</section>
<div class="grid">
<section class="panel">
<h2>Baseline Target</h2>
<form id="run-form">
<label>Provider</label>
<div class="provider-group" data-provider-scope="official">
{provider_buttons(providers)}
</div>
<input name="provider_name" type="hidden" value="{esc(default_provider.get('name', ''))}">
<div class="label-row">
<label>Provider base URL</label>
<a id="provider-home-link" class="provider-home-link" href="{esc(default_provider.get('home', ''))}" target="_blank" rel="noopener noreferrer" {"hidden" if not default_provider.get('home') else ""}>Official website</a>
</div>
<input name="base_url" value="{esc(default_provider.get('baseurl', ''))}" required>
<label>API key</label>
<input name="api_key" type="password" autocomplete="off" required>
<label>API type</label>
<select name="api_type">
<option value="openai" {"selected" if default_provider.get('type') == 'openai' else ""}>OpenAI compatible</option>
<option value="anthropic" {"selected" if default_provider.get('type') == 'anthropic' else ""}>Anthropic</option>
</select>
<button id="load-models-btn" class="secondary-button" type="button">Load models</button>
<label>Model identifier</label>
<div class="model-picker">
<input name="model" value="gpt-4o" required>
<select id="model-select" disabled>
<option value="">Load models to select</option>
</select>
</div>
<label>Display name</label>
<input name="official_name" value="OpenAI GPT-4o" required>
<button id="start-btn" type="submit">Start baseline run</button>
</form>
</section>
<section class="panel">
<h2>Progress</h2>
<div id="summary" class="muted">No run started.</div>
<div id="log" class="log"></div>
</section>
</div>
{run_script('/api/baseline/start')}
"""
return page_shell("Baseline", "baseline", body)
def test_page() -> bytes:
models = web_db.get_official_models()
providers = load_provider_config()["routers"]
default_provider = providers[0] if providers else {"name": "", "baseurl": "", "type": "openai"}
body = f"""
<h1>Test Provider Model</h1>
<p class="lede">Run the same suite through a routing service and compare it with a saved official baseline.</p>
<div class="grid">
<section class="panel">
<h2>Provider Target</h2>
<form id="run-form">
<label>Official baseline</label>
<select name="official_model_id" required>
{options([m for m in models if m.get('latest_baseline_run_id')])}
</select>
<label>Provider</label>
<div class="provider-group" data-provider-scope="routers">
{provider_buttons(providers)}
</div>
<input name="provider_name" type="hidden" value="{esc(default_provider.get('name', ''))}">
<div class="label-row">
<label>Provider base URL</label>
<a id="provider-home-link" class="provider-home-link" href="{esc(default_provider.get('home', ''))}" target="_blank" rel="noopener noreferrer" {"hidden" if not default_provider.get('home') else ""}>Official website</a>
</div>
<input name="base_url" value="{esc(default_provider.get('baseurl', ''))}" required>
<label>API key</label>
<input name="api_key" type="password" autocomplete="off" required>
<label>API type</label>
<select name="api_type">
<option value="openai" {"selected" if default_provider.get('type') == 'openai' else ""}>OpenAI compatible</option>
<option value="anthropic" {"selected" if default_provider.get('type') == 'anthropic' else ""}>Anthropic</option>
</select>
<button id="load-models-btn" class="secondary-button" type="button">Load models</button>
<label>Model identifier</label>
<div class="model-picker">
<input name="model" placeholder="Type a model or choose one below" required>
<select id="model-select" disabled>
<option value="">Load models to select</option>
</select>
</div>
<button id="start-btn" type="submit">Start provider test</button>
</form>
</section>
<section class="panel">
<h2>Progress</h2>
<div id="summary" class="muted">No run started.</div>
<div id="log" class="log"></div>
</section>
</div>
{run_script('/api/test/start')}
"""
return page_shell("Test Provider", "test", body)
def leaderboard_page(query: dict[str, list[str]]) -> bytes:
provider = query.get("provider", [""])[0]
model = query.get("model", [""])[0]
runs = web_db.list_runs(provider=provider or None, model=model or None)
providers = sorted({r.get("provider_name") for r in web_db.list_runs() if r.get("provider_name")})
models = sorted({r.get("model") for r in web_db.list_runs() if r.get("model")})
rows = []
for run in runs:
counts = web_db.category_pass_counts(run["id"])
sections = " ".join(
f'<span class="pill">{esc(cat)} {v["passed"]}/{v["total"]}</span>'
for cat, v in counts.items()
)
score = run.get("authenticity_score")
if score is None:
score = run.get("overall_score", 0)
rows.append(
"<tr>"
f"<td>{esc(run['started_at'])}<br><span class=\"muted\">#{run['id']} {esc(run['status'])}</span></td>"
f"<td>{esc(run.get('provider_name') or 'Official')}</td>"
f"<td>{esc(run.get('model'))}<br><span class=\"muted\">{esc(run.get('base_url') or 'default endpoint')}</span></td>"
f"<td>{esc(run.get('official_model_name') or '')}</td>"
f"<td>{sections}</td>"
f"<td><strong>{score:.1%}</strong><br><span class=\"muted\">{run.get('passed_tests', 0)}/{run.get('total_tests', 0)} passed</span></td>"
"</tr>"
)
if not rows:
rows.append('<tr><td colspan="6" class="muted">No runs match the current filters.</td></tr>')
provider_opts = '<option value="">All providers</option>' + "".join(
f'<option value="{esc(p)}" {"selected" if p == provider else ""}>{esc(p)}</option>'
for p in providers
)
model_opts = '<option value="">All models</option>' + "".join(
f'<option value="{esc(m)}" {"selected" if m == model else ""}>{esc(m)}</option>'
for m in models
)
body = f"""
<h1>Leaderboard</h1>
<p class="lede">Browse saved baseline and provider runs, ordered by recency. Filter by provider or by model to compare routing services.</p>
<section class="panel">
<form class="filters" method="get" action="/leaderboard">
<div><label>Provider</label><select name="provider">{provider_opts}</select></div>
<div><label>Model</label><select name="model">{model_opts}</select></div>
<button type="submit">Apply filters</button>
</form>
<table>
<thead>
<tr><th>Run</th><th>Provider</th><th>Model</th><th>Baseline</th><th>Sections</th><th>Final score</th></tr>
</thead>
<tbody>{''.join(rows)}</tbody>
</table>
</section>
"""
return page_shell("Leaderboard", "leaderboard", body)
def run_script(endpoint: str) -> str:
return f"""
<script>
const form = document.getElementById('run-form');
const log = document.getElementById('log');
const summary = document.getElementById('summary');
const btn = document.getElementById('start-btn');
const loadModelsBtn = document.getElementById('load-models-btn');
const modelInput = form.querySelector('[name="model"]');
const modelSelect = document.getElementById('model-select');
const baseUrlInput = form.querySelector('[name="base_url"]');
const apiTypeSelect = form.querySelector('[name="api_type"]');
const apiKeyInput = form.querySelector('[name="api_key"]');
const providerNameInput = form.querySelector('[name="provider_name"]');
const providerHomeLink = document.getElementById('provider-home-link');
function selectProvider(button) {{
document.querySelectorAll('.provider-option').forEach((item) => item.classList.remove('active'));
button.classList.add('active');
providerNameInput.value = button.dataset.providerName || '';
baseUrlInput.value = button.dataset.baseUrl || '';
apiTypeSelect.value = button.dataset.apiType || 'openai';
if (providerHomeLink) {{
const home = button.dataset.providerHome || '';
providerHomeLink.href = home;
providerHomeLink.hidden = !home;
}}
}}
document.querySelectorAll('.provider-option').forEach((button) => {{
button.addEventListener('click', () => selectProvider(button));
}});
if (modelSelect) {{
modelSelect.addEventListener('change', () => {{
if (modelSelect.value) modelInput.value = modelSelect.value;
}});
}}
if (loadModelsBtn) {{
loadModelsBtn.addEventListener('click', async () => {{
loadModelsBtn.disabled = true;
const previousText = loadModelsBtn.textContent;
loadModelsBtn.textContent = 'Loading...';
try {{
const response = await fetch('/api/models', {{
method: 'POST',
body: new URLSearchParams({{
api_type: apiTypeSelect.value,
base_url: baseUrlInput.value,
api_key: apiKeyInput.value
}})
}});
const payload = await response.json();
if (!response.ok) throw new Error(payload.error || 'Could not load models');
modelSelect.innerHTML = '';
const placeholder = document.createElement('option');
placeholder.value = '';
placeholder.textContent = payload.models.length ? 'Choose a loaded model' : 'No models returned';
modelSelect.appendChild(placeholder);
payload.models.forEach((model) => {{
const option = document.createElement('option');
option.value = model;
option.textContent = model;
modelSelect.appendChild(option);
}});
modelSelect.disabled = payload.models.length === 0;
if (payload.models.length && !modelInput.value) modelInput.value = payload.models[0];
summary.textContent = `Loaded ${{payload.models.length}} models from ${{providerNameInput.value || 'provider'}}.`;
}} catch (error) {{
summary.textContent = error.message;
}} finally {{
loadModelsBtn.disabled = false;
loadModelsBtn.textContent = previousText;
}}
}});
}}
function escapeHtml(value) {{
return String(value ?? '').replace(/[&<>'"]/g, (char) => ({{
'&': '&', '<': '<', '>': '>', "'": ''', '"': '"'
}}[char]));
}}
function rowFor(data) {{
if (!data.test_id) return null;
return log.querySelector(`[data-test-id="${{CSS.escape(data.test_id)}}"]`);
}}
function addLine(data) {{
let row = rowFor(data);
const isUpdate = Boolean(row);
if (!row) {{
row = document.createElement('div');
row.className = 'status-line';
if (data.test_id) row.dataset.testId = data.test_id;
}}
const statusClass = data.status === 'PASS' ? 'status-pass' : (data.status === 'FAIL' ? 'status-fail' : 'status-run');
row.innerHTML = `<div class="${{statusClass}}">${{escapeHtml(data.status || 'RUN')}}</div><div><strong>${{escapeHtml(data.test_id || '')}}</strong> ${{escapeHtml(data.test_name || data.message || '')}}<br><span class="muted">${{escapeHtml(data.details || '')}}</span></div><div>${{escapeHtml(data.score || '')}}</div>`;
if (!isUpdate) log.prepend(row);
}}
function renderSummary(data) {{
const auth = data.authenticity_score === null || data.authenticity_score === undefined ? null : data.authenticity_score;
const score = auth === null ? data.overall_score : auth;
const label = auth === null ? 'Run score' : 'Authenticity';
const categories = Object.entries(data.category_scores || {{}})
.map(([name, value]) => `<span class="pill">${{name}} ${{Math.round(value * 100)}}%</span>`)
.join(' ');
summary.innerHTML = `<div class="summary">
<div class="metric"><span>${{label}}</span><strong>${{Math.round((score || 0) * 100)}}%</strong></div>
<div class="metric"><span>Passed</span><strong>${{data.passed_tests}}/${{data.total_tests}}</strong></div>
<div class="metric"><span>Status</span><strong>${{data.status}}</strong></div>
<div class="metric"><span>Run ID</span><strong>#${{data.run_id}}</strong></div>
</div><div>${{categories}}</div>`;
}}
form.addEventListener('submit', async (event) => {{
event.preventDefault();
btn.disabled = true;
log.innerHTML = '';
summary.textContent = 'Starting run...';
const response = await fetch('{endpoint}', {{
method: 'POST',
body: new URLSearchParams(new FormData(form))
}});
const payload = await response.json();
if (!response.ok) {{
btn.disabled = false;
summary.textContent = payload.error || 'Could not start run.';
return;
}}
summary.textContent = `Run #${{payload.run_id}} is running...`;
const stream = new EventSource(`/api/jobs/${{payload.job_id}}/events`);
stream.onmessage = (event) => {{
const data = JSON.parse(event.data);
if (data.type === 'progress' || data.type === 'started') addLine(data);
if (data.type === 'summary') renderSummary(data);
if (data.type === 'error') {{
summary.textContent = data.message;
btn.disabled = false;
}}
if (data.type === 'complete') {{
btn.disabled = false;
stream.close();
}}
}};
stream.onerror = () => {{
btn.disabled = false;
stream.close();
}};
}});
</script>
"""
def fetch_model_list(api_type: str, base_url: str, api_key: str) -> list[str]:
if not base_url:
raise ValueError("Base URL is required to load models")
if not api_key:
raise ValueError("API key is required to load models")
root = base_url.rstrip("/")
headers = {"Accept": "application/json"}
if api_type == "anthropic":
url = root if root.endswith("/v1/models") else root + "/v1/models"
headers["x-api-key"] = api_key
headers["anthropic-version"] = "2023-06-01"
else:
url = root if root.endswith("/models") else root + "/models"
headers["Authorization"] = f"Bearer {api_key}"
request = urllib.request.Request(url, headers=headers, method="GET")
try:
with urllib.request.urlopen(request, timeout=30) as response:
payload = json.loads(response.read().decode("utf-8"))
except urllib.error.HTTPError as exc:
body = exc.read().decode("utf-8", errors="replace")[:300]
raise ValueError(f"Model list request failed with HTTP {exc.code}: {body}") from exc
except urllib.error.URLError as exc:
raise ValueError(f"Model list request failed: {exc.reason}") from exc
data = payload.get("data", payload if isinstance(payload, list) else [])
models = []
for item in data:
if isinstance(item, str):
models.append(item)
elif isinstance(item, dict):
model_id = item.get("id") or item.get("name") or item.get("model")
if model_id:
models.append(str(model_id))
return sorted(set(models), key=str.lower)
def load_baseline_run(official_model_id: int) -> tuple[dict[str, Any], int]:
official = web_db.get_official_model(official_model_id)
if not official:
raise ValueError("Official model not found")
baseline_run_id = official.get("latest_baseline_run_id")
if not baseline_run_id:
raise ValueError("Selected official model has no saved baseline yet")
return web_db.get_baseline_data(int(baseline_run_id)), int(baseline_run_id)
def run_benchmark_job(
job: WebJob,
*,
api_type: str,
api_key: str,
model: str,
base_url: Optional[str],
official_model_id: Optional[int] = None,
baseline_data: Optional[dict[str, Any]] = None,
baseline_run_id: Optional[int] = None,
) -> None:
runner = None
results: list[TestResult] = []
try:
runner = BenchmarkRunner(
api_type=api_type,
api_key=api_key,
model=model,
base_url=base_url or None,
)
job.emit({"type": "started", "status": "RUN", "message": "Benchmark started"})
for test in ALL_TESTS:
tr = runner.run_test(test, baseline_data)
results.append(tr)
pending_judge = bool(baseline_data and test.get("llm_judge"))
job.emit(
{
"type": "progress",
"status": "JUDGE" if pending_judge else ("PASS" if tr.passed else "FAIL"),
"test_id": tr.test_id,
"test_name": tr.test_name,
"details": "Queued for LLM judge" if pending_judge else tr.details[:240],
"score": "..." if pending_judge else f"{tr.score:.0%}",
}
)
if baseline_data:
job.emit({"type": "started", "status": "RUN", "message": "Running LLM judge batches"})
runner.apply_llm_judging(results, baseline_data, ALL_TESTS)
for tr in results:
if (tr.metadata or {}).get("llm_judge") or (tr.metadata or {}).get("llm_judge_error"):
job.emit(
{
"type": "progress",
"status": "PASS" if tr.passed else "FAIL",
"test_id": tr.test_id,
"test_name": tr.test_name,
"details": tr.details[:240],
"score": f"{tr.score:.0%}",
}
)
for tr in results:
web_db.store_test_result(job.run_id, tr.to_dict())
run = BenchmarkRun(
mode="test" if baseline_data else "official",
api_type=api_type,
model=model,
base_url=base_url or None,
timestamp=datetime.now(timezone.utc).isoformat(),
results=results,
)
run.calculate_summary()
run_data = run.to_dict()
comparison = None
if baseline_data:
official_results = [TestResult(**r) for r in baseline_data.values()]
official_run = BenchmarkRun(
mode="official",
api_type=api_type,
model=model,
base_url=None,
timestamp="",
results=official_results,
)
official_run.calculate_summary()
comparison = BenchmarkReporter.compare_runs(official_run, run)
OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
suffix = "provider" if baseline_data else "baseline"
output_path = OUTPUT_DIR / f"{suffix}_run_{job.run_id}.json"
output_payload = (
{"test_run": run_data, "comparison": comparison}
if comparison
else run_data
)
output_path.write_text(json.dumps(output_payload, indent=2, ensure_ascii=False), encoding="utf-8")
web_db.update_run_complete(
job.run_id,
status="completed",
run_data=run_data,
comparison=comparison,
)
if official_model_id and not baseline_data:
web_db.set_latest_baseline(official_model_id, job.run_id)
auth_score = None
if comparison:
auth_score = comparison["summary"].get("authenticity_score")
summary = {
"type": "summary",
"run_id": job.run_id,
"status": "completed",
"total_tests": run.total_tests,
"passed_tests": run.passed_tests,
"overall_score": run.overall_score,
"authenticity_score": auth_score,
"category_scores": run.category_scores,
}
job.summary = summary
job.status = "completed"
job.emit(summary)
job.emit({"type": "complete", "status": "DONE", "message": "Run completed"})
except Exception as exc:
job.status = "failed"
job.error = f"{type(exc).__name__}: {exc}"
web_db.update_run_complete(job.run_id, status="failed", error=job.error)
job.emit({"type": "error", "status": "FAIL", "message": job.error})
traceback.print_exc()
finally:
if runner:
runner.close()
def start_job(job: WebJob, target, kwargs: dict[str, Any]) -> None:
with JOBS_LOCK:
JOBS[job.id] = job
thread = threading.Thread(target=target, kwargs=kwargs, daemon=True)
thread.start()
class Handler(BaseHTTPRequestHandler):
server_version = "PureLLMWeb/0.1"
def do_GET(self) -> None:
parsed = urllib.parse.urlparse(self.path)
if parsed.path == "/":
self.send_html(baseline_page())
elif parsed.path == "/test":
self.send_html(test_page())
elif parsed.path == "/leaderboard":
self.send_html(leaderboard_page(urllib.parse.parse_qs(parsed.query)))
elif parsed.path.startswith("/api/jobs/") and parsed.path.endswith("/events"):
self.stream_events(parsed.path.split("/")[3])
else:
self.send_error(HTTPStatus.NOT_FOUND)
def do_POST(self) -> None:
length = int(self.headers.get("Content-Length", "0"))
form = parse_form(self.rfile.read(length))
parsed = urllib.parse.urlparse(self.path)
try:
if parsed.path == "/api/baseline/start":
self.start_baseline(form)
elif parsed.path == "/api/test/start":
self.start_provider_test(form)
elif parsed.path == "/api/models":
self.load_models(form)
else:
self.send_error(HTTPStatus.NOT_FOUND)
except Exception as exc:
self.send_json({"error": str(exc)}, HTTPStatus.BAD_REQUEST)
def load_models(self, form: dict[str, str]) -> None:
models = fetch_model_list(
form.get("api_type") or "openai",
form.get("base_url") or "",
form.get("api_key") or "",
)
self.send_json({"models": models})
def start_baseline(self, form: dict[str, str]) -> None:
api_key = form.get("api_key", "")
model = form.get("model", "")
if not api_key or not model:
raise ValueError("API key and model identifier are required")
api_type = form.get("api_type") or "openai"
base_url = form.get("base_url") or None
provider_name = form.get("provider_name") or "Official"
name = form.get("official_name") or model
official_model_id = web_db.upsert_official_model(
name=name,
api_type=api_type,
base_url=base_url,
model_name=model,
)
run_id = web_db.create_run(
mode="official",
api_type=api_type,
model=model,
base_url=base_url,
provider_name=provider_name,
official_model_id=official_model_id,
)
job = WebJob(id=f"job-{run_id}-{int(time.time())}", run_id=run_id, mode="official")
start_job(
job,
run_benchmark_job,
{
"job": job,
"api_type": api_type,
"api_key": api_key,
"model": model,
"base_url": base_url,
"official_model_id": official_model_id,
},
)
self.send_json({"job_id": job.id, "run_id": run_id})
def start_provider_test(self, form: dict[str, str]) -> None:
api_key = form.get("api_key", "")
model = form.get("model", "")
base_url = form.get("base_url")
provider_name = form.get("provider_name")
official_model_id = int(form.get("official_model_id") or "0")
if not api_key or not model or not base_url or not provider_name:
raise ValueError("Provider name, base URL, API key, and model are required")
baseline_data, baseline_run_id = load_baseline_run(official_model_id)
api_type = form.get("api_type") or "openai"
run_id = web_db.create_run(
mode="test",
api_type=api_type,
model=model,
base_url=base_url,
provider_name=provider_name,
official_model_id=official_model_id,
baseline_run_id=baseline_run_id,
)
job = WebJob(id=f"job-{run_id}-{int(time.time())}", run_id=run_id, mode="test")
start_job(
job,
run_benchmark_job,
{
"job": job,
"api_type": api_type,
"api_key": api_key,
"model": model,
"base_url": base_url,
"baseline_data": baseline_data,
"baseline_run_id": baseline_run_id,
},
)
self.send_json({"job_id": job.id, "run_id": run_id})
def stream_events(self, job_id: str) -> None:
with JOBS_LOCK:
job = JOBS.get(job_id)
if not job:
self.send_error(HTTPStatus.NOT_FOUND)
return
self.send_response(HTTPStatus.OK)
self.send_header("Content-Type", "text/event-stream")
self.send_header("Cache-Control", "no-cache")
self.send_header("Connection", "keep-alive")
self.end_headers()
while True:
try:
event = job.events.get(timeout=20)
self.wfile.write(b"data: " + json_bytes(event) + b"\n\n")
self.wfile.flush()
if event.get("type") in {"complete", "error"}:
break
except queue.Empty:
self.wfile.write(b": keepalive\n\n")
self.wfile.flush()
except (BrokenPipeError, ConnectionResetError):
break
def send_html(self, content: bytes, status: HTTPStatus = HTTPStatus.OK) -> None:
self.send_response(status)
self.send_header("Content-Type", "text/html; charset=utf-8")
self.send_header("Content-Length", str(len(content)))
self.end_headers()
self.wfile.write(content)
def send_json(self, data: Any, status: HTTPStatus = HTTPStatus.OK) -> None:
content = json_bytes(data)
self.send_response(status)
self.send_header("Content-Type", "application/json; charset=utf-8")
self.send_header("Content-Length", str(len(content)))
self.end_headers()
self.wfile.write(content)
def main() -> None:
import argparse
parser = argparse.ArgumentParser(description="Run the PureLLM web interface")
parser.add_argument("--host", default="127.0.0.1")
parser.add_argument("--port", type=int, default=8787)
args = parser.parse_args()
web_db.init_db()
server = ThreadingHTTPServer((args.host, args.port), Handler)
print(f"PureLLM web interface running at http://{args.host}:{args.port}")
try:
server.serve_forever()
except KeyboardInterrupt:
print("\nStopping server")
finally:
server.server_close()
if __name__ == "__main__":
main()