一、概述

AI助手是企业知识库系统的智能化核心组件,通过集成大语言模型(LLM)为用户提供基于知识库的智能问答能力。

本文将详细介绍如何在项目中实现完整的AI助手功能,包括后端服务搭建和多模型支持。

1.1 功能定位

AI助手作为知识库的智能交互入口,提供以下核心功能:

功能模块说明使用场景
多模型对话支持千问(Qwen)和DeepSeek等大模型切换不同AI模型回答问题
流式问答SSE流式输出AI回复内容实时展示AI思考过程
对话管理创建、删除、查询历史对话管理多轮对话上下文
消息持久化对话记录存储到MySQL,支持历史回看查看历史聊天记录
Markdown渲染AI回复支持代码高亮、表格、列表等格式技术问答、代码生成
反馈机制点赞/踩消息反馈,辅助改进AI质量收集用户反馈

1.2 技术架构

未命名绘图-第 11 页.jpg

1.3 涉及模块

模块说明
kb-ai新建模块,AI服务的核心后端,端口8086
kb-gateway网关路由配置,转发 /api/ai/** 请求到 kb-ai
kb-common公共模块,提供 Result、PageResult 等通用类
knowledge-base-frontend前端项目,实现AI对话页面和状态管理

1.4 技术选型

技术用途版本
LangChain4jAI大模型集成框架(OpenAI兼容接口)0.29.1
MySQL + MyBatis-Plus对话和消息数据持久化8.0 / 3.5.8
Spring SSE (SseEmitter)服务端推送流式响应Spring Boot 3.2
React + Zustand前端对话页面和状态管理React 18
ReactMarkdown + PrismMarkdown渲染和代码高亮-
Ant DesignUI组件库5.x

二、数据库设计

2.1 创建AI模块专属数据库

CREATE DATABASE IF NOT EXISTS `kb_ai`
  DEFAULT CHARACTER SET utf8mb4
  DEFAULT COLLATE utf8mb4_unicode_ci;

USE `kb_ai`;

2.2 对话表(conversation)

CREATE TABLE `conversation` (
  `id` BIGINT NOT NULL AUTO_INCREMENT COMMENT '对话ID',
  `title` VARCHAR(100) NOT NULL DEFAULT '新对话' COMMENT '对话标题',
  `user_id` BIGINT NOT NULL COMMENT '用户ID',
  `model` VARCHAR(50) NOT NULL DEFAULT 'qwen' COMMENT '模型名称(qwen/deepseek)',
  `system_prompt` TEXT DEFAULT NULL COMMENT '系统提示词',
  `tokens_used` INT NOT NULL DEFAULT 0 COMMENT 'Token使用量',
  `message_count` INT NOT NULL DEFAULT 0 COMMENT '消息数量',
  `status` TINYINT NOT NULL DEFAULT 0 COMMENT '状态(0-进行中,1-已结束)',
  `create_time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `update_time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  `deleted` TINYINT NOT NULL DEFAULT 0 COMMENT '删除标识',
  PRIMARY KEY (`id`),
  KEY `idx_user_id` (`user_id`),
  KEY `idx_status` (`status`),
  KEY `idx_update_time` (`update_time`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='AI对话表';

2.3 消息表(message)

CREATE TABLE `message` (
  `id` BIGINT NOT NULL AUTO_INCREMENT COMMENT '消息ID',
  `conversation_id` BIGINT NOT NULL COMMENT '对话ID',
  `role` VARCHAR(20) NOT NULL COMMENT '角色类型(system/user/assistant)',
  `content` TEXT NOT NULL COMMENT '消息内容',
  `tokens` INT NOT NULL DEFAULT 0 COMMENT 'Token数量',
  `create_time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `deleted` TINYINT NOT NULL DEFAULT 0 COMMENT '删除标识',
  PRIMARY KEY (`id`),
  KEY `idx_conversation_id` (`conversation_id`),
  KEY `idx_role` (`role`),
  KEY `idx_create_time` (`create_time`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='AI消息表';

2.4 反馈表(ai\_feedback)

CREATE TABLE `ai_feedback` (
  `id` BIGINT NOT NULL AUTO_INCREMENT COMMENT '反馈ID',
  `conversation_id` BIGINT NOT NULL COMMENT '对话ID',
  `message_id` BIGINT NOT NULL COMMENT '消息ID',
  `user_id` BIGINT NOT NULL COMMENT '用户ID',
  `feedback_type` VARCHAR(50) NOT NULL COMMENT '反馈类型(positive/negative)',
  `feedback_content` VARCHAR(500) DEFAULT NULL COMMENT '反馈内容',
  `rating` INT DEFAULT NULL COMMENT '评分(1-5分)',
  `create_time` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `deleted` TINYINT NOT NULL DEFAULT 0 COMMENT '删除标识',
  PRIMARY KEY (`id`),
  KEY `idx_conversation_id` (`conversation_id`),
  KEY `idx_message_id` (`message_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='AI反馈表';

2.5 字段说明

conversation表:

字段类型说明必填默认值
idBIGINT对话ID是自增
titleVARCHAR(100)对话标题是新对话
user\_idBIGINT用户ID是-
modelVARCHAR(50)AI模型名称是qwen
tokens\_usedINT累计Token消耗是0
message\_countINT消息总数是0
statusTINYINT对话状态是0

message表:

字段类型说明必填默认值
idBIGINT消息ID是自增
conversation\_idBIGINT关联对话ID是-
roleVARCHAR(20)角色是-
contentTEXT消息内容是-
tokensINTToken消耗是0

2.6 索引设计

  • idx\_user\_id:加速按用户查询对话列表
  • idx\_conversation\_id:加速查询对话下的消息
  • idx\_role:加速按角色筛选消息
  • idx\_create\_time:按时间排序查询消息历史

三、创建kb-ai模块

3.1 创建模块目录结构

在父项目 knowledge-base-backend 下创建新模块 kb-ai:

kb-ai/
  pom.xml
  src/main/java/com/knowledge/base/ai/
    AiApplication.java
    config/
      AiSecurityConfig.java
      LangChain4jConfig.java
      ModelProvider.java
    controller/
      AiChatController.java
      AiConversationController.java
      AiFeedbackController.java
    dto/
      ChatRequestDTO.java
    entity/
      Conversation.java
      Message.java
      AiFeedback.java
    mapper/
      ConversationMapper.java
      MessageMapper.java
      AiFeedbackMapper.java
    service/
      AiChatService.java
      AiConversationService.java
      AiFeedbackService.java
    service/impl/
      AiChatServiceImpl.java
      AiConversationServiceImpl.java
      AiFeedbackServiceImpl.java
    vo/
      ChatResponseVO.java
      ConversationVO.java
      MessageVO.java
      ModelVO.java
  src/main/resources/
    application.yml
    mapper/
      ConversationMapper.xml
      MessageMapper.xml
      AiFeedbackMapper.xml

3.2 配置pom.xml

创建 kb-ai/pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
         http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>com.knowledge.base</groupId>
        <artifactId>knowledge-base-backend</artifactId>
        <version>1.0.0-SNAPSHOT</version>
    </parent>
    <artifactId>kb-ai</artifactId>
    <packaging>jar</packaging>
    <name>Knowledge Base AI Service</name>
    <description>AI服务模块</description>
    <properties>
        <langchain4j.version>0.29.1</langchain4j.version>
    </properties>
    <dependencies>
        <!-- kb-common -->
        <dependency>
            <groupId>com.knowledge.base</groupId>
            <artifactId>kb-common</artifactId>
        </dependency>
        <!-- Spring Boot Web -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!-- Spring Boot Validation -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-validation</artifactId>
        </dependency>
        <!-- MyBatis Plus -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
        </dependency>
        <!-- Druid -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-3-starter</artifactId>
        </dependency>
        <!-- MySQL -->
        <dependency>
            <groupId>com.mysql</groupId>
            <artifactId>mysql-connector-j</artifactId>
            <scope>runtime</scope>
        </dependency>
        <!-- LangChain4j -->
        <dependency>
            <groupId>dev.langchain4j</groupId>
            <artifactId>langchain4j</artifactId>
            <version>${langchain4j.version}</version>
        </dependency>
        <dependency>
            <groupId>dev.langchain4j</groupId>
            <artifactId>langchain4j-open-ai</artifactId>
            <version>${langchain4j.version}</version>
        </dependency>
        <!-- Lombok -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <!-- Knife4j -->
        <dependency>
            <groupId>com.github.xiaoymin</groupId>
            <artifactId>knife4j-openapi3-jakarta-spring-boot-starter</artifactId>
        </dependency>
        <!-- Hutool -->
        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
        </dependency>
        <!-- FastJSON2 -->
        <dependency>
            <groupId>com.alibaba.fastjson2</groupId>
            <artifactId>fastjson2</artifactId>
        </dependency>
        <!-- Apache Commons -->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
        </dependency>
        <!-- Nacos 配置中心 & 服务注册与发现(可选) -->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

3.3 在父pom.xml中注册模块

编辑 knowledge-base-backend/pom.xml,在 <modules> 中添加:

<modules>
    <module>kb-common</module>
    <module>kb-gateway</module>
    <!-- ... 其他模块 ... -->
    <module>kb-ai</module>  <!-- 新增 -->
</modules>

3.4 配置application.yml

创建 kb-ai/src/main/resources/application.yml:

server:
  port: 8086

spring:
  application:
    name: kb-ai

  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/kb_ai?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true
    username: root
    password: 123456

  sql:
    init:
      mode: never

mybatis-plus:
  mapper-locations: classpath:mapper/*.xml
  type-aliases-package: com.knowledge.base.ai.entity
  configuration:
    map-underscore-to-camel-case: true
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
  global-config:
    db-config:
      id-type: auto
      logic-delete-field: deleted
      logic-delete-value: 1
      logic-not-delete-value: 0

# Qwen配置(使用OpenAI兼容接口)
qwen:
  api-key: ${QWEN_API_KEY:your-qwen-api-key}
  base-url: ${QWEN_BASE_URL:https://dashscope.aliyuncs.com/compatible-mode/v1}
  chat:
    options:
      model: ${QWEN_MODEL:qwen3-max}
      temperature: 0.3
      max-tokens: 4000

# DeepSeek配置
deepseek:
  api-key: ${DEEPSEEK_API_KEY:your-deepseek-api-key}
  model: deepseek-chat
  base-url: https://api.deepseek.com/v1
  max-tokens: 4096
  temperature: 0.7

# AI默认配置
ai:
  default-model: qwen

# 日志配置
logging:
  level:
    com.knowledge.base.ai: DEBUG
    dev.langchain4j: DEBUG
  pattern:
    console: '%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{50} - %msg%n'

3.5 创建启动类

创建 kb-ai/src/main/java/com/knowledge/base/ai/AiApplication.java:

package com.knowledge.base.ai;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * AI服务启动类
 *
 * @author 苏三
 * @since 1.0.0
 */
