37 lines
1.1 KiB
TypeScript
37 lines
1.1 KiB
TypeScript
import type { JSONValue } from "ai";
|
|
|
|
export type ToolErrorOutput =
|
|
| { type: "error-text"; value: string }
|
|
| { type: "error-json"; value: JSONValue };
|
|
|
|
export const serializeToolError = (error: unknown): string => {
|
|
if (error instanceof Error) {
|
|
return error.message;
|
|
}
|
|
if (typeof error === "string") {
|
|
return error;
|
|
}
|
|
try {
|
|
return JSON.stringify(error) ?? "An unknown tool error occurred";
|
|
} catch {
|
|
return "The tool returned an error that could not be serialized";
|
|
}
|
|
};
|
|
|
|
export const readStoredToolError = (
|
|
error: Readonly<{ type: string; value: string }> | null | undefined,
|
|
): ToolErrorOutput => {
|
|
if (!error) {
|
|
return { type: "error-text", value: "An unknown tool error occurred" };
|
|
}
|
|
if (error.type === "json") {
|
|
try {
|
|
const value: JSONValue = JSON.parse(error.value);
|
|
return { type: "error-json", value };
|
|
} catch {
|
|
// Older tool failures were saved as JSON even when their value was plain text.
|
|
}
|
|
}
|
|
return { type: "error-text", value: error.value };
|
|
};
|