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 -2Showing whitespace changes
public/scripts/tool-calling.js+15 -2
@@ -298,6 +298,19 @@ export class ToolManager {
298298 }
299299
300300 /**
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+ /**
301314 * Invokes a tool by name. Returns the result of the tool's action function.
302315 * @param {string} name The name of the tool to invoke.
303316 * @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 {
309322 throw new Error(`No tool with the name "${name}" has been registered.`);
310323 }
311324
312325 const invokeParameters = typeof parameters === 'string' ? JSONthis.parse#parseParameters(parameters) : parameters;
313326 const tool = this.#tools.get(name);
314327 const result = await tool.invoke(invokeParameters);
315328 return typeof result === 'string' ? result : JSON.stringify(result);
@@ -352,7 +365,7 @@ export class ToolManager {
352365
353366 try {
354367 const tool = this.#tools.get(name);
355368 const formatParameters = typeof parameters === 'string' ? JSONthis.parse#parseParameters(parameters) : parameters;
356369 return await tool.formatMessage(formatParameters);
357370 } catch (error) {
358371 console.error(`[ToolManager] An error occurred while formatting the tool call message for "${name}":`, error);