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

feat: 上传页增加大模型预检与连通性检测

- 新增 /sys/llmConfig/test:用最小请求检测配置可用性,失败返回原因而不抛异常
- 大模型设置保存后自动检测连通性,失败保留弹框便于就地修正
- 上传页进入时静默检查,未就绪改用页面内提示条引导,不打断上传
- 仅点「智能清洗」且模型未就绪时弹出引导弹框(项目 BasicModal)
- 补充 LlmService 连通性检测单测
cc 1 день назад
Родитель
Сommit
97c132e83b

+ 189 - 1
ai-electron/frontend/src/case/views/data/upload.vue

@@ -31,6 +31,20 @@
         </div>
       </div>
 
+      <!-- 大模型状态提示:非阻断,不打断上传;用户点「智能清洗」时才用弹框引导 -->
+      <div v-if="llmBannerVisible" class="llm-banner">
+        <ExclamationCircleOutlined class="llm-banner__icon" />
+        <div class="llm-banner__body">
+          <span class="llm-banner__title">大模型未就绪</span>
+          <span class="llm-banner__desc">{{ llmCheckMessage }}</span>
+          <span class="llm-banner__desc">未配置大模型将无法使用 AI 大模型进行数据清洗。</span>
+        </div>
+        <div class="llm-banner__actions">
+          <Button size="small" type="primary" @click="handleConfigureLlm">配置模型</Button>
+          <Button size="small" type="text" @click="dismissLlmBanner">关闭</Button>
+        </div>
+      </div>
+
       <div class="upload-layout">
         <aside class="left-panel">
           <div class="upload-picker">
@@ -179,14 +193,34 @@
         </section>
       </div>
     </div>
+
+    <!-- 大模型检查引导:进入页面校验一次配置与连通性,仅提示、不阻断 -->
+    <BasicModal
+      @register="registerLlmGuideModal"
+      title="大模型未就绪"
+      :width="560"
+      :centered="true"
+      okText="配置模型"
+      cancelText="关闭提示"
+      @ok="handleConfigureLlm"
+    >
+      <div class="llm-check">
+        <p class="llm-check__message">{{ llmCheckMessage }}</p>
+        <p class="llm-check__hint">未配置大模型,将无法使用 AI 大模型进行数据清洗。</p>
+        <p class="llm-check__hint">可先完成配置,保存时会自动检测连通性;也可以关闭提示后继续使用其他功能。</p>
+      </div>
+    </BasicModal>
+
+    <LlmSettingModal @register="registerLlmSettingModal" @success="handleLlmConfigured" />
   </div>
 </template>
 
 <script lang="ts" setup name="ViewsDataUpload">
   import { computed, h, onMounted, ref } from 'vue';
   import { onBeforeRouteLeave } from 'vue-router';
-  import { CloseOutlined, LeftOutlined } from '@ant-design/icons-vue';
+  import { CloseOutlined, ExclamationCircleOutlined, LeftOutlined } from '@ant-design/icons-vue';
   import { Button, Modal, Table, Tooltip, type TableColumnsType } from 'ant-design-vue';
+  import { BasicModal, useModal } from '@/core/components/Modal';
   import { useDesign } from '@/core/hooks/web/useDesign';
   import { useGo, useQuery } from '@/core/hooks/web/usePage';
   import { PageEnum } from '@/core/enums/pageEnum';
@@ -196,6 +230,8 @@
   import { clearUploadBatch, deletedFileList, preFileUpload, smartClean } from '@/case/api/govern/governApi';
   import { FileStatusEnum } from '@/case/types/enum';
   import { isDesktopDialogAvailable, pickDirectories } from '@/core/utils/desktop/pathPicker';
+  import { getLlmConfig, testLlmConfig } from '@/core/layouts/default/setting/api';
+  import LlmSettingModal from '@/core/layouts/default/setting/components/LlmSettingModal.vue';
   import CaseFlowTopBar from './components/CaseFlowTopBar.vue';
   import { resetImportProgressSession } from './importProgressSession';
   import type { FileInfo } from '@/types/api';
