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>
This commit is contained in:
Rebecca Turner
2025-06-02 03:18:04 -04:00
committed by GitHub
parent fa10833e52
commit 6bb07370f4

View File

@@ -297,6 +297,19 @@ export class ToolManager {
console.log(`[ToolManager] Unregistered function tool: ${name}`);
}
/**
* Parse tool call parameters -- they're usually JSON, but they can also be empty strings (which are not valid JSON apparently).
* @param {object} parameters The parameters for a tool call, usually a string with JSON inside
* @returns {object} The parsed parameters
*/
static #parseParameters(parameters) {
return parameters === ''
? {}
: typeof parameters === 'string'
? JSON.parse(parameters)
: parameters;
}
/**
* Invokes a tool by name. Returns the result of the tool's action function.
* @param {string} name The name of the tool to invoke.
@@ -309,7 +322,7 @@ export class ToolManager {
throw new Error(`No tool with the name "${name}" has been registered.`);
}
const invokeParameters = typeof parameters === 'string' ? JSON.parse(parameters) : parameters;
const invokeParameters = this.#parseParameters(parameters);
const tool = this.#tools.get(name);
const result = await tool.invoke(invokeParameters);
return typeof result === 'string' ? result : JSON.stringify(result);
@@ -352,7 +365,7 @@ export class ToolManager {
try {
const tool = this.#tools.get(name);
const formatParameters = typeof parameters === 'string' ? JSON.parse(parameters) : parameters;
const formatParameters = this.#parseParameters(parameters);
return await tool.formatMessage(formatParameters);
} catch (error) {
console.error(`[ToolManager] An error occurred while formatting the tool call message for "${name}":`, error);