@SpringBootApplication
@MapperScan("com.knowledge.base.ai.mapper")
public class AiApplication {

    public static void main(String[] args) {
        SpringApplication.run(AiApplication.class, args);
    }
}

四、实体类设计

4.1 创建Conversation实体类

创建 kb-ai/src/main/java/com/knowledge/base/ai/entity/Conversation.java:

package com.knowledge.base.ai.entity;

import com.baomidou.mybatisplus.annotation.*;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.time.LocalDateTime;

/**
 * AI对话实体类
 *
 * @author 苏三
 * @since 1.0.0
 */
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@TableName("conversation")
public class Conversation {

    /**
     * 主键ID
     */
    @TableId(value = "id", type = IdType.AUTO)
    private Long id;

    /**
     * 对话标题
     */
    @TableField("title")
    private String title;

    /**
     * 用户ID
     */
    @TableField("user_id")
    private Long userId;

    /**
     * 模型名称
     */
    @TableField("model")
    private String model;

    /**
     * 系统提示词
     */
    @TableField("system_prompt")
    private String systemPrompt;

    /**
     * Token使用量
     */
    @TableField("tokens_used")
    private Integer tokensUsed;

    /**
     * 消息数量
     */
    @TableField("message_count")
    private Integer messageCount;

    /**
     * 状态(0-进行中,1-已结束)
     */
    @TableField("status")
    private Integer status;

    /**
     * 创建时间
     */
    @TableField(value = "create_time", fill = FieldFill.INSERT)
    private LocalDateTime createTime;

    /**
     * 更新时间
     */
    @TableField(value = "update_time", fill = FieldFill.INSERT_UPDATE)
    private LocalDateTime updateTime;

    /**
     * 逻辑删除标志
     */
    @TableLogic
    @TableField("deleted")
    private Integer deleted;
}

4.2 创建Message实体类

创建 kb-ai/src/main/java/com/knowledge/base/ai/entity/Message.java:

package com.knowledge.base.ai.entity;

import com.baomidou.mybatisplus.annotation.*;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.time.LocalDateTime;

/**
 * AI消息实体类
 *
 * @author 苏三
 * @since 1.0.0
 */
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@TableName("message")
public class Message {

    /**
     * 主键ID
     */
    @TableId(value = "id", type = IdType.AUTO)
    private Long id;

    /**
     * 对话ID
     */
    @TableField("conversation_id")
    private Long conversationId;

    /**
     * 角色类型(system/user/assistant)
     */
    @TableField("role")
    private String role;

    /**
     * 消息内容
     */
    @TableField("content")
    private String content;

    /**
     * Token数量
     */
    @TableField("tokens")
    private Integer tokens;

    /**
     * 创建时间
     */
    @TableField(value = "create_time", fill = FieldFill.INSERT)
    private LocalDateTime createTime;

    /**
     * 逻辑删除标志
     */
    @TableLogic
    @TableField("deleted")
    private Integer deleted;
}

4.3 创建AiFeedback实体类

创建 kb-ai/src/main/java/com/knowledge/base/ai/entity/AiFeedback.java:

package com.knowledge.base.ai.entity;

import com.baomidou.mybatisplus.annotation.*;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.time.LocalDateTime;

/**
 * AI反馈实体类
 *
 * @author 苏三
 * @since 1.0.0
 */
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@TableName("ai_feedback")
public class AiFeedback {

    @TableId(value = "id", type = IdType.AUTO)
    private Long id;

    @TableField("conversation_id")
    private Long conversationId;

    @TableField("message_id")
    private Long messageId;

    @TableField("user_id")
    private Long userId;

    @TableField("feedback_type")
    private String feedbackType;

    @TableField("feedback_content")
    private String feedbackContent;

    @TableField("rating")
    private Integer rating;

    @TableField(value = "create_time", fill = FieldFill.INSERT)
    private LocalDateTime createTime;

    @TableLogic
    @TableField("deleted")
    private Integer deleted;
}

4.4 设计思路

  1. 对话与消息一对多:通过 conversation_id 外键关联,一条对话包含多条消息
  2. 逻辑删除:使用 MyBatis-Plus 的 @TableLogic 注解实现软删除
  3. 自动填充:create_time 和 update_time 使用 FieldFill 自动填充
  4. Token统计:在 conversation 表中冗余存储 tokens_used 和 message_count,避免频繁聚合查询

五、DTO和VO设计

5.1 创建ChatRequestDTO

创建 kb-ai/src/main/java/com/knowledge/base/ai/dto/ChatRequestDTO.java:

package com.knowledge.base.ai.dto;

import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotBlank;
import lombok.Data;

/**
 * AI对话请求DTO
 *
 * @author 苏三
 * @since 1.0.0
 */
@Data
@Schema(description = "AI对话请求")
public class ChatRequestDTO {

    @NotBlank(message = "消息内容不能为空")
    @Schema(description = "消息内容", example = "如何使用企业知识库?")
    private String content;

    @Schema(description = "对话ID(不传则创建新对话)", example = "1")
    private Long conversationId;

    @Schema(description = "模型名称:qwen或deepseek", example = "qwen")
    private String model;

    @Schema(description = "系统提示词", example = "你是一个知识库助手")
    private String systemPrompt;
}

5.2 创建ChatResponseVO

创建 kb-ai/src/main/java/com/knowledge/base/ai/vo/ChatResponseVO.java:

package com.knowledge.base.ai.vo;

import io.swagger.v3.oas.annotations.media.Schema;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * AI对话响应VO
 *
 * @author 苏三
 * @since 1.0.0
 */
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Schema(description = "AI对话响应")
public class ChatResponseVO {

    @Schema(description = "对话ID")
    private Long conversationId;

    @Schema(description = "消息ID")
    private Long messageId;

    @Schema(description = "回复内容")
    private String content;

    @Schema(description = "Token消耗")
    private Integer tokens;

    @Schema(description = "对话标题")
    private String title;
}

5.3 创建ConversationVO

创建 kb-ai/src/main/java/com/knowledge/base/ai/vo/ConversationVO.java:

package com.knowledge.base.ai.vo;

import io.swagger.v3.oas.annotations.media.Schema;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 对话VO
 *
 * @author 苏三
 * @since 1.0.0
 */
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Schema(description = "对话信息")
public class ConversationVO {

    @Schema(description = "主键ID")
    private Long id;

    @Schema(description = "对话标题")
    private String title;

