( code: string, apiKey: string )
| 28 | * @returns The execution result |
| 29 | */ |
| 30 | export async function executeCode( |
| 31 | code: string, |
| 32 | apiKey: string |
| 33 | ): Promise<ExecutionResult> { |
| 34 | try { |
| 35 | // Create a new code interpreter instance |
| 36 | const interpreter = new CodeInterpreter({ |
| 37 | apiKey, |
| 38 | }); |
| 39 | |
| 40 | // Execute the code |
| 41 | const result = await interpreter.runCode({ |
| 42 | code, |
| 43 | language: "python", |
| 44 | }); |
| 45 | |
| 46 | // Return the execution result |
| 47 | return { |
| 48 | text: result.output || "", |
| 49 | results: result.artifacts || [], |
| 50 | error: result.error ? { type: "error", value: result.error } : undefined, |
| 51 | logs: { |
| 52 | stdout: result.output ? result.output.split("\n") : [], |
| 53 | stderr: result.error ? result.error.split("\n") : [] |
| 54 | } |
| 55 | }; |
| 56 | } catch (error: unknown) { |
| 57 | const errorMessage = error instanceof Error ? error.message : String(error); |
| 58 | console.error("Error executing code:", errorMessage); |
| 59 | |
| 60 | // Return an error result |
| 61 | return { |
| 62 | text: "", |
| 63 | results: [], |
| 64 | error: { |
| 65 | type: "error", |
| 66 | value: errorMessage |
| 67 | }, |
| 68 | logs: { |
| 69 | stdout: [], |
| 70 | stderr: [errorMessage] |
| 71 | } |
| 72 | }; |
| 73 | } |
| 74 | } |
| 75 | |
| 76 | // Example usage |
| 77 | if (import.meta.main) { |
no outgoing calls
no test coverage detected