in spring-ai-alibaba-jmanus/src/main/java/com/alibaba/cloud/ai/example/manus/tool/code/CodeUtils.java [95:162]
public static CodeExecutionResult executeCode(String code, String lang, String filename, Boolean arm64,
Map<String, Object> kwargs) {
log.info("code:{}, lang:{}, filename:{}, arm64:{}, kwargs:{}", code, lang, filename, arm64, kwargs);
if (code == null && filename == null) {
String error_msg = "Either code or filename must be provided.";
log.error(error_msg);
throw new AssertionError(error_msg);
}
String workDir = kwargs.containsKey("work_dir") ? (String) kwargs.get("work_dir") : null;
// timeout = timeout != null ? timeout : DEFAULT_TIMEOUT;
// String original_filename = filename;
// if (WIN32 && Arrays.asList("sh", "shell").contains(lang) && !useDocker) {
// lang = "ps1";
// }
if (filename == null) {
String code_hash = md5(code);
filename = String.format("tmp_code_%s.%s", code_hash, lang.startsWith("python") ? "py" : lang);
}
if (workDir == null) {
workDir = WORKING_DIR;
}
String filepath = Paths.get(workDir, filename).toString();
String file_dir = Paths.get(filepath).getParent().toString();
try {
Files.createDirectories(Paths.get(file_dir));
}
catch (IOException e) {
e.printStackTrace();
}
if (code != null) {
try {
FileWriter fout = new FileWriter(filepath);
fout.write(code);
fout.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
log.info("filepath:{}", filepath);
ExecuteCommandResult executeCommandResult = null;
if (lang.equals("python")) {
List<String> cmds = new ArrayList<>();
if (arm64 != null) {
cmds.add("arch");
cmds.add(arm64 ? "-arm64" : "-x86_64");
}
cmds.add("python3");
cmds.add(filepath);
executeCommandResult = CodeUtils.executeCommand(cmds.toArray(new String[] {}));
}
else if (lang.equals("sh")) {
String[] cmd = { "sh", filepath, };
executeCommandResult = CodeUtils.executeCommand(cmd);
}
CodeExecutionResult codeExecutionResult = new CodeExecutionResult();
codeExecutionResult.setExitcode(executeCommandResult.getExitCode());
codeExecutionResult.setLogs(executeCommandResult.getOutput());
return codeExecutionResult;
}