ai: add common tool runtime and built-in tools
This commit is contained in:
@@ -0,0 +1,50 @@
|
||||
import {getToolHandlers} from "./registry";
|
||||
import {normalizeToolArguments} from "./utils";
|
||||
import {PYTHON_INTERPRETER_TOOL_NAME, PythonInterpreterInputFile, runPythonInterpreter} from "./python-interpretator";
|
||||
|
||||
export type ToolRuntimeContext = {
|
||||
pythonInputFiles?: PythonInterpreterInputFile[];
|
||||
};
|
||||
|
||||
function stringifyToolResult(result: unknown): string {
|
||||
if (typeof result === "string") return result;
|
||||
return JSON.stringify(result, null, 2);
|
||||
}
|
||||
|
||||
export async function executeToolCall(
|
||||
name: string,
|
||||
args?: unknown,
|
||||
context: ToolRuntimeContext = {},
|
||||
): Promise<string> {
|
||||
const handler = getToolHandlers()[name];
|
||||
|
||||
if (!handler) {
|
||||
return stringifyToolResult({
|
||||
error: `Unknown tool: ${name}`,
|
||||
});
|
||||
}
|
||||
|
||||
try {
|
||||
if (name === PYTHON_INTERPRETER_TOOL_NAME) {
|
||||
const result = await runPythonInterpreter(normalizeToolArguments(args), {
|
||||
executionTimeoutMs: 8_000,
|
||||
syntaxTimeoutMs: 3_000,
|
||||
maxCodeChars: 100_000,
|
||||
maxOutputChars: 20_000,
|
||||
inputFiles: context.pythonInputFiles,
|
||||
});
|
||||
|
||||
const s = stringifyToolResult(result);
|
||||
console.log("PYTHON_INTERPRETER_STRING_RESULT", s);
|
||||
|
||||
return s;
|
||||
}
|
||||
|
||||
const result = await handler(normalizeToolArguments(args));
|
||||
return stringifyToolResult(result);
|
||||
} catch (error) {
|
||||
return stringifyToolResult({
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
});
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user