adk-typescript
Version:
TypeScript port of Google's Agent Development Kit (ADK)
195 lines (194 loc) • 6.54 kB
JavaScript
;
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.codeExecutionTool = exports.CodeExecutionTool = void 0;
exports.executeCode = executeCode;
const FunctionTool_1 = require("./FunctionTool");
const child_process = __importStar(require("child_process"));
const os = __importStar(require("os"));
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const util = __importStar(require("util"));
// Promisified versions of fs functions
const writeFile = util.promisify(fs.writeFile);
const readFile = util.promisify(fs.readFile);
const unlink = util.promisify(fs.unlink);
const mkdir = util.promisify(fs.mkdir);
/**
* Map of supported languages and their configurations
*/
const LANGUAGE_CONFIGS = {
python: {
extension: '.py',
command: 'python',
args: (filename) => [filename]
},
javascript: {
extension: '.js',
command: 'node',
args: (filename) => [filename]
},
typescript: {
extension: '.ts',
command: 'ts-node',
args: (filename) => [filename]
},
bash: {
extension: '.sh',
command: 'bash',
args: (filename) => [filename]
},
// Add more languages as needed
};
/**
* Function to execute code in various languages
*
* @param params Parameters for the function
* @param params.language Programming language of the code
* @param params.code Code to execute
* @param context The tool context
* @returns Result of the code execution
*/
async function executeCode(params, context) {
const language = params.language.toLowerCase();
const code = params.code;
// Check if language is supported
if (!LANGUAGE_CONFIGS[language]) {
return {
stdout: '',
stderr: `Unsupported language: ${language}. Supported languages are: ${Object.keys(LANGUAGE_CONFIGS).join(', ')}`,
exitCode: 1,
executionTime: 0,
success: false
};
}
// Get language configuration
const config = LANGUAGE_CONFIGS[language];
// Create a temporary directory for the code
const tempDir = path.join(os.tmpdir(), 'code-execution', `run-${Date.now()}`);
await mkdir(tempDir, { recursive: true });
// Create a temporary file for the code
const filename = `code${config.extension}`;
const filepath = path.join(tempDir, filename);
await writeFile(filepath, code);
// Execute the code
const startTime = Date.now();
let stdout = '';
let stderr = '';
let exitCode = 0;
try {
// Execute the command with the code file
const command = config.command;
const args = config.args(filepath);
// Set a timeout for execution (30 seconds)
const timeout = 30000;
// Execute the process
const process = child_process.spawn(command, args, {
timeout,
cwd: tempDir
});
// Collect output
process.stdout.on('data', (data) => {
stdout += data.toString();
});
process.stderr.on('data', (data) => {
stderr += data.toString();
});
// Wait for process to exit
exitCode = await new Promise((resolve) => {
process.on('close', (code) => {
resolve(code ?? 0);
});
});
}
catch (error) {
stderr = `Error executing code: ${error.message}`;
exitCode = 1;
}
// Calculate execution time
const executionTime = Date.now() - startTime;
// Clean up temporary file
try {
await unlink(filepath);
}
catch (error) {
console.warn(`Error removing temporary file ${filepath}: ${error.message}`);
}
return {
stdout,
stderr,
exitCode,
executionTime,
success: exitCode === 0
};
}
/**
* Tool for executing code in various programming languages
*/
class CodeExecutionTool extends FunctionTool_1.FunctionTool {
/**
* Creates a new code execution tool
*/
constructor() {
super({
name: 'execute_code',
description: 'Executes code in various programming languages',
fn: executeCode,
functionDeclaration: {
name: 'execute_code',
description: 'Executes code in various programming languages',
parameters: {
type: 'object',
properties: {
language: {
type: 'string',
description: `Programming language of the code. Supported languages: ${Object.keys(LANGUAGE_CONFIGS).join(', ')}`
},
code: {
type: 'string',
description: 'Code to execute'
}
},
required: ['language', 'code']
}
}
});
}
}
exports.CodeExecutionTool = CodeExecutionTool;
/**
* Singleton instance of the Code Execution tool
*/
exports.codeExecutionTool = new CodeExecutionTool();