cc 5 dienas atpakaļ
vecāks
revīzija
e674e4abc0

+ 2 - 4
AI_AGENT.md

@@ -363,10 +363,8 @@ dm/
   绕过是静默的(只是多花钱、识别不出东西),不报错就发现不了,只有放在唯一入口才拦得住后续新增的调用点。
   加后缀时同步改 `FileTypeConstantsTest`(`whitelistEntriesAreNormalized` 会拦住「大写」和「带点号」的条目)
 - 同一批档案还给 AI 用:`file` 工具组(`FileAnalysisTool`)提供
-  `list_file_profiles`(清单检索)/ `stat_file_profiles_by_category`(分类统计)/
-  `get_file_sample`(读某份材料的正文样本,≤4000 字)。
-  ★ 三条硬约定:**正文绝不进列表**(单条样本 4000 字,50 行就是 20 万字,会冲爆上下文,
-  正文只能按需单份取);**命中超 5000 条报错而非截断**(截断会让模型以为材料就这么多);
+  `list_file_profiles`(清单检索)/ `stat_file_profiles_by_category`(分类统计)。
+  ★ 两条硬约定:**命中超 5000 条报错而非截断**(截断会让模型以为材料就这么多);
   **分类/状态认不出必须报错**(`FileCategoryEnum.parse` 认不出会落 `OTHER`,
   直接用它会让「过滤笔录」静默变成「过滤其他」)。
 

+ 22 - 3
ai-electron/frontend/src/workbench/api/http.ts

@@ -87,16 +87,35 @@ export function aiDeleteBody<T = any>(path: string, data?: any): Promise<T> {
   });
 }
 