    @Schema(description = "模型名称")
    private String model;

    @Schema(description = "Token使用量")
    private Integer tokensUsed;

    @Schema(description = "消息数量")
    private Integer messageCount;

    @Schema(description = "状态")
    private Integer status;

    @Schema(description = "创建时间")
    private LocalDateTime createTime;

    @Schema(description = "更新时间")
    private LocalDateTime updateTime;

    @Schema(description = "消息列表")
    private List<MessageVO> messages;
}

5.4 创建MessageVO

创建 kb-ai/src/main/java/com/knowledge/base/ai/vo/MessageVO.java:

package com.knowledge.base.ai.vo;

import io.swagger.v3.oas.annotations.media.Schema;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.time.LocalDateTime;

/**
 * AI消息VO
 *
 * @author 苏三
 * @since 1.0.0
 */
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Schema(description = "AI消息信息")
public class MessageVO {

    @Schema(description = "消息ID")
    private Long id;

    @Schema(description = "对话ID")
    private Long conversationId;

    @Schema(description = "角色类型")
    private String role;

    @Schema(description = "消息内容")
    private String content;

    @Schema(description = "Token数量")
    private Integer tokens;

    @Schema(description = "创建时间")
    private LocalDateTime createTime;
}

5.5 创建ModelVO

创建 kb-ai/src/main/java/com/knowledge/base/ai/vo/ModelVO.java:

package com.knowledge.base.ai.vo;

import io.swagger.v3.oas.annotations.media.Schema;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * AI模型VO
 *
 * @author 苏三
 * @since 1.0.0
 */
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Schema(description = "AI模型信息")
public class ModelVO {

    @Schema(description = "模型标识")
    private String key;

    @Schema(description = "显示名称")
    private String displayName;

    @Schema(description = "描述信息")
    private String description;

    @Schema(description = "是否为默认模型")
    private Boolean isDefault;
}

5.6 设计说明

类型用途特点
ChatRequestDTO接收前端对话请求简化参数,content必填,conversationId可选
ChatResponseVO返回对话结果包含conversationId和messageId供前端追踪
ConversationVO返回对话详情包含messages列表,支持历史消息回看
MessageVO消息展示映射Message实体的展示层
ModelVO模型列表返回key/displayName/description供前端下拉

六、配置类设计

6.1 创建LangChain4jConfig

创建 kb-ai/src/main/java/com/knowledge/base/ai/config/LangChain4jConfig.java:

package com.knowledge.base.ai.config;

import dev.langchain4j.model.chat.ChatLanguageModel;
import dev.langchain4j.model.openai.OpenAiChatModel;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.time.Duration;

/**
 * LangChain4j配置类
 * 通过OpenAI兼容接口同时支持千问和DeepSeek
 *
 * @author 苏三
 * @since 1.0.0
 */
@Configuration
public class LangChain4jConfig {

    @Value("${qwen.api-key}")
    private String qwenApiKey;

    @Value("${qwen.base-url}")
    private String qwenBaseUrl;

    @Value("${qwen.chat.options.model}")
    private String qwenModel;

    @Value("${qwen.chat.options.temperature}")
    private double qwenTemperature;

    @Value("${qwen.chat.options.max-tokens}")
    private int qwenMaxTokens;

    @Value("${deepseek.api-key}")
    private String deepseekApiKey;

    @Value("${deepseek.base-url}")
    private String deepseekBaseUrl;

    @Value("${deepseek.model}")
    private String deepseekModel;

    @Value("${deepseek.max-tokens}")
    private int deepseekMaxTokens;

    @Value("${deepseek.temperature}")
    private double deepseekTemperature;

    @Bean(name = "qwenChatModel")
    public ChatLanguageModel qwenChatModel() {
        return OpenAiChatModel.builder()
                .apiKey(qwenApiKey)
                .baseUrl(qwenBaseUrl)
                .modelName(qwenModel)
                .temperature(qwenTemperature)
                .maxTokens(qwenMaxTokens)
                .timeout(Duration.ofSeconds(120))
                .build();
    }

    @Bean(name = "deepseekChatModel")
    public ChatLanguageModel deepseekChatModel() {
        return OpenAiChatModel.builder()
                .apiKey(deepseekApiKey)
                .baseUrl(deepseekBaseUrl)
                .modelName(deepseekModel)
                .temperature(deepseekTemperature)
                .maxTokens(deepseekMaxTokens)
                .timeout(Duration.ofSeconds(120))
                .build();
    }
}

6.2 创建ModelProvider

创建 kb-ai/src/main/java/com/knowledge/base/ai/config/ModelProvider.java:

package com.knowledge.base.ai.config;

import com.knowledge.base.ai.vo.ModelVO;
import dev.langchain4j.model.chat.ChatLanguageModel;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * AI模型提供器
 * 根据模型名称路由到对应的ChatLanguageModel实例
 *
 * @author 苏三
 * @since 1.0.0
 */
@Component
public class ModelProvider {

    private final Map<String, ChatLanguageModel> modelMap;

    @Value("${ai.default-model}")
    private String defaultModelName;

    public ModelProvider(
            @Qualifier("qwenChatModel") ChatLanguageModel qwenModel,
            @Qualifier("deepseekChatModel") ChatLanguageModel deepseekModel) {
        modelMap = new ConcurrentHashMap<>();
        modelMap.put("qwen", qwenModel);
        modelMap.put("deepseek", deepseekModel);
    }

    /**
     * 根据模型名称获取对应的ChatLanguageModel
     *
     * @param modelName 模型名称
     * @return ChatLanguageModel实例
     */
    public ChatLanguageModel getModel(String modelName) {
        if (modelName == null || !modelMap.containsKey(modelName)) {
            return getDefaultModel();
        }
        return modelMap.get(modelName);
    }

    /**
     * 获取默认模型
     */
    public ChatLanguageModel getDefaultModel() {
        return modelMap.getOrDefault(defaultModelName, modelMap.values().iterator().next());
    }

    /**
     * 获取默认模型名称
     */
    public String getDefaultModelName() {
        return defaultModelName;
    }

    /**
     * 获取可用模型列表
     */
    public List<ModelVO> getAvailableModels() {
        return Arrays.asList(
                ModelVO.builder()
                        .key("qwen")
                        .displayName("通义千问")
                        .description("阿里云大语言模型,支持多轮对话、文本生成等")
                        .isDefault("qwen".equals(defaultModelName))
                        .build(),
                ModelVO.builder()
                        .key("deepseek")
                        .displayName("DeepSeek")
                        .description("深度求索大语言模型,擅长代码生成和深度推理")
                        .isDefault("deepseek".equals(defaultModelName))
                        .build()
        );
    }
}

6.3 创建AiSecurityConfig

创建 kb-ai/src/main/java/com/knowledge/base/ai/config/AiSecurityConfig.java:

package com.knowledge.base.ai.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;

/**
 * AI服务安全配置
 *
 * @author 苏三
 * @since 1.0.0
 */
@Configuration
@EnableWebSecurity
public class AiSecurityConfig {

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
            .csrf(csrf -> csrf.disable())
            .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
            .authorizeHttpRequests(auth -> auth
                .anyRequest().permitAll()
            );
        return http.build();
    }
}

七、数据访问层

7.1 创建ConversationMapper

创建 kb-ai/src/main/java/com/knowledge/base/ai/mapper/ConversationMapper.java:

package com.knowledge.base.ai.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.knowledge.base.ai.entity.Conversation;
import org.apache.ibatis.annotations.Mapper;

/**
 * 对话Mapper接口
 *
 * @author 苏三
 * @since 1.0.0
 */
@Mapper
public interface ConversationMapper extends BaseMapper<Conversation> {
}

7.2 创建MessageMapper

创建 kb-ai/src/main/java/com/knowledge/base/ai/mapper/MessageMapper.java:

package com.knowledge.base.ai.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.knowledge.base.ai.entity.Message;
import org.apache.ibatis.annotations.Mapper;

/**
 * 消息Mapper接口
 *
 * @author 苏三
 * @since 1.0.0
 */
@Mapper
public interface MessageMapper extends BaseMapper<Message> {
}

7.3 创建AiFeedbackMapper

创建 kb-ai/src/main/java/com/knowledge/base/ai/mapper/AiFeedbackMapper.java:

package com.knowledge.base.ai.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.knowledge.base.ai.entity.AiFeedback;
import org.apache.ibatis.annotations.Mapper;

/**
 * AI反馈Mapper接口
 *
 * @author 苏三
 * @since 1.0.0
 */
@Mapper
public interface AiFeedbackMapper extends BaseMapper<AiFeedback> {
}

7.4 设计说明

