|
| 1 | +import { CodeInterpreter, Logs, Result } from "@e2b/code-interpreter"; |
| 2 | +import type { JSONSchemaType } from "ajv"; |
| 3 | +import fs from "fs"; |
| 4 | +import { BaseTool, ToolMetadata } from "llamaindex"; |
| 5 | +import crypto from "node:crypto"; |
| 6 | +import path from "node:path"; |
| 7 | + |
| 8 | +export type InterpreterParameter = { |
| 9 | + code: string; |
| 10 | +}; |
| 11 | + |
| 12 | +export type InterpreterToolParams = { |
| 13 | + metadata?: ToolMetadata<JSONSchemaType<InterpreterParameter>>; |
| 14 | + apiKey?: string; |
| 15 | +}; |
| 16 | + |
| 17 | +export type InterpreterToolOuput = { |
| 18 | + isError: boolean; |
| 19 | + logs: Logs; |
| 20 | + extraResult: InterpreterExtraResult[]; |
| 21 | +}; |
| 22 | + |
| 23 | +type InterpreterExtraType = |
| 24 | + | "html" |
| 25 | + | "markdown" |
| 26 | + | "svg" |
| 27 | + | "png" |
| 28 | + | "jpeg" |
| 29 | + | "pdf" |
| 30 | + | "latex" |
| 31 | + | "json" |
| 32 | + | "javascript"; |
| 33 | + |
| 34 | +export type InterpreterExtraResult = { |
| 35 | + type: InterpreterExtraType; |
| 36 | + // url: string; |
| 37 | + filename: string; |
| 38 | +}; |
| 39 | + |
| 40 | +const DEFAULT_META_DATA: ToolMetadata<JSONSchemaType<InterpreterParameter>> = { |
| 41 | + name: "interpreter", |
| 42 | + description: ` |
| 43 | + - You are a Python interpreter. |
| 44 | + - You are given tasks to complete and you run python code to solve them. |
| 45 | + - The python code runs in a Jupyter notebook. Every time you call \`interpreter\` tool, the python code is executed in a separate cell. It's okay to make multiple calls to \`interpreter\`. |
| 46 | + - Display visualizations using matplotlib or any other visualization library directly in the notebook. Shouldn't save the visualizations to a file, just return the base64 encoded data. |
| 47 | + - You can install any pip package (if it exists) if you need to but the usual packages for data analysis are already preinstalled. |
| 48 | + - You can run any python code you want in a secure environment. |
| 49 | + `, // TODO: Add more guide to help AI use data to generate code (eg. wiki tool, google sheet tool data) |
| 50 | + parameters: { |
| 51 | + type: "object", |
| 52 | + properties: { |
| 53 | + code: { |
| 54 | + type: "string", |
| 55 | + description: "The python code to execute in a single cell.", |
| 56 | + }, |
| 57 | + }, |
| 58 | + required: ["code"], |
| 59 | + }, |
| 60 | +}; |
| 61 | + |
| 62 | +export class InterpreterTool implements BaseTool<InterpreterParameter> { |
| 63 | + private readonly outputDir = "data"; |
| 64 | + private readonly dataAPI = "/api/data/"; |
| 65 | + private apiKey?: string; |
| 66 | + metadata: ToolMetadata<JSONSchemaType<InterpreterParameter>>; |
| 67 | + codeInterpreter?: CodeInterpreter; |
| 68 | + |
| 69 | + constructor(params?: InterpreterToolParams) { |
| 70 | + this.metadata = params?.metadata || DEFAULT_META_DATA; |
| 71 | + this.apiKey = params?.apiKey || process.env.E2B_API_KEY; |
| 72 | + } |
| 73 | + |
| 74 | + public async initInterpreter() { |
| 75 | + if (!this.apiKey) { |
| 76 | + throw new Error( |
| 77 | + "E2B_API_KEY key is required to run code interpreter. Get it here: https://e2b.dev/docs/getting-started/api-key", |
| 78 | + ); |
| 79 | + } |
| 80 | + if (!this.codeInterpreter) { |
| 81 | + this.codeInterpreter = await CodeInterpreter.create({ |
| 82 | + apiKey: this.apiKey, |
| 83 | + }); |
| 84 | + } |
| 85 | + return this.codeInterpreter; |
| 86 | + } |
| 87 | + |
| 88 | + public async codeInterpret(code: string): Promise<InterpreterToolOuput> { |
| 89 | + console.log( |
| 90 | + `\n${"=".repeat(50)}\n> Running following AI-generated code:\n${code}\n${"=".repeat(50)}`, |
| 91 | + ); |
| 92 | + const interpreter = await this.initInterpreter(); |
| 93 | + const exec = await interpreter.notebook.execCell(code); |
| 94 | + if (exec.error) console.error("[Code Interpreter error]", exec.error); |
| 95 | + const extraResult = await this.getExtraResult(exec.results[0]); |
| 96 | + const result: InterpreterToolOuput = { |
| 97 | + isError: !!exec.error, |
| 98 | + logs: exec.logs, |
| 99 | + extraResult, |
| 100 | + }; |
| 101 | + return result; |
| 102 | + } |
| 103 | + |
| 104 | + async call(input: InterpreterParameter): Promise<InterpreterToolOuput> { |
| 105 | + const result = await this.codeInterpret(input.code); |
| 106 | + await this.codeInterpreter?.close(); |
| 107 | + return result; |
| 108 | + } |
| 109 | + |
| 110 | + private async getExtraResult( |
| 111 | + res?: Result, |
| 112 | + ): Promise<InterpreterExtraResult[]> { |
| 113 | + if (!res) return []; |
| 114 | + const output: InterpreterExtraResult[] = []; |
| 115 | + |
| 116 | + try { |
| 117 | + const formats = res.formats(); // formats available for the result. Eg: ['png', ...] |
| 118 | + const base64DataArr = formats.map((f) => res[f as keyof Result]); // get base64 data for each format |
| 119 | + |
| 120 | + // save base64 data to file and return the url |
| 121 | + for (let i = 0; i < formats.length; i++) { |
| 122 | + const ext = formats[i]; |
| 123 | + const base64Data = base64DataArr[i]; |
| 124 | + if (ext && base64Data) { |
| 125 | + const { filename } = this.saveToDisk(base64Data, ext); |
| 126 | + output.push({ |
| 127 | + type: ext as InterpreterExtraType, |
| 128 | + filename, |
| 129 | + // url: this.getDataUrl(filename), |
| 130 | + }); |
| 131 | + } |
| 132 | + } |
| 133 | + } catch (error) { |
| 134 | + console.error("Error when saving data to disk", error); |
| 135 | + } |
| 136 | + |
| 137 | + return output; |
| 138 | + } |
| 139 | + |
| 140 | + // Consider saving to cloud storage instead but it may cost more for you |
| 141 | + // See: https://e2b.dev/docs/sandbox/api/filesystem#write-to-file |
| 142 | + private saveToDisk( |
| 143 | + base64Data: string, |
| 144 | + ext: string, |
| 145 | + ): { |
| 146 | + outputPath: string; |
| 147 | + filename: string; |
| 148 | + } { |
| 149 | + const filename = `${crypto.randomUUID()}.${ext}`; // generate a unique filename |
| 150 | + const buffer = Buffer.from(base64Data, "base64"); |
| 151 | + const outputPath = this.getOutputPath(filename); |
| 152 | + fs.writeFileSync(outputPath, buffer); |
| 153 | + console.log(`Saved file to ${outputPath}`); |
| 154 | + return { |
| 155 | + outputPath, |
| 156 | + filename, |
| 157 | + }; |
| 158 | + } |
| 159 | + |
| 160 | + private getOutputPath(filename: string): string { |
| 161 | + // if outputDir doesn't exist, create it |
| 162 | + if (!fs.existsSync(this.outputDir)) { |
| 163 | + fs.mkdirSync(this.outputDir, { recursive: true }); |
| 164 | + } |
| 165 | + return path.join(this.outputDir, filename); |
| 166 | + } |
| 167 | + |
| 168 | + private getDataUrl(filename: string): string { |
| 169 | + return `${this.dataAPI}${filename}`; |
| 170 | + } |
| 171 | +} |
0 commit comments