-/** 上传到 /resource/oss/upload(返回 OssDTO,含 ossId/createBy) */
-export function aiUpload(file: File, onUploadProgress?: (e: any) => void): Promise<any> {
+/**
+ * 上传到 /resource/oss/upload(返回 OssDTO,含 ossId/createBy)
+ *
+ * <p>{@code defHttp.uploadFile} 直接调用 axiosInstance.request,不经过全局
+ * transformRequestHook,拿到的是原生 AxiosResponse(body 形如 {@code { code, msg, data }})。
+ * 这里统一拆包并判定失败,避免调用方把响应对象当 OssDTO 用:ossId 为空会让后端
+ * 文档登记报「请先上传文件」。</p>
+ */
+export async function aiUpload(file: File, onUploadProgress?: (e: any) => void): Promise<any> {
   const { ctxPath, adminPath } = useGlobSetting();
-  return defHttp.uploadFile(
+  const res: any = await defHttp.uploadFile(
     {
       url: ctxPath + adminPath + '/resource/oss/upload',
       onUploadProgress,
     },
     { file, filename: file.name },
   );
+  if (res?.status >= 400) {
+    throw new Error(res?.data?.msg || res?.data?.message || `文件上传失败(HTTP ${res?.status})`);
+  }
+  // 若将来 uploadFile 接入统一转换,res 本身就是业务数据,此时无 code 字段,原样返回
+  const body = res?.data && typeof res.data === 'object' ? res.data : res;
+  if (!body) {
+    throw new Error('文件上传失败');
+  }
+  if (body.code !== undefined && body.code !== 200) {
+    throw new Error(body.msg || body.message || '文件上传失败');
+  }
+  return body.code !== undefined ? body.data : body;
 }
 
 /** 导出 xlsx(后端返回二进制流) */

+ 1 - 0
ai-electron/frontend/src/workbench/api/tool.ts

@@ -11,6 +11,7 @@ export interface ToolVO {
   paramsSchema?: string;
   implName?: string;
   status?: string;
+  sortOrder?: number;
   tags?: any[];
   remark?: string;
   [key: string]: any;

+ 3 - 3
ai-electron/frontend/src/workbench/views/agent/expert/index.vue

@@ -226,7 +226,7 @@
         <a-form-item label="工具集">
           <a-select v-model:value="selectedToolCodes" mode="multiple" allow-clear placeholder="请选择业务工具" style="width: 100%">
             <a-select-option v-for="item in toolOptions" :key="item.toolCode" :value="item.toolCode">
-              {{ item.toolName }}({{ item.readOnly ? '只读' : '读写' }})
+              {{ item.toolName }}({{ item.toolType === '1' ? '写入' : '只读' }})
             </a-select-option>
           </a-select>
         </a-form-item>
@@ -801,7 +801,7 @@
     (form.value.toolBindings ?? []).forEach((bind: any) => {
       const name = toolLabel(bind.toolCode);
       toolNames.push(name);
-      if (toolOptions.value.find((item) => item.toolCode === bind.toolCode)?.readOnly === false) {
+      if (toolOptions.value.find((item) => item.toolCode === bind.toolCode)?.toolType === '1') {
         writeToolNames.push(name);
       }
     });
@@ -859,7 +859,7 @@
       description: form.value.description,
       tools: (form.value.toolBindings ?? []).map((bind: any) => ({
         name: toolLabel(bind.toolCode),
-        readOnly: toolOptions.value.find((item) => item.toolCode === bind.toolCode)?.readOnly !== false,
+        readOnly: toolOptions.value.find((item) => item.toolCode === bind.toolCode)?.toolType !== '1',
       })),
       hasKnowledgeBase: (form.value.kbIds ?? []).length > 0,
     } as any);

+ 17 - 0
ai-electron/frontend/src/workbench/views/integration/registry/index.vue

@@ -142,6 +142,17 @@
             <a-radio value="1">写入</a-radio>
           </a-radio-group>
         </a-form-item>
+        <a-form-item name="sortOrder">
+          <template #label>
+            <span class="wb-label-tip">
+              排序
+              <a-tooltip title="列表与智能体工具选择下拉按该值升序展示,数值越小越靠前;同值按工具编码升序。默认 0。">
+                <Icon icon="i-mdi:information-outline" class="wb-label-tip__icon" tabindex="0" />
+              </a-tooltip>
+            </span>
+          </template>
+          <a-input-number v-model:value="form.sortOrder" :min="0" :precision="0" style="width: 160px" />
+        </a-form-item>
         <a-form-item name="implName">
           <template #label>
             <span class="wb-label-tip">
@@ -346,6 +357,7 @@
               {{ detail.record.status === '0' ? '启用' : '停用' }}
             </a-tag>
           </a-descriptions-item>
+          <a-descriptions-item label="排序">{{ detail.record.sortOrder ?? 0 }}</a-descriptions-item>
           <a-descriptions-item label="实现标识">{{ detail.record.implName || '-' }}</a-descriptions-item>
           <a-descriptions-item label="标签">
             <template v-if="detail.record.tags?.length">
@@ -383,6 +395,7 @@
     AForm,
     AFormItem,
     AInput,
+    AInputNumber,
     ARadio,
     ARadioGroup,
     ASelect,
@@ -446,6 +459,7 @@
     paramsSchema?: string;
     implName?: string;
     status?: string;
+    sortOrder?: number;
     tagIds?: Id[];
     remark?: string;
   }
@@ -508,6 +522,7 @@
     paramsSchema: undefined,
     implName: undefined,
     status: '0',
+    sortOrder: 0,
     tagIds: [],
     remark: undefined,
   });
@@ -559,6 +574,7 @@
   }));
 
   const columns: any[] = [
+    { title: '排序', dataIndex: 'sortOrder', key: 'sortOrder', width: 70, align: 'center' },
     { title: '工具编码', dataIndex: 'toolCode', key: 'toolCode', width: 130, align: 'center', ellipsis: true },
     { title: '工具名称', dataIndex: 'toolName', key: 'toolName', width: 130, align: 'center', ellipsis: true },
     { title: '类型', key: 'toolType', width: 64, align: 'center', slot: 'toolType' },
@@ -672,6 +688,7 @@
       paramsSchema: data.paramsSchema,
       implName: data.implName,
       status: data.status ?? '0',
+      sortOrder: data.sortOrder ?? 0,
       tagIds: (data.tags ?? []).map((tag: ToolTagVO) => tag.id),
       remark: data.remark,
     };

