File size: 8,766 Bytes
5bb7ffa
 
 
 
 
a8293d1
 
5bb7ffa
 
 
 
 
 
a8293d1
5bb7ffa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a8293d1
5bb7ffa
 
 
a8293d1
 
 
 
 
 
 
5bb7ffa
a8293d1
 
 
5bb7ffa
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
// DR Tulu 2 agent logic, ported from allenai/dr-tulu2 (drtulu2-client): the general-web system prompt, the two tools
// (`search`, `webterminal`), the 150-call budget with its final warning, and Qwen3.5's XML tool-call format.
// Pure functions, no DOM and no model: tested in Node against the Python chat template (test_agent.mjs).

export const MAX_TOOL_CALLS = 150;
// prompts/final-warning.txt, the text every released eval/training config passes to the harness
export const FINAL_WARNING = 'IMPORTANT: This was your last allowed tool call. Do not call another tool. Answer the question now using the evidence you have gathered.';

// docstring-derived tool definitions, as the harness exposes them to the model
export const TOOLS = [
  { type: 'function', function: { name: 'search',
    description: 'Find candidate web sources for a query.\n\nUse this for discovery. The returned titles and snippets help select\ncandidate URLs, but must not be treated as verified source evidence.',
    parameters: { type: 'object', properties: {
      query: { type: 'string', description: 'Focused web search query.' } }, required: ['query'] } } },
  { type: 'function', function: { name: 'webterminal',
    description: 'Open a source URL and inspect its page contents with a terminal pipeline.\n\nUse this after search: a search snippet is only a lead. Inspect the\nsource itself with commands such as `browse <url> | rg -n -i pattern`.',
    parameters: { type: 'object', properties: {
      command: { type: 'string', description: 'A `browse <url>` command, optionally followed by a pipeline.' } }, required: ['command'] } } },
];

// Python's json.dumps(ensure_ascii=False): ", " and ": " separators (what the chat template's `tojson` prints)
export function pyJson(v) {
  if (v === null) return 'null';
  if (typeof v === 'string' || typeof v === 'number' || typeof v === 'boolean') return JSON.stringify(v);
  if (Array.isArray(v)) return '[' + v.map(pyJson).join(', ') + ']';
  return '{' + Object.entries(v).map(([k, x]) => JSON.stringify(k) + ': ' + pyJson(x)).join(', ') + '}';
}

const TOOL_FORMAT = '\n\nIf you choose to call a function ONLY reply in the following format with NO suffix:\n\n<tool_call>\n<function=example_function_name>\n<parameter=example_parameter_1>\nvalue_1\n</parameter>\n<parameter=example_parameter_2>\nThis is the value for the second parameter\nthat can span\nmultiple lines\n</parameter>\n</function>\n</tool_call>\n\n<IMPORTANT>\nReminder:\n- Function calls MUST follow the specified format: an inner <function=...></function> block must be nested within <tool_call></tool_call> XML tags\n- Required parameters MUST be specified\n- You may provide optional reasoning for your function call in natural language BEFORE the function call, but NOT after\n- If there is no function call available, answer the question like normal with your current knowledge and do not tell the user about function calls\n</IMPORTANT>';

// The first turn exactly as DR-Tulu2-4B's chat_template.jinja renders [system, user] with tools and the generation prompt.
export function firstPrompt(system, question, tools = TOOLS) {
  let s = '<|im_start|>system\n# Tools\n\nYou have access to the following functions:\n\n<tools>';
  for (const t of tools) s += '\n' + pyJson(t);
  s += '\n</tools>' + TOOL_FORMAT;
  if (system.trim()) s += '\n\n' + system.trim();
  s += '<|im_end|>\n';
  s += '<|im_start|>user\n' + question.trim() + '<|im_end|>\n';
  return s + '<|im_start|>assistant\n<think>\n';
}

// Text to append after the model's turn (its stop token <|im_end|> is fed separately): the tool responses as one user
// turn, then the next generation prompt. Same layout the template gives role="tool" messages.
export function toolTurn(outputs) {
  let s = '\n<|im_start|>user';
  for (const o of outputs) s += '\n<tool_response>\n' + o.trim() + '\n</tool_response>';
  return s + '<|im_end|>\n<|im_start|>assistant\n<think>\n';
}

