Spaces:
Running

tool-research-v4 / renderers.js
evalstate's picture
evalstate HF Staff
Launch v4 scrollable interactive explainer (Responses, Messages & Chat Completions)
eae7b5f verified
Raw History Blame Contribute Delete
73.5 kB
// Real browser/Node ES module renderers for all 13 open-weight tool-calling dialects. import { Template } from "./vendor/jinja.js"; import { REPORT_DATA } from "./data.js"; const MODELS_BY_KEY = new Map(REPORT_DATA.models.map((m) => [m.key, m])); const TEMPLATE_CACHE = new Map(); const TOKEN_REGEX_CACHE = new Map(); const PATH_MAP_BY_TOOLS = new WeakMap(); function getModel(modelKey) { const m = MODELS_BY_KEY.get(modelKey); if (!m) throw new Error(`Unknown modelKey: ${modelKey}`); return m; } function getCompiledTemplate(modelKey) { let tmpl = TEMPLATE_CACHE.get(modelKey); if (!tmpl) { const m = getModel(modelKey); tmpl = new Template(m.chatTemplate); TEMPLATE_CACHE.set(modelKey, tmpl); } return tmpl; } function escapeRegex(s) { return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); } function getSpecialTokenRegex(modelKey) { let entry = TOKEN_REGEX_CACHE.get(modelKey); if (!entry) { const m = getModel(modelKey); const toks = Object.keys(m.specialTokens || {}) .filter((t) => t.length > 0) .sort((a, b) => b.length - a.length); const re = toks.length ? new RegExp(toks.map(escapeRegex).join("|"), "g") : null; entry = { re, map: m.specialTokens || {} }; TOKEN_REGEX_CACHE.set(modelKey, entry); } return entry; } function tokenizeSpecials(modelKey, text, extraProps = null) { if (!text) return []; const { re, map } = getSpecialTokenRegex(modelKey); if (!re) { return [extraProps ? { k: "t", text, ...extraProps } : { k: "t", text }]; } const out = []; re.lastIndex = 0; let last = 0; let m; while ((m = re.exec(text)) !== null) { if (m.index > last) { const chunk = text.slice(last, m.index); out.push(extraProps ? { k: "t", text: chunk, ...extraProps } : { k: "t", text: chunk }); } const tokText = m[0]; const tokId = Object.prototype.hasOwnProperty.call(map, tokText) ? map[tokText] : null; out.push( extraProps ? { k: "tok", text: tokText, tokenId: tokId, ...extraProps } : { k: "tok", text: tokText, tokenId: tokId } ); last = m.index + tokText.length; } if (last < text.length) { const tail = text.slice(last); out.push(extraProps ? { k: "t", text: tail, ...extraProps } : { k: "t", text: tail }); } return out; } // ============================================================================= // 1. normalizeToolsInput(parsedJson) // ============================================================================= export function normalizeToolsInput(parsedJson) { let rawList; let wrapperPrefix = ""; let wasSingleObject = false; if (Array.isArray(parsedJson)) { rawList = parsedJson; } else if (parsedJson && typeof parsedJson === "object") { if (Array.isArray(parsedJson.tools)) { rawList = parsedJson.tools; wrapperPrefix = "tools."; } else if (parsedJson.type === "function" || parsedJson.function || parsedJson.inputSchema || parsedJson.input_schema || parsedJson.name) { rawList = [parsedJson]; wasSingleObject = true; } else { throw new Error("Expected an array of tools, a { tools: [...] } object, or a single tool definition."); } } else { throw new Error("Tools JSON must be an array or object."); } let inputFormat = "openai"; const pathPrefixMap = []; const tools = rawList.map((item, idx) => { const itemPrefix = wasSingleObject ? "" : `${wrapperPrefix}${idx}.`; if (item && typeof item === "object" && item.type === "function" && item.function && typeof item.function === "object") { pathPrefixMap.push({ openaiPrefix: `${idx}.function.`, editorPrefix: `${itemPrefix}function.`, paramsOpenai: `${idx}.function.parameters`, paramsEditor: `${itemPrefix}function.parameters`, }); return item; } if (item && typeof item === "object" && "input_schema" in item) { inputFormat = "messages"; pathPrefixMap.push({ openaiPrefix: `${idx}.function.`, editorPrefix: itemPrefix, paramsOpenai: `${idx}.function.parameters`, paramsEditor: `${itemPrefix}input_schema`, }); const fn = { name: item.name || `tool_${idx}`, description: item.description || "", parameters: item.input_schema || { type: "object", properties: {} }, }; return { type: "function", function: fn }; } if (item && typeof item === "object" && ("inputSchema" in item || ("name" in item && !("function" in item)))) { inputFormat = "mcp"; pathPrefixMap.push({ openaiPrefix: `${idx}.function.`, editorPrefix: itemPrefix, paramsOpenai: `${idx}.function.parameters`, paramsEditor: `${itemPrefix}inputSchema`, }); const fn = { name: item.name || `tool_${idx}`, description: item.description || "", parameters: item.inputSchema || item.parameters || { type: "object", properties: {} }, }; return { type: "function", function: fn }; } throw new Error(`Tool at index ${idx} is not in OpenAI, Messages, or MCP format.`); }); PATH_MAP_BY_TOOLS.set(tools, pathPrefixMap); return { tools, inputFormat, pathPrefixMap }; } function mapPathToEditor(tools, openaiPath) { const maps = PATH_MAP_BY_TOOLS.get(tools); if (!maps || !openaiPath) return openaiPath; for (const m of maps) { if (openaiPath === m.paramsOpenai) return m.paramsEditor; if (openaiPath.startsWith(m.paramsOpenai + ".")) { return m.paramsEditor + openaiPath.slice(m.paramsOpenai.length); } if (openaiPath.startsWith(m.openaiPrefix)) { return m.editorPrefix + openaiPath.slice(m.openaiPrefix.length); } } return openaiPath; } // ============================================================================= // 2A. Kimi-K2.6 JS port of moonshotai/Kimi-K2.6/tool_declaration_ts.py // ============================================================================= const TS_INDENT = " "; const TS_FIELD_DELIM = ",\n"; function pyRepr(val) { if (typeof val === "boolean") return val ? "True" : "False"; if (val === null || val === undefined) return "None"; if (typeof val === "number") return String(val); return JSON.stringify(val); } function formatTsDescription(description, indent = "") { return String(description) .split("\n") .map((line) => (line ? `${indent}// ${line}` : "")) .join("\n"); } function formatDocstring(node, indent) { const lines = []; if (node.description) { lines.push(formatTsDescription(node.description, indent)); } const cKeys = Object.keys(node.constraints || {}).sort(); if (cKeys.length > 0) { const cStr = cKeys.map((k) => `${k}: ${node.constraints[k]}`).join(", "); lines.push(`${indent}// ${cStr}`); } return lines.map((x) => x + "\n").join(""); } function createRegistry() { return { definitions: {}, hasSelfRef: false, registerDefinitions(defs) { if (!defs) return; for (const [k, v] of Object.entries(defs)) { this.definitions[k] = v; } }, resolveRef(ref) { if (ref === "#") { this.hasSelfRef = true; return { $self_ref: true }; } if (ref.startsWith("#/$defs/")) { const defName = ref.split("/").pop(); if (!(defName in this.definitions)) throw new Error(`Reference not found: ${ref}`); return this.definitions[defName]; } throw new Error(`Unsupported reference format: ${ref}`); }, }; } function extractConstraints(extraProps, allowedKeys) { const out = {}; if (!extraProps || typeof extraProps !== "object") return out; for (const k of allowedKeys) { if (Object.prototype.hasOwnProperty.call(extraProps, k)) { out[k] = extraProps[k]; } } return out; } function parseK2ParamType(schema, registry) { if (typeof schema === "boolean") { return { kind: "scalar", type: schema ? "any" : "null", description: "", constraints: {}, }; } if (!schema || typeof schema !== "object") { return { kind: "scalar", type: "any", description: "", constraints: {} }; } if ("$ref" in schema && registry) { const resolved = registry.resolveRef(schema.$ref); const isSelfRef = Boolean(resolved.$self_ref); return { kind: "ref", refName: isSelfRef ? "parameters" : schema.$ref.split("/").pop(), isSelfRef, description: schema.description || "", constraints: {}, }; } if ("anyOf" in schema) { return { kind: "anyOf", types: schema.anyOf.map((t) => parseK2ParamType(t, registry)), description: schema.description || "", constraints: {}, }; } if ("enum" in schema) { return { kind: "enum", enumVals: schema.enum, description: schema.description || "", constraints: {}, }; } if ("type" in schema) { const typ = schema.type; if (Array.isArray(typ)) { const mapping = { string: "string", number: "number", integer: "number", boolean: "boolean", null: "null", object: "{}", array: "Array<any>", }; return { kind: "union", types: typ.map((t) => mapping[t] || t), description: schema.description || "", constraints: {}, }; } if (typ === "object") { return parseK2ObjectType(schema, registry); } if (typ === "array") { const item = schema.items ? parseK2ParamType(schema.items, registry) : { kind: "scalar", type: "any", description: "", constraints: {} }; return { kind: "array", item, description: schema.description || "", constraints: extractConstraints(schema, ["minItems", "maxItems"]), }; } const allowed = typ === "string" ? ["maxLength", "minLength", "pattern"] : typ === "number" || typ === "integer" ? ["maximum", "minimum"] : []; return { kind: "scalar", type: typ, description: schema.description || "", constraints: extractConstraints(schema, allowed), }; } if (Object.keys(schema).length === 0) { return { kind: "scalar", type: "any", description: "", constraints: {} }; } // Fallback for schemaless objects with properties if ("properties" in schema) { return parseK2ObjectType(schema, registry); } return { kind: "scalar", type: "any", description: schema.description || "", constraints: {} }; } function parseK2ObjectType(schema, registry) { const node = { kind: "object", description: (schema && schema.description) || "", constraints: {}, properties: [], additionalProperties: undefined, }; if (!schema || typeof schema !== "object") return node; if (schema.$defs && registry) { registry.registerDefinitions(schema.$defs); } if ("additionalProperties" in schema) { const ap = schema.additionalProperties; if (ap && typeof ap === "object") { node.additionalProperties = parseK2ParamType(ap, registry); } else { node.additionalProperties = ap; } } if (!schema.properties || typeof schema.properties !== "object") return node; const reqSet = new Set(Array.isArray(schema.required) ? schema.required : []); node.properties = Object.entries(schema.properties).map(([name, prop]) => ({ name, type: parseK2ParamType(prop, registry), optional: !reqSet.has(name), defaultVal: prop && typeof prop === "object" && "default" in prop ? prop.default : undefined, })); return node; } function renderK2Param(param, indent = "") { let comments = formatDocstring(param.type, indent); if (param.defaultVal !== undefined && param.defaultVal !== null) { const defaultRepr = typeof param.defaultVal === "number" || typeof param.defaultVal === "boolean" ? pyRepr(param.defaultVal) : JSON.stringify(param.defaultVal); comments += `${indent}// Default: ${defaultRepr}\n`; } return `${comments}${indent}${param.name}${param.optional ? "?" : ""}: ${renderK2Type(param.type, indent)}`; } function renderK2Type(node, indent = "") { switch (node.kind) { case "scalar": return node.type === "integer" ? "number" : node.type; case "ref": return node.refName; case "enum": return node.enumVals .map((e) => (typeof e === "string" ? `"${e}"` : pyRepr(e))) .join(" | "); case "anyOf": return node.types.map((t) => renderK2Type(t, indent)).join(" | "); case "union": return node.types.join(" | "); case "array": { const itemDoc = formatDocstring(node.item, indent + TS_INDENT); if (itemDoc) { return `Array<\n${itemDoc}${indent}${TS_INDENT}${renderK2Type(node.item, indent + TS_INDENT)}\n${indent}>`; } return `Array<${renderK2Type(node.item, indent)}>`; } case "object": { const reqParams = node.properties.filter((p) => !p.optional).sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0)); const optParams = node.properties.filter((p) => p.optional).sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0)); const allParams = [...reqParams, ...optParams]; const paramStrs = allParams.map((p) => renderK2Param(p, indent + TS_INDENT)); if (node.additionalProperties !== undefined && node.additionalProperties !== null) { let apStr = "any"; if (node.additionalProperties === true) apStr = "any"; else if (node.additionalProperties === false) apStr = "never"; else if (typeof node.additionalProperties === "object") { apStr = renderK2Type(node.additionalProperties, indent + TS_INDENT); } paramStrs.push(`${indent + TS_INDENT}[k: string]: ${apStr}`); } if (paramStrs.length === 0) return "{}"; const inner = `\n${paramStrs.join(TS_FIELD_DELIM)}\n`; return `{${inner}${indent}}`; } default: return "any"; } } function encodeToolsToTypescriptStyle(tools) { if (!tools || !tools.length) return ""; const functions = []; for (const tool of tools) { if (tool && tool.type === "function" && tool.function) { const fn = tool.function; const registry = createRegistry(); const parsed = parseK2ObjectType(fn.parameters || {}, registry); const interfaces = []; let rootInterfaceName = null; if (registry.hasSelfRef) { rootInterfaceName = "parameters"; const pStr = parsed.properties.map((p) => renderK2Param(p, TS_INDENT)).join(TS_FIELD_DELIM); const body = pStr ? `\n${pStr}\n` : ""; interfaces.push(`interface ${rootInterfaceName} {${body}}`); } for (const [defName, defSchema] of Object.entries(registry.definitions)) { const objType = parseK2ParamType(defSchema, registry); const pStr = renderK2Type(objType, ""); const descPart = defSchema && defSchema.description ? formatTsDescription(defSchema.description) + "\n" : ""; interfaces.push(`${descPart}interface ${defName} ${pStr}`); } const interfaceStr = interfaces.join("\n"); const fnName = fn.name || "function"; const typeDef = rootInterfaceName ? `type ${fnName} = (_: ${rootInterfaceName}) => any;` : `type ${fnName} = (_: ${renderK2Type(parsed, "")}) => any;`; const descStr = fn.description ? formatTsDescription(fn.description) : ""; functions.push([interfaceStr, descStr, typeDef].filter(Boolean).join("\n")); } } if (!functions.length) return ""; return `# Tools\n\n## functions\nnamespace functions {\n${functions.join("\n")}\n}\n`; } // ============================================================================= // 2B. Kimi-K3.1-Pro JS port of moonshotai/Kimi-K3.1-Pro/encoding_k3.py // ============================================================================= const K3_OPEN = "<|open|>"; const K3_CLOSE = "<|close|>"; const K3_SEP = "<|sep|>"; const K3_END_MSG = "<|end_of_msg|>"; function k3EscapeAttr(val) { return String(val).replace(/&/g, "&amp;").replace(/"/g, "&quot;"); } function k3OpenTag(tag, attrs = []) { let out = K3_OPEN + tag; for (const [k, v] of attrs) { out += ` ${k}="${k3EscapeAttr(v)}"`; } return out + K3_SEP; } function k3CloseTag(tag) { return K3_CLOSE + tag + K3_SEP; } function pyJsonDumps(val, { compact = false, sortKeys = false } = {}) { const itemSep = compact ? "," : ", "; const keySep = compact ? ":" : ": "; if (val === null || val === undefined) return "null"; if (typeof val === "boolean" || typeof val === "number" || typeof val === "string") { return JSON.stringify(val); } if (Array.isArray(val)) { return "[" + val.map((x) => pyJsonDumps(x, { compact, sortKeys })).join(itemSep) + "]"; } if (typeof val === "object") { const keys = Object.keys(val); if (sortKeys) keys.sort(); const entries = []; for (const k of keys) { if (val[k] === undefined) continue; entries.push(JSON.stringify(k) + keySep + pyJsonDumps(val[k], { compact, sortKeys })); } return "{" + entries.join(itemSep) + "}"; } return JSON.stringify(val); } function deepSortDict(obj) { if (Array.isArray(obj)) return obj.map(deepSortDict); if (obj && typeof obj === "object") { const out = {}; for (const k of Object.keys(obj).sort()) { out[k] = deepSortDict(obj[k]); } return out; } return obj; } function k3XtmlType(val) { if (typeof val === "boolean") return "boolean"; if (val === null || val === undefined) return "null"; if (typeof val === "number") return "number"; if (typeof val === "string") return "string"; if (Array.isArray(val)) return "array"; return "object"; } function k3XtmlValue(val) { if (typeof val === "string") return val; return pyJsonDumps(val, { compact: false, sortKeys: false }); } function k3NormalizeArgs(rawArgs) { let parsed = rawArgs; if (typeof rawArgs === "string") { try { parsed = JSON.parse(rawArgs); } catch { return []; } } if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) { return Object.entries(parsed).map(([k, v]) => [k, k3XtmlType(v), k3XtmlValue(v)]); } return []; } function renderKimiK3Prompt(tools, messages, opts = {}) { const addGenerationPrompt = opts.addGenerationPrompt ?? true; const thinking = opts.thinking ?? true; const hasTools = Array.isArray(tools) && tools.length > 0; const parts = []; if (hasTools) { const body = "# Tools\nHere are the available tools, described in JSONSchema.\n\n```json\n" + pyJsonDumps(tools, { compact: true, sortKeys: true }) + "\n```"; parts.push(k3OpenTag("message", [["role", "system"], ["type", "tool-declare"]])); parts.push(body); parts.push(k3CloseTag("message")); parts.push(K3_END_MSG); } let lastToolCalls = null; let toolIndex = 0; for (const msg of messages || []) { const role = msg.role; if (role === "user") { const attrs = [["role", "user"]]; if (msg.name) attrs.push(["name", msg.name]); parts.push(k3OpenTag("message", attrs)); if (msg.content) parts.push(String(msg.content)); parts.push(k3CloseTag("message")); parts.push(K3_END_MSG); } else if (role === "system") { const attrs = [["role", "system"]]; if (msg.name) attrs.push(["name", msg.name]); parts.push(k3OpenTag("message", attrs)); if (msg.content) parts.push(String(msg.content)); parts.push(k3CloseTag("message")); parts.push(K3_END_MSG); } else if (role === "assistant") { lastToolCalls = msg.tool_calls || null; toolIndex = 0; const attrs = [["role", "assistant"]]; if (msg.name) attrs.push(["name", msg.name]); parts.push(k3OpenTag("message", attrs)); if (thinking) { parts.push(k3OpenTag("think")); const rc = msg.reasoning_content || msg.reasoning; if (rc !== undefined && rc !== null && String(rc) !== "") { parts.push(String(rc)); } parts.push(k3CloseTag("think")); } parts.push(k3OpenTag("response")); if (msg.content) parts.push(String(msg.content)); parts.push(k3CloseTag("response")); if (lastToolCalls && lastToolCalls.length) { parts.push(k3OpenTag("tools")); lastToolCalls.forEach((tc, i) => { const fn = tc.function || tc; parts.push(k3OpenTag("call", [["tool", fn.name], ["index", i + 1]])); const args = k3NormalizeArgs(fn.arguments); for (const [k, typ, txt] of args) { parts.push(k3OpenTag("argument", [["key", k], ["type", typ]])); parts.push(txt); parts.push(k3CloseTag("argument")); } parts.push(k3CloseTag("call")); }); parts.push(k3CloseTag("tools")); } parts.push(k3CloseTag("message")); parts.push(K3_END_MSG); } else if (role === "tool") { toolIndex += 1; let toolName = msg.tool || msg.name; if (!toolName && lastToolCalls && toolIndex <= lastToolCalls.length) { const tc = lastToolCalls[toolIndex - 1]; toolName = (tc.function || tc).name; } parts.push( k3OpenTag("message", [ ["role", "tool"], ["tool", toolName || "tool"], ["index", toolIndex], ]) ); if (msg.content !== undefined && msg.content !== null) { parts.push(typeof msg.content === "string" ? msg.content : JSON.stringify(msg.content)); } parts.push(k3CloseTag("message")); parts.push(K3_END_MSG); } } if (addGenerationPrompt) { parts.push(k3OpenTag("message", [["role", "assistant"]])); parts.push(k3OpenTag(thinking ? "think" : "response")); } return parts.join(""); } // ============================================================================= // 2. renderModelPrompt(modelKey, tools, messages, opts) // ============================================================================= export function renderModelPrompt(modelKey, tools, messages, opts = { addGenerationPrompt: true }) { const m = getModel(modelKey); const addGenerationPrompt = opts?.addGenerationPrompt ?? true; if (m.templateKind === "python-xtml") { return renderKimiK3Prompt(tools, messages, { addGenerationPrompt, ...opts }); } const tmpl = getCompiledTemplate(modelKey); const ctx = { messages, tools, add_generation_prompt: addGenerationPrompt, bos_token: m.bosToken || "", eos_token: m.eosToken || "", pad_token: m.padToken || "", unk_token: m.unkToken || "", }; if (m.templateKind === "jinja+ts" && tools && tools.length) { ctx.tools_ts_str = encodeToolsToTypescriptStyle(tools); } return tmpl.render(ctx); } // ============================================================================= // 3. renderAnnotatedPrompt(modelKey, tools, userPrompt) // ============================================================================= function splitRegionsRaw(modelKey, tools, rawPrompt, userPrompt) { // Locate exact user & generation-prompt boundaries via sentinel render // (immune to tool descriptions that equal userPrompt or contain role markers) const USER_SENTINEL = "__USER_TURN_SENTINEL_9f8a__"; let userIdx = -1; let userEnd = -1; let genStartAbs = rawPrompt.length; try { const sentMsgs = [{ role: "user", content: USER_SENTINEL }]; const pSentNoGen = renderModelPrompt(modelKey, tools, sentMsgs, { addGenerationPrompt: false }); const pSentYesGen = renderModelPrompt(modelKey, tools, sentMsgs, { addGenerationPrompt: true }); const sIdx = pSentNoGen.indexOf(USER_SENTINEL); if (sIdx >= 0) { const uLen = userPrompt ? userPrompt.length : 0; if (rawPrompt.slice(sIdx, sIdx + uLen) === (userPrompt || "")) { userIdx = sIdx; userEnd = sIdx + uLen; } let cp = 0; const lim = Math.min(pSentNoGen.length, pSentYesGen.length); while (cp < lim && pSentNoGen[cp] === pSentYesGen[cp]) cp++; const genLen = pSentYesGen.length - cp; if (genLen >= 0 && genLen <= rawPrompt.length) { genStartAbs = rawPrompt.length - genLen; } } } catch { // Fallback below if sentinel render fails } if (userIdx < 0 && userPrompt) { userIdx = rawPrompt.lastIndexOf(userPrompt); userEnd = userIdx >= 0 ? userIdx + userPrompt.length : -1; } // Helper to locate [start, end) of the schema block per model // Uses last match for closing delimiters so multi-tool blocks (e.g. gemma4) and // literal closing tags inside descriptions are spanned cleanly. function findSchemaBounds(head) { if (modelKey === "gemma4") { const firstOpen = head.indexOf("<|tool>"); const lastClose = head.lastIndexOf("<tool|>"); if (firstOpen >= 0 && lastClose > firstOpen + 7) { return [firstOpen + "<|tool>".length, lastClose]; } return null; } const patterns = { qwen38: [/<tools>\n?/, /<\/tools>/g], kimi26: [/# Tools\n/, /(?=<\|im_end\|>)/g], kimi31: [/```json\n/, /\n```/g], glm53: [/\n<tools>\n/, /\n<\/tools>/g], hy4: [/\n<tools>\n/, /\n<\/tools>/g], deepseek41: [/### Available Tool Schemas\n+/, /\n\nYou MUST strictly follow/g], inkling2: [/<\|content_xml\|>/, /(?=<\|end_message\|>)/g], gptoss: [/namespace functions \{/, /\} \/\/ namespace functions/g], mistral4: [/\[AVAILABLE_TOOLS\]/, /\[\/AVAILABLE_TOOLS\]/g], minimax31: [/<tools>\n?/, /<\/tools>/g], glimmer: [/\/\/ Tool metadata\n/, /\n\nHere's an example/g], beam: [/# Tools\n/, /(?=<\|end\|>)/g], }; const pair = patterns[modelKey]; if (!pair) return null; const mStart = head.match(pair[0]); if (!mStart) return null; const sStart = mStart.index + mStart[0].length; const rest = head.slice(sStart); let lastMatch = null; for (const m of rest.matchAll(pair[1])) { lastMatch = m; } if (!lastMatch) return null; const sEnd = sStart + lastMatch.index; if (sEnd <= sStart) return null; return [sStart, sEnd]; } // Locate where the user turn framing starts (just before userPrompt) function findUserTurnStart(beforeUser) { const userAnchors = [ "<|im_start|>user", "<|im_user|>", '<|open|>message role="user"', "<|user|>", "<|hy_start:opensource|>user", "<|User|>", "<|message_user|>", "<|start|>user", "<|turn>user", "[INST]", "]~b]user", ]; let best = -1; for (const a of userAnchors) { const idx = beforeUser.lastIndexOf(a); if (idx > best) best = idx; } return best >= 0 ? best : beforeUser.length; } const regions = []; const push = (kind, label, sub, text) => { if (text && text.length > 0) { regions.push({ kind, label, sub, rawText: text }); } }; if (userIdx < 0) { push("sys", "Rendered prompt", "full prompt", rawPrompt); return regions; } const beforeUser = rawPrompt.slice(0, userIdx); const userTurnStart = findUserTurnStart(beforeUser); const preUser = rawPrompt.slice(0, userTurnStart); const userHeader = rawPrompt.slice(userTurnStart, userIdx); const safeGenStart = Math.max(userEnd, Math.min(genStartAbs, rawPrompt.length)); const userTail = rawPrompt.slice(userEnd, safeGenStart); const genText = rawPrompt.slice(safeGenStart); const bounds = findSchemaBounds(preUser); if (bounds) { const [sStart, sEnd] = bounds; const beforeSchema = preUser.slice(0, sStart); const schemaText = preUser.slice(sStart, sEnd); const afterSchema = preUser.slice(sEnd); // Split beforeSchema into sys vs tmpl if there's a clear tool-instructions header const tmplSplit = beforeSchema.search(/(?=# Tools|## Tools|You have access to|You may call one or more|<tools>|\[AVAILABLE_TOOLS\]|<\|tool>|<\|im_system\|>tool_declare|<\|message_system\|>tool_declare|<\|open\|>message role="system" type="tool-declare")/); if (tmplSplit > 0) { push("sys", "System prompt", "identity & settings", beforeSchema.slice(0, tmplSplit)); push("tmpl", "Tool framing", "template wrapper", beforeSchema.slice(tmplSplit)); } else if (beforeSchema.length > 0) { push("tmpl", "System & tool framing", "template header", beforeSchema); } push("schema", "Serialized tool schema", "from your tools JSON", schemaText); if (afterSchema.length > 0) { push("tmpl", "Tool instructions", "calling rules & close", afterSchema); } } else if (preUser.length > 0) { push("sys", "System prompt", "template header", preUser); } push("user", "User turn", "user message", userHeader + userPrompt + userTail); if (genText.length > 0) { push("gen", "Generation prompt", "assistant opener", genText); } return regions; } function deepClone(obj) { return JSON.parse(JSON.stringify(obj)); } function previewVal(v) { if (typeof v === "string") { return v.length > 36 ? `"${v.slice(0, 33)}…"` : `"${v}"`; } const s = JSON.stringify(v); return s.length > 40 ? s.slice(0, 37) + "…" : s; } function collectSchemaFields(tools) { const fields = []; if (!Array.isArray(tools)) return fields; function walkObjectProps(objSchema, basePath, baseKeys, shortPrefix) { if (!objSchema || typeof objSchema !== "object") return; if (objSchema.properties && typeof objSchema.properties === "object") { for (const [propName, propSchema] of Object.entries(objSchema.properties)) { const pPath = `${basePath}.properties.${propName}`; const pKeys = [...baseKeys, "properties", propName]; const pShort = shortPrefix ? `${shortPrefix}.${propName}` : propName; fields.push({ path: pPath, pathKeys: pKeys, shortPath: pShort, role: "param", kind: "prop_key", propName, objSchemaPath: basePath, objSchemaPathKeys: baseKeys, value: propName, valuePreview: propName, }); if (propSchema && typeof propSchema === "object") { if (propSchema.type !== undefined) { fields.push({ path: `${pPath}.type`, pathKeys: [...pKeys, "type"], shortPath: `${pShort}.type`, role: "cons", kind: "type", value: propSchema.type, valuePreview: previewVal(propSchema.type), }); } if (propSchema.description) { fields.push({ path: `${pPath}.description`, pathKeys: [...pKeys, "description"], shortPath: `${pShort}.description`, role: "desc", kind: "desc", value: propSchema.description, valuePreview: previewVal(propSchema.description), }); } if (Array.isArray(propSchema.enum)) { fields.push({ path: `${pPath}.enum`, pathKeys: [...pKeys, "enum"], shortPath: `${pShort}.enum`, role: "cons", kind: "enum", value: propSchema.enum, valuePreview: previewVal(propSchema.enum), }); } for (const ck of ["minimum", "maximum", "default", "minLength", "maxLength", "pattern"]) { if (Object.prototype.hasOwnProperty.call(propSchema, ck) && propSchema[ck] !== undefined) { fields.push({ path: `${pPath}.${ck}`, pathKeys: [...pKeys, ck], shortPath: `${pShort}.${ck}`, role: "cons", kind: ck, value: propSchema[ck], valuePreview: previewVal(propSchema[ck]), }); } } if (propSchema.type === "object" || propSchema.properties) { walkObjectProps(propSchema, pPath, pKeys, pShort); } if (propSchema.items && typeof propSchema.items === "object") { if (propSchema.items.properties) { walkObjectProps(propSchema.items, `${pPath}.items`, [...pKeys, "items"], `${pShort}[]`); } else if (propSchema.items.type) { fields.push({ path: `${pPath}.items.type`, pathKeys: [...pKeys, "items", "type"], shortPath: `${pShort}[].type`, role: "cons", kind: "type", value: propSchema.items.type, valuePreview: previewVal(propSchema.items.type), }); } } } } } if (Array.isArray(objSchema.required) && objSchema.required.length > 0) { fields.push({ path: `${basePath}.required`, pathKeys: [...baseKeys, "required"], shortPath: shortPrefix ? `${shortPrefix}.required` : "required", role: "cons", kind: "required", value: objSchema.required, valuePreview: previewVal(objSchema.required), }); } if (Object.prototype.hasOwnProperty.call(objSchema, "additionalProperties") && objSchema.additionalProperties !== undefined) { fields.push({ path: `${basePath}.additionalProperties`, pathKeys: [...baseKeys, "additionalProperties"], shortPath: shortPrefix ? `${shortPrefix}.additionalProperties` : "additionalProperties", role: "cons", kind: "additionalProperties", value: objSchema.additionalProperties, valuePreview: previewVal(objSchema.additionalProperties), }); } } tools.forEach((t, idx) => { const fn = t && t.function; if (!fn) return; const fBase = `${idx}.function`; const fKeys = [idx, "function"]; const prefix = tools.length > 1 ? `${fn.name || idx}.` : ""; if (fn.name) { fields.push({ path: `${fBase}.name`, pathKeys: [...fKeys, "name"], shortPath: `${prefix}name`, role: "name", kind: "fn_name", value: fn.name, valuePreview: previewVal(fn.name), }); } if (fn.description) { fields.push({ path: `${fBase}.description`, pathKeys: [...fKeys, "description"], shortPath: `${prefix}description`, role: "desc", kind: "desc", value: fn.description, valuePreview: previewVal(fn.description), }); } if (fn.parameters) { walkObjectProps(fn.parameters, `${fBase}.parameters`, [...fKeys, "parameters"], prefix ? prefix.slice(0, -1) : ""); } }); return fields; } function getByPath(root, pathOrKeys) { const parts = Array.isArray(pathOrKeys) ? pathOrKeys : String(pathOrKeys).split("."); let cur = root; for (const p of parts) { if (cur == null || typeof cur !== "object") return undefined; if (!Object.prototype.hasOwnProperty.call(cur, p)) return undefined; cur = cur[p]; } return cur; } function setByPath(root, pathOrKeys, val) { const parts = Array.isArray(pathOrKeys) ? pathOrKeys : String(pathOrKeys).split("."); if (!parts.length) return; let cur = root; for (let i = 0; i < parts.length - 1; i++) { if (cur == null || typeof cur !== "object") return; if (!Object.prototype.hasOwnProperty.call(cur, parts[i])) return; cur = cur[parts[i]]; } if (cur != null && typeof cur === "object") { const last = parts[parts.length - 1]; if (last !== "__proto__" && last !== "constructor" && last !== "prototype") { cur[last] = val; } } } function deleteByPath(root, pathOrKeys) { const parts = Array.isArray(pathOrKeys) ? pathOrKeys : String(pathOrKeys).split("."); if (!parts.length) return; let cur = root; for (let i = 0; i < parts.length - 1; i++) { if (cur == null || typeof cur !== "object") return; if (!Object.prototype.hasOwnProperty.call(cur, parts[i])) return; cur = cur[parts[i]]; } if (cur != null && typeof cur === "object") { const last = parts[parts.length - 1]; if (Object.prototype.hasOwnProperty.call(cur, last)) { delete cur[last]; } } } function diffSnippet(orig, perturbed) { let start = 0; const minLen = Math.min(orig.length, perturbed.length); while (start < minLen && orig[start] === perturbed[start]) start++; let endOrig = orig.length; let endPert = perturbed.length; while (endOrig > start && endPert > start && orig[endOrig - 1] === perturbed[endPert - 1]) { endOrig--; endPert--; } // Expand slightly to word/line boundary for readability const raw = orig.slice(start, endOrig).trim(); if (raw.length > 0 && raw.length <= 48) return raw; const ctxStart = Math.max(0, start - 10); const ctxEnd = Math.min(orig.length, Math.max(endOrig, start + 18) + 10); const snippet = orig.slice(ctxStart, ctxEnd).replace(/\n/g, " ").trim(); return snippet.length > 48 ? snippet.slice(0, 45) + "…" : snippet; } function diffRange(orig, perturbed) { let start = 0; const minLen = Math.min(orig.length, perturbed.length); while (start < minLen && orig[start] === perturbed[start]) start++; let endOrig = orig.length; let endPert = perturbed.length; while (endOrig > start && endPert > start && orig[endOrig - 1] === perturbed[endPert - 1]) { endOrig--; endPert--; } return [start, endOrig]; } function analyzeProvenance(modelKey, tools, userPrompt, rawPrompt, schemaText, schemaOffset) { const messages = [{ role: "user", content: userPrompt }]; const rawFields = collectSchemaFields(tools); const fieldOutcomes = []; const spans = []; // { start, end, path, role, how } relative to schemaText const renderSafe = (t) => { try { return renderModelPrompt(modelKey, t, messages, { addGenerationPrompt: true }); } catch { return null; } }; // Pass 1: Sentinel substitution for names, descriptions, and property keys const sentinelTools = deepClone(tools); const sentinelEntries = []; const fieldKey = (f) => JSON.stringify(f.pathKeys); // Process property keys deepest-first so renaming a parent key doesn't break child paths const propKeyFields = rawFields .filter((f) => f.kind === "prop_key") .sort((a, b) => b.pathKeys.length - a.pathKeys.length); rawFields.forEach((f, idx) => { if (f.kind === "fn_name") { const sentinel = `${f.value}__zq${idx}__`; setByPath(sentinelTools, f.pathKeys, sentinel); sentinelEntries.push({ field: f, sentinel, orig: String(f.value) }); } else if (f.kind === "desc") { const sentinel = `ZQDESC${idx}QZ`; setByPath(sentinelTools, f.pathKeys, sentinel); sentinelEntries.push({ field: f, sentinel, orig: String(f.value) }); } }); // Rename property keys in sentinelTools while preserving alphabetical order for (const f of propKeyFields) { const idx = rawFields.indexOf(f); const sentinel = `${f.propName}__zq${idx}__`; const obj = getByPath(sentinelTools, f.objSchemaPathKeys); if (obj && obj.properties && Object.prototype.hasOwnProperty.call(obj.properties, f.propName)) { const newProps = {}; for (const [k, v] of Object.entries(obj.properties)) { newProps[k === f.propName ? sentinel : k] = v; } obj.properties = newProps; if (Array.isArray(obj.required)) { obj.required = obj.required.map((r) => (r === f.propName ? sentinel : r)); } sentinelEntries.push({ field: f, sentinel, orig: f.propName }); } } const sentinelPrompt = renderSafe(sentinelTools); const foundByPath = new Map(); if (sentinelPrompt) { const usedPositions = new Set(); for (const entry of sentinelEntries) { const inSent = sentinelPrompt.indexOf(entry.sentinel); const fk = fieldKey(entry.field); if (inSent === -1) { foundByPath.set(fk, { status: "dropped", inPrompt: "—", note: "omitted by template" }); } else { // Locate exact original string in schemaText let pos = schemaText.indexOf(entry.orig); while (pos >= 0 && usedPositions.has(pos)) { pos = schemaText.indexOf(entry.orig, pos + 1); } if (pos >= 0) { usedPositions.add(pos); spans.push({ start: pos, end: pos + entry.orig.length, path: mapPathToEditor(tools, entry.field.path), role: entry.field.role, how: null, }); } const snippet = entry.orig.length > 44 ? entry.orig.slice(0, 41) + "…" : entry.orig; foundByPath.set(fk, { status: "kept", inPrompt: snippet, note: entry.field.kind === "desc" && schemaText.includes("// " + entry.orig.slice(0, 12)) ? "rendered as // comment" : "preserved in prompt", }); } } } // Pass 2: Ablation / perturbation for constraints & any field not resolved by sentinels for (const f of rawFields) { const fk = fieldKey(f); if (foundByPath.has(fk)) { const res = foundByPath.get(fk); fieldOutcomes.push({ path: mapPathToEditor(tools, f.path), shortPath: f.shortPath, role: f.role, valuePreview: f.valuePreview, inPrompt: res.inPrompt, status: res.status, note: res.note, }); continue; } const pertTools = deepClone(tools); if (f.kind === "type") { const alt = f.value === "string" ? "boolean" : "string"; setByPath(pertTools, f.pathKeys, alt); } else if (f.kind === "enum") { setByPath(pertTools, f.pathKeys, ["__zq_enum_probe__"]); } else if (f.kind === "required") { setByPath(pertTools, f.pathKeys, []); } else if (f.kind === "additionalProperties") { setByPath(pertTools, f.pathKeys, !f.value); } else { deleteByPath(pertTools, f.pathKeys); } const pertPrompt = renderSafe(pertTools); if (pertPrompt === null || pertPrompt === rawPrompt) { fieldOutcomes.push({ path: mapPathToEditor(tools, f.path), shortPath: f.shortPath, role: f.role, valuePreview: f.valuePreview, inPrompt: "—", status: "dropped", note: "omitted by template", }); continue; } // Prompt changed! Determine kept vs rewritten + exact span const [dStart, dEnd] = diffRange(rawPrompt, pertPrompt); const snippet = diffSnippet(rawPrompt, pertPrompt); const localStart = dStart - schemaOffset; const localEnd = dEnd - schemaOffset; let status = "kept"; let note = "serialized JSON"; let how = null; if (f.kind === "type") { const exactJson = `"type": "${f.value}"`; const compactJson = `"type":"${f.value}"`; if (schemaText.includes(exactJson) || schemaText.includes(compactJson)) { status = "kept"; note = "serialized JSON"; } else if (f.value === "integer" && snippet.includes("number")) { status = "rewritten"; note = "integer → number"; how = "integer → number"; } else if (snippet.includes(String(f.value).toUpperCase())) { status = "rewritten"; note = `${f.value} → ${String(f.value).toUpperCase()}`; how = note; } else { status = "rewritten"; note = `rendered as ${snippet}`; how = note; } } else if (f.kind === "required") { if (schemaText.includes('"required"')) { status = "kept"; note = "serialized JSON"; } else { status = "rewritten"; note = "required/optional syntax (?)"; how = "optional → ?"; } } else if (f.kind === "enum") { if (schemaText.includes('"enum"')) { status = "kept"; note = "serialized JSON"; } else if (snippet.includes("|")) { status = "rewritten"; note = "TS union type (|)"; how = "enum → union"; } else { status = "rewritten"; note = "template-formatted enum"; how = "enum rewritten"; } } else if (f.kind === "additionalProperties") { if (schemaText.includes('"additionalProperties"')) { status = "kept"; note = "serialized JSON"; } else if (snippet.includes("[k: string]")) { status = "rewritten"; note = "TS index signature"; how = "additionalProperties → [k: string]"; } else { status = "rewritten"; note = "template-formatted"; } } else { // minimum, maximum, default, etc. if (schemaText.includes(`"${f.kind}"`)) { status = "kept"; note = "serialized JSON"; } else { status = "rewritten"; note = `rendered as ${snippet}`; how = `${f.kind} → comment`; } } if (localStart >= 0 && localEnd > localStart && localEnd <= schemaText.length && localEnd - localStart <= 120) { spans.push({ start: localStart, end: localEnd, path: mapPathToEditor(tools, f.path), role: f.role, how, }); } fieldOutcomes.push({ path: mapPathToEditor(tools, f.path), shortPath: f.shortPath, role: f.role, valuePreview: f.valuePreview, inPrompt: snippet || "—", status, note, }); } return { fieldOutcomes, spans }; } function buildSchemaSegments(modelKey, schemaText, spans) { // Sort spans by start ascending, then shorter spans first; drop overlapping spans const sorted = [...spans] .filter((s) => s.start >= 0 && s.end > s.start && s.end <= schemaText.length) .sort((a, b) => a.start - b.start || a.end - b.end); const nonOverlapping = []; let cursor = 0; for (const sp of sorted) { if (sp.start >= cursor) { nonOverlapping.push(sp); cursor = sp.end; } } const segs = []; let pos = 0; for (const sp of nonOverlapping) { if (sp.start > pos) { segs.push(...tokenizeSpecials(modelKey, schemaText.slice(pos, sp.start))); } const seg = { k: "s", text: schemaText.slice(sp.start, sp.end), path: sp.path, role: sp.role, }; if (sp.how) seg.how = sp.how; segs.push(seg); pos = sp.end; } if (pos < schemaText.length) { segs.push(...tokenizeSpecials(modelKey, schemaText.slice(pos))); } return segs; } export function renderAnnotatedPrompt(modelKey, tools, userPrompt) { const messages = [{ role: "user", content: userPrompt }]; const rawPrompt = renderModelPrompt(modelKey, tools, messages, { addGenerationPrompt: true }); const rawRegions = splitRegionsRaw(modelKey, tools, rawPrompt, userPrompt); let schemaOffset = 0; let schemaText = ""; let running = 0; for (const r of rawRegions) { if (r.kind === "schema") { schemaOffset = running; schemaText = r.rawText; break; } running += r.rawText.length; } const { fieldOutcomes, spans } = schemaText ? analyzeProvenance(modelKey, tools, userPrompt, rawPrompt, schemaText, schemaOffset) : { fieldOutcomes: [], spans: [] }; let schemaChars = 0; let tracedSchemaChars = 0; let templateChars = 0; let userChars = 0; let specialTokenCount = 0; const regions = rawRegions.map((r) => { const segments = r.kind === "schema" ? buildSchemaSegments(modelKey, r.rawText, spans) : tokenizeSpecials(modelKey, r.rawText); if (r.kind === "schema") schemaChars += r.rawText.length; else if (r.kind === "user") userChars += r.rawText.length; else templateChars += r.rawText.length; for (const seg of segments) { if (seg.k === "tok") specialTokenCount++; if (seg.k === "s") tracedSchemaChars += seg.text.length; } return { kind: r.kind, label: r.label, sub: r.sub, segments, }; }); let keptCount = 0; let rewrittenCount = 0; let droppedCount = 0; for (const f of fieldOutcomes) { if (f.status === "kept") keptCount++; else if (f.status === "rewritten") rewrittenCount++; else if (f.status === "dropped") droppedCount++; } return { rawPrompt, regions, fields: fieldOutcomes, stats: { totalChars: rawPrompt.length, schemaOffset, schemaChars, tracedSchemaChars, templateChars, userChars, specialTokenCount, keptCount, rewrittenCount, droppedCount, }, }; } // ============================================================================= // 4. Live Argument Synthesis + renderToolReturnTurn // ============================================================================= function valueMatchesType(val, typ) { if (typ === "string") return typeof val === "string"; if (typ === "integer") return typeof val === "number" && Number.isInteger(val); if (typ === "number") return typeof val === "number" && Number.isFinite(val); if (typ === "boolean") return typeof val === "boolean"; if (typ === "null") return val === null; if (typ === "array") return Array.isArray(val); if (typ === "object") return val !== null && typeof val === "object" && !Array.isArray(val); return true; } function isValidForSchema(val, schema) { if (!schema || typeof schema !== "object") return true; if (Array.isArray(schema.enum)) { const vj = JSON.stringify(val); if (!schema.enum.some((e) => JSON.stringify(e) === vj)) return false; } if (schema.type !== undefined) { const types = Array.isArray(schema.type) ? schema.type : [schema.type]; if (types.length > 0 && !types.some((t) => valueMatchesType(val, t))) return false; } if (typeof val === "number") { if (typeof schema.minimum === "number" && val < schema.minimum) return false; if (typeof schema.maximum === "number" && val > schema.maximum) return false; if (typeof schema.exclusiveMinimum === "number" && val <= schema.exclusiveMinimum) return false; if (typeof schema.exclusiveMaximum === "number" && val >= schema.exclusiveMaximum) return false; } if (typeof val === "string") { if (typeof schema.minLength === "number" && val.length < schema.minLength) return false; if (typeof schema.maxLength === "number" && val.length > schema.maxLength) return false; } if (val && typeof val === "object" && !Array.isArray(val) && schema.properties) { for (const [k, propSch] of Object.entries(schema.properties)) { if (Object.prototype.hasOwnProperty.call(val, k) && !isValidForSchema(val[k], propSch)) { return false; } } } if (Array.isArray(val) && schema.items && typeof schema.items === "object") { for (const item of val) { if (!isValidForSchema(item, schema.items)) return false; } } return true; } function synthesizeValueForSchema(propName, propSchema, presetArgs) { if (!propSchema || typeof propSchema !== "object") { if (presetArgs && Object.prototype.hasOwnProperty.call(presetArgs, propName)) { return presetArgs[propName]; } return "sample"; } // Only reuse preset sampleArgs[propName] if it satisfies the live schema constraints if ( presetArgs && Object.prototype.hasOwnProperty.call(presetArgs, propName) && isValidForSchema(presetArgs[propName], propSchema) ) { return presetArgs[propName]; } if (propSchema.default !== undefined && isValidForSchema(propSchema.default, propSchema)) { return propSchema.default; } if (Array.isArray(propSchema.enum) && propSchema.enum.length > 0) { const validEnum = propSchema.enum.find((v) => isValidForSchema(v, propSchema)); return validEnum !== undefined ? validEnum : propSchema.enum[0]; } const typ = Array.isArray(propSchema.type) ? propSchema.type.find((t) => t !== "null") || "null" : propSchema.type; if (typ === "null") return null; if (typ === "boolean") return true; if (typ === "integer" || typ === "number") { const min = typeof propSchema.minimum === "number" ? propSchema.minimum : typeof propSchema.exclusiveMinimum === "number" ? propSchema.exclusiveMinimum + (typ === "integer" ? 1 : 0.5) : null; const max = typeof propSchema.maximum === "number" ? propSchema.maximum : typeof propSchema.exclusiveMaximum === "number" ? propSchema.exclusiveMaximum - (typ === "integer" ? 1 : 0.5) : null; let cand = 3; if (min !== null && cand < min) cand = min; if (max !== null && cand > max) cand = max; if (min !== null && max !== null && min <= max) { cand = Math.min(max, Math.max(min, cand)); } return typ === "integer" ? Math.trunc(cand) : cand; } if (typ === "array") { const itemVal = synthesizeValueForSchema(`${propName}_item`, propSchema.items || { type: "string" }, null); return [itemVal]; } if (typ === "object" || propSchema.properties) { const nestedPreset = presetArgs && Object.prototype.hasOwnProperty.call(presetArgs, propName) && presetArgs[propName] && typeof presetArgs[propName] === "object" && !Array.isArray(presetArgs[propName]) ? presetArgs[propName] : null; const out = {}; for (const [k, v] of Object.entries(propSchema.properties || {})) { out[k] = synthesizeValueForSchema(k, v, nestedPreset); } return out; } let s = `example_${propName}`; if (typeof propSchema.maxLength === "number" && s.length > propSchema.maxLength) { s = s.slice(0, Math.max(0, propSchema.maxLength)); } return s; } function synthesizeArgsForTool(tool, presetId = "search") { const fn = tool?.function || {}; const params = fn.parameters || {}; const props = params.properties || {}; const preset = REPORT_DATA.presets[presetId] || REPORT_DATA.presets.search; const presetArgs = preset?.sampleArgs || {}; const args = {}; for (const [k, schema] of Object.entries(props)) { args[k] = synthesizeValueForSchema(k, schema, presetArgs); } return args; } function commonPrefixLen(a, b) { let i = 0; const lim = Math.min(a.length, b.length); while (i < lim && a[i] === b[i]) i++; return i; } export function renderToolReturnTurn( modelKey, tools, userPrompt, sampleArgsOverride = null, sampleResultOverride = null ) { const fn = tools?.[0]?.function || { name: "search_models", parameters: { properties: {} } }; const fnName = fn.name || "search_models"; const presetId = fnName === "create_ticket" ? "ticket" : "search"; const preset = REPORT_DATA.presets[presetId] || REPORT_DATA.presets.search; const presetFnName = preset?.tools?.[0]?.function?.name; const argsObj = sampleArgsOverride !== null && sampleArgsOverride !== undefined ? sampleArgsOverride : synthesizeArgsForTool(tools?.[0], presetId); let resultObj; if (sampleResultOverride !== null && sampleResultOverride !== undefined) { resultObj = sampleResultOverride; } else if (fnName === presetFnName) { resultObj = preset.sampleToolResult; } else { resultObj = { ok: true, tool: fnName }; } const resultStr = typeof resultObj === "string" ? resultObj : JSON.stringify(resultObj); const toolCallId = modelKey === "kimi26" ? `functions.${fnName}:0` : "call_1"; const messages = [ { role: "user", content: userPrompt }, { role: "assistant", content: "", tool_calls: [ { id: toolCallId, type: "function", function: { name: fnName, arguments: argsObj, }, }, ], }, { role: "tool", tool_call_id: toolCallId, name: fnName, content: resultStr, }, ]; // Differential template rendering locates exact assistant_call / tool_response / next_gen // boundaries without scanning untrusted argument or tool-result strings for global markers. const p0 = renderModelPrompt(modelKey, tools, messages.slice(0, 1), { addGenerationPrompt: false }); const p1 = renderModelPrompt(modelKey, tools, messages.slice(0, 2), { addGenerationPrompt: false }); const p2 = renderModelPrompt(modelKey, tools, messages, { addGenerationPrompt: false }); const rawFullPrompt = renderModelPrompt(modelKey, tools, messages, { addGenerationPrompt: true }); const cp0 = commonPrefixLen(p0, rawFullPrompt); const cp1 = Math.max(cp0, commonPrefixLen(p1, rawFullPrompt)); const cp2 = Math.max(cp1, commonPrefixLen(p2, rawFullPrompt)); const turnDeltaText = rawFullPrompt.slice(cp0); const assistantPart = rawFullPrompt.slice(cp0, cp1); const toolRespPart = rawFullPrompt.slice(cp1, cp2); const nextGenPart = rawFullPrompt.slice(cp2); const segments = []; if (assistantPart.length > 0) { segments.push(...tokenizeSpecials(modelKey, assistantPart, { part: "assistant_call" })); } if (toolRespPart.length > 0) { segments.push(...tokenizeSpecials(modelKey, toolRespPart, { part: "tool_response" })); } if (nextGenPart.length > 0) { segments.push(...tokenizeSpecials(modelKey, nextGenPart, { part: "next_gen" })); } return { rawFullPrompt, turnDeltaText, segments, }; } // ============================================================================= // 5. buildModelReply(modelKey, tools, replyMode, presetId) // ============================================================================= function formatGemma4Value(v) { if (typeof v === "string") return `<|"|>${v}<|"|>`; if (typeof v === "boolean" || typeof v === "number") return String(v); if (Array.isArray(v)) return `[${v.map(formatGemma4Value).join(",")}]`; if (v && typeof v === "object") { return `{${Object.keys(v).sort().map((k) => `${k}:${formatGemma4Value(v[k])}`).join(",")}}`; } return "null"; } function formatMinimaxXml(key, val, ns = "]<]minimax[>[") { if (val === null || val === undefined) { return `${ns}<${key}>${ns}</${key}>`; } if (typeof val === "boolean") { return `${ns}<${key}>${JSON.stringify(val)}${ns}</${key}>`; } if (Array.isArray(val)) { const items = val.map((item) => formatMinimaxXml("item", item, ns)).join(""); return `${ns}<${key}>${items}${ns}</${key}>`; } if (typeof val === "object") { const inner = Object.entries(val) .filter(([, v]) => v !== null && v !== undefined) .map(([k, v]) => formatMinimaxXml(k, v, ns)) .join(""); return `${ns}<${key}>${inner}${ns}</${key}>`; } return `${ns}<${key}>${String(val)}${ns}</${key}>`; } export function buildModelReply(modelKey, tools, replyMode = "call", presetId = "search") { const m = getModel(modelKey); const sp = m.specialTokens || {}; const tokId = (s) => (Object.prototype.hasOwnProperty.call(sp, s) ? sp[s] : null); const preset = REPORT_DATA.presets[presetId] || REPORT_DATA.presets.search; const fn = tools?.[0]?.function || { name: "search_models", parameters: { properties: {} } }; const fnName = fn.name || "search_models"; const argsObj = synthesizeArgsForTool(tools?.[0], presetId); const argsJson = JSON.stringify(argsObj); const reasoning = `The user wants ${fnName}; I have all required parameters.`; const textReply = preset.textReply || "Here is the answer without calling a tool."; const pieces = []; const add = (text, kind, laneIdx, explicitTokId = undefined) => { const p = { text, kind, laneIdx }; if (explicitTokId !== undefined) p.tokenId = explicitTokId; else if (kind === "tok" || kind === "tok-call" || kind === "tok-eos") { p.tokenId = tokId(text); } pieces.push(p); }; const stopToken = replyMode === "call" ? m.stopTokenCall : m.stopTokenText; const stopTokenId = tokId(stopToken); if (replyMode === "text") { switch (modelKey) { case "gptoss": case "beam": add("<|channel|>", "tok", 0); add("analysis", "think", 0); add("<|message|>", "tok", 0); add(reasoning, "think", 0); add("<|end|>", "tok", 0); add("<|start|>", "tok", 1); add("assistant", "marker", 1); add("<|channel|>", "tok", 1); add("final", "marker", 1); add("<|message|>", "tok", 1); add(textReply, "text", 1); add(stopToken, "tok-eos", 2, stopTokenId); break; case "kimi31": add(reasoning, "think", 0); add("<|close|>", "tok", 0); add("think", "think", 0); add("<|sep|>", "tok", 0); add("<|open|>", "tok", 1); add("response", "marker", 1); add("<|sep|>", "tok", 1); add(textReply, "text", 1); add("<|close|>", "tok", 1); add("response", "marker", 1); add("<|sep|>", "tok", 1); add("<|close|>", "tok", 2); add("message", "marker", 2); add("<|sep|>", "tok", 2); add(stopToken, "tok-eos", 2, stopTokenId); break; case "gemma4": // Default non-thinking prompt already closes <|channel>thought\n<channel|> add(textReply, "text", 0); add(stopToken, "tok-eos", 1, stopTokenId); break; case "hy4": add(reasoning, "think", 0); add("</think:opensource>", "tok", 0); add(textReply, "text", 1); add(stopToken, "tok-eos", 2, stopTokenId); break; case "mistral4": add("[THINK]", "tok", 0); add(reasoning, "think", 0); add("[/THINK]", "tok", 0); add(textReply, "text", 1); add(stopToken, "tok-eos", 2, stopTokenId); break; case "minimax31": add("<mm:think>" + reasoning + "</mm:think>", "think", 0); add(textReply, "text", 1); add(stopToken, "tok-eos", 2, stopTokenId); break; case "glimmer": add(" to=self", "think", 0); add("<|message|>", "tok", 0); add(reasoning, "think", 0); add("<|eom|>", "tok", 0); add("<|start|>", "tok", 1); add("assistant to=user", "marker", 1); add("<|message|>", "tok", 1); add(textReply, "text", 1); add(stopToken, "tok-eos", 2, stopTokenId); break; case "inkling2": add("<|message_model|>", "tok", 0); add("<|content_thinking|>", "tok", 0); add(reasoning, "think", 0); add("<|end_message|>", "tok", 0); add("<|message_model|>", "tok", 1); add("<|content_text|>", "tok", 1); add(textReply, "text", 1); add("<|end_message|>", "tok", 2); add(stopToken, "tok-eos", 2, stopTokenId); break; default: add(reasoning + "\n", "think", 0); add("</think>", "tok", 0); add("\n\n", "text", 0); add(textReply, "text", 1); add(stopToken, "tok-eos", 2, stopTokenId); break; } } else { // replyMode === "call" const entries = Object.entries(argsObj); switch (modelKey) { case "qwen38": add(reasoning + "\n", "think", 0); add("</think>", "tok", 0); add("\n\n", "text", 0); add("<tool_call>", "tok-call", 1); add(`\n<function=${fnName}>\n`, "marker", 2); for (const [k, v] of entries) { add(`<parameter=${k}>\n`, "arg-key", 3); add(`${typeof v === "string" ? v : JSON.stringify(v)}\n`, "arg-val", 3); add("</parameter>\n", "marker", 3); } add("</function>\n", "marker", 4); add("</tool_call>", "tok-call", 4); add(stopToken, "tok-eos", 5, stopTokenId); break; case "kimi26": add(reasoning, "think", 0); add("</think>", "tok", 0); add("<|tool_calls_section_begin|>", "tok-call", 1); add("<|tool_call_begin|>", "tok-call", 2); add(`functions.${fnName}:0`, "marker", 2); add("<|tool_call_argument_begin|>", "tok-call", 3); add(argsJson, "arg-val", 3); add("<|tool_call_end|>", "tok-call", 4); add("<|tool_calls_section_end|>", "tok-call", 4); add(stopToken, "tok-eos", 5, stopTokenId); break; case "kimi31": add(reasoning, "think", 0); add("<|close|>", "tok", 0); add("think", "think", 0); add("<|sep|>", "tok", 0); add("<|open|>", "tok", 0); add("response", "marker", 0); add("<|sep|>", "tok", 0); add("<|close|>", "tok", 0); add("response", "marker", 0); add("<|sep|>", "tok", 0); add("<|open|>", "tok-call", 1); add("tools", "marker", 1); add("<|sep|>", "tok-call", 1); add("<|open|>", "tok-call", 2); add(`call tool="${k3EscapeAttr(fnName)}" index="1"`, "marker", 2); add("<|sep|>", "tok-call", 2); for (const [k, v] of entries) { add("<|open|>", "tok", 3); add(`argument key="${k3EscapeAttr(k)}" type="${k3XtmlType(v)}"`, "arg-key", 3); add("<|sep|>", "tok", 3); add(k3XtmlValue(v), "arg-val", 3); add("<|close|>", "tok", 3); add("argument", "marker", 3); add("<|sep|>", "tok", 3); } add("<|close|>", "tok-call", 4); add("call", "marker", 4); add("<|sep|>", "tok-call", 4); add("<|close|>", "tok-call", 4); add("tools", "marker", 4); add("<|sep|>", "tok-call", 4); add("<|close|>", "tok", 5); add("message", "marker", 5); add("<|sep|>", "tok", 5); add(stopToken, "tok-eos", 5, stopTokenId); break; case "glm53": add(reasoning, "think", 0); add("</think>", "tok", 0); add("<tool_call>", "tok-call", 1); add(fnName, "marker", 2); for (const [k, v] of entries) { add("<arg_key>", "tok", 3); add(k, "arg-key", 3); add("</arg_key>", "tok", 3); add("<arg_value>", "tok", 3); add(typeof v === "string" ? v : JSON.stringify(v), "arg-val", 3); add("</arg_value>", "tok", 3); } add("</tool_call>", "tok-call", 4); add(stopToken, "tok-eos", 5, stopTokenId); break; case "hy4": add(reasoning, "think", 0); add("</think:opensource>", "tok", 0); add("<tool_calls:opensource>", "tok-call", 1); add("<tool_call:opensource>", "tok-call", 1); add(fnName, "marker", 2); for (const [k, v] of entries) { add("<arg_key:opensource>", "tok", 3); add(k, "arg-key", 3); add("</arg_key:opensource>", "tok", 3); add("<arg_value:opensource>", "tok", 3); add(typeof v === "string" ? v : JSON.stringify(v), "arg-val", 3); add("</arg_value:opensource>", "tok", 3); } add("</tool_call:opensource>", "tok-call", 4); add("</tool_calls:opensource>", "tok-call", 4); add(stopToken, "tok-eos", 5, stopTokenId); break; case "deepseek41": add(reasoning, "think", 0); add("</think>", "tok", 0); add("\n\n", "text", 0); add("<|DSML| calls>\n", "marker", 1); add(`<|DSML| invoke name="${fnName}">\n`, "marker", 2); for (const [k, v] of entries) { const isStr = typeof v === "string"; add(`<|DSML| parameter name="${k}" string="${isStr}">`, "arg-key", 3); add(isStr ? v : JSON.stringify(v), "arg-val", 3); add("</|DSML| parameter>\n", "marker", 3); } add("</|DSML| invoke>\n</|DSML| calls>", "marker", 4); add(stopToken, "tok-eos", 5, stopTokenId); break; case "inkling2": { const sortedArgs = {}; for (const k of Object.keys(argsObj).sort()) sortedArgs[k] = argsObj[k]; add("<|message_model|>", "tok", 0); add("<|content_thinking|>", "tok", 0); add(reasoning, "think", 0); add("<|end_message|>", "tok", 0); add("<|message_model|>", "tok-call", 1); add(fnName, "marker", 1); add("<|content_invoke_tool_json|>", "tok-call", 2); add(JSON.stringify({ name: fnName, args: sortedArgs }), "arg-val", 3); add("<|end_message|>", "tok", 4); add(stopToken, "tok-eos", 5, stopTokenId); break; } case "gptoss": add("<|channel|>", "tok", 0); add("analysis", "think", 0); add("<|message|>", "tok", 0); add(reasoning, "think", 0); add("<|end|>", "tok", 0); add("<|start|>", "tok-call", 1); add(`assistant to=functions.${fnName}`, "marker", 1); add("<|channel|>", "tok-call", 2); add("commentary ", "marker", 2); add("<|constrain|>", "tok-call", 2); add("json", "marker", 2); add("<|message|>", "tok-call", 2); add(argsJson, "arg-val", 3); add(stopToken, "tok-eos", 4, stopTokenId); break; case "gemma4": // Default non-thinking prompt already closes <|channel>thought\n<channel|> add("<|tool_call>", "tok-call", 0); add(`call:${fnName}{`, "marker", 1); Object.keys(argsObj) .sort() .forEach((k, idx) => { if (idx > 0) add(",", "marker", 2); add(`${k}:`, "arg-key", 2); add(formatGemma4Value(argsObj[k]), "arg-val", 2); }); add("}", "marker", 3); add("<tool_call|>", "tok-call", 3); add(stopToken, "tok-eos", 4, stopTokenId); break; case "mistral4": add("[THINK]", "tok", 0); add(reasoning, "think", 0); add("[/THINK]", "tok", 0); add("[TOOL_CALLS]", "tok-call", 1); add(fnName, "marker", 2); add("[ARGS]", "tok-call", 3); add(argsJson, "arg-val", 4); add(stopToken, "tok-eos", 5, stopTokenId); break; case "minimax31": add("<mm:think>" + reasoning + "</mm:think>", "think", 0); add("]<]minimax[>[", "tok-call", 1); add("<tool_call>\n", "marker", 1); add("]<]minimax[>[", "tok-call", 2); add(`<invoke name="${fnName}">`, "marker", 2); for (const [k, v] of entries) { if (v === null || v === undefined) continue; add(formatMinimaxXml(k, v), "arg-val", 3); } add("]<]minimax[>[", "tok-call", 4); add("</invoke>\n", "marker", 4); add("]<]minimax[>[", "tok-call", 4); add("</tool_call>", "marker", 4); add(stopToken, "tok-eos", 5, stopTokenId); break; case "glimmer": add(" to=self", "think", 0); add("<|message|>", "tok", 0); add(reasoning, "think", 0); add("<|eom|>", "tok", 0); add("<|start|>", "tok-call", 1); add(`assistant to=${fnName}`, "marker", 1); add("<|message|>", "tok-call", 1); add(`<atem:function_calls>\n<atem:invoke name="${fnName}">\n`, "marker", 2); for (const [k, v] of entries) { add(`<atem:parameter name="${k}">`, "arg-key", 3); add(typeof v === "string" ? v : JSON.stringify(v), "arg-val", 3); add("</atem:parameter>\n", "marker", 3); } add("</atem:invoke>\n</atem:function_calls>", "marker", 4); add(stopToken, "tok-eos", 5, stopTokenId); break; case "beam": add("<|channel|>", "tok", 0); add("analysis", "think", 0); add("<|message|>", "tok", 0); add(reasoning, "think", 0); add("<|end|>", "tok", 0); add("<|start|>", "tok-call", 1); add(`assistant to=${fnName}`, "marker", 1); add("<|channel|>", "tok-call", 2); add("analysis ", "marker", 2); add("<|constrain|>", "tok-call", 2); add("xml", "marker", 2); add("<|message|>", "tok-call", 2); entries.forEach(([k, v], idx) => { add(`<rfl:parameter name="${k}">\n`, "arg-key", 3); add(`${typeof v === "string" ? v : JSON.stringify(v)}\n`, "arg-val", 3); add(idx < entries.length - 1 ? "</rfl:parameter>\n" : "</rfl:parameter>", "marker", 3); }); add(stopToken, "tok-eos", 4, stopTokenId); break; } } const parsedToolCall = replyMode === "call" ? { id: "call_01", type: "function", function: { name: fnName, arguments: argsJson, }, } : null; const apiFinishReason = replyMode === "call" ? "tool_calls" : "stop"; const messagesStopReason = replyMode === "call" ? "tool_use" : "end_turn"; const assistantContent = replyMode === "call" ? null : textReply; const responseJson = { id: `chatcmpl-${modelKey}-${presetId}`, object: "chat.completion", model: m.id, choices: [ { index: 0, message: { role: "assistant", content: assistantContent, reasoning_content: reasoning, ...(parsedToolCall ? { tool_calls: [parsedToolCall] } : {}), }, finish_reason: apiFinishReason, }, ], }; const messagesContent = []; if (reasoning) messagesContent.push({ type: "thinking", thinking: reasoning }); if (replyMode === "call") { messagesContent.push({ type: "tool_use", id: "toolu_01", name: fnName, input: argsObj, }); } else { messagesContent.push({ type: "text", text: textReply }); } const messagesResponseJson = { id: `msg_${modelKey}_${presetId}`, type: "message", role: "assistant", model: m.id, content: messagesContent, stop_reason: messagesStopReason, }; return { pieces, parsedToolCall, assistantContent, reasoningContent: reasoning, stopToken, stopTokenId, dedicatedStopToken: m.dedicatedStopToken, stopKind: m.stopKind, engineFinishReason: "stop", apiFinishReason, messagesStopReason, responseJson, messagesResponseJson, }; }
// Real browser/Node ES module renderers for all 13 open-weight tool-calling dialects.
import { Template } from "./vendor/jinja.js";
import { REPORT_DATA } from "./data.js";
const MODELS_BY_KEY = new Map(REPORT_DATA.models.map((m) => [m.key, m]));
const TEMPLATE_CACHE = new Map();
const TOKEN_REGEX_CACHE = new Map();
const PATH_MAP_BY_TOOLS = new WeakMap();
function getModel(modelKey) {
const m = MODELS_BY_KEY.get(modelKey);
if (!m) throw new Error(`Unknown modelKey: ${modelKey}`);
return m;
}
function getCompiledTemplate(modelKey) {
let tmpl = TEMPLATE_CACHE.get(modelKey);
if (!tmpl) {
const m = getModel(modelKey);
tmpl = new Template(m.chatTemplate);
TEMPLATE_CACHE.set(modelKey, tmpl);
}
return tmpl;
}
function escapeRegex(s) {
return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
function getSpecialTokenRegex(modelKey) {
let entry = TOKEN_REGEX_CACHE.get(modelKey);
if (!entry) {
const m = getModel(modelKey);
const toks = Object.keys(m.specialTokens || {})
.filter((t) => t.length > 0)
.sort((a, b) => b.length - a.length);
const re = toks.length ? new RegExp(toks.map(escapeRegex).join("|"), "g") : null;
entry = { re, map: m.specialTokens || {} };
TOKEN_REGEX_CACHE.set(modelKey, entry);
}
return entry;
}
function tokenizeSpecials(modelKey, text, extraProps = null) {
if (!text) return [];
const { re, map } = getSpecialTokenRegex(modelKey);
if (!re) {
return [extraProps ? { k: "t", text, ...extraProps } : { k: "t", text }];
}
const out = [];
re.lastIndex = 0;
let last = 0;
let m;
while ((m = re.exec(text)) !== null) {
if (m.index > last) {
const chunk = text.slice(last, m.index);
out.push(extraProps ? { k: "t", text: chunk, ...extraProps } : { k: "t", text: chunk });
}
const tokText = m[0];
const tokId = Object.prototype.hasOwnProperty.call(map, tokText) ? map[tokText] : null;
out.push(
extraProps
? { k: "tok", text: tokText, tokenId: tokId, ...extraProps }
: { k: "tok", text: tokText, tokenId: tokId }
);
last = m.index + tokText.length;
}
if (last < text.length) {
const tail = text.slice(last);
out.push(extraProps ? { k: "t", text: tail, ...extraProps } : { k: "t", text: tail });
}
return out;
}
// =============================================================================
// 1. normalizeToolsInput(parsedJson)
// =============================================================================
export function normalizeToolsInput(parsedJson) {
let rawList;
let wrapperPrefix = "";
let wasSingleObject = false;
if (Array.isArray(parsedJson)) {
rawList = parsedJson;
} else if (parsedJson && typeof parsedJson === "object") {
if (Array.isArray(parsedJson.tools)) {
rawList = parsedJson.tools;
wrapperPrefix = "tools.";
} else if (parsedJson.type === "function" || parsedJson.function || parsedJson.inputSchema || parsedJson.input_schema || parsedJson.name) {
rawList = [parsedJson];
wasSingleObject = true;
} else {
throw new Error("Expected an array of tools, a { tools: [...] } object, or a single tool definition.");
}
} else {
throw new Error("Tools JSON must be an array or object.");
}
let inputFormat = "openai";