@@ -210,6 +246,19 @@
   const RECLEAN_CONTEXT_STORAGE_KEY = 'case_clean_reclean_context';
   const CASE_DATA_REFRESH_EVENT = 'case-data:refresh';
 
+  /** 大模型配置弹框(项目 BasicModal,直接引入避免异步加载前注册不到) */
+  const [registerLlmSettingModal, { openModal: openLlmSettingModal }] = useModal();
+  /** 大模型检查引导弹框(项目 BasicModal):仅在点「智能清洗」且模型未就绪时使用 */
+  const [registerLlmGuideModal, { openModal: openLlmGuideModal, closeModal: closeLlmGuideModal }] = useModal();
+  const llmCheckMessage = ref('');
+  /** 大模型是否可用;入口检查结果只驱动页面提示条,不弹窗打断 */
+  const llmReady = ref(false);
+  const llmBannerVisible = ref(false);
+  /** 用户手动关闭提示条后,本次停留不再自动弹出(点智能清洗仍会校验) */
+  const llmBannerDismissed = ref(false);
+  /** 复用同一次检查,避免入口与「智能清洗」各发一次模型请求 */
+  let llmCheckPromise: Promise<boolean> | null = null;
+
   type UploadMode = 'single' | 'folder';
 
   /** 进入上传页即生成批次 id,本页所有文件统一使用该批次(Long 型,上限约 1.7e18,安全) */
@@ -619,8 +668,72 @@
     }
   };
 
+  /**
+   * 检查大模型:是否已配置、能否正常连接。
+   *
+   * <p>入口检查只更新页面内的提示条,不弹窗、不阻断上传;
+   * 只有用户点「智能清洗」(真正依赖模型的操作)时才用弹框引导。
+   */
+  const showLlmBanner = (message: string) => {
+    llmCheckMessage.value = message;
+    if (!llmBannerDismissed.value) {
+      llmBannerVisible.value = true;
+    }
+  };
+
+  const dismissLlmBanner = () => {
+    llmBannerDismissed.value = true;
+    llmBannerVisible.value = false;
+  };
+
+  const runLlmCheck = async (): Promise<boolean> => {
+    try {
+      const config = await getLlmConfig();
+      if (!config?.baseUrl?.trim() || !config?.model?.trim()) {
+        llmReady.value = false;
+        showLlmBanner('尚未配置大模型服务。');
+        return false;
+      }
+      const result = await testLlmConfig();
+      if (!result?.connected) {
+        llmReady.value = false;
+        showLlmBanner(result?.message || '大模型连接失败,请检查服务地址、模型名称与网络配置。');
+        return false;
+      }
+      llmReady.value = true;
+      llmBannerVisible.value = false;
+      return true;
+    } catch (error: any) {
+      llmReady.value = false;
+      showLlmBanner(error?.message || '大模型状态检查失败,请检查网络或服务是否可用。');
+      return false;
+    }
+  };
+
+  /** 复用同一次检查:入口与「智能清洗」不会各发一次模型请求 */
+  const ensureLlmReady = (): Promise<boolean> => {
+    if (!llmCheckPromise) {
+      llmCheckPromise = runLlmCheck();
+    }
+    return llmCheckPromise;
+  };
+
+  /** 大模型保存且连接通过:解除限制并收起提示条 */
+  const handleLlmConfigured = () => {
+    llmReady.value = true;
+    llmBannerVisible.value = false;
+    llmCheckPromise = Promise.resolve(true);
+  };
+
+  /** 打开大模型设置弹框(提示条与引导弹框共用),保存时由设置弹框自行检测连通性 */
+  const handleConfigureLlm = () => {
+    closeLlmGuideModal();
+    openLlmSettingModal(true);
+  };
+
   onMounted(() => {
     restoreParsedResults();
+    void ensureLlmReady();
   });
 
   const isOwnBatchStorage = () => {
@@ -937,6 +1050,14 @@
     if (!hasCleanableSheet.value || smartCleaning.value) return;
     smartCleaning.value = true;
     try {
+      // 智能清洗依赖大模型:入口提示条不打断上传,真正点清洗时才校验并弹框引导
+      if (!llmReady.value) {
+        const ready = await ensureLlmReady();
+        if (!ready) {
+          openLlmGuideModal(true);
+          return;
+        }
+      }
       const fileInfos = allFileInfos.value as unknown as FileInfo[];
       persistFileInfos(allFileInfos.value);
       const res = await smartClean({ fileInfos, reClean: 0 });
@@ -1736,4 +1857,71 @@
       }
     }
   }
