最近很多B站粉丝(Java 开发者)留言问我:想在项目里快速接入 AI 大模型,怎么做最简单?试了一圈,LangChain4j 确实是目前最顺手的方案,不用拼报文、不用处理复杂上下文,几行代码就能跑起来。
今天我就直接从头到尾带你做一个可上线的智能客服,包含:基础对话、上下文记忆、本地知识库检索、完整前端页面,全程干货,不啰嗦。
一、LangChain4j 是干嘛的?
简单说:它就是 Java 生态里对接大模型的 “脚手架”,帮你屏蔽不同厂商(通义、豆包、OpenAI 等)的接口差异,内置对话记忆、文档读取、检索、函数调用等能力,让你专注业务,不用折腾底层调用。
二、环境准备
- JDK 17+
- SpringBoot 3.x
- 通义千问 API Key(免费够用)
- IDEA
三、项目搭建(简化版)
pom.xml 只需要这些:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- langchain4j -->
<dependency>
<groupId>dev.langchain4j</groupId>
<artifactId>langchain4j-spring-boot-starter</artifactId>
<version>0.34.0</version>
</dependency>
<dependency>
<groupId>dev.langchain4j</groupId>
<artifactId>langchain4j-qwen</artifactId>
<version>0.34.0</version>
</dependency>
</dependencies>
application.yml:
server:
port: 8080
langchain4j:
qwen:
api-key: 你的APIKEY
model-name: qwen-turbo
四、核心实现:带本地知识库的智能客服
我直接写一个生产可用级别的服务:
- 用 List<String> 模拟本地知识库
- 遍历匹配用户问题,做最简单的 RAG 检索
- 专业提示词
- 上下文对话记忆
import dev.langchain4j.data.message.AiMessage;
import dev.langchain4j.data.message.SystemMessage;
import dev.langchain4j.data.message.UserMessage;
import dev.langchain4j.memory.ChatMemory;
import dev.langchain4j.memory.chat.MessageWindowChatMemory;
import dev.langchain4j.model.chat.ChatLanguageModel;
import dev.langchain4j.model.qwen.QwenChatModel;
import jakarta.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Service
public class AICustomerService {
@Value("${langchain4j.qwen.api-key}")
private String apiKey;
private ChatLanguageModel chatModel;
private final Map<String, ChatMemory> userMemoryMap = new HashMap<>();
// 本地知识库(模拟数据库/文档)
private final List<String> localKnowledgeBase = new ArrayList<>();
@PostConstruct
public void init() {
// 初始化模型
chatModel = QwenChatModel.builder()
.apiKey(apiKey)
.modelName("qwen-turbo")
.build();
// 初始化本地知识库
localKnowledgeBase.add("发货规则:16点前下单当天发货,16点后下单次日发货");
localKnowledgeBase.add("物流时效:省内1-2天,外省3天左右,偏远地区4-5天");
localKnowledgeBase.add("售后政策:支持7天无理由,质量问题包邮退换");
localKnowledgeBase.add("订单查询:在我的-订单中心查看物流与状态");
localKnowledgeBase.add("优惠券:满100减10,满200减25,有效期7天");
}
public String chat(String userId, String userMessage) {
// 每个用户独立对话记忆
ChatMemory chatMemory = userMemoryMap.computeIfAbsent(userId,
k -> MessageWindowChatMemory.builder().maxMessages(20).build());
// 遍历知识库,匹配相关内容
String knowledge = matchKnowledge(userMessage);
// 构建专业提示词
String systemPrompt = buildPrompt(knowledge);
// 首次对话加载系统提示
if (chatMemory.messages().isEmpty()) {
chatMemory.add(SystemMessage.from(systemPrompt));
}
// 用户消息
chatMemory.add(UserMessage.from(userMessage));
// AI 回答
AiMessage aiMessage = chatModel.generate(chatMemory.messages()).content();
chatMemory.add(aiMessage);
return aiMessage.text();
}
/**
* 遍历本地知识库做简单匹配
*/
private String matchKnowledge(String userMsg) {
StringBuilder sb = new StringBuilder();
String lowerMsg = userMsg.toLowerCase();
for (String knowledge : localKnowledgeBase) {
String lowerKb = knowledge.toLowerCase();
// 简单关键词匹配,真实项目可换成向量检索
if (lowerKb.contains(lowerMsg) || lowerMsg.contains("发货") || lowerMsg.contains("物流") || lowerMsg.contains("售后")) {
sb.append("- ").append(knowledge).append("\n");
}
}
return !sb.isEmpty() ? sb.toString() : "暂无相关知识库内容";
}
/**
* 高质量提示词
*/
private String buildPrompt(String knowledge) {
return """
你是电商平台官方智能客服,请遵守以下规则:
1. 回答礼貌、简洁、专业,口语化不生硬
2. 只回答电商订单、物流、售后、商品相关问题,无关问题直接拒绝
3. 必须优先使用下面提供的【本地知识库】内容回答,不允许编造答案
4. 知识库没有答案时,统一回复:抱歉,这个问题我需要为您转接人工客服
【本地知识库】:
%s
""".formatted(knowledge);
}
}
接口层:
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/ai")
public class AIController {
@Resource
private AICustomerService aiCustomerService;
@GetMapping("/customer-service")
public String chat(String userId, String msg) {
return aiCustomerService.chat(userId, msg);
}
}
五、完整前端聊天页面
在 resources/static 下新建 chat.html,复制以下全部代码:
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>智能客服</title>
<style>
*{margin:0;padding:0;box-sizing:border-box;font-family:system-ui}
body{max-width:600px;margin:20px auto;background:#f5f7fa}
.chat-wrapper{height:650px;background:#fff;border-radius:12px;box-shadow:0 2px 10px #0000000d;display:flex;flex-direction:column}
.chat-body{flex:1;padding:15px;overflow-y:auto}
.message{margin:10px 0;padding:10px 14px;border-radius:16px;max-width:75%;line-height:1.5}
.message-user{background:#007bff;color:white;margin-left:auto}
.message-ai{background:#e9ecef;color:#222}
.chat-footer{display:flex;padding:12px;gap:10px;border-top:1px solid #eee}
input{flex:1;padding:12px 16px;border:1px solid #ddd;border-radius:24px;outline:none}
button{padding:12px 20px;background:#007bff;color:white;border:none;border-radius:24px;cursor:pointer}
</style>
</head>
<body>
<div class="chat-wrapper">
<div class="chat-body" id="chatBody"></div>
<div class="chat-footer">
<input type="text" id="msgInput" placeholder="请输入问题...">
<button onclick="send()">发送</button>
</div>
</div>
<script>
const userId = "user_001";
const chatBody = document.getElementById("chatBody");
const msgInput = document.getElementById("msgInput");
function send() {
const msg = msgInput.value.trim();
if (!msg) return;
// 显示用户消息
chatBody.innerHTML += `<div class="message message-user">${msg}</div>`;
msgInput.value = "";
// 请求后端
fetch(`/ai/customer-service?userId=${userId}&msg=${encodeURIComponent(msg)}`)
.then(res => res.text())
.then(aiMsg => {
chatBody.innerHTML += `<div class="message message-ai">${aiMsg}</div>`;
chatBody.scrollTop = chatBody.scrollHeight;
});
}
// 回车发送
msgInput.addEventListener("keydown", e => {
if (e.key === "Enter") send()
});
</script>
</body>
</html>
六、运行测试
启动项目,访问:
http://localhost:8080/chat.html
你可以测试:
- “什么时候发货?”
- “物流多久到?”
- “可以退换吗?”
- “今天天气怎么样?”(会被拒绝)
AI 会严格按照你的本地知识库回答,不会乱编,上下文也能记住。
提示
AI 会严格按照你的本地知识库回答,不会乱编,上下文也能记住。
七、真实项目怎么升级?
这篇已经是最小可用版本,想上生产只需要扩展:
- 把 List 知识库换成 MySQL / MongoDB / ES
- 关键词匹配换成向量数据库(Milvus、Chroma 等)
- 本地内存记忆换成 Redis 存储
- 加入流式输出(打字机效果)
- 加入接口限流、日志、异常监控
八、总结
LangChain4j 对 Java 开发者真的非常友好,不用懂太多 AI 原理,也能快速做出 AI 应用。这篇从环境、接口、后端逻辑到前端页面全给你配齐了,复制就能跑,改改就能进项目。