Fix #4083 JSON parse error when tool does not accept parameters (#4084) * Fix #4083: JSON parse error when tool does not accept parameters * Reformat for visual coolness --------- Co-authored-by: Cohee <18619528+Cohee1207@users.noreply.github.com>

6bb07370f4a42af4c7fc7c9e370a4890c4eb82fd

Rebecca Turner <rebecca@iarna.org>

Signed
1 files changed, +15 -2Ignore whitespace
public/scripts/tool-calling.js+15 -2
@@ -298,6 +298,19 @@ export class ToolManager {
298 }298 }
299299
300 /**300 /**
301 * Parse tool call parameters -- they're usually JSON, but they can also be empty strings (which are not valid JSON apparently).
302 * @param {object} parameters The parameters for a tool call, usually a string with JSON inside
303 * @returns {object} The parsed parameters
304 */
305 static #parseParameters(parameters) {
306 return parameters === ''
307 ? {}
308 : typeof parameters === 'string'
309 ? JSON.parse(parameters)
310 : parameters;
311 }
312
313 /**
301 * Invokes a tool by name. Returns the result of the tool's action function.314 * Invokes a tool by name. Returns the result of the tool's action function.
302 * @param {string} name The name of the tool to invoke.315 * @param {string} name The name of the tool to invoke.
303 * @param {object} parameters Function parameters. For example, if the tool requires a "name" parameter, you would pass {name: "value"}.316 * @param {object} parameters Function parameters. For example, if the tool requires a "name" parameter, you would pass {name: "value"}.
@@ -309,7 +322,7 @@ export class ToolManager {
309 throw new Error(`No tool with the name "${name}" has been registered.`);322 throw new Error(`No tool with the name "${name}" has been registered.`);
310 }323 }
311324
312 const invokeParameters = typeof parameters === 'string' ? JSON.parse(parameters) : parameters;325 const invokeParameters = this.#parseParameters(parameters);
313 const tool = this.#tools.get(name);326 const tool = this.#tools.get(name);
314 const result = await tool.invoke(invokeParameters);327 const result = await tool.invoke(invokeParameters);
315 return typeof result === 'string' ? result : JSON.stringify(result);328 return typeof result === 'string' ? result : JSON.stringify(result);
@@ -352,7 +365,7 @@ export class ToolManager {
352365
353 try {366 try {
354 const tool = this.#tools.get(name);367 const tool = this.#tools.get(name);
355 const formatParameters = typeof parameters === 'string' ? JSON.parse(parameters) : parameters;368 const formatParameters = this.#parseParameters(parameters);
356 return await tool.formatMessage(formatParameters);369 return await tool.formatMessage(formatParameters);
357 } catch (error) {370 } catch (error) {
358 console.error(`[ToolManager] An error occurred while formatting the tool call message for "${name}":`, error);371 console.error(`[ToolManager] An error occurred while formatting the tool call message for "${name}":`, error);