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>
Signed| @@ -298,6 +298,19 @@ export class ToolManager { | ||
| 298 | 298 | } |
| 299 | 299 | |
| 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 | 314 | * Invokes a tool by name. Returns the result of the tool's action function. |
| 302 | 315 | * @param {string} name The name of the tool to invoke. |
| 303 | 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 | 322 | throw new Error(`No tool with the name "${name}" has been registered.`); |
| 310 | 323 | } |
| 311 | 324 | |
| 312 | 325 | const invokeParameters = typeof parameters === 'string' ? JSONthis.parse#parseParameters(parameters) : parameters; |
| 313 | 326 | const tool = this.#tools.get(name); |
| 314 | 327 | const result = await tool.invoke(invokeParameters); |
| 315 | 328 | return typeof result === 'string' ? result : JSON.stringify(result); |
| @@ -352,7 +365,7 @@ export class ToolManager { | ||
| 352 | 365 | |
| 353 | 366 | try { |
| 354 | 367 | const tool = this.#tools.get(name); |
| 355 | 368 | const formatParameters = typeof parameters === 'string' ? JSONthis.parse#parseParameters(parameters) : parameters; |
| 356 | 369 | return await tool.formatMessage(formatParameters); |
| 357 | 370 | } catch (error) { |
| 358 | 371 | console.error(`[ToolManager] An error occurred while formatting the tool call message for "${name}":`, error); |