( code: string, method: string, args: (string | object | undefined)[], )
| 14 | * @returns {Promise<T>} - The result from executing the Python code. |
| 15 | */ |
| 16 | export async function runPythonCode<T = unknown>( |
| 17 | code: string, |
| 18 | method: string, |
| 19 | args: (string | object | undefined)[], |
| 20 | ): Promise<T> { |
| 21 | let tempDirectory: string | undefined; |
| 22 | try { |
| 23 | tempDirectory = await createSecureTempDirectory('promptfoo-python-code-'); |
| 24 | const tempFilePath = await writeSecureTempFile(tempDirectory, 'script.py', code); |
| 25 | // Necessary to await so temp file doesn't get deleted. |
| 26 | const result = await runPython<T>(tempFilePath, method, args); |
| 27 | return result; |
| 28 | } catch (error) { |
| 29 | logger.error(`Error executing Python code: ${error}`); |
| 30 | throw error; |
| 31 | } finally { |
| 32 | if (tempDirectory) { |
| 33 | try { |
| 34 | await removeSecureTempDirectory(tempDirectory); |
| 35 | } catch (error) { |
| 36 | logger.error(`Error removing temporary Python code directory: ${error}`); |
| 37 | } |
| 38 | } |
| 39 | } |
| 40 | } |
no test coverage detected
searching dependent graphs…