Basic Structure
This commit is contained in:
10
src/tools/codeExecution.test.ts
Normal file
10
src/tools/codeExecution.test.ts
Normal 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");
|
||||
});
|
||||
});
|
||||
44
src/tools/codeExecution.tool.ts
Normal file
44
src/tools/codeExecution.tool.ts
Normal 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 };
|
||||
Reference in New Issue
Block a user