Skip to content

Commit 5f14a2f

Browse files
committed
fix: handle JSON contents of create_new_file
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. Fixes: #8972
1 parent c96ff0d commit 5f14a2f

File tree

1 file changed

+29
-3
lines changed

1 file changed

+29
-3
lines changed

core/tools/parseArgs.ts

Lines changed: 29 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -18,15 +18,41 @@ export function getStringArg(
1818
argName: string,
1919
allowEmpty = false,
2020
): string {
21-
if (!args || !(argName in args) || typeof args[argName] !== "string") {
21+
if (!args || !(argName in args)) {
2222
throw new Error(
2323
`\`${argName}\` argument is required${allowEmpty ? "" : " and must not be empty or whitespace-only"}. (type string)`,
2424
);
2525
}
26-
if (!allowEmpty && !args[argName].trim()) {
26+
27+
let value = args[argName];
28+
29+
// Handle case where JSON content was parsed into an object by the tool call parser.
30+
// If the arguments to the tool call are valid JSON (e.g. the model attempts to create a .json file)
31+
// the earlier call to JSON.parse() will have deeply parsed the returned contents.
32+
// If that has happened, convert back to string.
33+
if (typeof value === "object" && value !== null) {
34+
// Special handling for contents parameter which should always be a string
35+
if (argName === "contents") {
36+
value = JSON.stringify(value);
37+
return value;
38+
} else {
39+
throw new Error(
40+
`Argument \`${argName}\` must be a string, not an object`,
41+
);
42+
}
43+
}
44+
45+
if (!allowEmpty && !value.trim()) {
2746
throw new Error(`Argument ${argName} must not be empty or whitespace-only`);
2847
}
29-
return args[argName];
48+
49+
if (typeof value !== "string") {
50+
throw new Error(
51+
`\`${argName}\` argument is required${allowEmpty ? "" : " and must not be empty or whitespace-only"}. (type string)`,
52+
);
53+
}
54+
55+
return value;
3056
}
3157

3258
export function getOptionalStringArg(

0 commit comments

Comments
 (0)