File size: 14,192 Bytes
5bb7ffa
a8293d1
 
5bb7ffa
 
 
 
 
 
 
 
a8293d1
 
 
5bb7ffa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a8293d1
5bb7ffa
 
 
 
 
 
 
a46a122
5bb7ffa
 
 
a46a122
5bb7ffa
 
a8293d1
 
 
 
 
 
 
 
 
 
5bb7ffa
a8293d1
87e03d2
5bb7ffa
 
87e03d2
 
 
 
 
 
 
 
 
 
 
 
5bb7ffa
a8293d1
 
 
 
5bb7ffa
 
 
 
 
 
a8293d1
5bb7ffa
a8293d1
 
d36cf5b
 
a8293d1
 
 
5bb7ffa
a8293d1
 
 
 
 
 
 
 
 
 
5bb7ffa
 
a8293d1
 
5bb7ffa
a8293d1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5bb7ffa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { createEngine } from './engine.js';
import { search, webterminal, setSignal } from './tools.js';
import { TOOLS, MAX_TOOL_CALLS, FINAL_WARNING, firstPrompt, toolTurn, parseAssistant, typedArgs, extractAnswer, extractionPrompt, parseExtraction, EXTRACT_SAMPLING } from './agent.js';

const q = new URLSearchParams(location.search);
const local = (v) => (v && v.startsWith('/') && !v.startsWith('//') ? v : null);   // test hooks accept same-origin paths only
// bartowski's imatrix K-quant of allenai/DR-Tulu2-4B, used as published (no re-hosting)
const GGUF = local(q.get('gguf')) || 'https://huggingface.co/bartowski/allenai_DR-Tulu2-4B-GGUF/resolve/main/allenai_DR-Tulu2-4B-Q4_K_M.gguf';
const GGUF_BYTES = 2736583872;
const USE_GPU = q.get('gpu') !== '0';
const IM_END = '<|im_end|>';
const CTX = Number(q.get('ctx')) || 32768, MAX_NEW = 16384;      // context tokens wanted, and per assistant turn (upstream: 32768 per turn of a 262k context)
const LEAD_IN = 'Based on the sources I read, here is my final answer.\n\n';
const CONTEXT_WARNING = '[TOKEN BUDGET EXCEEDED] You are in the final 10% of the context budget. You should now do your best to compose the final answer.';   // upstream's wording (environment.py)
const EXAMPLES = [
  ['Who wrote the music for the 2017 Argentine film "Desire", and where was that composer born?', 'film composer'],
  ['What is the current world record for the men\'s 100 m freestyle in a 50 m pool, who holds it, and when was it set?', 'sports record'],
  ['Which open-weight language models above 100B parameters were released in the last six months, and who made them?', 'recent models'],
];

const $ = (id) => document.getElementById(id);
const ui = { form: $('ask'), q: $('q'), go: $('go'), stop: $('stop'), status: $('status'), bar: $('bar').firstElementChild, answer: $('answer'),
  short: $('short'), report: $('report'), trail: $('trail'), store: $('store'), wipe: $('wipe'), examples: $('examples') };
const mb = (b) => `${Math.round(b / 1e6)} MB`;
const tick = () => new Promise((r) => setTimeout(r, 0));
let aborted = false;

function status(text, frac = null, bad = false) {
  ui.status.textContent = text; ui.status.classList.toggle('bad', bad);
  if (frac !== null) ui.bar.style.width = `${Math.round(Math.max(0, Math.min(1, frac)) * 100)}%`;
}

