|
| 1 | +/** |
| 2 | + * Tool Call Repair — fixes broken JSON from local LLMs. |
| 3 | + * |
| 4 | + * Common issues: |
| 5 | + * - Trailing commas in JSON objects/arrays |
| 6 | + * - Single quotes instead of double quotes |
| 7 | + * - Missing closing braces/brackets |
| 8 | + * - Unquoted property names |
| 9 | + * - Extra text before/after JSON |
| 10 | + * - Escaped quotes inside strings |
| 11 | + */ |
| 12 | + |
| 13 | +/** |
| 14 | + * Attempt to repair broken JSON from a tool call. |
| 15 | + * Returns parsed object or null if unfixable. |
| 16 | + */ |
| 17 | +export function repairJson(raw: string): any | null { |
| 18 | + // 1. Try direct parse first |
| 19 | + try { return JSON.parse(raw) } catch {} |
| 20 | + |
| 21 | + let fixed = raw.trim() |
| 22 | + |
| 23 | + // 2. Extract JSON from surrounding text (model might wrap it) |
| 24 | + const jsonMatch = fixed.match(/\{[\s\S]*\}/) |
| 25 | + if (jsonMatch) fixed = jsonMatch[0] |
| 26 | + |
| 27 | + // 3. Fix single quotes → double quotes (but not inside strings) |
| 28 | + fixed = fixed.replace(/'/g, '"') |
| 29 | + |
| 30 | + // 4. Fix trailing commas |
| 31 | + fixed = fixed.replace(/,\s*([}\]])/g, '$1') |
| 32 | + |
| 33 | + // 5. Fix unquoted keys: { key: "value" } → { "key": "value" } |
| 34 | + fixed = fixed.replace(/(\{|,)\s*([a-zA-Z_]\w*)\s*:/g, '$1"$2":') |
| 35 | + |
| 36 | + // 6. Fix missing closing braces |
| 37 | + const openBraces = (fixed.match(/\{/g) || []).length |
| 38 | + const closeBraces = (fixed.match(/\}/g) || []).length |
| 39 | + for (let i = 0; i < openBraces - closeBraces; i++) fixed += '}' |
| 40 | + |
| 41 | + const openBrackets = (fixed.match(/\[/g) || []).length |
| 42 | + const closeBrackets = (fixed.match(/\]/g) || []).length |
| 43 | + for (let i = 0; i < openBrackets - closeBrackets; i++) fixed += ']' |
| 44 | + |
| 45 | + // 7. Try parse again |
| 46 | + try { return JSON.parse(fixed) } catch {} |
| 47 | + |
| 48 | + // 8. Last resort: try to extract key-value pairs with regex |
| 49 | + try { |
| 50 | + const nameMatch = raw.match(/["']?name["']?\s*[:=]\s*["']([^"']+)["']/i) |
| 51 | + const argsMatch = raw.match(/["']?arguments["']?\s*[:=]\s*(\{[^}]*\})/i) |
| 52 | + if (nameMatch) { |
| 53 | + let args = {} |
| 54 | + if (argsMatch) { |
| 55 | + try { args = JSON.parse(argsMatch[1].replace(/'/g, '"')) } catch {} |
| 56 | + } |
| 57 | + return { name: nameMatch[1], arguments: args } |
| 58 | + } |
| 59 | + } catch {} |
| 60 | + |
| 61 | + return null |
| 62 | +} |
| 63 | + |
| 64 | +/** |
| 65 | + * Repair tool call arguments that might be a string instead of object. |
| 66 | + */ |
| 67 | +export function repairToolCallArgs(args: any): Record<string, any> { |
| 68 | + if (typeof args === 'object' && args !== null) return args |
| 69 | + if (typeof args === 'string') { |
| 70 | + const parsed = repairJson(args) |
| 71 | + if (parsed && typeof parsed === 'object') return parsed |
| 72 | + } |
| 73 | + return {} |
| 74 | +} |
| 75 | + |
| 76 | +/** |
| 77 | + * Extract tool calls from model content when native tool calling fails. |
| 78 | + * Looks for JSON patterns that look like tool calls. |
| 79 | + */ |
| 80 | +export function extractToolCallsFromContent(content: string): { name: string; arguments: Record<string, any> }[] { |
| 81 | + const calls: { name: string; arguments: Record<string, any> }[] = [] |
| 82 | + |
| 83 | + // Pattern 1: {"name": "tool_name", "arguments": {...}} |
| 84 | + const pattern1 = /\{\s*"(?:name|tool|function)"\s*:\s*"([^"]+)"\s*,\s*"(?:arguments|args|parameters|input)"\s*:\s*(\{[^}]*\})\s*\}/gi |
| 85 | + let match |
| 86 | + while ((match = pattern1.exec(content)) !== null) { |
| 87 | + const args = repairJson(match[2]) |
| 88 | + if (args) calls.push({ name: match[1], arguments: args }) |
| 89 | + } |
| 90 | + |
| 91 | + // Pattern 2: tool_name(arg1, arg2) — function call syntax |
| 92 | + if (calls.length === 0) { |
| 93 | + const pattern2 = /\b(web_search|web_fetch|file_read|file_write|file_list|file_search|shell_execute|code_execute|system_info|process_list|screenshot)\s*\(\s*([^)]*)\)/gi |
| 94 | + while ((match = pattern2.exec(content)) !== null) { |
| 95 | + const argStr = match[2].trim() |
| 96 | + let args: Record<string, any> = {} |
| 97 | + if (argStr) { |
| 98 | + // Try to parse as JSON |
| 99 | + const parsed = repairJson(`{${argStr}}`) |
| 100 | + if (parsed) args = parsed |
| 101 | + else { |
| 102 | + // Simple single-argument: treat as the first required param |
| 103 | + args = { query: argStr.replace(/^["']|["']$/g, '') } |
| 104 | + } |
| 105 | + } |
| 106 | + calls.push({ name: match[1], arguments: args }) |
| 107 | + } |
| 108 | + } |
| 109 | + |
| 110 | + return calls |
| 111 | +} |
0 commit comments