使用 MyBatis-Plus 的 BaseMapper,提供开箱即用的CRUD方法:

  • insert(T entity) - 插入
  • deleteById(Serializable id) - 逻辑删除
  • updateById(T entity) - 更新
  • selectById(Serializable id) - 按ID查询
  • selectList(Wrapper<T> wrapper) - 条件查询
  • selectPage(IPage<T> page, Wrapper<T> wrapper) - 分页查询

八、业务逻辑层

8.1 创建AiChatService接口

创建 kb-ai/src/main/java/com/knowledge/base/ai/service/AiChatService.java:

package com.knowledge.base.ai.service;

import com.knowledge.base.ai.dto.ChatRequestDTO;
import com.knowledge.base.ai.vo.ChatResponseVO;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

/**
 * AI对话Service接口
 *
 * @author 苏三
 * @since 1.0.0
 */
public interface AiChatService {

    /**
     * 非流式AI对话
     */
    ChatResponseVO chat(ChatRequestDTO requestDTO, Long userId);

    /**
     * 流式AI对话(SSE)
     */
    SseEmitter chatStream(ChatRequestDTO requestDTO, Long userId);
}

8.2 创建AiConversationService接口

创建 kb-ai/src/main/java/com/knowledge/base/ai/service/AiConversationService.java:

package com.knowledge.base.ai.service;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.knowledge.base.ai.dto.ChatRequestDTO;
import com.knowledge.base.ai.entity.Conversation;
import com.knowledge.base.ai.vo.ConversationVO;

/**
 * AI对话管理Service接口
 *
 * @author 苏三
 * @since 1.0.0
 */
public interface AiConversationService {

    /**
     * 通过DTO创建对话
     */
    Long createConversation(ChatRequestDTO requestDTO, Long userId);

    /**
     * 通过标题创建对话
     */
    Long createConversation(String title, Long userId);

    /**
     * 获取对话详情
     */
    ConversationVO getConversation(Long conversationId, Long userId);

    /**
     * 获取对话列表(分页)
     */
    IPage<ConversationVO> listConversations(Long userId, Long current, Long size);

    /**
     * 删除对话
     */
    boolean deleteConversation(Long conversationId, Long userId);

    /**
     * 更新对话状态
     */
    boolean updateStatus(Long conversationId, Integer status);

    /**
     * 更新Token统计
     */
    boolean updateTokens(Long conversationId, Integer tokens);

    /**
     * 更新对话标题
     */
    boolean updateTitle(Long conversationId, String title);

    /**
     * 增加消息数量
     */
    boolean incrementMessageCount(Long conversationId, Integer count);

    /**
     * 按ID查询
     */
    Conversation getById(Long conversationId);
}

8.3 创建AiChatServiceImpl

创建 kb-ai/src/main/java/com/knowledge/base/ai/service/impl/AiChatServiceImpl.java:

package com.knowledge.base.ai.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.knowledge.base.ai.config.ModelProvider;
import com.knowledge.base.ai.dto.ChatRequestDTO;
import com.knowledge.base.ai.entity.Conversation;
import com.knowledge.base.ai.entity.Message;
import com.knowledge.base.ai.mapper.ConversationMapper;
import com.knowledge.base.ai.mapper.MessageMapper;
import com.knowledge.base.ai.service.AiChatService;
import com.knowledge.base.ai.service.AiConversationService;
import com.knowledge.base.ai.vo.ChatResponseVO;
import dev.langchain4j.data.message.AiMessage;
import dev.langchain4j.data.message.UserMessage;
import dev.langchain4j.model.chat.ChatLanguageModel;
import dev.langchain4j.model.output.Response;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * AI对话Service实现类
 *
 * @author 苏三
 * @since 1.0.0
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class AiChatServiceImpl extends ServiceImpl<ConversationMapper, Conversation>
        implements AiChatService {

    private final ModelProvider modelProvider;
    private final MessageMapper messageMapper;
    private final AiConversationService conversationService;

    @Override
    public ChatResponseVO chat(ChatRequestDTO requestDTO, Long userId) {
        final String modelName = requestDTO.getModel() != null
                ? requestDTO.getModel() : modelProvider.getDefaultModelName();
        try {
            // 解析或创建对话
            Long conversationId = requestDTO.getConversationId();
            if (conversationId == null) {
                conversationId = conversationService.createConversation(requestDTO, userId);
            } else {
                Conversation existingConv = conversationService.getById(conversationId);
                if (existingConv == null || !existingConv.getUserId().equals(userId)) {
                    log.warn("对话不存在或无权访问,创建新对话");
                    conversationId = conversationService.createConversation(requestDTO, userId);
                } else {
                    updateConversationTitle(existingConv, requestDTO.getContent());
                }
            }

            // 调用AI模型
            ChatLanguageModel chatModel = modelProvider.getModel(requestDTO.getModel());
            log.info("发起AI请求:model={}, conversationId={}", modelName, conversationId);

            UserMessage userMessage = UserMessage.from(requestDTO.getContent());
            Response<AiMessage> response = chatModel.generate(userMessage);
            String responseContent = response.content().text();

            // 保存用户消息
            Message userMsgEntity = Message.builder()
                    .conversationId(conversationId)
                    .role("user")
                    .content(requestDTO.getContent())
                    .tokens(estimateTokens(requestDTO.getContent()))
                    .build();
            messageMapper.insert(userMsgEntity);

            // 保存AI消息
            Message aiMsgEntity = Message.builder()
                    .conversationId(conversationId)
                    .role("assistant")
                    .content(responseContent)
                    .tokens(estimateTokens(responseContent))
                    .build();
            messageMapper.insert(aiMsgEntity);

            // 更新对话统计
            int totalTokens = userMsgEntity.getTokens() + aiMsgEntity.getTokens();
            conversationService.updateTokens(conversationId, totalTokens);

            Conversation conversation = conversationService.getById(conversationId);
            String title = conversation != null ? conversation.getTitle() : "新对话";

            log.info("AI对话完成:conversationId={}, tokens={}", conversationId, totalTokens);

            return ChatResponseVO.builder()
                    .conversationId(conversationId)
                    .messageId(aiMsgEntity.getId())
                    .content(responseContent)
                    .tokens(totalTokens)
                    .title(title)
                    .build();

        } catch (Exception e) {
            log.error("AI对话失败: {}", e.getMessage(), e);
            throw new RuntimeException("AI对话失败: " + e.getMessage());
        }
    }

    @Override
    public SseEmitter chatStream(ChatRequestDTO requestDTO, Long userId) {
        SseEmitter emitter = new SseEmitter(30 * 60 * 1000L);

        try {
            final Long conversationIdFinal = requestDTO.getConversationId();
            Long conversationId = conversationIdFinal;
            if (conversationId == null) {
                conversationId = conversationService.createConversation(requestDTO, userId);
            } else {
                Conversation existingConv = conversationService.getById(conversationId);
                if (existingConv == null || !existingConv.getUserId().equals(userId)) {
                    log.warn("对话不存在或无权访问,创建新对话");
                    conversationId = conversationService.createConversation(requestDTO, userId);
                } else {
                    updateConversationTitle(existingConv, requestDTO.getContent());
                }
            }
            final Long finalConversationId = conversationId;
            final String modelName = requestDTO.getModel() != null
                    ? requestDTO.getModel() : modelProvider.getDefaultModelName();

            CompletableFuture.runAsync(() -> {
                try {
                    ChatLanguageModel chatModel = modelProvider.getModel(modelName);
                    log.info("发起AI流式请求:model={}, conversationId={}", modelName, finalConversationId);

                    UserMessage userMessage = UserMessage.from(requestDTO.getContent());

                    // 保存用户消息
                    Message userMsgEntity = Message.builder()
                            .conversationId(finalConversationId)
                            .role("user")
                            .content(requestDTO.getContent())
                            .tokens(estimateTokens(requestDTO.getContent()))
                            .build();
                    messageMapper.insert(userMsgEntity);

                    // 调用AI模型并发送SSE事件
                    Response<AiMessage> response = chatModel.generate(userMessage);
                    String fullResponse = response.content().text();

                    emitter.send(SseEmitter.event()
                            .name("message")
                            .data(fullResponse));

                    // 保存AI消息
                    Message aiMsgEntity = Message.builder()
                            .conversationId(finalConversationId)
                            .role("assistant")
                            .content(fullResponse)
                            .tokens(estimateTokens(fullResponse))
                            .build();
                    messageMapper.insert(aiMsgEntity);

                    AtomicInteger totalTokens = new AtomicInteger(userMsgEntity.getTokens());
                    totalTokens.addAndGet(aiMsgEntity.getTokens());
                    conversationService.updateTokens(finalConversationId, totalTokens.get());

                    emitter.send(SseEmitter.event()
                            .name("done")
                            .data(ChatResponseVO.builder()
                                    .conversationId(finalConversationId)
                                    .messageId(aiMsgEntity.getId())
                                    .content(fullResponse)
                                    .tokens(totalTokens.get())
                                    .build()));

                    emitter.complete();

                } catch (Exception e) {
                    log.error("流式对话失败: {}", e.getMessage(), e);
                    try {
                        emitter.send(SseEmitter.event()
                                .name("error")
                                .data(e.getMessage() != null ? e.getMessage() : "AI服务调用失败"));
                        emitter.complete();
                    } catch (IOException ioException) {
                        log.error("发送错误事件失败: {}", ioException.getMessage());
                    }
                }
            });

        } catch (Exception e) {
            log.error("创建SSE发射器失败: {}", e.getMessage(), e);
            emitter.completeWithError(e);
        }

        return emitter;
    }

    /**
     * 如果对话标题仍是默认值(以"新对话"开头),从第一条消息内容更新标题
     */
    private void updateConversationTitle(Conversation conversation, String content) {
        String currentTitle = conversation.getTitle();
        if (currentTitle != null && currentTitle.startsWith("新对话")
                && content != null && !content.isEmpty()) {
            String newTitle = content.length() > 30 ? content.substring(0, 30) : content;
            conversation.setTitle(newTitle);
            conversation.setUpdateTime(LocalDateTime.now());
            this.updateById(conversation);
            log.info("更新对话标题:conversationId={}, title={}", conversation.getId(), newTitle);
        }
    }

    /**
     * 估算Token数量(简单算法:中文1字=1token,英文4字符=1token)
     */
    private int estimateTokens(String text) {
        if (text == null || text.isEmpty()) {
            return 0;
        }
        int chineseChars = text.replaceAll("[^\\u4e00-\\u9fa5]", "").length();
        int otherChars = text.length() - chineseChars;
        return chineseChars + (otherChars / 4);
    }
}