+ 18 - 0
ai-server/src/main/java/com/zsjz/ai/common/compat/OssService.java

@@ -69,6 +69,24 @@ public class OssService {
         return storage.getPublicUrl("");
     }
 
+    /**
+     * 读取 OSS 文件字节(服务端内部直读本地存储)。
+     *
+     * <p>解析 / 转写等内部消费必须直接读存储,不能回源 {@code /files/**}:
+     * 该端点需要登录态,服务端内部请求没有 token,会拿到 {@code code=401} 的
+     * JSON 并被当成文件内容(表现为「解析文本」里出现 401 报文)。</p>
+     *
+     * @param ossId OSS 主键
+     * @return 文件字节
+     */
+    public byte[] readBytes(Long ossId) {
+        AiOss oss = ossId == null ? null : aiOssMapper.selectById(ossId);
+        if (oss == null || StringUtils.isBlank(oss.getFileName())) {
+            throw new ServiceException("文件不存在或已被删除,请重新上传");
+        }
+        return storage.downloadBytes(oss.getFileName());
+    }
+
     public void deleteByIds(String ossIds) {
         List<Long> ids = parseIds(ossIds);
         if (ids.isEmpty()) {

+ 1 - 1
ai-server/src/main/java/com/zsjz/ai/module/ai/core/agent/tools/business/BusinessToolCatalog.java

@@ -124,7 +124,7 @@ public class BusinessToolCatalog {
             "list_persons");
 
     private static final List<String> FILE_TOOLS = List.of(
-            "list_file_profiles", "stat_file_profiles_by_category", "get_file_sample");
+            "list_file_profiles", "stat_file_profiles_by_category");
 
     private static final List<String> EDS_TOOLS = List.of(
             "list_eds_packages", "get_eds_catalog",

+ 5 - 93
ai-server/src/main/java/com/zsjz/ai/module/ai/core/agent/tools/business/FileAnalysisTool.java

@@ -5,9 +5,7 @@ import com.zsjz.ai.common.enums.AiParseStatusEnum;
 import com.zsjz.ai.common.enums.FileCategoryEnum;
 import com.zsjz.ai.common.model.dm.entity.FileAiProfile;
 import com.zsjz.ai.common.model.dm.query.FileAiProfileQuery;
-import com.zsjz.ai.common.utils.Json;
 import com.zsjz.ai.module.dm.ai.FileAiProfileService;
-import com.zsjz.ai.module.dm.ai.FileSampleExtractor;
 import io.agentscope.core.message.ToolResultBlock;
 import io.agentscope.core.tool.Tool;
 import io.agentscope.core.tool.ToolParam;
@@ -24,7 +22,7 @@ import java.util.TreeSet;
 import java.util.stream.Collectors;
 
 /**
- * 非表格材料档案类 Agent 工具集(3 个工具),把 {@code file_ai_profile} 表暴露给 Agent。
+ * 非表格材料档案类 Agent 工具集(2 个工具),把 {@code file_ai_profile} 表暴露给 Agent。
  *
  * <h3>这张表是什么</h3>
  * 用户上传的 txt / doc / docx / pdf / ppt / 压缩包 这类文件<b>不落盘</b>
@@ -33,21 +31,16 @@ import java.util.stream.Collectors;
  * {@code category}(业务分类)+ {@code summary}(一句话摘要)+ {@code keywords} + {@code sampleText}。
  * 详见 {@code module/dm/ai/FileAiProfileService}。
  *
- * <h3>为什么「分析」只能是这三个动作</h3>
+ * <h3>为什么「分析」只能是这两个动作</h3>
  * 原文件没落盘,能复用的只有表里那点东西,所以工具不做「重新解析文件」这类承诺:
  * <ol>
  *   <li>{@code list_file_profiles}:按分类/关键词检索材料清单;</li>
- *   <li>{@code stat_file_profiles_by_category}:摸清材料构成(各类多少份、什么格式);</li>
- *   <li>{@code get_file_sample}:把某份材料的正文片段(≤4000 字)读给模型 ——
- *       这是全链路里<b>唯一</b>能看到材料原文的入口,也是「基于材料内容回答」的关键。</li>
+ *   <li>{@code stat_file_profiles_by_category}:摸清材料构成(各类多少份、什么格式)。</li>
  * </ol>
  * 表格类文件(xls/xlsx/csv)解析出的业务数据走各自域的工具,与这里无关。
  *
- * <h3>三个必须踩对的点</h3>
+ * <h3>两个必须踩对的点</h3>
  * <ul>
- *   <li><b>绝不把 {@code sampleText} 放进表格</b>:单条样本上限 4000 字,50 行就是 20 万字,
- *       直接冲爆模型上下文。列表工具只输出元信息,正文必须显式用 {@code get_file_sample} 取,
- *       且一次只取一份 —— 这是刻意的「按需下钻」。</li>
  *   <li><b>只返回头部预览</b>:结果集只回传列定义 + 前 50 行 + 全量行数,
  *       超出行数用 {@code totalRows} 如实告知,避免让模型误以为只有这些材料。</li>
  *   <li><b>分类/状态入参宽松解析</b>:模型经常回传中文(「笔录」「识别成功」),
@@ -72,17 +65,6 @@ public class FileAnalysisTool {
         return 0;
     }
 
-    /**
-     * 读取正文样本的默认长度
-     */
-    private static final int SAMPLE_DEFAULT_CHARS = 2000;
-
-    /**
-     * 读取正文样本的上限:直接复用采集侧的常量,避免两处 4000 各写一遍后漂移 ——
-     * 采集时就截断到这个长度,要更多也没有。
-     */
-    private static final int SAMPLE_MAX_CHARS = FileSampleExtractor.MAX_SAMPLE_CHARS;
-
     /**
      * 分类统计里「识别不出分类」的兜底标签
      */
@@ -100,7 +82,7 @@ public class FileAnalysisTool {
      * 检索非表格材料清单
      */
     @Tool(name = "list_file_profiles",
-          description = "检索非表格材料清单(txt/doc/pdf/ppt/压缩包),返回分类与摘要;看正文用当前工具列表中的材料正文工具。",
+          description = "检索非表格材料清单(txt/doc/pdf/ppt/压缩包),返回分类与摘要。",
           readOnly = true)
     public ToolResultBlock listFileProfiles(
             @ToolParam(name = "query", description = "筛选条件,全部可空(不传即查全部)")
@@ -142,32 +124,6 @@ public class FileAnalysisTool {
         }
     }
 
-    /**
-     * 读取某份材料的正文样本
-     */
-    @Tool(name = "get_file_sample",
-          description = "读取某份非表格材料的正文片段(Tika 抽取的文本样本);fileId 从当前工具列表中的材料清单工具取。",
-          readOnly = true)
-    public ToolResultBlock getFileSample(
-            @ToolParam(name = "query", description = "材料 ID 与返回长度")
-            FileToolSpecs.FileSampleSpec query) {
-        FileToolSpecs.FileSampleSpec spec = query == null ? new FileToolSpecs.FileSampleSpec() : query;
-        try {
-            if (spec.fileId == null) {
-                return ToolResults.error("fileId 必传,取自 list_file_profiles 返回表格的 fileId 列");
-            }
-            FileAiProfile profile = profileService.getByFileId(spec.fileId);
-            if (profile == null) {
-                return ToolResults.error("未找到 fileId=" + spec.fileId + " 的材料档案。"
-                        + "请先用 list_file_profiles 确认该材料存在并取到正确的 fileId"
-                        + "(注意:表格类文件 xls/xlsx/csv 不在这张表里)");
-            }
-            return ToolResults.ok(Json.toStr(buildSamplePayload(profile, spec.maxLength)));
-        } catch (Exception e) {
-            return fail("读取材料正文样本", e);
-        }
-    }
-
     // ==================== 内部实现 ====================
 
     /**
@@ -246,50 +202,6 @@ public class FileAnalysisTool {
         return rows;
     }
 
-    /**
-     * 单份材料的正文样本载荷。
-     */
-    private static Map<String, Object> buildSamplePayload(FileAiProfile profile, Number maxLength) {
-        int limit = normalizeSampleLength(maxLength);
-        String text = profile.getSampleText();
-        boolean truncated = text != null && text.length() > limit;
-
-        Map<String, Object> payload = new LinkedHashMap<>();
-        payload.put("fileId", profile.getFileId());
-        payload.put("fileName", profile.getFileName());
-        payload.put("category", categoryLabel(profile.getCategory()));
-        payload.put("summary", profile.getSummary());
-        payload.put("keywords", profile.getKeywords());
-        payload.put("mimeType", profile.getMimeType());
-        payload.put("sampleLength", profile.getSampleLength());
-        payload.put("sampleText", text == null ? null : (truncated ? text.substring(0, limit) : text));
-        payload.put("truncated", truncated);
-        payload.put("failReason", profile.getFailReason());
-        if (text == null) {
-            payload.put("note", "该材料没有可用的文本样本(扫描件、加密压缩包、纯图片等),"
-                    + "无法提供正文;原因见 failReason。");
-        } else if (truncated) {
-            payload.put("note", "样本已被截断:完整样本共 " + text.length() + " 字符,本次返回前 " + limit
-                    + " 字符(上限 " + SAMPLE_MAX_CHARS + ")。需要看后面的内容请说明,"
-                    + "或改从 list_file_profiles 的 summary / keywords 判断材料内容。");
-        }
-        return payload;
-    }
-
-    /**
-     * 样本长度归一化:null 取默认,非法取默认,超上限截断到上限。
-     */
-    private static int normalizeSampleLength(Number maxLength) {
-        if (maxLength == null) {
-            return SAMPLE_DEFAULT_CHARS;
-        }
-        int value = maxLength.intValue();
-        if (value <= 0) {
-            return SAMPLE_DEFAULT_CHARS;
-        }
-        return Math.min(value, SAMPLE_MAX_CHARS);
-    }
-
     /**
      * 分类名 → 中文(落库存的是 {@code FileCategoryEnum} 的 name)。
      */

+ 0 - 23
ai-server/src/main/java/com/zsjz/ai/module/ai/core/agent/tools/business/FileToolSpecs.java

@@ -82,27 +82,4 @@ public final class FileToolSpecs {
                    required = false)
         public String parseStatus;
     }
-
-    /**
-     * 读取材料正文样本参数({@code get_file_sample})
-     */
-    @JsonInclude(JsonInclude.Include.NON_NULL)
-    public static class FileSampleSpec {
-
-        /**
-         * 材料 ID
-         */
-        @ToolParam(name = "fileId",
-                   description = "材料 ID,必填;取自 list_file_profiles 返回表格的 fileId 列(或 stat 结果里对应分类下再列一次)",
-                   required = true)
-        public Long fileId;
-
-        /**
-         * 最多返回多少字符
-         */
-        @ToolParam(name = "maxLength",
-                   description = "最多返回多少字符,默认 2000,上限 4000(采集时定的样本上限就是 4000,传更大也只能拿到 4000)",
-                   required = false)
-        public Number maxLength;
-    }
 }

+ 5 - 0
ai-server/src/main/java/com/zsjz/ai/module/ai/domain/AiTool.java

@@ -91,6 +91,11 @@ public class AiTool extends BaseEntity {
      */
     private String mcpExposed;
 
+    /**
+     * 排序值(升序,越小越靠前;默认 0)
+     */
+    private Integer sortOrder;
+
     /**
      * 备注
      */

+ 5 - 0
ai-server/src/main/java/com/zsjz/ai/module/ai/domain/bo/AiToolBo.java

@@ -67,6 +67,11 @@ public class AiToolBo implements Serializable {
      */
     private String status;
 
+    /**
+     * 排序值(升序,越小越靠前;新增留空默认 0,修改留空保持原值)
+     */
+    private Integer sortOrder;
+
     /**
      * 备注
      */

+ 5 - 0
ai-server/src/main/java/com/zsjz/ai/module/ai/domain/vo/AiToolVo.java

@@ -68,6 +68,11 @@ public class AiToolVo implements Serializable {
     @TableField(exist = false)
     private List<AiToolTagVo> tags;
 
+    /**
+     * 排序值(升序,越小越靠前;默认 0)
+     */
+    private Integer sortOrder;
+
     /**
      * 备注
      */

+ 7 - 16
ai-server/src/main/java/com/zsjz/ai/module/ai/service/impl/AiChatAttachmentServiceImpl.java

@@ -1,6 +1,5 @@
 package com.zsjz.ai.module.ai.service.impl;
 
-import cn.hutool.http.HttpUtil;
 import com.baomidou.mybatisplus.core.toolkit.Wrappers;
 import lombok.RequiredArgsConstructor;
 import lombok.extern.slf4j.Slf4j;
@@ -216,15 +215,18 @@ public class AiChatAttachmentServiceImpl implements IAiChatAttachmentService {
 
     @Override
     public byte[] downloadBytes(Long ossId) {
-        String url = resolveUrl(ossId);
+        // 直读本地存储:/files/** 需要登录态,服务端内部 HTTP 请求没有 token,
+        // 会把 401 报文当成附件内容(解析 / OCR 出来的都是错误 JSON)
         byte[] bytes;
         try {
-            bytes = HttpUtil.downloadBytes(url);
+            bytes = ossService.readBytes(ossId);
+        } catch (ServiceException e) {
+            throw e;
         } catch (Exception e) {
-            throw new ServiceException("文件下载失败:" + e.getMessage());
+            throw new ServiceException("文件读取失败:" + e.getMessage());
         }
         if (bytes == null || bytes.length == 0) {
-            throw new ServiceException("文件下载失败,请检查对象存储配置与文件是否仍然存在");
+            throw new ServiceException("文件读取失败,请检查文件是否仍然存在");
         }
         return bytes;
     }
@@ -338,17 +340,6 @@ public class AiChatAttachmentServiceImpl implements IAiChatAttachmentService {
         return vo;
     }
 
-    /**
-     * 解析 OSS 服务端读写地址(下载用,忽略对外域名,不存在即报错)。
-     */
-    private String resolveUrl(Long ossId) {
-        String url = resolveInternalUrlQuietly(ossId);
-        if (StringUtils.isBlank(url)) {
-            throw new ServiceException("文件不存在或已被删除,请重新上传");
-        }
-        return url;
-    }
-
     /**
      * 解析 OSS 服务端读写地址(下载用,忽略对外域名,不存在时返回 null 而不报错)。
      */

+ 14 - 24
ai-server/src/main/java/com/zsjz/ai/module/ai/service/impl/AiDocumentServiceImpl.java

@@ -1,6 +1,5 @@
 package com.zsjz.ai.module.ai.service.impl;
 
-import cn.hutool.http.HttpUtil;
 import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
 import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
 import com.baomidou.mybatisplus.core.toolkit.Wrappers;
@@ -271,7 +270,12 @@ public class AiDocumentServiceImpl implements IAiDocumentService {
             }
             throw new ServiceException("文档解析失败:" + e.getMessage());
         }
-        return queryById(id);
+        // 解析可能跑在批量线程池(无 Sa-Token 上下文),不能走 queryById:
+        // 其 requireVisibleKb 会调用 LoginHelper.getUserId() 抛「上下文尚未初始化」,
+        // 导致「自动入库」解析成功后中断、无法继续向量化
+        AiDocumentVo vo = baseMapper.selectVoById(id);
+        fillFileUrl(vo);
+        return vo;
     }
 
     @Override
@@ -981,19 +985,23 @@ public class AiDocumentServiceImpl implements IAiDocumentService {
     /**
      * 下载文档字节。
      *
+     * <p>直接读本地存储,不要回源 {@code /files/**}:该端点需要登录态,
+     * 服务端内部 HTTP 请求没有 token,会把 401 报文当成文件内容解析。</p>
+     *
      * @param document 文档
      * @return 文件字节
      */
     private byte[] download(AiDocument document) {
-        String url = resolveInternalUrl(document.getOssId());
         byte[] bytes;
         try {
-            bytes = HttpUtil.downloadBytes(url);
+            bytes = ossService.readBytes(document.getOssId());
+        } catch (ServiceException e) {
+            throw e;
         } catch (Exception e) {
-            throw new ServiceException("文件下载失败:" + e.getMessage());
+            throw new ServiceException("文件读取失败:" + e.getMessage());
         }
         if (bytes == null || bytes.length == 0) {
-            throw new ServiceException("文件下载失败,请检查对象存储配置与文件是否仍然存在");
+            throw new ServiceException("文件读取失败,请检查文件是否仍然存在");
         }
         return bytes;
     }
@@ -1036,24 +1044,6 @@ public class AiDocumentServiceImpl implements IAiDocumentService {
         }
     }
 
-    /**
-     * 解析 OSS 文件的服务端读写地址(下载/解析源文件用,忽略对外域名)。
-     *
-     * @param ossId OSS 主键
-     * @return 服务端读写地址
-     */
-    private String resolveInternalUrl(Long ossId) {
-        if (ossId == null) {
-            throw new ServiceException("文件未上传,请重新上传后再提交");
-        }
-        String urls = ossService.selectInternalUrlByIds(String.valueOf(ossId));
-        if (StringUtils.isBlank(urls)) {
-            throw new ServiceException("文件不存在或已被删除,请重新上传");
-        }
-        int index = urls.indexOf(',');
-        return index > 0 ? urls.substring(0, index) : urls;
-    }
-
     /**
      * 更新解析状态。
      *

+ 29 - 7
ai-server/src/main/java/com/zsjz/ai/module/ai/service/impl/AiModelConfigServiceImpl.java

@@ -423,9 +423,9 @@ public class AiModelConfigServiceImpl implements IAiModelConfigService {
             result.setMessage("本地模型目前仅支持向量模型(embedding)");
             return;
         }
-        if (StringUtils.isBlank(bo.getBaseUrl())) {
-            bo.setBaseUrl(defaultLocalModelPath());
-        }
+        // 修改既有模型再切换到本地提供商时,baseUrl 会被前端置空,
+        // fillFromStored 又会把原在线模型的服务地址补回来;统一归一化为内置模型目录
+        bo.setBaseUrl(resolveLocalModelPath(bo.getBaseUrl()));
         Integer dimension = bo.getDimension();
         if (dimension == null || dimension <= 0) {
             result.setSuccess(false);
@@ -662,10 +662,8 @@ public class AiModelConfigServiceImpl implements IAiModelConfigService {
             if (!isEmbedding(entity.getModelType())) {
                 throw new ServiceException("本地 ONNX 模型目前仅支持向量模型(embedding)");
             }
-            // 本地模型目录不在页面展示 / 修改:新建时用内置模型目录兜底
-            if (StringUtils.isBlank(entity.getBaseUrl())) {
-                entity.setBaseUrl(defaultLocalModelPath());
-            }
+            // 本地模型目录不在页面展示 / 修改:空白或残留的 HTTP 地址统一用内置模型目录兜底
+            entity.setBaseUrl(resolveLocalModelPath(entity.getBaseUrl()));
             if (entity.getDimension() == null || entity.getDimension() <= 0) {
                 throw new ServiceException("本地向量模型必须填写向量维度(bge-m3 为 1024)");
             }
@@ -696,6 +694,30 @@ public class AiModelConfigServiceImpl implements IAiModelConfigService {
         return StringUtils.isNotBlank(path) ? path : "qingjian/system/models/bge-m3";
     }
 
+    /**
+     * 本地模型目录归一化:空白或误填 HTTP 服务地址时回退内置模型目录。
+     *
+     * <p>本地模型的目录由服务端内置、页面不展示也不允许修改。把既有在线模型改成
+     * 本地提供商时,表单里残留的服务地址(或按主键从旧配置补齐的地址)不是目录,
+     * 不能直接交给 {@code validateModelDir},否则连通性测试 / 保存会误报
+     * 「本地 ONNX 模型需要填写模型目录」。显式填写的非 HTTP 目录原样保留,
+     * 兼容通过 API 指定其他本地模型。</p>
+     *
+     * @param baseUrl 入参中的模型目录
+     * @return 可用于本地推理的模型目录
+     */
+    private String resolveLocalModelPath(String baseUrl) {
+        String path = StringUtils.trim(baseUrl);
+        if (StringUtils.isBlank(path)) {
+            return defaultLocalModelPath();
+        }
+        String lower = path.toLowerCase(Locale.ROOT);
+        if (lower.startsWith("http://") || lower.startsWith("https://")) {
+            return defaultLocalModelPath();
+        }
+        return path;
+    }
+
     /**
      * 归一化提供商:本地模型的别名(本地 / 内置 / onnx)统一落为 {@code local}。
      *

+ 8 - 0
ai-server/src/main/java/com/zsjz/ai/module/ai/service/impl/AiToolServiceImpl.java

@@ -90,6 +90,8 @@ public class AiToolServiceImpl implements IAiToolService {
     public List<AiToolVo> queryOptions() {
         LambdaQueryWrapper<AiTool> lqw = Wrappers.lambdaQuery();
         lqw.eq(AiTool::getStatus, AiTool.STATUS_ENABLED);
+        // 业务工具选择下拉按管理端配置的排序值展示(同值按编码,保证顺序稳定)
+        lqw.orderByAsc(AiTool::getSortOrder);
         lqw.orderByAsc(AiTool::getToolCode);
         return baseMapper.selectVoList(lqw);
     }
@@ -217,6 +219,10 @@ public class AiToolServiceImpl implements IAiToolService {
         if (StringUtils.isBlank(entity.getStatus())) {
             entity.setStatus(exists == null ? AiTool.STATUS_ENABLED : exists.getStatus());
         }
+        // 排序值:新增未填按 0;修改未填沿用原值(MapStruct 转换后为 null)
+        if (entity.getSortOrder() == null) {
+            entity.setSortOrder(exists == null ? 0 : exists.getSortOrder());
+        }
     }
 
     /**
@@ -232,6 +238,8 @@ public class AiToolServiceImpl implements IAiToolService {
             .or().like(AiTool::getToolName, bo.getKeyword()));
         lqw.eq(StringUtils.isNotBlank(bo.getToolType()), AiTool::getToolType, bo.getToolType());
         lqw.eq(StringUtils.isNotBlank(bo.getStatus()), AiTool::getStatus, bo.getStatus());
+        // 管理端列表:排序值升序,同值按工具编码升序
+        lqw.orderByAsc(AiTool::getSortOrder);
         lqw.orderByAsc(AiTool::getToolCode);
         return lqw;
     }

Failā izmaiņas netiks attēlotas, jo tās ir par lielu
+ 1 - 1
sql/ai_business_tools_seed.sql


+ 3 - 0
sql/ai_orchestration.sql

@@ -813,11 +813,14 @@ create table if not exists ai_tool (
     update_by     bigint,
     update_time   timestamp,
     mcp_exposed   char(1)      default '0',
+    sort_order    integer      not null default 0,
     constraint pk_ai_tool primary key (id)
 );
 
 comment on table ai_tool is '业务工具注册表(可被智能体调用的语义化工具)';
 
+comment on column ai_tool.sort_order is '排序值(升序,越小越靠前;默认 0)';
+
 comment on column ai_tool.tool_type is '工具类型(0只读 1写入;写入类需 P2 的 HITL 确认闭环)';
 
 comment on column ai_tool.params_schema is '参数定义(JSON Schema)';

+ 12 - 0
sql/ai_tool_sort_order_20261119.sql

@@ -0,0 +1,12 @@
+-- ============================================================
+-- 业务工具注册表新增排序字段(2026-11-19)
+--
+-- 用途:业务工具注册页 / 智能体工具选择下拉按 sort_order 升序展示,
+--       数值越小越靠前,默认 0;同值再按工具编码升序,保证顺序稳定。
+-- 幂等:可重复执行。
+-- ============================================================
+
+alter table ai_tool
+    add column if not exists sort_order integer not null default 0;
+
+comment on column ai_tool.sort_order is '排序值(升序,越小越靠前;默认 0)';

Daži faili netika attēloti, jo izmaiņu fails ir pārāk liels