// Split the model's raw text (the prompt already ended with "<think>\n") into thinking, visible text and tool calls.
// Tolerant like vLLM's qwen3_coder parser: a missing </tool_call>, </function> or </parameter> still yields the call.
export function parseAssistant(raw) {
  let thinking = '', rest = raw;
  const k = raw.indexOf('</think>');
  if (k >= 0) { thinking = raw.slice(0, k).trim(); rest = raw.slice(k + 8).replace(/<\/think>/g, ''); }
  const calls = [], chunks = rest.split('<tool_call>');
  for (const chunk of chunks.slice(1)) {
    const body = chunk.split('</tool_call>')[0];
    const f = body.match(/<function=([^>\n]+)>([\s\S]*?)(?:<\/function>|$)/);
    if (!f) continue;
    const args = {}, pre = /<parameter=([^>\n]+)>\n?([\s\S]*?)(?:\n?<\/parameter>|\n?(?=<parameter=)|\n?(?=<\/function>)|$)/g;
    let p;
    while ((p = pre.exec(f[2]))) { args[p[1].trim()] = p[2]; if (p[0] === '') pre.lastIndex++; }
    for (const k of Object.keys(args)) args[k] = args[k].replace(/\n$/, '');
    calls.push({ name: f[1].trim(), args });
  }
  const content = chunks[0].trim();
  return { thinking: k >= 0 ? thinking : raw.replace(/<tool_call>[\s\S]*$/, '').trim(), content, calls, finished: k >= 0 };
}

// Typed arguments per the schema (vLLM's parser does this for the harness), then the call as the backend expects it.
export function typedArgs(call) {
  const def = TOOLS.find((t) => t.function.name === call.name);
  if (!def) return null;
  const props = def.function.parameters.properties, out = {};
  for (const [k, v] of Object.entries(call.args)) {
    if (!props[k]) continue;
    out[k] = props[k].type === 'integer' ? parseInt(v, 10) : v;
  }
  for (const r of def.function.parameters.required) if (out[r] === undefined || Number.isNaN(out[r])) return null;
  return out;
}

// Optional {"answer": ...} fence (the model is not asked for one; used only if it volunteers it).
export function extractAnswer(text) {
  const all = [...text.matchAll(/```json\s*([\s\S]*?)```/g)];
  for (let i = all.length - 1; i >= 0; i--) { try { const a = JSON.parse(all[i][1]); if (a && (typeof a.answer === 'string' || typeof a.answer === 'number')) return String(a.answer); } catch { /* next */ } }
  return null;
}

// The short answer: the extraction step of Ai2's grader (BROWSECOMP_ANSWER_EXTRACTION_PROMPT, prompts/browsecomp-judge.json), run on the final report.
const EXTRACT = "I will give you a [question], and a verbose candidate [response] to this [question]. You are to extract the final predicted answer from the [response] to this [question].\n\n[question]: {question}\n\n[response]: {response}\n\nCarefully read the model's reasoning and identify the **final concluded exact answer**. Put 'None' if there is no concluded exact, final answer to extract from the response.\n\nYou should output in the following format:\n<explanation>brief explanation for why this is the final concluded exact answer in the response</explanation>\n<extracted_answer>the exact final answer extracted</extracted_answer>";
export const EXTRACT_SAMPLING = { temperature: 0.7, top_p: 0.8, top_k: 20, min_p: 0, presence_penalty: 1.5 };   // training/judging.py _stage
export function extractionPrompt(question, response) {
  return '<|im_start|>user\n' + EXTRACT.replace('{question}', () => question.trim()).replace('{response}', () => response.trim()) + '<|im_end|>\n<|im_start|>assistant\n<think>\n\n</think>\n\n';
}
export function parseExtraction(out) {
  const m = [...out.matchAll(/<extracted_answer>([\s\S]*?)<\/extracted_answer>/gi)].pop();
  const a = m ? m[1].trim() : '';
  return !a || /^none\.?$/i.test(a) ? null : a;
}

// vLLM-style sampler: temperature, top-k, top-p, presence penalty over the tokens generated so far.
export function sample(logits, seen, { temperature = 1.0, topK = 20, topP = 0.95, presence = 1.5 } = {}, rnd = Math.random) {
  const n = logits.length, work = new Float32Array(logits);
  if (presence) for (const t of seen) work[t] -= presence;
  // top-k candidates by partial selection
  const k = Math.min(topK > 0 ? topK : n, n), idx = new Int32Array(k), val = new Float32Array(k).fill(-Infinity);
  for (let i = 0; i < n; i++) {
    const x = work[i];
    if (x > val[k - 1]) {
      let j = k - 1;
      while (j > 0 && val[j - 1] < x) { val[j] = val[j - 1]; idx[j] = idx[j - 1]; j--; }
      val[j] = x; idx[j] = i;
    }
  }
  const mx = val[0], p = new Float64Array(k);
  let sum = 0;
  for (let i = 0; i < k; i++) { p[i] = Math.exp((val[i] - mx) / temperature); sum += p[i]; }
  let cut = k, acc = 0;
  for (let i = 0; i < k; i++) { acc += p[i] / sum; if (acc >= topP) { cut = i + 1; break; } }
  let tot = 0; for (let i = 0; i < cut; i++) tot += p[i];
  let r = rnd() * tot;
  for (let i = 0; i < cut; i++) { r -= p[i]; if (r <= 0) return idx[i]; }
  return idx[cut - 1];
}