| 1 | import { ToolCallDelta } from ".."; |
| 2 | |
| 3 | export function safeParseToolCallArgs( |
| 4 | toolCall: ToolCallDelta, |
| 5 | ): Record<string, any> { |
| 6 | try { |
| 7 | return JSON.parse(toolCall.function?.arguments?.trim() || "{}"); |
| 8 | } catch (e) { |
| 9 | //console.error( |
| 10 | // `Failed to parse tool call arguments:\nTool call: ${toolCall.function?.name + " " + toolCall.id}\nArgs:${toolCall.function?.arguments}\n`, |
| 11 | //); |
| 12 | return {}; |
| 13 | } |
| 14 | } |
| 15 | |
| 16 | export function getStringArg( |
| 17 | args: any, |
| 18 | argName: string, |
| 19 | allowEmpty = false, |
| 20 | ): string { |
| 21 | if (!args || !(argName in args) || typeof args[argName] !== "string") { |
| 22 | throw new Error( |
| 23 | `\`${argName}\` argument is required${allowEmpty ? "" : " and must not be empty or whitespace-only"}. (type string)`, |
| 24 | ); |
| 25 | } |
| 26 | if (!allowEmpty && !args[argName].trim()) { |
| 27 | throw new Error(`Argument ${argName} must not be empty or whitespace-only`); |
| 28 | } |
| 29 | return args[argName]; |
| 30 | } |
| 31 | |
| 32 | export function getOptionalStringArg( |
| 33 | args: any, |
| 34 | argName: string, |
| 35 | allowEmpty = false, |
| 36 | ) { |
| 37 | if (typeof args?.[argName] === "undefined") { |
| 38 | return undefined; |
| 39 | } |
| 40 | return getStringArg(args, argName, allowEmpty); |
| 41 | } |
| 42 | |
| 43 | export function getNumberArg(args: any, argName: string): number { |
| 44 | if (!args || !(argName in args)) { |
| 45 | throw new Error(`Argument \`${argName}\` is required (type number)`); |
| 46 | } |
| 47 | const value = args[argName]; |
| 48 | if (typeof value === "string") { |
| 49 | const parsed = parseInt(value, 10); |
| 50 | if (isNaN(parsed)) { |
| 51 | throw new Error(`Argument \`${argName}\` must be a valid number`); |
| 52 | } |
| 53 | return parsed; |
| 54 | } |
| 55 | if (typeof value !== "number" || isNaN(value)) { |
| 56 | throw new Error(`Argument \`${argName}\` must be a valid number`); |
| 57 | } |
| 58 | return Math.floor(value); // Ensure integer for line numbers (supports negative numbers) |
| 59 | } |
| 60 | |
| 61 | export function getBooleanArg(args: any, argName: string, required = false) { |
| 62 | if (!args || !(argName in args)) { |
| 63 | if (required) { |
| 64 | throw new Error(`Argument \`${argName}\` is required (type boolean)`); |
| 65 | } else { |
| 66 | return undefined; |
| 67 | } |
| 68 | } |
| 69 | if (typeof args[argName] === "string") { |
| 70 | if (args[argName].toLowerCase() === "false") { |
| 71 | return false; |
| 72 | } |
| 73 | if (args[argName].toLowerCase() === "true") { |
| 74 | return true; |
| 75 | } |
| 76 | } |
| 77 | if (typeof args[argName] !== "boolean") { |
| 78 | throw new Error(`Argument \`${argName}\` must be a boolean true or false`); |
| 79 | } |
| 80 | return args[argName]; |
| 81 | } |