-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathchw_llm_tool_3.html
More file actions
596 lines (551 loc) · 28.4 KB
/
chw_llm_tool_3.html
File metadata and controls
596 lines (551 loc) · 28.4 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CHW LLM Feedback Tool</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.18.5/xlsx.full.min.js"></script>
<style>
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&family=JetBrains+Mono:wght@400;500&display=swap');
:root {
--bg:#0f1419; --sf:#1a1f2e; --sf2:#232940; --bd:#2d3548;
--tx:#e2e8f0; --tx2:#8892a4; --ac:#6366f1; --ac2:#818cf8;
--gn:#22c55e; --rd:#ef4444; --or:#f59e0b;
--mono:'JetBrains Mono','SF Mono','Fira Code',monospace;
--sans:'Inter',-apple-system,sans-serif;
}
*{box-sizing:border-box;margin:0;padding:0}
body{font-family:var(--sans);background:var(--bg);color:var(--tx);min-height:100vh}
.container{max-width:960px;margin:0 auto;padding:28px 20px}
h1{font-size:21px;font-weight:700;margin-bottom:2px}
.sub{color:var(--tx2);font-size:12px;margin-bottom:24px}
.step{background:var(--sf);border:1px solid var(--bd);border-radius:8px;padding:18px;margin-bottom:14px}
.step-h{display:flex;align-items:center;gap:8px;margin-bottom:12px}
.step-n{background:var(--ac);color:#fff;width:24px;height:24px;border-radius:50%;display:flex;align-items:center;justify-content:center;font-size:12px;font-weight:700;flex-shrink:0}
.step-t{font-size:14px;font-weight:600}
label{display:block;font-size:11px;color:var(--tx2);font-weight:500;text-transform:uppercase;letter-spacing:.5px;margin-bottom:4px}
textarea{width:100%;min-height:150px;background:var(--bg);border:1px solid var(--bd);border-radius:6px;color:var(--tx);font-family:var(--mono);font-size:11.5px;padding:10px;resize:vertical;line-height:1.6}
textarea:focus,input:focus,select:focus{outline:none;border-color:var(--ac)}
input[type=text],input[type=password],input[type=number],select{background:var(--bg);border:1px solid var(--bd);border-radius:4px;color:var(--tx);font-size:12px;padding:7px 10px;font-family:var(--sans)}
select{cursor:pointer}
.btn{padding:7px 16px;border-radius:6px;border:none;font-size:12px;font-weight:600;cursor:pointer;font-family:var(--sans);transition:opacity .15s}
.btn:hover{opacity:.85} .btn:disabled{opacity:.4;cursor:not-allowed}
.btn-p{background:var(--ac);color:#fff} .btn-g{background:#16a34a;color:#fff}
.btn-d{background:#dc262622;color:var(--rd);border:1px solid #dc262644}
.btn-s{background:var(--sf2);color:var(--tx);border:1px solid var(--bd)}
.row{display:flex;gap:8px;align-items:center;flex-wrap:wrap}
.file-drop{border:2px dashed var(--bd);border-radius:8px;padding:24px;text-align:center;cursor:pointer;position:relative;transition:border-color .2s}
.file-drop:hover{border-color:var(--ac)}
.file-drop input{position:absolute;inset:0;opacity:0;cursor:pointer}
.file-info{background:var(--sf2);border-radius:6px;padding:8px 12px;margin-top:8px;font-size:12px;color:var(--tx2);display:flex;justify-content:space-between;align-items:center}
.prog-bar{height:4px;background:var(--sf2);border-radius:2px;overflow:hidden;margin-top:8px}
.prog-fill{height:100%;background:var(--ac);border-radius:2px;transition:width .3s}
.log{background:var(--bg);border:1px solid var(--bd);border-radius:6px;padding:8px;max-height:160px;overflow-y:auto;font-family:var(--mono);font-size:11px;line-height:1.6;color:var(--tx2);margin-top:8px}
.log .err{color:var(--rd)} .log .ok{color:var(--gn)} .log .info{color:var(--ac2)}
.card{background:var(--bg);border:1px solid var(--bd);border-radius:6px;padding:10px;margin-bottom:6px}
.pill{display:inline-block;border-radius:9999px;padding:2px 8px;font-size:10px;font-weight:600;margin:1px 3px 1px 0}
.pill-r{background:#22c55e22;color:var(--gn)} .pill-u{background:#ef444422;color:var(--rd)} .pill-m{background:#f59e0b22;color:var(--or)} .pill-w{background:#f59e0b22;color:var(--or)}
.log .warn{color:var(--or)}
.meta{font-size:10px;color:var(--tx2);margin-top:4px;font-family:var(--mono)}
.meta span{margin-right:10px}
.meta .warn-tag{color:var(--or);font-weight:600}
.grid5{display:grid;grid-template-columns:1fr 80px 55px 55px 55px;font-size:12px}
.grid5 .hdr{padding:6px 4px;font-size:10px;font-weight:600;color:var(--tx2);text-transform:uppercase}
.grid5 .cell{padding:5px 4px;border-top:1px solid var(--bd)}
.cb-row{display:flex;align-items:center;gap:8px;margin-top:10px;cursor:pointer}
.cb-row input{accent-color:var(--ac);width:16px;height:16px}
.hint{font-size:11px;color:var(--tx2);margin-top:4px;font-style:italic}
.collapsible{cursor:pointer} .collapsible:hover{background:var(--sf2)}
pre.resp{font-family:var(--mono);font-size:11px;white-space:pre-wrap;color:var(--tx2);line-height:1.5;max-height:200px;overflow:auto;margin:8px 0 0}
@media(max-width:640px){.container{padding:14px}.step{padding:12px}.grid5{grid-template-columns:1fr 60px 40px 40px 40px;font-size:11px}}
</style>
</head>
<body>
<div class="container">
<h1>CHW LLM Feedback Tool</h1>
<p class="sub">Upload CHW notes → run through an LLM with your prompt → analyze which tests are recommended</p>
<!-- 1: API -->
<div class="step">
<div class="step-h"><div class="step-n">1</div><div class="step-t">API Configuration</div></div>
<div class="row" style="gap:14px">
<div style="min-width:140px">
<label>Main Model</label>
<select id="model">
<optgroup label="GPT-5.4 (Latest)">
<option>gpt-5.4</option><option>gpt-5.4-mini</option><option>gpt-5.4-nano</option>
</optgroup>
<optgroup label="GPT-5.x (Older)">
<option>gpt-5.2</option><option>gpt-5.1</option>
<option>gpt-5</option><option>gpt-5-mini</option><option>gpt-5-nano</option>
</optgroup>
<optgroup label="GPT-4.x">
<option>gpt-4o</option><option>gpt-4o-mini</option>
<option>gpt-4.1</option><option>gpt-4.1-mini</option><option>gpt-4.1-nano</option>
</optgroup>
<optgroup label="Reasoning (o-series)">
<option>o3-mini</option><option>o1</option><option>o1-mini</option>
</optgroup>
</select>
</div>
<div style="min-width:140px">
<label>Extraction Model</label>
<select id="extractModel">
<optgroup label="GPT-5.4 (Latest)">
<option>gpt-5.4-mini</option><option>gpt-5.4-nano</option><option>gpt-5.4</option>
</optgroup>
<optgroup label="GPT-5.x (Older)">
<option>gpt-5-mini</option><option>gpt-5-nano</option><option>gpt-5.2</option>
</optgroup>
<optgroup label="GPT-4.x">
<option>gpt-4o-mini</option><option>gpt-4o</option>
<option>gpt-4.1-mini</option><option>gpt-4.1-nano</option><option>gpt-4.1</option>
</optgroup>
<optgroup label="Reasoning (o-series)">
<option>o3-mini</option><option>o1-mini</option><option>o1</option>
</optgroup>
</select>
</div>
<div style="flex:1;min-width:180px">
<label>OpenAI API Key</label>
<div class="row">
<input id="apiKey" type="password" placeholder="sk-..." style="flex:1">
<button class="btn btn-s" onclick="let e=$('apiKey');e.type=e.type==='password'?'text':'password'">Show</button>
</div>
</div>
<div style="flex:1;min-width:240px">
<label>Proxy URL <span style="text-transform:none;font-weight:400">(your Cloudflare Worker)</span></label>
<input id="proxyUrl" type="text" value="https://llm-worker.robert-pless.workers.dev" style="width:100%">
</div>
<div style="min-width:90px">
<label>Concurrency</label>
<input id="conc" type="number" value="3" min="1" max="10" style="width:60px">
</div>
<div style="min-width:100px">
<label>Timeout (sec)</label>
<input id="timeout" type="number" value="120" min="30" max="600" style="width:70px">
</div>
<div style="min-width:100px">
<label>Max Tokens</label>
<input id="maxTok" type="number" value="4096" min="256" max="16384" style="width:80px">
</div>
</div>
<p class="hint">Key is sent from your browser → your proxy → OpenAI. Never stored.</p>
</div>
<!-- 2: Prompts -->
<div class="step">
<div class="step-h"><div class="step-n">2</div><div class="step-t">Prompts</div></div>
<label>Main LLM Prompt <span style="font-weight:400;text-transform:none">— <code style="color:var(--ac2)">{note}</code> = CHW note</span></label>
<textarea id="mainPrompt">You are a clinical decision support system reviewing community health worker (CHW) consultation notes.
CONTEXT:
- This clinic serves a region where only 4% of patients presenting with fever-like symptoms actually test positive for malaria.
- Approximately 50% of CHWs currently test for malaria regardless of presentation.
- Over-testing wastes limited rapid diagnostic test (RDT) supplies and delays appropriate care.
TASK:
Review the following CHW consultation note and provide clinical feedback. What diagnostic tests do you recommend and why? Flag any tests that seem unnecessary given the presentation. Suggest any tests the CHW may have missed.
CHW NOTE:
{note}</textarea>
<div style="margin-top:12px">
<label>Test Extraction Prompt <span style="font-weight:400;text-transform:none">— <code style="color:var(--ac2)">{note}</code> + <code style="color:var(--ac2)">{feedback}</code></span></label>
<textarea id="extractPrompt" style="min-height:110px">Given this CHW consultation note and LLM clinical feedback, determine whether the LLM recommends adding or removing tests for malaria, anemia, and urinalysis.
CHW NOTE:
{note}
LLM FEEDBACK:
{feedback}
Respond ONLY with a JSON object (no markdown, no backticks):
{
"recommend_adding_malaria_test": 0 or 1,
"recommend_removing_malaria_test": 0 or 1,
"recommend_adding_anemia_test": 0 or 1,
"recommend_removing_anemia_test": 0 or 1,
"recommend_adding_urinalysis": 0 or 1,
"recommend_removing_urinalysis": 0 or 1
}</textarea>
</div>
</div>
<!-- 3: Upload -->
<div class="step">
<div class="step-h"><div class="step-n">3</div><div class="step-t">Upload CHW Notes</div></div>
<p style="font-size:12px;color:var(--tx2);margin-bottom:8px">
Excel/CSV with columns: <code style="color:var(--ac2)">assessment_id</code>, <code style="color:var(--ac2)">CHW1_unassisted</code>
</p>
<div class="file-drop" id="fileDrop">
<input type="file" accept=".xlsx,.xls,.csv" id="fileInput" onchange="handleFile(event)">
<div style="font-size:26px;margin-bottom:6px">📄</div>
<p style="color:var(--tx2);font-size:12px">Drop file here or click to browse</p>
</div>
<div id="fileInfo" style="display:none" class="file-info">
<span id="fileInfoText"></span>
<button class="btn btn-s" onclick="clearFile()" style="padding:3px 10px;font-size:11px">Clear</button>
</div>
<label class="cb-row"><input type="checkbox" id="debugMode"><span style="font-size:13px;text-transform:none;color:var(--tx)">Debug mode — first 10 rows only</span></label>
</div>
<!-- 4: Run -->
<div class="step">
<div class="step-h"><div class="step-n">4</div><div class="step-t">Run</div></div>
<div class="row">
<button class="btn btn-p" id="runBtn" onclick="runPipeline()" disabled>Run Pipeline</button>
<button class="btn btn-d" id="stopBtn" onclick="stopPipeline()" style="display:none">Stop</button>
<button class="btn btn-g" id="dlBtn" onclick="exportResults()" style="display:none">⬇ Download Results .xlsx</button>
<span id="statusText" style="font-size:12px;color:var(--tx2)"></span>
</div>
<div id="progressWrap" style="display:none">
<div class="prog-bar"><div class="prog-fill" id="progFill"></div></div>
<div style="font-size:11px;color:var(--tx2);margin-top:4px" id="progText"></div>
</div>
<div class="log" id="log" style="display:none"></div>
</div>
<!-- 5: Results -->
<div class="step" id="resultsSection" style="display:none">
<div class="step-h"><div class="step-n">5</div><div class="step-t">Results</div></div>
<div class="row" style="justify-content:space-between;margin-bottom:10px">
<span style="font-size:14px;font-weight:600">Test Recommendation Summary</span>
<button class="btn btn-g" onclick="exportResults()">Download .xlsx</button>
</div>
<div id="summaryGrid"></div>
<div class="row" style="justify-content:space-between;margin:16px 0 8px">
<span style="font-size:14px;font-weight:600">Per-Note Results</span>
<span id="resultStats" style="font-size:11px;color:var(--tx2)"></span>
</div>
<div id="noteResults"></div>
</div>
</div>
<script>
let DATA = [], RESULTS = [], aborted = false;
const $ = id => document.getElementById(id);
const esc = s => String(s).replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>').replace(/"/g,'"');
function log(msg, cls='') {
const el = $('log'); el.style.display='block';
el.innerHTML += `<div class="${cls}">${new Date().toLocaleTimeString()} — ${msg}</div>`;
el.scrollTop = el.scrollHeight;
}
function setProg(done, total) {
$('progressWrap').style.display='block';
$('progFill').style.width = (total ? done/total*100 : 0)+'%';
$('progText').textContent = `${done}/${total} (${total ? Math.round(done/total*100) : 0}%)`;
}
// ── File ──
const drop = $('fileDrop');
drop.addEventListener('dragover', e => { e.preventDefault(); drop.style.borderColor='var(--ac)'; });
drop.addEventListener('dragleave', () => drop.style.borderColor='');
drop.addEventListener('drop', e => { e.preventDefault(); drop.style.borderColor='';
if(e.dataTransfer.files.length){ $('fileInput').files=e.dataTransfer.files; handleFile({target:{files:e.dataTransfer.files}}); }
});
function handleFile(e) {
const f = e.target.files?.[0]; if(!f) return;
const reader = new FileReader();
reader.onload = evt => {
const wb = XLSX.read(evt.target.result, {type:'array'});
const ws = wb.Sheets[wb.SheetNames[0]];
const json = XLSX.utils.sheet_to_json(ws, {defval:''});
if(!json.length) return;
const cols = Object.keys(json[0]);
const idCol = cols.find(c => c.toLowerCase().replace(/\s+/g,'_') === 'assessment_id');
const noteCol = cols.find(c => c.toLowerCase().replace(/\s+/g,'_') === 'chw1_unassisted');
if(!idCol || !noteCol){ alert(`Need: assessment_id, CHW1_unassisted\nFound: ${cols.join(', ')}`); return; }
DATA = json.map(r => ({ id: String(r[idCol]||'').trim(), note: String(r[noteCol]||'').trim() })).filter(r => r.note);
$('fileInfo').style.display='flex';
$('fileInfoText').textContent = `${f.name} — ${DATA.length} rows`;
$('runBtn').disabled = false;
};
reader.readAsArrayBuffer(f);
}
function clearFile() { DATA=[]; RESULTS=[]; $('fileInfo').style.display='none'; $('fileInput').value=''; $('runBtn').disabled=true; $('resultsSection').style.display='none'; }
// ── API ──
// Returns { content, finish_reason, latency_ms, prompt_tokens, completion_tokens, warnings[] }
async function callLLM(prompt, modelOverride) {
const key = $('apiKey').value.trim();
const model = modelOverride || $('model').value;
const proxy = $('proxyUrl').value.trim();
const timeoutSec = parseInt($('timeout').value) || 120;
const maxTok = parseInt($('maxTok').value) || 4096;
if(!key) throw new Error('No API key');
if(!proxy) throw new Error('No proxy URL');
const isReasoning = model.startsWith('o1') || model.startsWith('o3');
const isNew = model.startsWith('gpt-5');
const body = { model, messages: [{role:'user', content: prompt}] };
if(!isReasoning) {
if(isNew) { body.max_completion_tokens = maxTok; }
else { body.max_tokens = maxTok; }
}
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), timeoutSec * 1000);
const t0 = performance.now();
let resp;
try {
resp = await fetch(proxy, {
method: 'POST',
headers: { 'Content-Type':'application/json', 'Authorization': `Bearer ${key}` },
body: JSON.stringify(body),
signal: controller.signal,
});
} catch(e) {
clearTimeout(timer);
if(e.name === 'AbortError') {
throw new Error(`TIMEOUT after ${timeoutSec}s — model likely still processing. Increase timeout or simplify prompt.`);
}
throw new Error(`Network error: ${e.message}`);
}
clearTimeout(timer);
const latency_ms = Math.round(performance.now() - t0);
let d;
try {
d = await resp.json();
} catch(e) {
throw new Error(`Non-JSON response (HTTP ${resp.status}) after ${latency_ms}ms — proxy may have timed out`);
}
if(d.error) {
const msg = d.error.message || JSON.stringify(d.error);
throw new Error(`API error: ${msg} (${latency_ms}ms)`);
}
const choice = d.choices?.[0];
const content = choice?.message?.content || '';
const finish_reason = choice?.finish_reason || 'unknown';
const prompt_tokens = d.usage?.prompt_tokens || 0;
const completion_tokens = d.usage?.completion_tokens || 0;
// Build warnings list
const warnings = [];
if(!content) {
warnings.push('EMPTY_RESPONSE: API returned no content');
}
if(finish_reason === 'length') {
warnings.push(`TRUNCATED: hit max_tokens (${maxTok}). Response is incomplete.`);
}
if(finish_reason !== 'stop' && finish_reason !== 'length' && content) {
warnings.push(`UNEXPECTED finish_reason="${finish_reason}"`);
}
if(!choice) {
warnings.push('NO_CHOICES: API response had no choices array');
}
return { content, finish_reason, latency_ms, prompt_tokens, completion_tokens, warnings };
}
const TEST_FIELDS = [
'recommend_adding_malaria_test','recommend_removing_malaria_test',
'recommend_adding_anemia_test','recommend_removing_anemia_test',
'recommend_adding_urinalysis','recommend_removing_urinalysis',
];
const EMPTY_TESTS = Object.fromEntries(TEST_FIELDS.map(f=>[f,0]));
function parseTests(text) {
try {
const c = text.replace(/```json\s*/g,'').replace(/```\s*/g,'').trim();
const o = JSON.parse(c);
const out = {};
TEST_FIELDS.forEach(f => { out[f] = o[f] ? 1 : 0; });
return out;
} catch { return {...EMPTY_TESTS}; }
}
// ── Pipeline ──
async function runPipeline() {
if(!DATA.length) return;
const mainP = $('mainPrompt').value;
const extP = $('extractPrompt').value;
const conc = parseInt($('conc').value)||3;
const debug = $('debugMode').checked;
const rows = debug ? DATA.slice(0,10) : DATA;
RESULTS = rows.map(r => ({
...r, llm_response:'', extract_raw:'', ...EMPTY_TESTS, error:'',
warnings:[], finish_reason:'', latency_ms:0, prompt_tokens:0, completion_tokens:0,
ext_finish_reason:'', ext_latency_ms:0,
}));
aborted = false;
$('runBtn').disabled=true; $('stopBtn').style.display='inline-block';
$('log').innerHTML=''; $('log').style.display='none'; $('resultsSection').style.display='none';
log(`Pipeline: ${rows.length} notes, main=${$('model').value}, extract=${$('extractModel').value}, conc=${conc}, timeout=${$('timeout').value}s, max_tokens=${$('maxTok').value}`, 'info');
let done = 0;
const total = rows.length * 2;
setProg(0, total);
const mainModel = $('model').value;
const extractModelVal = $('extractModel').value;
// Phase 1: Main LLM call
const q1 = rows.map((_,i)=>i);
const w1 = async () => {
while(q1.length && !aborted) {
const i = q1.shift(); if(i===undefined) break;
try {
const r = await callLLM(mainP.replace(/\{note\}/g, rows[i].note), mainModel);
RESULTS[i].llm_response = r.content;
RESULTS[i].finish_reason = r.finish_reason;
RESULTS[i].latency_ms = r.latency_ms;
RESULTS[i].prompt_tokens = r.prompt_tokens;
RESULTS[i].completion_tokens = r.completion_tokens;
RESULTS[i].warnings = r.warnings;
if(r.warnings.length) {
r.warnings.forEach(w => log(`[${i+1}/${rows.length}] ⚠ ${rows[i].id}: ${w}`, 'warn'));
}
if(!r.content) {
RESULTS[i].error = `Empty response (finish_reason=${r.finish_reason}, ${r.latency_ms}ms)`;
log(`[${i+1}/${rows.length}] ✗ ${rows[i].id}: Empty response after ${r.latency_ms}ms (finish=${r.finish_reason}, prompt_tok=${r.prompt_tokens}, compl_tok=${r.completion_tokens})`, 'err');
} else {
const tag = r.finish_reason === 'length' ? '⚠ TRUNCATED' : '✓';
log(`[${i+1}/${rows.length}] ${tag} ${rows[i].id} (${r.latency_ms}ms, ${r.completion_tokens} tok, finish=${r.finish_reason})`, r.finish_reason === 'length' ? 'warn' : 'ok');
}
} catch(e) {
RESULTS[i].error = e.message;
log(`[${i+1}/${rows.length}] ✗ ${rows[i].id}: ${e.message}`, 'err');
}
done++; setProg(done, total);
}
};
await Promise.all(Array.from({length:Math.min(conc,rows.length)}, w1));
if(aborted){ finish('Stopped'); return; }
const emptyCount = RESULTS.filter(r => !r.llm_response && !r.error).length;
const truncCount = RESULTS.filter(r => r.finish_reason === 'length').length;
log(`Phase 1 done. ${emptyCount} empty responses, ${truncCount} truncated. Extracting tests with ${extractModelVal}...`, 'info');
// Phase 2: Extraction
const q2 = rows.map((_,i)=>i).filter(i => RESULTS[i].llm_response && !RESULTS[i].error);
const w2 = async () => {
while(q2.length && !aborted) {
const i = q2.shift(); if(i===undefined) break;
try {
const filled = extP.replace(/\{note\}/g,rows[i].note).replace(/\{feedback\}/g,RESULTS[i].llm_response);
const r = await callLLM(filled, extractModelVal);
RESULTS[i].extract_raw = r.content;
RESULTS[i].ext_finish_reason = r.finish_reason;
RESULTS[i].ext_latency_ms = r.latency_ms;
if(r.warnings.length) {
r.warnings.forEach(w => log(`[ext ${i+1}] ⚠ ${w}`, 'warn'));
RESULTS[i].warnings.push(...r.warnings.map(w => `[extract] ${w}`));
}
const p = parseTests(r.content);
Object.assign(RESULTS[i], p);
} catch(e) {
log(`[ext ${i+1}] ✗ ${e.message}`, 'err');
RESULTS[i].warnings.push(`[extract] ${e.message}`);
}
done++; setProg(done, total);
}
};
await Promise.all(Array.from({length:Math.min(conc,q2.length||1)}, w2));
finish(aborted ? 'Stopped' : 'Complete');
}
function finish(status) {
$('runBtn').disabled=false; $('stopBtn').style.display='none';
$('dlBtn').style.display = RESULTS.some(r=>r.llm_response) ? 'inline-block' : 'none';
$('statusText').textContent = status;
const ok = RESULTS.filter(r=>!r.error).length;
const errs = RESULTS.filter(r=>r.error).length;
const warns = RESULTS.filter(r=>r.warnings.length > 0).length;
const empty = RESULTS.filter(r=>!r.llm_response).length;
const trunc = RESULTS.filter(r=>r.finish_reason==='length').length;
log(`${status}. ${ok} succeeded, ${errs} errors, ${warns} with warnings, ${empty} empty, ${trunc} truncated.`, 'info');
renderResults();
}
function stopPipeline() { aborted=true; }
// ── Render ──
const FIELD_LABELS = {
recommend_adding_malaria_test: {label:'Add malaria', cls:'pill-r'},
recommend_removing_malaria_test: {label:'Remove malaria', cls:'pill-u'},
recommend_adding_anemia_test: {label:'Add anemia', cls:'pill-r'},
recommend_removing_anemia_test: {label:'Remove anemia', cls:'pill-u'},
recommend_adding_urinalysis: {label:'Add urinalysis', cls:'pill-r'},
recommend_removing_urinalysis: {label:'Remove urinalysis', cls:'pill-u'},
};
function statusColor(r) {
if(r.error) return 'rd';
if(r.warnings.length || r.finish_reason === 'length' || !r.llm_response) return 'or';
return 'gn';
}
function renderResults() {
$('resultsSection').style.display='block';
const ok = RESULTS.filter(r=>!r.error).length;
const errs = RESULTS.filter(r=>r.error).length;
const warns = RESULTS.filter(r=>r.warnings.length>0 && !r.error).length;
// Summary
let sh = '<div style="display:grid;grid-template-columns:1fr 80px 70px;font-size:12px;border:1px solid var(--bd);border-radius:6px;overflow:hidden">';
sh += '<div class="hdr">Recommendation</div><div class="hdr">Count</div><div class="hdr">% of Notes</div>';
TEST_FIELDS.forEach(f => {
const n = RESULTS.filter(r=>!r.error && r[f]===1).length;
const info = FIELD_LABELS[f];
const color = f.includes('adding') ? 'var(--gn)' : 'var(--rd)';
sh += `<div class="cell" style="color:${color}">${info.label}</div>`;
sh += `<div class="cell" style="font-weight:700">${n}/${ok}</div>`;
sh += `<div class="cell">${ok ? Math.round(n/ok*100) : 0}%</div>`;
});
sh += '</div>';
$('summaryGrid').innerHTML = sh;
$('resultStats').textContent = `${ok} ok, ${warns} warnings, ${errs} errors`;
// Per-note
let nh = '';
RESULTS.forEach((r,i) => {
const pills = TEST_FIELDS
.filter(f => r[f] === 1)
.map(f => `<span class="pill ${FIELD_LABELS[f].cls}">${FIELD_LABELS[f].label}</span>`)
.join('');
const sc = statusColor(r);
const statusPills = [];
if(r.finish_reason === 'length') statusPills.push('<span class="pill pill-w">TRUNCATED</span>');
if(!r.llm_response && !r.error) statusPills.push('<span class="pill pill-w">EMPTY</span>');
if(r.error) statusPills.push('<span class="pill pill-u">ERROR</span>');
nh += `<div class="card collapsible" style="border-left:3px solid var(--${sc})" onclick="this.querySelector('.detail').style.display=this.querySelector('.detail').style.display==='none'?'block':'none'">
<div class="row" style="justify-content:space-between">
<div class="row" style="flex:1;min-width:0;overflow:hidden">
<span style="font-weight:700;font-size:11px;flex-shrink:0">${esc(r.id)}</span>
<span style="font-size:11px;color:var(--tx2);overflow:hidden;text-overflow:ellipsis;white-space:nowrap">${esc(r.note.slice(0,65))}…</span>
</div>
<div class="row" style="flex-shrink:0">${statusPills.join('')}${pills}<span style="font-size:10px;color:var(--tx2);margin-left:4px">▶</span></div>
</div>
<div class="detail" style="display:none">
<div class="meta">
<span>latency: ${r.latency_ms}ms</span>
<span>finish: ${r.finish_reason || '—'}</span>
<span>tokens: ${r.prompt_tokens}→${r.completion_tokens}</span>
${r.ext_latency_ms ? `<span>ext: ${r.ext_latency_ms}ms (${r.ext_finish_reason})</span>` : ''}
</div>
${r.error ? `<div style="color:var(--rd);font-size:12px;margin-top:6px">Error: ${esc(r.error)}</div>` : ''}
${r.warnings.length ? `<div style="color:var(--or);font-size:11px;margin-top:4px">${r.warnings.map(w=>'⚠ '+esc(w)).join('<br>')}</div>` : ''}
<pre class="resp">${esc(r.llm_response || '(no response)')}</pre>
</div>
</div>`;
});
$('noteResults').innerHTML = nh;
$('resultsSection').scrollIntoView({behavior:'smooth'});
}
// ── Export ──
function exportResults() {
if(!RESULTS.length) return;
const model = $('model').value;
const extModel = $('extractModel').value;
const ws1 = XLSX.utils.json_to_sheet(RESULTS.map(r=>{
const row = {
assessment_id:r.id, CHW1_unassisted:r.note,
LLM_response:r.llm_response, extraction_json:r.extract_raw,
};
TEST_FIELDS.forEach(f => { row[f] = r[f]; });
row.finish_reason = r.finish_reason;
row.latency_ms = r.latency_ms;
row.prompt_tokens = r.prompt_tokens;
row.completion_tokens = r.completion_tokens;
row.warnings = r.warnings.join('; ');
row.error = r.error;
return row;
}));
const ok=RESULTS.filter(r=>!r.error).length;
const ws2 = XLSX.utils.json_to_sheet(
TEST_FIELDS.map(f => ({
recommendation: FIELD_LABELS[f].label,
count: RESULTS.filter(r=>!r.error && r[f]===1).length,
total: ok,
pct: (ok ? (RESULTS.filter(r=>!r.error && r[f]===1).length/ok*100).toFixed(1) : 0) + '%',
}))
);
const ws3 = XLSX.utils.json_to_sheet([
{param:'main_model',value:model},{param:'extraction_model',value:extModel},
{param:'notes',value:RESULTS.length},
{param:'errors',value:RESULTS.filter(r=>r.error).length},
{param:'empty_responses',value:RESULTS.filter(r=>!r.llm_response).length},
{param:'truncated',value:RESULTS.filter(r=>r.finish_reason==='length').length},
{param:'warnings',value:RESULTS.filter(r=>r.warnings.length>0).length},
{param:'timeout_sec',value:$('timeout').value},
{param:'max_tokens',value:$('maxTok').value},
{param:'main_prompt',value:$('mainPrompt').value},
{param:'extract_prompt',value:$('extractPrompt').value},
{param:'timestamp',value:new Date().toISOString()},
]);
const wb = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(wb,ws1,'Results');
XLSX.utils.book_append_sheet(wb,ws2,'Test Summary');
XLSX.utils.book_append_sheet(wb,ws3,'Config');
XLSX.writeFile(wb, `chw_results_${model}_${new Date().toISOString().slice(0,10)}.xlsx`);
}
</script>
</body>
</html>