+
+  .llm-check {
+    display: flex;
+    flex-direction: column;
+    gap: 8px;
+
+    &__message {
+      margin: 0;
+      color: #374151;
+      font-size: 13px;
+      line-height: 1.7;
+    }
+
+    &__hint {
+      margin: 0;
+      color: #6b7280;
+      font-size: 12px;
+      line-height: 1.7;
+    }
+  }
+
+  /* 大模型状态提示条:页面内非阻断提示,避免上传途中突然弹窗 */
+  .llm-banner {
+    display: flex;
+    flex: 0 0 auto;
+    align-items: center;
+    gap: 10px;
+    padding: 8px 12px;
+    color: #92400e;
+    background: #fffbeb;
+    border: 1px solid #fde68a;
+    border-radius: 10px;
+
+    &__icon {
+      flex: 0 0 auto;
+      font-size: 15px;
+      color: #d97706;
+    }
+
+    &__body {
+      display: flex;
+      flex: 1 1 auto;
+      flex-wrap: wrap;
+      align-items: baseline;
+      gap: 2px 10px;
+      min-width: 0;
+    }
+
+    &__title {
+      flex: 0 0 auto;
+      font-size: 13px;
+      font-weight: 600;
+    }
+
+    &__desc {
+      color: #b45309;
+      font-size: 12px;
+      line-height: 1.6;
+    }
+
+    &__actions {
+      display: flex;
+      flex: 0 0 auto;
+      align-items: center;
+      gap: 4px;
+    }
+  }
 </style>

+ 22 - 0
ai-electron/frontend/src/core/layouts/default/setting/api.ts

