diff --git a/core/tools/parseArgs.ts b/core/tools/parseArgs.ts index 543e6ba53..14885c979 100644 --- a/core/tools/parseArgs.ts +++ b/core/tools/parseArgs.ts @@ -18,15 +18,41 @@ export function getStringArg( argName: string, allowEmpty = false, ): string { - if (!args || !(argName in args) || typeof args[argName] !== "string") { + if (!args || !(argName in args)) { throw new Error( `\`${argName}\` argument is required${allowEmpty ? "" : " and must not be empty or whitespace-only"}. (type string)`, ); } - if (!allowEmpty && !args[argName].trim()) { + + let value = args[argName]; + + // Handle case where JSON content was parsed into an object by the tool call parser. + // If the arguments to the tool call are valid JSON (e.g. the model attempts to create a .json file) + // the earlier call to JSON.parse() will have deeply parsed the returned contents. + // If that has happened, convert back to string. + if (typeof value === "object" && value !== null) { + // Special handling for contents parameter which should always be a string + if (argName === "contents") { + value = JSON.stringify(value); + return value; + } else { + throw new Error( + `Argument \`${argName}\` must be a string, not an object`, + ); + } + } + + if (!allowEmpty && !value.trim()) { throw new Error(`Argument ${argName} must not be empty or whitespace-only`); } - return args[argName]; + + if (typeof value !== "string") { + throw new Error( + `\`${argName}\` argument is required${allowEmpty ? "" : " and must not be empty or whitespace-only"}. (type string)`, + ); + } + + return value; } export function getOptionalStringArg(