// ---------------------------------------------------------------- model
let enginePromise = null;
const loadEngine = () => (enginePromise ||= (async () => {
  if (USE_GPU && !navigator.gpu) status('No WebGPU in this browser: running on the CPU (slow).', 0);
  const system = (await (await fetch('prompt.json')).json()).chat_template[0].content;
  if (window.__testEngine) { status('Model ready.', 1); return { engine: window.__testEngine, system }; }   // test hook: a stand-in engine
  const engine = await createEngine({ url: GGUF, nCtx: CTX, gpu: USE_GPU && !!navigator.gpu,
    onProgress: (loaded, total) => status(`Downloading the model: ${mb(loaded)} of ${mb(total || GGUF_BYTES)}, first time only`, loaded / (total || GGUF_BYTES)),
    onStatus: (t) => status(t) });
  status('Model ready.', 1);
  return { engine, system };
})().catch((e) => { enginePromise = null; throw e; }));

// ---------------------------------------------------------------- transcript
function el(tag, cls, text) { const e = document.createElement(tag); if (cls) e.className = cls; if (text !== undefined) e.textContent = text; return e; }

function stepCard(n) {
  const d = el('details', 'step live');
  const s = el('summary'); s.append(el('span', 'n', `${n}.`), el('span', 'tool', 'thinking…'), el('span', 'arg', ''));
  d.open = true; d.append(s); ui.trail.prepend(d);   // newest on top, open while it works; older steps stay collapsed below
  return { d, set(tool, arg) { s.children[1].textContent = tool; s.children[2].textContent = arg || ''; },
    think(text) { let t = d.querySelector('.think'); if (!t) { t = el('div', 'think'); d.append(t); } t.textContent = text; t.scrollTop = t.scrollHeight; },
    result(text) { d.querySelector('pre')?.remove(); d.append(el('pre', '', text)); d.classList.remove('live'); } };
  // (the card is closed by the research loop once its tool result is in)
}

// Text with clickable links, built from text nodes and <a> elements only (never innerHTML).
function linkify(node, text) {
  node.replaceChildren(); let last = 0;
  for (const m of text.matchAll(/\[([^\]\n]+)\]\((https?:\/\/[^\s)]+)\)|(https?:\/\/[^\s<>)\]"']+[^\s<>)\]"'.,;:!?])/g)) {
    node.append(text.slice(last, m.index));
    const a = el('a', '', m[1] || m[3]); a.href = m[2] || m[3]; a.target = '_blank'; a.rel = 'noopener noreferrer'; node.append(a);
    last = m.index + m[0].length;
  }
  node.append(text.slice(last));
}
function showAnswer(text, short) {
  ui.answer.hidden = false; ui.short.textContent = short || ''; linkify(ui.report, text.trim());
  ui.answer.scrollIntoView({ block: 'start' });                       // land on the start of the answer
}

// Belt and braces for iframes that swallow wheel scrolling (seen in the Space's embedded view): if a wheel turn did not move anything,
// scroll the page ourselves. An inner scroller (a step's output) that did take the wheel is left alone.
addEventListener('wheel', (e) => {
  if (e.ctrlKey || e.defaultPrevented) return;
  const page = document.body, inner = e.target.closest?.('pre, .think, #report'), b0 = page.scrollTop, i0 = inner ? inner.scrollTop : 0;
  requestAnimationFrame(() => requestAnimationFrame(() => {
    if (page.scrollTop !== b0 || (inner && inner.scrollTop !== i0)) return;
    const dy = e.deltaMode === 1 ? e.deltaY * 40 : e.deltaMode === 2 ? e.deltaY * page.clientHeight : e.deltaY, max = page.scrollHeight - page.clientHeight;
    if ((dy > 0 && b0 < max) || (dy < 0 && b0 > 0)) page.scrollTop = b0 + dy;
  }));
}, { passive: true });

// ---------------------------------------------------------------- tools (run in this page: tools.js)
async function callTool(name, args, signal) {
  setSignal(signal);
  try { return name === 'search' ? await search(args.query) : await webterminal(args.command); }
  catch (e) { if (e?.name === 'AbortError') throw e; return `Error: the tool failed (${e?.message || e}).`; }
}