@@ -49,6 +49,28 @@ export const getLlmConfig = () => defHttp.get<LlmConfig>({ url: adminPath + '/sy
 export const saveLlmConfig = (config: LlmConfig) =>
   defHttp.post<void>({ url: adminPath + '/sys/llmConfig', params: config });
 
+/** 大模型连通性检测结果 */
+export interface LlmTestResult {
+  /** 是否连通(已配置、服务可达且返回 200) */
+  connected: boolean;
+  /** 实际请求的模型名 */
+  modelName: string;
+  /** 检测耗时(毫秒);后端 Long 统一序列化为字符串 */
+  elapsedMs: number | string;
+  /** 失败原因或「连接正常」 */
+  message: string;
+}
+
+/**
+ * 检测已保存的大模型配置能否正常连接。
+ * 后端会发一条最小请求(10 秒超时),失败时也返回 200 + connected=false,便于前端引导。
+ */
+export const testLlmConfig = () =>
+  defHttp.post<LlmTestResult>({
+    url: adminPath + '/sys/llmConfig/test',
+    timeout: 20 * 1000,
+  });
+
 /**
  * 上传升级包并执行升级(Web 化:前端上传 zip,不再传服务端路径)。
  * 升级耗时较长(解压 + 复制基础库 + 逐案执行案件库升级 SQL),超时给了 30 分钟。

+ 31 - 5
ai-electron/frontend/src/core/layouts/default/setting/components/LlmSettingModal.vue

@@ -126,11 +126,16 @@
   import { BasicModal, useModalInner } from '@/core/components/Modal';
   import { useDesign } from '@/core/hooks/web/useDesign';
   import { useMessage } from '@/core/hooks/web/useMessage';
-  import { getLlmConfig, saveLlmConfig, type LlmConfig } from '../api';
+  import { getLlmConfig, saveLlmConfig, testLlmConfig, type LlmConfig, type LlmTestResult } from '../api';
 
   const { prefixCls } = useDesign('llm-setting');
   const { createMessage } = useMessage();
 
+  /** 保存且连通性检测通过后抛出,供上传页等入口解除限制 */
+  const emit = defineEmits<{
+    (e: 'success', result: LlmTestResult): void;
+  }>();
+
   interface LlmConfigForm {
     baseUrl: string;
     apiKey: string;
@@ -240,11 +245,32 @@
     saving.value = true;
     setModalProps({ confirmLoading: true });
     try {
-      await saveLlmConfig(payload);
-      createMessage.success('大模型配置已保存');
+      try {
+        await saveLlmConfig(payload);
+      } catch (error: any) {
+        createMessage.error(error?.message || '保存大模型配置失败');
+        return;
+      }
+
+      // 保存后立即做一次连通性检测:配置能写进去不代表模型可用,
+      // 失败时保留弹框,方便用户就地修正地址/模型/Key
+      let result: LlmTestResult;
+      try {
+        result = await testLlmConfig();
+      } catch (error: any) {
+        createMessage.error(`配置已保存,但连接检测失败:${error?.message || '网络异常'}`);
+        return;
+      }
+      if (!result?.connected) {
+        createMessage.error(`配置已保存,但连接失败:${result?.message || '请检查服务地址、模型与网络'}`);
+        return;
+      }
+
+      createMessage.success(
+        result.elapsedMs ? `大模型配置已保存,连接正常(${result.elapsedMs}ms)` : '大模型配置已保存,连接正常',
+      );
+      emit('success', result);
       closeModal();
-    } catch (error: any) {
-      createMessage.error(error?.message || '保存大模型配置失败');
     } finally {
       saving.value = false;
       setModalProps({ confirmLoading: false });

+ 41 - 0
ai-server/src/main/java/com/zsjz/ai/common/llm/LlmService.java

@@ -175,6 +175,47 @@ public class LlmService {
     public record StructuredResult<T>(T value, LlmResult raw) {
     }
 
+    // ==================== 连通性自检 ====================
+
+    /**
+     * 连通性自检:用一条最小请求验证「已配置 + 服务可达 + 返回 200」。
+     *
+     * <p>不抛异常:设置页与上传页的引导弹框需要把失败原因展示给用户,
+     * 因此成功/失败、模型名、耗时与错误信息都放在返回值里。
+     * 思考模式强制关闭,避免推理 token 吃光 max_tokens 被误判为连接失败;
+     * 总时长限制 10 秒,避免引导弹框长时间等待。
+     */
+    public ConnectivityResult testConnection() {
+        LlmProperties config = configSupplier.get();
+        String model = StringUtils.hasText(config.getModel()) ? config.getModel().trim() : "";
+        if (!StringUtils.hasText(config.getBaseUrl()) || !StringUtils.hasText(model)) {
+            return new ConnectivityResult(false, model, 0L,
+                    "尚未配置大模型:请填写服务地址与模型名称");
+        }
+        long start = System.currentTimeMillis();
+        try {
+            LlmResult result = chatDetail(LlmRequest.builder()
+                    .user("请只回复两个字母:OK")
+                    .temperature(0.0)
+                    .maxTokens(16)
+                    .enableThinking(false)
+                    .timeout(Duration.ofSeconds(10))
+                    .build());
+            return new ConnectivityResult(true, result.modelName(), result.elapsedMs(), "连接正常");
+        } catch (Exception e) {
+            String message = StringUtils.hasText(e.getMessage()) ? e.getMessage() : "连接失败";
+            log.warn("大模型连通性检测失败: model={}, error={}", model, message);
+            return new ConnectivityResult(false, model, System.currentTimeMillis() - start, message);
+        }
+    }
+
+    /**
+     * 连通性检测结果:是否连通、模型名、耗时与可直接展示给用户的说明。
+     */
+    public record ConnectivityResult(boolean connected, String modelName,
+                                     long elapsedMs, String message) {
+    }
+
     // ==================== 内部 ====================
 
     private String requireModel(LlmProperties config) {

+ 16 - 0
ai-server/src/main/java/com/zsjz/ai/module/plat/controller/SystemController.java

@@ -3,6 +3,7 @@ package com.zsjz.ai.module.plat.controller;
 
 import com.zsjz.ai.common.config.Result;
 import com.zsjz.ai.common.llm.LlmConfigService;
+import com.zsjz.ai.common.llm.LlmService;
 import com.zsjz.ai.common.model.plat.dto.LlmConfigDTO;
 import com.zsjz.ai.common.model.plat.dto.ServiceHealthDTO;
 import com.zsjz.ai.common.model.plat.entity.SystemInfo;
@@ -53,6 +54,9 @@ public class SystemController {
     @Autowired
     private LlmConfigService llmConfigService;
 
+    @Autowired
+    private LlmService llmService;
+
     /**
      * 健康检查接口
      * 用于检测系统是否正常运行
@@ -87,6 +91,18 @@ public class SystemController {
         return Result.succeed();
     }
 
+    /**
+     * 检测大模型连通性
+     *
+     * <p>用已保存的配置发一条最小请求:未配置、地址不可达、鉴权失败、超时等情况
+     * 都返回 {@code connected=false} + 可直接展示的原因,不抛异常,
+     * 便于设置页保存后校验以及上传页的引导弹框。
+     */
+    @PostMapping("/llmConfig/test")
+    public Result<LlmService.ConnectivityResult> testLlmConfig() {
+        return Result.succeed(llmService.testConnection());
+    }
+
     /**
      * 系统服务健康状态
      * 供「设置 → 系统服务」展示后端、PostgreSQL 的可用性与探测耗时

+ 40 - 0
ai-server/src/test/java/com/zsjz/ai/common/llm/LlmServiceTest.java

@@ -346,6 +346,46 @@ class LlmServiceTest {
         assertEquals(500, assertThrows(ServerException.class, () -> llmService.chat("hi")).getCode());
     }
 
+    @Test
+    @DisplayName("连通性自检:成功返回 connected=true + 模型名,并强制关闭思考模式")
+    void testConnectionSucceeds() throws Exception {
+        stub(200, completion("OK"), 0);
+
+        LlmService.ConnectivityResult result = llmService.testConnection();
+
+        assertTrue(result.connected());
+        assertEquals("stub-model", result.modelName());
+        assertTrue(result.elapsedMs() >= 0);
+        assertEquals("连接正常", result.message());
+        JsonNode body = sentBody();
+        assertEquals(16, body.path("max_tokens").asInt());
+        assertFalse(body.path("chat_template_kwargs").path("enable_thinking").asBoolean(true));
+    }
+
+    @Test
+    @DisplayName("连通性自检:未配置时返回 connected=false,不抛异常")
+    void testConnectionReportsMissingConfig() {
+        LlmProperties empty = new LlmProperties();
+        empty.setBaseUrl("");
+        empty.setModel("");
+
+        LlmService.ConnectivityResult result = new LlmService(empty).testConnection();
+
+        assertFalse(result.connected());
+        assertTrue(result.message().contains("尚未配置"));
+    }
+
+    @Test
+    @DisplayName("连通性自检:服务端 500 也返回 connected=false + 原因,不抛异常")
+    void testConnectionReportsHttpFailure() {
+        stub(500, "{\"error\":\"boom\"}", 0);
+
+        LlmService.ConnectivityResult result = llmService.testConnection();
+
+        assertFalse(result.connected());
+        assertTrue(result.message().contains("HTTP 500"));
+    }
+
     /** 结构化输出用的目标类型 */
     public static class Person {
         public String name;