Просмотр исходного кода

feat(python): 默认使用项目内置 Python 解释器

- 新增 qingjian/system/python 解释器路径常量
- command 默认改为相对路径,运行时按项目根解析为绝对路径
- 内置解释器覆盖源码仓库与独立部署包两种目录布局
- 内置缺失时才回退到配置值/系统 PATH,并打印警告
cc 2 недель назад
Родитель
Сommit
e54214f45e

+ 10 - 0
ai-server/src/main/java/com/zsjz/ai/common/constants/PathConst.java

@@ -103,6 +103,16 @@ public class PathConst {
     public static final Path TOOLS_PATH = SYSTEM_PATH.resolve("tools");
     public static final Path EXTENSION_PATH = SYSTEM_PATH.resolve("extension");
 
+    /**
+     * 内置 Python 解释器(随项目分发,不依赖系统 PATH)。
+     *
+     * <p>源码仓库布局:{@code qingjian/system/python/};
+     * 独立部署包布局:{@code <root>/python/}(见 {@code PythonExecutor#resolvePythonCommand} 的候选顺序)。</p>
+     */
+    public static final Path PYTHON_HOME = SYSTEM_PATH.resolve("python");
+    public static final Path PYTHON_PATH_WIN = PYTHON_HOME.resolve("python.exe");
+    public static final Path PYTHON_PATH_LINUX = PYTHON_HOME.resolve("bin").resolve("python3");
+
     /**
      * 升级暂存目录
      */

+ 69 - 7
ai-server/src/main/java/com/zsjz/ai/module/agent/python/PythonExecutor.java

@@ -1,5 +1,6 @@
 package com.zsjz.ai.module.agent.python;
 
+import com.zsjz.ai.common.constants.PathConst;
 import com.zsjz.ai.common.context.CaseContextHolder;
 import com.zsjz.ai.common.datasource.CaseDataSourceRegistry;
 import com.zsjz.ai.common.model.plat.entity.CaseInfo;
@@ -15,6 +16,7 @@ import java.io.IOException;
 import java.nio.charset.StandardCharsets;
 import java.nio.file.Files;
 import java.nio.file.Path;
+import java.nio.file.Paths;
 import java.util.ArrayList;
 import java.util.Comparator;
 import java.util.List;
@@ -176,6 +178,66 @@ public class PythonExecutor {
         this.storageLayout = storageLayout;
     }
 
+    /**
+     * 解析后的 Python 解释器路径(懒加载,配置在启动后不会变)。
+     */
+    private volatile String resolvedPythonCommand;
+
+    /**
+     * 解析 Python 解释器:默认使用随项目分发的内置 Python,不依赖系统 PATH。
+     *
+     * <p>`etl.python.command` 若显式配置为路径(含分隔符 / .exe / 以 . 开头),优先按配置执行;
+     * 相对路径按项目根目录解析。内置解释器候选同时覆盖两种目录布局:</p>
+     * <ul>
+     *   <li>源码仓库:{@code qingjian/system/python/python.exe};</li>
+     *   <li>独立部署包:{@code <root>/python/python.exe}。</li>
+     * </ul>
+     * <p>只有内置解释器都不存在时才回退到配置值(兼容开发机已有 Python 的情况)。</p>
+     */
+    private String pythonCommand() {
+        String cached = resolvedPythonCommand;
+        if (cached != null) {
+            return cached;
+        }
+        synchronized (this) {
+            if (resolvedPythonCommand == null) {
+                resolvedPythonCommand = resolvePythonCommand();
+            }
+            return resolvedPythonCommand;
+        }
+    }
+
+    private String resolvePythonCommand() {
+        String configured = etlProperties.getPython().getCommand();
+        configured = configured == null ? "" : configured.trim();
+        boolean looksLikePath = configured.contains("/") || configured.contains("\\")
+                || configured.endsWith(".exe") || configured.startsWith(".");
+        if (looksLikePath) {
+            Path configuredPath = Paths.get(configured);
+            Path absolute = configuredPath.isAbsolute()
+                    ? configuredPath
+                    : PathConst.ROOT_PATH.resolve(configured);
+            if (Files.isRegularFile(absolute)) {
+                return absolute.toAbsolutePath().normalize().toString();
+            }
+            log.warn("配置的 Python 解释器不存在,尝试使用内置解释器: {}", absolute);
+        }
+        for (Path candidate : List.of(
+                PathConst.PYTHON_PATH_WIN,
+                PathConst.PYTHON_PATH_LINUX,
+                PathConst.ROOT_PATH.resolve("python").resolve("python.exe"),
+                PathConst.ROOT_PATH.resolve("python").resolve("bin").resolve("python3"))) {
+            if (Files.isRegularFile(candidate)) {
+                String command = candidate.toAbsolutePath().normalize().toString();
+                log.info("使用内置 Python 解释器: {}", command);
+                return command;
+            }
+        }
+        String fallback = configured.isEmpty() ? "python" : configured;
+        log.warn("未找到内置 Python 解释器,回退到系统命令: {}", fallback);
+        return fallback;
+    }
+
     /**
      * 依赖检测缓存(null = 未检测;true/false = 检测结果)
      */
@@ -250,7 +312,7 @@ public class PythonExecutor {
                 return PythonResult.error("关系图辅助模块写入失败: " + e.getMessage());
             }
 
-            ProcessBuilder pb = new ProcessBuilder(etlProperties.getPython().getCommand(), "main.py")
+            ProcessBuilder pb = new ProcessBuilder(pythonCommand(), "main.py")
                     .directory(sandbox.toFile());
             // 指向快照副本:原库被本进程写锁持有,子进程连只读都打不开(见类注释)
             String pythonDbFile = resolvePythonDbFile(workspaceId, dbFile);
@@ -353,24 +415,24 @@ public class PythonExecutor {
      */
     private boolean detect() {
         try {
-            Process process = new ProcessBuilder(etlProperties.getPython().getCommand(), "-c", CHECK_IMPORTS).start();
+            String command = pythonCommand();
+            Process process = new ProcessBuilder(command, "-c", CHECK_IMPORTS).start();
             if (!process.waitFor(30, TimeUnit.SECONDS)) {
                 process.destroyForcibly();
                 process.waitFor(5, TimeUnit.SECONDS);
-                log.error("Python 依赖检测超时(execute_python 工具将不注册): command={}",
-                        etlProperties.getPython().getCommand());
+                log.error("Python 依赖检测超时(execute_python 工具将不注册): command={}", command);
                 return false;
             }
             if (process.exitValue() == 0) {
-                log.info("Python 执行环境就绪: command={}", etlProperties.getPython().getCommand());
+                log.info("Python 执行环境就绪: command={}", command);
                 return true;
             }
             log.info("Python 执行环境不可用(command={},需安装依赖: pip install pandas duckdb matplotlib),"
-                    + "execute_python 工具将不注册", etlProperties.getPython().getCommand());
+                    + "execute_python 工具将不注册", command);
             return false;
         } catch (Exception e) {
             log.error("Python 检测失败(execute_python 工具将不注册): command={}, error={}",
-                    etlProperties.getPython().getCommand(), e.getMessage());
+                    pythonCommand(), e.getMessage());
             return false;
         }
     }

+ 8 - 2
ai-server/src/main/java/com/zsjz/ai/module/agent/python/PythonProperties.java

@@ -13,8 +13,14 @@ public class PythonProperties {
     /** 是否启用 Python 工具 */
     private boolean enabled = true;
 
-    /** Python 解释器命令(可配置绝对路径,如 python3 / D:\envs\etl\python.exe) */
-    private String command = "python";
+    /**
+     * Python 解释器命令。
+     *
+     * <p>默认使用随项目分发的 {@code qingjian/system/python/python.exe}(相对项目根);
+     * 显式配置相对路径时按项目根目录解析,配置绝对路径时直接使用。
+     * 内置解释器不存在时才回退到系统 PATH 中的 {@code python}。</p>
+     */
+    private String command = "qingjian/system/python/python.exe";
 
     /** 执行超时秒数(超时强制终止进程) */
     private int timeoutSeconds = 60;