// ---------------------------------------------------------------- the research loop
async function research(question) {
  aborted = false;
  ui.answer.hidden = true; ui.trail.replaceChildren();
  const ctl = new AbortController(); ui.stop.onclick = () => { aborted = true; ctl.abort(); };   // Stop works during the download, a generation and a tool call
  const { engine, system } = await loadEngine();
  if (aborted) { status('Stopped.', 0); return; }
  const nCtx = Math.min(CTX, engine.nCtx || CTX), RESERVE = Math.min(6000, Math.floor(nCtx * 0.2));   // room kept free for the final report
  const today = q.get('date') === '0' ? '' : `\n\nToday's date is ${new Date().toLocaleDateString('en-CA')}.`;   // not in Ai2's prompt: without it the model assumes its training year and searches for stale news
  let transcript = firstPrompt(system + today, question), calls = 0, step = 0, t0 = performance.now(), genTokens = 0, ctxTokens = await engine.countTokens(transcript), wrapUp = false;

  // One streamed generation from `prompt` into `card`; returns the raw text and how it ended.
  async function generate(prompt, card, sampling) {
    let raw = '', finish = null, n = 0, tStart = 0, lastUi = 0;
    const used = prompt === transcript ? ctxTokens : await engine.countTokens(prompt), room = nCtx - used - 64;
    if (room < 128) return { raw: '', finish: 'length', n: 0 };
    for await (const part of engine.complete(prompt, { maxTokens: Math.min(MAX_NEW, room), signal: ctl.signal, sampling })) {
      if (part.progress?.total) status(`Reading the conversation… ${Math.round(100 * part.progress.processed / part.progress.total)}%`, part.progress.processed / part.progress.total);
      if (part.text) { if (!n) tStart = performance.now(); raw += part.text; n++; }
      if (part.finish) finish = part.finish;
      const now = performance.now();
      if (part.text && now - lastUi > 250) {
        lastUi = now; card.think(parseAssistant(raw).thinking);
        status(`Thinking… ${n} tokens · ${(n * 1000 / Math.max(1, now - tStart)).toFixed(1)} tokens/s · context ${(used + n).toLocaleString()} · tool calls ${calls}/${MAX_TOOL_CALLS}`);
      }
    }
    genTokens += n;
    return { raw, finish, n };
  }

  try {
    let final = null;                                                 // the report text once the model has written it
    for (;;) {
      step++;
      const card = stepCard(step);
      status(`Reading the conversation (${ctxTokens.toLocaleString()} tokens)…`, 0);
      const { raw } = await generate(transcript, card);
      const parsed = parseAssistant(raw);
      card.think(parsed.thinking);
      if (!(parsed.finished && parsed.calls.length && !wrapUp)) {     // a report: the model answered, ran out of room mid-thought, or kept calling tools after the final warning
        if (parsed.finished && !parsed.calls.length) final = parsed.content || parsed.thinking;
        else {                                                        // close the thinking ourselves and make it write the report (no more tools)
          status('Asking the model for its final report…');
          const more = await generate(transcript + parsed.thinking + '\n</think>\n\n' + LEAD_IN, card);   // the lead-in keeps it writing prose instead of calling another tool
          final = more.raw.split('<tool_call>')[0].replace(/<\/think>/g, '').trim() || parsed.thinking;
        }
      }
      if (final !== null) {
        card.d.remove();
        if (!final.trim()) final = 'The model ran out of room before it could write a report. Try a narrower question.';
        const volunteered = extractAnswer(final), report = final.replace(volunteered ? /```json[\s\S]*?```\s*$/ : /$^/, '');
        showAnswer(report, volunteered || '');
        status(`Done in ${Math.round((performance.now() - t0) / 1000)} s · ${calls} tool calls · ${genTokens.toLocaleString()} tokens generated. Extracting the short answer…`, 1);
        if (!volunteered && report.trim()) {                          // the extraction step of Ai2's grader, on the report
          try {
            let out = ''; for await (const part of engine.complete(extractionPrompt(question, report.slice(-12000)), { maxTokens: 400, signal: ctl.signal, sampling: EXTRACT_SAMPLING })) out += part.text;
            const short = parseExtraction(out); if (short) ui.short.textContent = short;
          } catch { /* the report alone is fine */ }
        }
        status(`Done in ${Math.round((performance.now() - t0) / 1000)} s · ${calls} tool calls · ${genTokens.toLocaleString()} tokens generated.`, 1);
        return;
      }
      const outputs = [];
      for (const c of parsed.calls) {
        const args = typedArgs(c);
        if (calls >= MAX_TOOL_CALLS) { outputs.push(`Tool not executed: tool-call budget exhausted. ${FINAL_WARNING}`); wrapUp = true; continue; }
        if (!args) { outputs.push(`Error: invalid call to ${c.name}. Available tools: ${TOOLS.map((t) => t.function.name).join(', ')}.`); continue; }
        calls++;
        card.set(c.name, c.name === 'search' ? args.query : args.command);
        status(`Tool call ${calls}/${MAX_TOOL_CALLS}: ${c.name}…`);
        let out = await callTool(c.name, args, ctl.signal);
        if (calls === MAX_TOOL_CALLS) { out += `\n\n${FINAL_WARNING}`; wrapUp = true; }
        card.result(out); outputs.push(out);
      }
      card.d.classList.remove('live'); card.d.open = false;
      let next = raw + IM_END + toolTurn(outputs);
      let nextTokens = await engine.countTokens(transcript + next);
      if (!wrapUp && nextTokens > nCtx * 0.8) {                      // upstream's token-budget warning, at 80% of what fits here
        outputs[outputs.length - 1] += `\n\n${CONTEXT_WARNING}`; wrapUp = true;
        next = raw + IM_END + toolTurn(outputs); nextTokens = await engine.countTokens(transcript + next);
      }
      if (nextTokens > nCtx - RESERVE) {                             // still too big: keep the model's turn, drop the tool text, and make it write the report
        wrapUp = true;
        next = raw + IM_END + toolTurn(outputs.map(() => `Tool output omitted: the context window is full. ${FINAL_WARNING}`));
        nextTokens = await engine.countTokens(transcript + next);
      }
      transcript += next; ctxTokens = nextTokens;
      await tick();
    }
  } catch (e) { if (aborted || e?.name === 'AbortError') { status('Stopped.', 0); return; } throw e; }
}