8.4 创建AiConversationServiceImpl

创建 kb-ai/src/main/java/com/knowledge/base/ai/service/impl/AiConversationServiceImpl.java:

package com.knowledge.base.ai.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.knowledge.base.ai.dto.ChatRequestDTO;
import com.knowledge.base.ai.entity.Conversation;
import com.knowledge.base.ai.entity.Message;
import com.knowledge.base.ai.mapper.ConversationMapper;
import com.knowledge.base.ai.mapper.MessageMapper;
import com.knowledge.base.ai.service.AiConversationService;
import com.knowledge.base.ai.vo.ConversationVO;
import com.knowledge.base.ai.vo.MessageVO;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * AI对话管理Service实现类
 *
 * @author 苏三
 * @since 1.0.0
 */
@Slf4j
@Service
public class AiConversationServiceImpl extends ServiceImpl<ConversationMapper, Conversation>
        implements AiConversationService {

    @Resource
    private ConversationMapper conversationMapper;

    @Resource
    private MessageMapper messageMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createConversation(ChatRequestDTO requestDTO, Long userId) {
        log.info("创建对话:userId={}", userId);

        // 使用用户第一个问题作为标题
        String title = requestDTO.getContent();
        if (title != null && title.length() > 30) {
            title = title.substring(0, 30);
        }

        Conversation conversation = new Conversation();
        conversation.setTitle(title != null ? title : "新对话");
        conversation.setUserId(userId);
        conversation.setModel(requestDTO.getModel() != null ? requestDTO.getModel() : "qwen");
        conversation.setTokensUsed(0);
        conversation.setMessageCount(0);
        conversation.setStatus(0);
        conversation.setCreateTime(LocalDateTime.now());
        conversation.setUpdateTime(LocalDateTime.now());
        conversation.setDeleted(0);

        int count = conversationMapper.insert(conversation);
        if (count <= 0) {
            throw new RuntimeException("创建对话失败");
        }

        log.info("对话创建成功:conversationId={}", conversation.getId());
        return conversation.getId();
    }

    @Override
    public ConversationVO getConversation(Long conversationId, Long userId) {
        log.info("获取对话详情:conversationId={}, userId={}", conversationId, userId);

        if (conversationId == null) {
            throw new RuntimeException("对话ID不能为空");
        }

        Conversation conversation = conversationMapper.selectById(conversationId);
        if (conversation == null) {
            throw new RuntimeException("对话不存在");
        }

        if (!conversation.getUserId().equals(userId)) {
            throw new RuntimeException("无权访问该对话");
        }

        ConversationVO vo = convertToVO(conversation);

        // 加载对话消息
        List<Message> messages = messageMapper.selectList(
                new LambdaQueryWrapper<Message>()
                        .eq(Message::getConversationId, conversationId)
                        .orderByAsc(Message::getCreateTime)
        );
        vo.setMessages(messages.stream().map(this::convertMessageToVO).collect(Collectors.toList()));

        return vo;
    }

    @Override
    public IPage<ConversationVO> listConversations(Long userId, Long current, Long size) {
        log.info("获取对话列表:userId={}, current={}, size={}", userId, current, size);

        LambdaQueryWrapper<Conversation> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Conversation::getUserId, userId)
                .orderByDesc(Conversation::getUpdateTime);

        Page<Conversation> page = new Page<>(current, size);
        IPage<Conversation> conversationPage = conversationMapper.selectPage(page, wrapper);

        return conversationPage.convert(this::convertToVO);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteConversation(Long conversationId, Long userId) {
        log.info("删除对话:conversationId={}, userId={}", conversationId, userId);

        if (conversationId == null) {
            throw new RuntimeException("对话ID不能为空");
        }

        Conversation conversation = conversationMapper.selectById(conversationId);
        if (conversation == null) {
            throw new RuntimeException("对话不存在");
        }

        if (!conversation.getUserId().equals(userId)) {
            throw new RuntimeException("无权删除该对话");
        }

        int count = conversationMapper.deleteById(conversationId);
        log.info("对话删除成功:conversationId={}", conversationId);
        return count > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateStatus(Long conversationId, Integer status) {
        Conversation conversation = conversationMapper.selectById(conversationId);
        if (conversation == null) {
            throw new RuntimeException("对话不存在");
        }
        conversation.setStatus(status);
        conversation.setUpdateTime(LocalDateTime.now());
        return conversationMapper.updateById(conversation) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateTokens(Long conversationId, Integer tokens) {
        Conversation conversation = conversationMapper.selectById(conversationId);
        if (conversation == null) {
            throw new RuntimeException("对话不存在");
        }
        conversation.setTokensUsed(
                (conversation.getTokensUsed() != null ? conversation.getTokensUsed() : 0) + tokens);
        conversation.setUpdateTime(LocalDateTime.now());
        return conversationMapper.updateById(conversation) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateTitle(Long conversationId, String title) {
        Conversation conversation = conversationMapper.selectById(conversationId);
        if (conversation == null) {
            throw new RuntimeException("对话不存在");
        }
        conversation.setTitle(title);
        conversation.setUpdateTime(LocalDateTime.now());
        return conversationMapper.updateById(conversation) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean incrementMessageCount(Long conversationId, Integer count) {
        Conversation conversation = conversationMapper.selectById(conversationId);
        if (conversation == null) {
            throw new RuntimeException("对话不存在");
        }
        conversation.setMessageCount(
                (conversation.getMessageCount() != null ? conversation.getMessageCount() : 0) + count);
        conversation.setUpdateTime(LocalDateTime.now());
        return conversationMapper.updateById(conversation) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createConversation(String title, Long userId) {
        log.info("创建对话(通过标题):title={}, userId={}", title, userId);

        Conversation conversation = new Conversation();
        conversation.setTitle(title);
        conversation.setUserId(userId);
        conversation.setModel("qwen");
        conversation.setTokensUsed(0);
        conversation.setMessageCount(0);
        conversation.setStatus(0);
        conversation.setCreateTime(LocalDateTime.now());
        conversation.setUpdateTime(LocalDateTime.now());
        conversation.setDeleted(0);

        int count = conversationMapper.insert(conversation);
        if (count <= 0) {
            throw new RuntimeException("创建对话失败");
        }

        log.info("对话创建成功:conversationId={}", conversation.getId());
        return conversation.getId();
    }

    @Override
    public Conversation getById(Long conversationId) {
        return conversationMapper.selectById(conversationId);
    }

    // ============ 转换方法 ============

    private MessageVO convertMessageToVO(Message message) {
        return MessageVO.builder()
                .id(message.getId())
                .conversationId(message.getConversationId())
                .role(message.getRole())
                .content(message.getContent())
                .tokens(message.getTokens())
                .createTime(message.getCreateTime())
                .build();
    }

    private ConversationVO convertToVO(Conversation conversation) {
        return ConversationVO.builder()
                .id(conversation.getId())
                .title(conversation.getTitle())
                .model(conversation.getModel())
                .tokensUsed(conversation.getTokensUsed())
                .messageCount(conversation.getMessageCount())
                .status(conversation.getStatus())
                .createTime(conversation.getCreateTime())
                .updateTime(conversation.getUpdateTime())
                .build();
    }
}

九、控制器层

9.1 创建AiChatController

创建 kb-ai/src/main/java/com/knowledge/base/ai/controller/AiChatController.java:

package com.knowledge.base.ai.controller;

import com.knowledge.base.ai.config.ModelProvider;
import com.knowledge.base.ai.dto.ChatRequestDTO;
import com.knowledge.base.ai.service.AiChatService;
import com.knowledge.base.ai.vo.ChatResponseVO;
import com.knowledge.base.ai.vo.ModelVO;
import com.knowledge.base.common.result.Result;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.util.List;

/**
 * AI对话控制器
 *
 * @author 苏三
 * @since 1.0.0
 */
@Slf4j
@RestController
@RequestMapping("/chat")
@RequiredArgsConstructor
@Tag(name = "AI对话", description = "AI对话相关接口")
public class AiChatController {

    private final AiChatService aiChatService;
    private final ModelProvider modelProvider;

    /**
     * 获取可用AI模型列表
     */
    @GetMapping("/models")
    @Operation(summary = "获取AI模型列表", description = "获取当前可用的AI大模型列表")
    public Result<List<ModelVO>> getModels() {
        List<ModelVO> models = modelProvider.getAvailableModels();
        return Result.success(models);
    }

    /**
     * AI对话(非流式)
     */
    @PostMapping
    @Operation(summary = "AI对话", description = "与AI进行对话")
    public Result<ChatResponseVO> chat(@Validated @RequestBody ChatRequestDTO requestDTO,
                                        HttpServletRequest request) {
        Long userId = getUserId(request);
        ChatResponseVO response = aiChatService.chat(requestDTO, userId);
        return Result.success(response);
    }

    /**
     * AI流式对话(SSE)
     */
    @PostMapping("/stream")
    @Operation(summary = "AI流式对话", description = "与AI进行流式对话")
    public SseEmitter chatStream(@Validated @RequestBody ChatRequestDTO requestDTO,
                                  HttpServletRequest request) {
        Long userId = getUserId(request);
        return aiChatService.chatStream(requestDTO, userId);
    }

    /**
     * 获取用户ID
     */
    private Long getUserId(HttpServletRequest request) {
        String userId = request.getHeader("X-User-Id");
        if (userId != null) {
            return Long.parseLong(userId);
        }
        return 1L; // 默认用户ID
    }
}

9.2 创建AiConversationController

创建 kb-ai/src/main/java/com/knowledge/base/ai/controller/AiConversationController.java:

package com.knowledge.base.ai.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.knowledge.base.ai.service.AiConversationService;
import com.knowledge.base.ai.vo.ConversationVO;
import com.knowledge.base.common.result.Result;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * AI对话管理控制器
 *
 * @author 苏三
 * @since 1.0.0
 */
@Slf4j
@RestController
@RequestMapping("/conversation")
@RequiredArgsConstructor
@Tag(name = "AI对话管理", description = "AI对话管理相关接口")
public class AiConversationController {

    private final AiConversationService conversationService;

    /**
     * 创建新对话
     */
    @PostMapping
    @Operation(summary = "创建新对话", description = "创建新的AI对话")
    public Result<ConversationVO> createConversation(@RequestBody Map<String, String> body,
                                                       HttpServletRequest request) {
        Long userId = getUserId(request);
        String title = body.getOrDefault("title", "新对话");
        Long conversationId = conversationService.createConversation(title, userId);
        ConversationVO conversation = conversationService.getConversation(conversationId, userId);
        return Result.success(conversation);
    }

    /**
     * 获取对话列表
     */
    @GetMapping("/list")
    @Operation(summary = "获取对话列表", description = "获取当前用户的对话列表")
    public Result<IPage<ConversationVO>> listConversations(
            @RequestParam(defaultValue = "1") Long current,
            @RequestParam(defaultValue = "50") Long size,
            HttpServletRequest request) {
        Long userId = getUserId(request);
        IPage<ConversationVO> conversations = conversationService.listConversations(userId, current, size);
        return Result.success(conversations);
    }

    /**
     * 获取对话详情(含消息)
     */
    @GetMapping("/{id}")
    @Operation(summary = "获取对话详情", description = "获取对话详细信息(含消息列表)")
    public Result<ConversationVO> getConversation(@PathVariable Long id,
                                                   HttpServletRequest request) {
        Long userId = getUserId(request);
        ConversationVO conversation = conversationService.getConversation(id, userId);
        return Result.success(conversation);
    }

    /**
     * 删除对话
     */
    @DeleteMapping("/{id}")
    @Operation(summary = "删除对话", description = "删除指定对话")
    public Result<Boolean> deleteConversation(@PathVariable Long id,
                                               HttpServletRequest request) {
        Long userId = getUserId(request);
        boolean success = conversationService.deleteConversation(id, userId);
        return Result.success(success);
    }

    /**
     * 获取用户ID
     */
    private Long getUserId(HttpServletRequest request) {
        String userId = request.getHeader("X-User-Id");
        if (userId != null) {
            return Long.parseLong(userId);
        }
        return 1L;
    }
}

9.3 API接口一览

方法路径说明
GET/chat/models获取可用AI模型列表
POST/chat非流式AI对话
POST/chat/stream流式AI对话(SSE)
POST/conversation创建新对话
GET/conversation/list获取对话列表(分页)
GET/conversation/{id}获取对话详情(含消息)
DELETE/conversation/{id}删除对话

十、网关路由配置

10.1 添加kb-ai路由

编辑 kb-gateway/src/main/resources/application.yml,添加kb-ai路由:

spring:
  cloud:
    gateway:
      routes:
        # ... 其他路由 ...

        # kb-ai AI服务路由
        - id: kb-ai
          uri: lb://kb-ai
          predicates:
            - Path=/api/ai/**
          filters:
            - StripPrefix=2

路由说明:

  • id: kb-ai - 路由唯一标识
  • uri: lb://kb-ai - 通过Nacos负载均衡转发到kb-ai服务
  • Path=/api/ai/** - 匹配所有 /api/ai/ 开头的请求
  • StripPrefix=2 - 去掉前两级路径:/api/ai/chat/stream → /chat/stream

十一、前端类型定义

11.1 添加AI相关TypeScript类型

编辑 knowledge-base-frontend/src/types/index.ts,添加以下类型:

// AI相关类型

/** AI消息 */
export interface AIMessage {
  id: string;
  role: 'user' | 'assistant' | 'system';
  content: string;
  timestamp: string;
}

/** AI对话 */
export interface AIConversation {
  id: string | number;
  title: string;
  messages: AIMessage[];
  messageCount?: number;
  model?: string;
  status?: number;
  tokensUsed?: number;
  createdAt?: string;
  updatedAt?: string;
  createTime?: string;
  updateTime?: string;
}

/** AI对话请求 */
export interface AIRequest {
  question: string;
  conversationId?: string;
  model?: string;
  context?: {
    documentIds?: string[];
    knowledgeBase?: boolean;
  };
}

/** AI模型选项 */
export interface AIModelOption {
  key: string;
  displayName: string;
  description: string;
  isDefault?: boolean;
}

/** AI反馈 */
export interface AIFeedback {
  messageId: string;
  conversationId: string;
  type: 'like' | 'dislike';
  comment?: string;
}

/** AI快捷问题 */
export interface AIQuickQuestion {
  id: string;
  title: string;
  question: string;
  icon?: string;
  category?: string;
}

11.2 添加AI相关常量

编辑 knowledge-base-frontend/src/constants/index.ts,添加:

// AI配置
export const AI_CONFIG = {
  MAX_TOKENS: 4000,
  TEMPERATURE: 0.3,
  DEFAULT_MODEL: 'qwen',
  MODELS: {
    qwen: {
      key: 'qwen',
      displayName: '通义千问',
      description: '阿里云大语言模型,支持多轮对话、文本生成等',
      color: '#2563eb',
    },
    deepseek: {
      key: 'deepseek',
      displayName: 'DeepSeek',
      description: '深度求索大语言模型,擅长代码生成和深度推理',
      color: '#10b981',
    },
  },
} as const;

十二、前端服务层

12.1 创建AI服务

创建 knowledge-base-frontend/src/services/ai.service.ts:

import { http } from './request';
import { AIRequest, AIConversation, AIQuickQuestion, AIModelOption } from '@/types';
import { tokenStorage } from '@/utils/token-storage';

export const aiService = {
  /** 获取可用AI模型列表 */
  getModels: () => {
    return http.get<AIModelOption[]>('/ai/chat/models');
  },

  /** AI非流式问答 */
  ask: (data: AIRequest) => {
    return http.post<{
      content: string;
      conversationId: string;
      messageId: string;
      tokens: number;
    }>('/ai/chat', {
      content: data.question,
      conversationId: data.conversationId,
      model: data.model,
    });
  },

  /** 获取对话列表 */
  getConversations: async (): Promise<AIConversation[]> => {
    const pageData = await http.get<any>('/ai/conversation/list');
    return pageData?.records || pageData || [];
  },

  /** 获取对话详情(含消息) */
  getConversation: (id: string) => {
    return http.get<AIConversation>(`/ai/conversation/${id}`);
  },

  /** 创建新对话 */
  createConversation: (title: string) => {
    return http.post<AIConversation>('/ai/conversation', { title });
  },

  /** 删除对话 */
  deleteConversation: (id: string) => {
    return http.delete(`/ai/conversation/${id}`);
  },

  /** 流式问答(SSE) */
  askStream: (
    data: AIRequest,
    onMessage: (message: string) => void,
    onDone?: (result: {
      conversationId: number | string;
      messageId: number | string;
      content: string;
      tokens: number;
    }) => void,
    onError?: (error: string) => void,
  ) => {
    return fetch(`${import.meta.env.VITE_API_BASE_URL}/ai/chat/stream`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': tokenStorage.getAuthorizationHeader(),
      },
      body: JSON.stringify({
        content: data.question,
        conversationId: data.conversationId,
        model: data.model,
      }),
    }).then(async (response) => {
      if (!response.ok) {
        throw new Error(`HTTP ${response.status}: ${response.statusText}`);
      }
      const reader = response.body?.getReader();
      const decoder = new TextDecoder();

      if (!reader) throw new Error('无法读取响应流');

      let buffer = '';
      let currentEvent = '';
      let messageLines: string[] = [];

      while (true) {
        const { done, value } = await reader.read();
        if (done) break;

        buffer += decoder.decode(value, { stream: true });
        const lines = buffer.split('\n');
        buffer = lines.pop() || '';

        for (const line of lines) {
          if (line.startsWith('event:')) {
            if (messageLines.length > 0) {
              onMessage(messageLines.join('\n'));
              messageLines = [];
            }
            currentEvent = line.slice(6).trim();
            continue;
          }

          if (line.startsWith('data:')) {
            const data = line.startsWith('data: ') ? line.slice(6) : line.slice(5);

            if (currentEvent === 'error') {
              onError?.(data);
              continue;
            }

            if (currentEvent === 'done') {
              try {
                const parsed = JSON.parse(data);
                onDone?.(parsed);
              } catch { /* ignore */ }
              continue;
            }

            messageLines.push(data);
            continue;
          }

          if (line === '') {
            if (messageLines.length > 0) {
              onMessage(messageLines.join('\n'));
              messageLines = [];
            }
            currentEvent = '';
          }
        }
      }

      if (messageLines.length > 0) {
        onMessage(messageLines.join('\n'));
      }
    });
  },

  /** 提交反馈 */
  submitFeedback: (data: {
    messageId: string;
    conversationId: string;
    type: 'like' | 'dislike';
  }) => {
    return http.post('/ai/feedback', data);
  },

  /** 获取快捷问题 */
  getQuickQuestions: () => {
    return http.get<AIQuickQuestion[]>('/ai/quick-questions');
  },
};

export default aiService;

十三、前端状态管理

13.1 创建AI Store

创建 knowledge-base-frontend/src/stores/ai.store.ts:

import { create } from 'zustand';
import { AIConversation, AIMessage, AIModelOption } from '@/types';
import { aiService } from '@/services';

interface AIState {
  conversations: AIConversation[];
  currentConversation: AIConversation | null;
  isLoading: boolean;
  isStreaming: boolean;
  currentResponse: string;
  selectedModel: string;
  availableModels: AIModelOption[];

  // Actions
  fetchConversations: () => Promise<void>;
  createConversation: (title: string) => Promise<AIConversation>;
  deleteConversation: (id: string) => Promise<void>;
  setCurrentConversation: (conversation: AIConversation | null) => void;
  loadConversationMessages: (conversationId: string) => Promise<void>;
  sendMessage: (message: string, _conversationId?: string) => Promise<void>;
  clearConversation: (id: string) => Promise<void>;
  fetchModels: () => Promise<void>;
  setSelectedModel: (model: string) => void;
  reset: () => void;
}

export const useAIStore = create<AIState>((set, get) => ({
  conversations: [],
  currentConversation: null,
  isLoading: false,
  isStreaming: false,
  currentResponse: '',
  selectedModel: 'qwen',
  availableModels: [],

  fetchConversations: async () => {
    set({ isLoading: true });
    try {
      const apiConversations = await aiService.getConversations();
      const { currentConversation, conversations: existingConvs } = get();
      const existingMap = new Map(existingConvs.map((c) => [String(c.id), c]));
      if (currentConversation) {
        existingMap.set(String(currentConversation.id), currentConversation);
      }
      const merged = apiConversations.map((api) => {
        const existing = existingMap.get(String(api.id));
        return existing && existing.messages
          ? { ...api, messages: existing.messages }
          : api;
      });
      set({ conversations: merged, isLoading: false });
    } catch (error) {
      set({ isLoading: false });
      throw error;
    }
  },

  createConversation: async (title: string) => {
    const conversation = await aiService.createConversation(title);
    set((state) => ({
      conversations: [conversation, ...state.conversations],
      currentConversation: conversation,
    }));
    return conversation;
  },

  deleteConversation: async (id: string) => {
    await aiService.deleteConversation(id);
    set((state) => ({
      conversations: state.conversations.filter(
        (c) => String(c.id) !== String(id)
      ),
      currentConversation:
        String(state.currentConversation?.id) === String(id)
          ? null
          : state.currentConversation,
    }));
  },

  setCurrentConversation: (conversation: AIConversation | null) => {
    set({ currentConversation: conversation });
    // 自动加载历史消息
    if (
      conversation &&
      conversation.id &&
      (!conversation.messages || conversation.messages.length === 0)
    ) {
      get().loadConversationMessages(String(conversation.id));
    }
  },

  loadConversationMessages: async (conversationId: string) => {
    try {
      const conv = await aiService.getConversation(conversationId);
      const messages: AIMessage[] = ((conv as any).messages || []).map(
        (m: any) => ({
          id: String(m.id),
          role: m.role,
          content: m.content,
          timestamp: m.createTime || m.timestamp,
        })
      );
      set((state) => ({
        currentConversation: {
          ...state.currentConversation,
          id: String(conv.id),
          title: (conv as any).title || state.currentConversation?.title || '',
          messages,
          messageCount: (conv as any).messageCount,
          model: (conv as any).model,
        },
        isLoading: false,
        conversations: state.conversations.map((c) =>
          String(c.id) === String(conversationId)
            ? { ...c, messages, messageCount: (conv as any).messageCount }
            : c
        ),
      }));
    } catch (error) {
      console.error('加载对话消息失败:', error);
      set({ isLoading: false });
    }
  },

  sendMessage: async (message: string, _conversationId?: string) => {
    const { selectedModel } = get();
    set({ isLoading: true, isStreaming: true, currentResponse: '' });

    const userMessage: AIMessage = {
      id: Date.now().toString(),
      role: 'user',
      content: message,
      timestamp: new Date().toISOString(),
    };

    let currentConv = get().currentConversation;
    if (!currentConv) {
      currentConv = {
        id: '',
        title: message.slice(0, 30),
        messages: [userMessage],
        createdAt: new Date().toISOString(),
        updatedAt: new Date().toISOString(),
      };
      set({ currentConversation: currentConv });
    } else {
      const existingMessages = currentConv.messages || [];
      const title =
        existingMessages.length === 0
          ? message.slice(0, 30)
          : currentConv.title;
      currentConv = {
        ...currentConv,
        title,
        messages: [...existingMessages, userMessage],
        updatedAt: new Date().toISOString(),
      };
      set({ currentConversation: currentConv });
    }

    try {
      const realId =
        currentConv.id && String(currentConv.id) !== ''
          ? String(currentConv.id)
          : undefined;
      let resolvedConversationId: string | undefined = realId;
      let resolvedMessageId: string | undefined;

      await aiService.askStream(
        {
          question: message,
          conversationId: realId,
          model: selectedModel,
          context: { knowledgeBase: true },
        },
        (chunk: string) => {
          set((state) => ({
            currentResponse: state.currentResponse + chunk,
          }));
        },
        (result) => {
          resolvedConversationId = String(result.conversationId);
          resolvedMessageId = String(result.messageId);
        },
        (errorMsg: string) => {
          throw new Error(errorMsg);
        }
      );

      const finalConversationId = resolvedConversationId || realId || '';
      const finalContent = get().currentResponse;

      const assistantMessage: AIMessage = {
        id: resolvedMessageId || (Date.now() + 1).toString(),
        role: 'assistant',
        content: finalContent,
        timestamp: new Date().toISOString(),
      };

      set((state) => {
        const conv = state.currentConversation;
        if (!conv)
          return { isLoading: false, isStreaming: false, currentResponse: '' };
        const updatedConv = {
          ...conv,
          id: finalConversationId,
          messages: [...conv.messages, assistantMessage],
          updatedAt: new Date().toISOString(),
        };
        const isNewConversation = !realId && finalConversationId;
        const conversations = isNewConversation
          ? [
              updatedConv,
              ...state.conversations.filter(
                (c) => String(c.id) !== finalConversationId
              ),
            ]
          : state.conversations.map((c) =>
              String(c.id) === finalConversationId ? updatedConv : c
            );
        return {
          currentConversation: updatedConv,
          conversations,
          isLoading: false,
          isStreaming: false,
          currentResponse: '',
        };
      });
    } catch (error) {
      set({ isLoading: false, isStreaming: false, currentResponse: '' });
      throw error;
    }
  },

  clearConversation: async (id: string) => {
    await aiService.clearConversation(id);
    set((state) => ({
      currentConversation:
        state.currentConversation?.id === id
          ? { ...state.currentConversation, messages: [] }
          : state.currentConversation,
    }));
  },

  fetchModels: async () => {
    try {
      const models = await aiService.getModels();
      set({ availableModels: models });
      const { selectedModel } = get();
      if (!selectedModel && models.length > 0) {
        const defaultModel = models.find((m) => m.isDefault);
        set({ selectedModel: defaultModel ? defaultModel.key : models[0].key });
      }
    } catch (error) {
      console.error('获取AI模型列表失败:', error);
      const { AI_CONFIG } = await import('@/constants');
      const fallbackModels: AIModelOption[] = Object.values(AI_CONFIG.MODELS).map(
        (m) => ({
          key: m.key,
          displayName: m.displayName,
          description: m.description,
          isDefault: m.key === AI_CONFIG.DEFAULT_MODEL,
        })
      );
      set({ availableModels: fallbackModels });
    }
  },

  setSelectedModel: (model: string) => {
    set({ selectedModel: model });
  },

  reset: () => {
    set({
      conversations: [],
      currentConversation: null,
      currentResponse: '',
      availableModels: [],
    });
  },
}));

十四、前端页面组件

创建 knowledge-base-frontend/src/pages/AIAssistantPage.tsx,这是最核心的前端组件,包含以下结构:

AIAssistantPage
├── 侧边栏(280-320px宽)
│   ├── 新建对话按钮
│   └── 对话历史列表
│       ├── 对话标题
│       └── 删除操作菜单
├── 主对话区域
│   ├── 顶栏(AI助手标题 + 模型选择器)
│   ├── 消息容器(可滚动)
│   │   ├── 空状态(快捷提问入口)
│   │   ├── UserMessageBubble(用户消息气泡)
│   │   ├── AIMessageBubble(AI消息气泡)
│   │   └── 流式响应(正在输入状态)
│   └── 输入区域(文本框 + 发送按钮)

14.1 关键组件说明

UserMessageBubble:用户消息气泡,包含消息内容、时间戳、重试按钮和用户头像。

AIMessageBubble:AI消息气泡,包含:

  • ReactMarkdown + remarkGfm 渲染Markdown内容
  • Prism语法高亮代码块 + 复制按钮
  • 表格、图片、链接的自定义样式
  • 点赞/踩反馈按钮
  • 知识引用面板

CodeBlock:代码块组件,支持语法高亮(oneDark主题)和一键复制。

空状态(renderEmptyState):当无对话时展示,包含AI助手问候语和快捷提问列表。

14.2 核心样式常量

const COLORS = {
  pageBg: '#f7f8fa',
  cardBg: '#ffffff',
  cardBorder: '#e9ebf0',
  sidebarBg: '#fafbfc',
  sidebarBorder: '#edf0f4',
  sidebarHover: '#f1f4f9',
  sidebarActive: '#e8edf4',
  userBubbleBg: '#eff3ff',
  userBubbleBorder: '#d9e2f7',
  userBubbleText: '#1a1d23',
  userAvatarBg: '#5b7ce6',
  aiBubbleBg: '#ffffff',
  aiBubbleBorder: '#e9ebf0',
  aiBubbleText: '#1a1d23',
  aiAvatarStart: '#6366f1',
  aiAvatarEnd: '#8b5cf6',
  actionColor: '#9ca3af',
  actionHoverColor: '#4b5563',
  actionActiveColor: '#5b7ce6',
  inputBg: '#f9fafb',
  inputBorder: '#e5e7eb',
  inputFocusBorder: '#6366f1',
  sendBtnStart: '#6366f1',
  sendBtnEnd: '#8b5cf6',
  quickTagBg: '#f1f4f9',
  quickTagHover: '#e4e9f2',
  quickTagText: '#4b5563',
  dividerColor: '#edf0f4',
  timestampColor: '#9ca3af',
  codeBlockBg: '#1e1e2e',
  codeBlockText: '#cdd6f4',
};
关于AIAssistantPage.tsx的完整代码,由于篇幅较长(约1495行),请参考项目中的实际文件。核心逻辑已在上面各层代码中说明。

十五、路由和导航集成

15.1 配置前端路由

编辑 knowledge-base-frontend/src/router/index.tsx:

const AIAssistantPage = lazy(() => import('@/pages/AIAssistantPage'));

// 在路由配置中添加
{
  path: 'ai',
  element: (
    <Suspense fallback={<LoadingFallback />}>
      <AIAssistantPage />
    </Suspense>
  ),
},

15.2 添加导航链接

编辑 knowledge-base-frontend/src/components/layout/MainLayout.tsx,在导航栏添加AI助手入口:

<a
  href="/ai"
  className={`nav-link ${location.pathname === '/ai' ? 'active' : ''}`}
  onClick={(e) => handleNavClick(e, '/ai')}
>
  <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
    <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"></path>
  </svg>
  AI助手
</a>

15.3 注册服务导出

编辑 knowledge-base-frontend/src/services/index.ts:

export { default as aiService } from './ai.service';

编辑 knowledge-base-frontend/src/stores/index.ts:

export { useAIStore } from './ai.store';

编辑 knowledge-base-frontend/src/pages/index.tsx:

export { default as AIAssistantPage } from './AIAssistantPage';

测试

16.1 启动服务

# 1. 确保MySQL已启动且kb_ai数据库已创建
# 2. 启动kb-ai服务
cd knowledge-base-backend/kb-ai
mvn spring-boot:run

# 3. 启动前端
cd knowledge-base-frontend
npm run dev

访问AI助手页面:http://localhost:3002/ai

  1. 模型切换:点击顶栏模型选择器,切换通义千问和DeepSeek

    截屏2026-05-26 18.50.56.png

  2. 发送消息:输入问题后按Enter,观察AI流式回复

    截屏2026-05-26 18.52.01.png

  3. Markdown渲染:提问技术问题,验证代码高亮、表格、列表等格式

    截屏2026-05-26 18.53.23.png

  4. 新建对话:点击侧边栏"新建对话"按钮,创建新对话

    截屏2026-05-26 18.53.54.png

  5. 历史查看:点击侧边栏对话项,验证历史消息正确加载

    截屏2026-05-26 18.54.26.png

  6. 对话删除:点击对话右侧"..."菜单,删除对话

    截屏2026-05-26 18.54.58.png

    总结

    本文介绍了在企业知识库项目中增加AI助手功能的完整实现,涵盖:

    1. 数据库设计:conversation、message、ai\_feedback三张表
    2. 后端模块:kb-ai微服务,基于LangChain4j集成千问和DeepSeek
    3. 流式对话:使用Spring SseEmitter实现SSE流式响应
    4. 前端页面:完整的AI对话界面,支持Markdown渲染和代码高亮
    5. 状态管理:基于Zustand的AI Store,管理对话和消息状态

    通过本教程的步骤,可以完成从零搭建AI助手功能的全流程开发。

最后修改:2026 年 10 月 24 日
如果觉得我的文章对你有用,请随意赞赏