| 321 | * @returns The execution result |
| 322 | */ |
| 323 | export async function installPackages( |
| 324 | packages: string[], |
| 325 | language: "python" | "javascript" | "typescript" = "python", |
| 326 | options: CodeInterpreterOptions = {} |
| 327 | ): Promise<ExecutionResult> { |
| 328 | const sandbox = await createSandbox(options); |
| 329 | |
| 330 | try { |
| 331 | let installCommand: string; |
| 332 | |
| 333 | if (language === "python") { |
| 334 | installCommand = `import sys\nimport subprocess\nsubprocess.check_call([sys.executable, "-m", "pip", "install", "${packages.join('", "')}"])`; |
| 335 | } else if (language === "javascript" || language === "typescript") { |
| 336 | installCommand = `const { execSync } = require('child_process');\ntry {\n console.log(execSync('npm install ${packages.join(" ")}', { encoding: 'utf8' }));\n} catch (error) {\n console.error('Installation failed:', error.message);\n}`; |
| 337 | } else { |
| 338 | throw new Error(`Unsupported language: ${language}`); |
| 339 | } |
| 340 | |
| 341 | // @ts-ignore - Ignore TypeScript errors for API compatibility |
| 342 | const execution = await sandbox.runCode(installCommand, { |
| 343 | language, |
| 344 | onStdout: (data: any) => console.log("[stdout]", data), |
| 345 | onStderr: (data: any) => console.error("[stderr]", data) |
| 346 | }); |
| 347 | |
| 348 | // Format the result to match our ExecutionResult interface |
| 349 | const result: ExecutionResult = { |
| 350 | text: execution.text || "", |
| 351 | results: execution.results || [], |
| 352 | error: execution.error ? { |
| 353 | type: "error", |
| 354 | value: typeof execution.error === 'string' ? execution.error : |
| 355 | (JSON.stringify(execution.error)) |
| 356 | } : null, |
| 357 | logs: { |
| 358 | stdout: Array.isArray(execution.logs?.stdout) ? execution.logs.stdout : |
| 359 | (execution.logs?.stdout ? [execution.logs.stdout] : []), |
| 360 | stderr: Array.isArray(execution.logs?.stderr) ? execution.logs.stderr : |
| 361 | (execution.logs?.stderr ? [execution.logs.stderr] : []) |
| 362 | } |
| 363 | }; |
| 364 | |
| 365 | const isError = result.error !== null && result.error !== undefined; |
| 366 | console.log( |
| 367 | `Package installation ${isError ? "failed" : "completed"}`, |
| 368 | { |
| 369 | packages, |
| 370 | language, |
| 371 | error: isError && result.error ? result.error.value : undefined |
| 372 | } |
| 373 | ); |
| 374 | |
| 375 | return result; |
| 376 | } catch (error: unknown) { |
| 377 | const errorMessage = error instanceof Error ? error.message : String(error); |
| 378 | console.error("Package installation failed", { error: errorMessage, packages, language }); |
| 379 | |
| 380 | // Return an error result |