做介绍英文网站,手游传奇发布网站999,p2p网站的建设,青岛辅德网络技术有限公司系统整体架构设计基于 LangChain4j 框架构建的智能对话系统采用 前后端分离 大模型中枢 的三层架构设计#xff0c;实现了与豆包类似的智能交互体验。系统架构图如下所示#xff1a;┌────────────────────────────────────…系统整体架构设计基于 LangChain4j 框架构建的智能对话系统采用 前后端分离 大模型中枢 的三层架构设计实现了与豆包类似的智能交互体验。系统架构图如下所示
┌──────────────────────────────────────────────────────────┐
│ 前端展示层 │
│ ┌─────────┐ ┌─────────┐ ┌─────────┐ ┌─────────┐ │
│ │ 对话界面 │ │ 输入组件 │ │ 历史记录 │ │ 用户操作 │ │
│ └─────────┘ └─────────┘ └─────────┘ └─────────┘ │
├──────────────────────────────────────────────────────────┤
│ 通信与协议层 │
│ ┌────────────┐ ┌────────────┐ ┌────────────┐ │
│ │ SSSE │ │ REST API │ │ 消息格式 │ │
│ └────────────┘ └────────────┘ └────────────┘ │
├──────────────────────────────────────────────────────────┤
│ 后端逻辑层 │
│ ┌─────────┐ ┌─────────┐ ┌─────────┐ ┌─────────┐ │
│ │ 模型调用 │ │ 上下文 │ │ 提示工程 │ │ 检索增强 │ │
│ │ (LLM) │ │ 管理 │ │ 模块 │ │ (RAG) │ │
│ └─────────┘ └─────────┘ └─────────┘ └─────────┘ │
├──────────────────────────────────────────────────────────┤
│ 数据持久层 │
│ ┌─────────┐ ┌─────────┐ ┌─────────┐ ┌─────────┐ │
│ │ 对话历史 │ │ 向量存储 │ │ 知识库 │ │ 用户信息 │ │
│ └─────────┘ └─────────┘ └─────────┘ └─────────┘ │
└──────────────────────────────────────────────────────────┘
图 1LangChain4j 智能对话系统架构图该架构的核心优势在于前后端解耦前端采用 Vue3 构建交互界面后端基于 LangChain4j 处理 AI 逻辑分工明确大模型能力封装通过 LangChain4j 标准化接口屏蔽不同 LLM 提供商的差异企业级扩展支持集群部署、负载均衡和数据持久化满足高并发场景前端功能模块详解1. 对话界面模块前端界面采用 Vue3 实现模仿豆包的 UI 设计风格主要包含三大区域顶部导航区中部对话区以及底部输入区。
template!-- 整体容器 --div classdoubao-layout!-- 1. 顶部导航区 --header classdoubao-headerdiv classheader-inner!-- 标题与新对话 --div classleft-group el-button typeprimary iconPlus sizemini classmr-4 clickhandleNewChat新对话/el-buttonh2 classheader-title{{ chatTitle }}/h2/div!-- 操作与头像 --div classright-groupel-icon clickhandleShareShare //el-iconel-icon clickhandleFavoriteStar //el-iconel-avatar sizemediumsrchttps://img0.baidu.com/it/u2648433959,1760892301fm253fmtautoapp120fJPEG?w500h500classcursor-pointer clickhandleUserCenter //div/div/header!-- 2. 对话内容区 --div classchat-container!-- 对话内容区 --section classdoubao-chat refchatContainerdiv classchat-inner!-- 对话历史列表 --div v-for(msg, index) in chatHistory :keyindex classmessage-container!-- 用户消息 - 居右对齐 --div v-ifmsg.isUser classuser-messagediv classmessage-bubblediv styledisplay: flex;align-items: center; classmessage-contentp styletext-align: left;margin-right: 7px; classmessage-text{{ msg.content}}/pel-avatar sizemediumsrchttps://img0.baidu.com/it/u2648433959,1760892301fm253fmtautoapp120fJPEG?w500h500classavatar-fixed clickhandleUserCenter //div/div/div!-- AI消息 - 居左对齐 --div v-else classai-messagediv classmessage-bubblediv styledisplay: flex;align-items: center; classmessage-contentel-avatar sizemedium src/doubao.png clickhandleUserCenterclassavatar-fixed /p styletext-align: left;margin-left: 7px; classmessage-text{{ msg.content }}/p/div/div/div/div/div/section/div!-- 3. 输入对话框 --footer classdoubao-inputdiv classinput-innerel-input v-modelprompt classinput-main placeholder请输入内容... clearablekeyup.entersendMessage /el-button typeprimary iconSearch sizemini classml-2 clicksendMessagestylemargin-left: 10px;发送/el-button/div/footer/div
/template核心交互逻辑自动滚动通过监听chatHistory变化使用scrollTop scrollHeight实现新消息自动定位对话标题根据历史记录动态更新标题使用computed属性实现响应式用户操作集成分享复制链接、收藏引导快捷键、新建对话等功能2. 状态管理模块采用组合式 API 管理对话状态核心代码如下
import { ref, computed, watch } from vue;
import { useRoute } from vue-router;
import { ElMessage } from element-plus;// 对话状态
const chatHistory ref([]);
const prompt ref();
const isLoading ref(false);
const currentAIResponse ref();// 动态标题
const route useRoute();
const chatTitle computed(() {if (chatHistory.value.length 1) {const firstUserMsg chatHistory.value.find(msg msg.isUser);return firstUserMsg?.content || 新对话;}return 新对话;
});// 自动滚动
const chatContainer ref(null);
const scrollToBottom () {if (chatContainer.value) {chatContainer.value.scrollTop chatContainer.value.scrollHeight;}
};
watch(chatHistory, () nextTick(scrollToBottom));3. 主要功能展示创建新对话对话详情后端核心功能实现后端基于 LangChain4j 框架构建核心功能模块包括配置文件
server:port: 9000servlet:encoding:charset: UTF-8enabled: trueforce: true# openai相关配置
openai:apiKey: #替换成自己的apiKeymodel: gpt-4o-minibaseUrl: https://api.chatanywhere.tech/v1/temperature: 0.7# 单条对话最多存储多少条对话历史记录maxMessages: 100spring:application:name: llm_appdatasource:druid:url: jdbc:mysql://localhost:3306/llm_app?useUnicodetruecharacterEncodingutf-8allowMultiQueriestrueusername: # 数据库用户名password: # 数据库密码 不存储到数据库就不需要driver-class-name: com.mysql.cj.jdbc.Drivertype: com.alibaba.druid.pool.DruidDataSourcedata:redis:password: # 你的redis密码 如果设置了database: 1host: localhostport: 6379timeout: 50001. 大模型交互模块通过LLMConfig进行统一配置统一管理大模型调用支持多模型切换
package com.example.config;import com.example.entity.ChatLLM;
import com.example.service.*;
import dev.langchain4j.memory.chat.ChatMemoryProvider;
import dev.langchain4j.memory.chat.MessageWindowChatMemory;
import dev.langchain4j.memory.chat.TokenWindowChatMemory;
import dev.langchain4j.model.chat.ChatModel;
import dev.langchain4j.model.chat.StreamingChatModel;
import dev.langchain4j.model.openai.OpenAiChatModel;
import dev.langchain4j.model.openai.OpenAiStreamingChatModel;
import dev.langchain4j.model.openai.OpenAiTokenCountEstimator;
import dev.langchain4j.service.AiServices;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;/*** Author: znly* Description:* Date: 2025/7/2 9:08*/
Configuration
public class LLMConfig {Autowiredprivate ApplicationContext context;Resourceprivate RedisChatMemoryStore redisChatMemoryStore;Autowiredprivate OpenAIProperties openAIProperties;Beanpublic ChatModel chatModel() {return OpenAiChatModel.builder().modelName(openAIProperties.getModel()).baseUrl(openAIProperties.getBaseUrl()).apiKey(openAIProperties.getApiKey()).temperature(openAIProperties.getTemperature()).build();}/*** 创建一个流式模型** return*/Beanpublic StreamingChatModel streamingChatModel() {return OpenAiStreamingChatModel.builder().modelName(openAIProperties.getModel()).baseUrl(openAIProperties.getBaseUrl()).apiKey(openAIProperties.getApiKey()).temperature(openAIProperties.getTemperature()).maxTokens(openAIProperties.getMaxTokens()).build();}Beanpublic ChatLLMService chatLLMService(StreamingChatModel streamingChatModel) {return AiServices.builder(ChatLLMService.class).streamingChatModel(streamingChatModel).chatMemoryProvider(memoryId - {return MessageWindowChatMemory.withMaxMessages(10);}).build();}Bean(name chatMessageWindowChatMemory)public ChatMemoryAssistant chatMessageWindowChatMemory(ChatModel chatModel) {return AiServices.builder(ChatMemoryAssistant.class).chatModel(chatModel).chatMemoryProvider(memoryId - {return MessageWindowChatMemory.withMaxMessages(10);}).build();}Bean(name chatTokenWindowChatMemory)public ChatMemoryAssistant chatTokenWindowChatMemory(ChatModel chatModel) {return AiServices.builder(ChatMemoryAssistant.class).chatModel(chatModel).chatMemoryProvider(memoryId - {return TokenWindowChatMemory.withMaxTokens(1000, new OpenAiTokenCountEstimator(gpt-4o-mini));}).build();}Bean(name chatRedisChatMemory)public ChatMemoryAssistant chatRedisChatMemory(ChatModel chatModel) {ChatMemoryProvider chatMemoryProvider memoryId - MessageWindowChatMemory.builder().id(memoryId).maxMessages(10).chatMemoryStore(redisChatMemoryStore).build();return AiServices.builder(ChatMemoryAssistant.class).chatModel(chatModel).chatMemoryProvider(chatMemoryProvider).build();}Bean(name chatExternal)public ChatLLMServiceSimple chatLLMServiceExternal(ChatModel chatModel) {return AiServices.builder(ChatLLMServiceSimple.class).chatModel(chatModel).tools(new WeatherService()).build();}Bean(name chatLLM)public ChatMemoryAssistant chatLLM(ChatModel chatModel) {ChatMemoryProvider chatMemoryProvider memoryId - MessageWindowChatMemory.builder().id(memoryId).maxMessages(10).chatMemoryStore(redisChatMemoryStore).build();return AiServices.builder(ChatMemoryAssistant.class).chatModel(chatModel).chatMemoryProvider(chatMemoryProvider).tools(new ExternalService()).build();}Bean(name chatLLMStream)public ChatMemoryAssistant chatLLMStream(StreamingChatModel streamingChatModel) {ChatMemoryProvider chatMemoryProvider memoryId - MessageWindowChatMemory.builder().id(memoryId).maxMessages(openAIProperties.getMaxMessages()).chatMemoryStore(redisChatMemoryStore).build();return AiServices.builder(ChatMemoryAssistant.class).streamingChatModel(streamingChatModel).chatMemoryProvider(chatMemoryProvider).tools(new ExternalService()).build();}}
2. 上下文管理模块实现对话历史的存储与检索支持会话级和用户级上下文本系统通过redis实现临时存储不存储至数据库可以在配置文件中中对存储上限进行动态修改。
Bean(name chatLLMStream)public ChatMemoryAssistant chatLLMStream(StreamingChatModel streamingChatModel) {ChatMemoryProvider chatMemoryProvider memoryId - MessageWindowChatMemory.builder().id(memoryId).maxMessages(openAIProperties.getMaxMessages()).chatMemoryStore(redisChatMemoryStore).build();return AiServices.builder(ChatMemoryAssistant.class).streamingChatModel(streamingChatModel).chatMemoryProvider(chatMemoryProvider).tools(new ExternalService()).build();}3. 提示工程模块封装提示词模板与解析逻辑提升大模型输出质量例如可以利用SystemMessage来定义你的提示词确保大模型只回复相关领域的知识内容。
package com.example.service;import dev.langchain4j.service.MemoryId;
import dev.langchain4j.service.SystemMessage;
import dev.langchain4j.service.UserMessage;
import reactor.core.publisher.Flux;/*** Author: znly* Description:* Date: 2025/7/3 10:43*/
public interface ChatMemoryAssistant {/*** 带记忆缓存的对话* param userId* param prompt* return*/
SystemMessage(你是一位本科和研究生均毕业于北京大学的专业后端开发工程师拥有十年大厂后端开发工作经验你的主要编程语言是java和python。
你只能回答你的业务领域内的问题如果问题涉及到其他领域请回复不知道)String chat(MemoryId String memoryId, UserMessage String prompt);FluxString chatStream(MemoryId String memoryId, UserMessage String prompt);}
4. 函数调用针对大模型对于相关城市天气当天时间等需要联网查询或者是用户自己相关的知识可以通过Tool这个注解来实现函数调用。例如针对天气和时间问题会调用以下两个函数来执行大模型不会直接回答。
package com.example.service;import dev.langchain4j.agent.tool.P;
import dev.langchain4j.agent.tool.Tool;
import org.springframework.stereotype.Service;import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;/*** Author: znly* Description: 外部服务类* Date: 2025/7/3 22:18*/
Service
public class ExternalService {Tool(value 今天天气怎么样)public String getWeather(P(城市) String city) {System.out.println(城市 city);//调用外部 服务return 今天 city 的天气是晴天;}Tool(value 今天日期是多少)public String getDate() {System.out.println(今天日期 LocalDate.now().toString());return LocalDate.now().toString();}Tool(value 告诉我现在的北京时间)public String getTime() {// 获取当前时间LocalDateTime now LocalDateTime.now();// 定义日期时间格式DateTimeFormatter formatter DateTimeFormatter.ofPattern(yyyy-MM-dd HH:mm:ss);// 格式化时间String formattedDateTime now.format(formatter);// 输出格式化后的时间System.out.println(当前时间: formattedDateTime);return 当前时间是: formattedDateTime;}
}
5. 检索增强生成 (RAG) 模块结合向量检索与大模型生成提升专业领域回答准确性
// 文档加载与处理
DocumentLoader loader new FileSystemDocumentLoader(knowledge-base);
DocumentParser parser new MarkdownDocumentParser();
TextSplitter splitter new RecursiveCharacterTextSplitter(RecursiveCharacterTextSplitterConfig.builder().chunkSize(800).chunkOverlap(100).build()
);
ListDocument documents splitter.split(parser.parse(loader.load()));// 向量存储
EmbeddingModel embeddingModel OpenAiEmbeddingModel.builder().apiKey(API_KEY).build();
EmbeddingStore embeddingStore PineconeEmbeddingStore.builder().apiKey(PINECONE_KEY).environment(us-west1-gcp).indexName(knowledge-index).build();
embeddingStore.storeDocuments(documents, embeddingModel);// RAG服务
Rag rag Rag.builder().embeddingModel(embeddingModel).embeddingStore(embeddingStore).documentLoader(loader).textSplitter(splitter).build();// 生成回答
String userQuery 如何配置LangChain4j的RAG模块;
ListDocument relevantDocs rag.relatedDocuments(userQuery, 3);
String response rag.chain().promptTemplate(PromptTemplate.builder().template(根据以下文档回答用户问题\n{documents}\n用户问题{userQuery}\n回答).build()).languageModel(model).build().invoke(Map.of(documents, relevantDocs, userQuery, userQuery));技术亮点与创新点1. 多模态对话增强在标准文本对话基础上扩展支持富文本处理解析 Markdown 格式输出支持加粗、列表等样式代码块处理自动识别代码块并高亮显示提升技术对话体验数学公式支持通过 KaTeX 渲染 LaTeX 公式满足学术交流需求2. 智能对话控制实现多种对话策略追问策略当用户问题不明确时自动生成追问提示如 你能具体说明一下吗多轮上下文智能截断过长对话历史保留关键信息基于令牌数统计敏感词过滤集成内容安全模块自动识别并处理敏感信息3. 企业级能力集成与企业系统深度整合OA 系统集成对接企业 OA 系统自动提取日程、审批等信息CRM 集成根据客户历史订单生成个性化推荐知识库对接连接企业内部知识库提供专业领域支持应用场景与典型案例1. 企业智能客服某电商平台集成该系统后实现85% 的常见问题自动解答减少客服人力成本基于购买历史的个性化推荐提升转化率 15%多轮对话上下文保持客户满意度提升 20%2. 技术支持助手为软件开发团队提供代码问题解答基于官方文档和项目代码库错误日志分析与解决方案推荐技术选型建议如 Spring Boot 与 Quarkus 如何选择3. 学术研究助手服务科研人员文献摘要生成与关键信息提取实验方案设计建议论文写作辅助语法检查、引用建议总结与未来规划基于 LangChain4j 构建的智能对话系统充分发挥了 Java 的企业级优势和 LangChain4j 的大模型集成能力在功能完整性、性能表现和可扩展性方面均达到生产级水平。系统不仅实现了豆包的核心对话功能还通过 RAG 技术、多模态支持和企业级集成拓展了智能对话的应用边界。未来规划包括多模态增强支持语音、图像输入输出实现更自然的交互联邦学习集成保护企业数据隐私支持跨机构协作边缘计算优化针对边缘设备进行模型轻量化和推理优化低代码平台提供可视化流程编排工具降低使用门槛该系统的成功实践证明Java 与 LangChain4j 的组合不仅适用于企业级大模型应用开发还能在用户体验、性能优化和系统集成方面超越传统 Python 方案为智能对话技术的工业化落地提供了新的技术路径。