Basic Structure

This commit is contained in:
2025-08-24 15:16:02 -05:00
parent 797fb638f4
commit 9a176a7735
11 changed files with 139 additions and 8 deletions

View File

@@ -0,0 +1,10 @@
import { CodeExecutionTool } from "./codeExecution.tool";
describe("CodeExecutionTool", () => {
it("should execute code and return the output", async () => {
const tool = new CodeExecutionTool();
const code = "console.log('Hello, world!');";
const result = await tool._call(code);
expect(result).toBe("Hello, world!\n");
});
});

View File

@@ -0,0 +1,44 @@
import { Tool } from "langchain/tools";
import Docker from 'dockerode';
class CodeExecutionTool extends Tool {
name = "code-execution";
description = "A tool for executing code in a sandboxed environment.";
private docker = new Docker();
async _call(code: string): Promise<string> {
try {
const container = await this.docker.createContainer({
Image: 'alpine',
Cmd: ['node', '-e', code],
Tty: false,
HostConfig: {
AutoRemove: true,
}
});
const stream = await container.attach({ stream: true, stdout: true, stderr: true });
await container.start();
return new Promise((resolve, reject) => {
let output = '';
stream.on('data', (chunk) => {
output += chunk.toString('utf8');
});
stream.on('end', () => {
resolve(output);
});
stream.on('error', (err) => {
reject(err);
});
});
} catch (err: any) {
return `Error executing code: ${err.message}`;
}
}
}
export { CodeExecutionTool };