// ---------------------------------------------------------------- UI
ui.form.addEventListener('submit', async (e) => {
  e.preventDefault();
  const question = ui.q.value.trim();
  if (!question) return;
  ui.go.disabled = true; ui.stop.hidden = false;
  try { await research(question); } catch (err) { console.error(err); status(err?.message || String(err), null, true); }
  ui.go.disabled = false; ui.stop.hidden = true; storage();
});
ui.q.addEventListener('keydown', (e) => { if (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) ui.form.requestSubmit(); });
for (const [text, label] of EXAMPLES) {
  const b = el('button', '', label); b.type = 'button'; b.title = text;
  b.addEventListener('click', () => { ui.q.value = text; ui.q.focus(); });
  ui.examples.append(b);
}
$('repo').href = 'https://huggingface.co/bartowski/allenai_DR-Tulu2-4B-GGUF'; $('repo').textContent = 'bartowski/allenai_DR-Tulu2-4B-GGUF';
async function storage() { try { const e = await navigator.storage.estimate(); ui.store.textContent = `This site stores ${mb(e.usage || 0)} in this browser.`; } catch { ui.store.textContent = ''; } }
ui.wipe.addEventListener('click', async () => { try { const root = await navigator.storage.getDirectory(); for await (const [name] of root.entries()) await root.removeEntry(name, { recursive: true }); } catch { /* nothing cached */ } enginePromise = null; ui.store.textContent = 'Deleted. The model downloads again next time.'; });
storage();
window.__dr = { loadEngine, research };       // test hook