|
| 1 | +/* |
| 2 | + * Copyright (C) 2026 github.com/MaloneTalk |
| 3 | + * |
| 4 | + * This program is free software: you can redistribute it and/or modify |
| 5 | + * it under the terms of the GNU Affero General Public License as |
| 6 | + * published by the Free Software Foundation, either version 3 of the |
| 7 | + * License, or any later version. |
| 8 | + * |
| 9 | + * This program is distributed in the hope that it will be useful, |
| 10 | + * but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 11 | + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 12 | + * GNU Affero General Public License for more details. |
| 13 | + * |
| 14 | + * You should have received a copy of the GNU Affero General Public License |
| 15 | + * along with this program. If not, see <https://www.gnu.org/licenses/>. |
| 16 | + * limitations under the License. |
| 17 | + */ |
| 18 | +package io.github.malonetalk.agent.tools; |
| 19 | + |
| 20 | +import io.agentscope.core.tool.Tool; |
| 21 | +import io.agentscope.core.tool.ToolParam; |
| 22 | +import java.io.IOException; |
| 23 | +import java.nio.charset.StandardCharsets; |
| 24 | +import java.nio.file.Files; |
| 25 | +import java.nio.file.Path; |
| 26 | +import java.util.Comparator; |
| 27 | +import java.util.concurrent.Semaphore; |
| 28 | +import java.util.concurrent.TimeUnit; |
| 29 | +import lombok.extern.slf4j.Slf4j; |
| 30 | +import org.springframework.stereotype.Component; |
| 31 | + |
| 32 | +@Slf4j |
| 33 | +@Component |
| 34 | +public class ExecutePythonTool implements MarkAgentTool { |
| 35 | + |
| 36 | + private static final int TIMEOUT_SECONDS = 30; |
| 37 | + private static final int MAX_CONCURRENT = 5; |
| 38 | + private final Semaphore semaphore = new Semaphore(MAX_CONCURRENT); |
| 39 | + |
| 40 | + @Tool( |
| 41 | + name = "execute_python", |
| 42 | + description = |
| 43 | + """ |
| 44 | + Execute Python code for data analysis. \ |
| 45 | + Available libraries: pandas, numpy, scipy. \ |
| 46 | + SQL query results have already been obtained in the conversation; \ |
| 47 | + include the data directly in the Python code. \ |
| 48 | + Print analysis results to stdout using print(). \ |
| 49 | + Only use this when statistical computation \ |
| 50 | + (correlation, regression, distribution tests, etc.) cannot be done in SQL.\ |
| 51 | + """) |
| 52 | + public String executePython( |
| 53 | + @ToolParam( |
| 54 | + name = "code", |
| 55 | + description = |
| 56 | + """ |
| 57 | + Python code to execute for data analysis. \ |
| 58 | + Must be self-contained and include any data inline.\ |
| 59 | + """) |
| 60 | + String code) { |
| 61 | + |
| 62 | + if (!semaphore.tryAcquire()) { |
| 63 | + return String.format( |
| 64 | + "Error: too many concurrent Python executions (max %d), try again later.", |
| 65 | + MAX_CONCURRENT); |
| 66 | + } |
| 67 | + try { |
| 68 | + return doExecute(code); |
| 69 | + } finally { |
| 70 | + semaphore.release(); |
| 71 | + } |
| 72 | + } |
| 73 | + |
| 74 | + private String doExecute(String code) { |
| 75 | + Path tmpDir = null; |
| 76 | + try { |
| 77 | + tmpDir = Files.createTempDirectory("pyexec-"); |
| 78 | + Path script = tmpDir.resolve("script.py"); |
| 79 | + Files.writeString(script, code); |
| 80 | + |
| 81 | + var process = |
| 82 | + new ProcessBuilder("python3", "-I", script.toString()) |
| 83 | + .directory(tmpDir.toFile()) |
| 84 | + .redirectErrorStream(true) |
| 85 | + .start(); |
| 86 | + |
| 87 | + boolean finished = process.waitFor(TIMEOUT_SECONDS, TimeUnit.SECONDS); |
| 88 | + if (!finished) { |
| 89 | + process.destroyForcibly(); |
| 90 | + process.waitFor(5, TimeUnit.SECONDS); |
| 91 | + return "Error: execution timed out after " + TIMEOUT_SECONDS + " seconds."; |
| 92 | + } |
| 93 | + |
| 94 | + String output = |
| 95 | + new String(process.getInputStream().readAllBytes(), StandardCharsets.UTF_8); |
| 96 | + |
| 97 | + if (process.exitValue() != 0) { |
| 98 | + return "Error (exit " + process.exitValue() + "):\n" + output; |
| 99 | + } |
| 100 | + return output; |
| 101 | + } catch (IOException e) { |
| 102 | + log.error("Python execution I/O error", e); |
| 103 | + return "Error: " + e.getMessage(); |
| 104 | + } catch (InterruptedException e) { |
| 105 | + Thread.currentThread().interrupt(); |
| 106 | + return "Error: execution interrupted."; |
| 107 | + } finally { |
| 108 | + if (tmpDir != null) { |
| 109 | + try (var walk = Files.walk(tmpDir)) { |
| 110 | + walk.sorted(Comparator.reverseOrder()) |
| 111 | + .forEach( |
| 112 | + p -> { |
| 113 | + try { |
| 114 | + Files.deleteIfExists(p); |
| 115 | + } catch (IOException ignored) { |
| 116 | + // best-effort cleanup |
| 117 | + } |
| 118 | + }); |
| 119 | + } catch (IOException ignored) { |
| 120 | + // best-effort cleanup |
| 121 | + } |
| 122 | + } |
| 123 | + } |
| 124 | + } |
| 125 | +} |
0 commit comments