1. 企业级智能客服系统架构设计
在构建智能客服系统时,架构设计是决定系统可扩展性和稳定性的关键因素。我们采用四层架构设计,确保各功能模块解耦且职责单一。
1.1 四层架构详解
网关层作为系统入口,承担着重要的流量管控和安全防护职责:
- 使用Spring Cloud Gateway实现API路由
- 集成OAuth2进行身份认证
- 配置Redis实现分布式限流
- 基于Nacos实现灰度发布策略
业务层包含多个微服务,每个服务专注特定业务领域:
- 会话管理服务:维护WebSocket长连接,处理消息路由
- 工单管理服务:实现工单CRUD和状态流转
- 人工坐席调度服务:管理人工客服资源分配
- 通知推送服务:处理短信、邮件等通知渠道
AI层是系统的智能核心,包含多个关键组件:
- 意图识别引擎:分析用户输入,确定问题类型
- RAG问答系统:基于知识库提供精准回答
- Agent工具调用:执行具体业务操作
- 多模型路由:根据场景选择合适的大模型
数据层采用多种存储方案应对不同需求:
- MySQL:存储结构化业务数据
- Redis:缓存会话状态和热点数据
- Milvus:向量检索知识库内容
- Elasticsearch:全文检索历史工单
- MinIO:存储文档和多媒体文件
1.2 微服务拆分策略
我们遵循"单一职责"原则进行服务拆分,每个服务都有明确的边界:
| 服务名称 | 核心职责 | 关键技术栈 |
|---|---|---|
| gateway-service | 统一入口、鉴权、限流 | Spring Cloud Gateway + OAuth2 |
| session-service | 会话管理、消息路由 | Spring WebSocket + Redis |
| ai-service | AI能力集成 | Spring AI Alibaba 1.1 |
| knowledge-service | 知识库管理 | Spring AI + Milvus |
| ticket-service | 工单管理 | Spring Boot + MySQL |
| analytics-service | 监控分析 | Micrometer + Grafana |
这种拆分方式使得每个服务可以独立开发、测试和部署,大大提升了系统的可维护性。
需要模型API调用? 免费领10W Token,多模型网关一键接入 Claude、DeepSeek 等主流模型。
2. 项目初始化与基础配置
2.1 Maven多模块配置
父POM采用dependencyManagement统一管理依赖版本,避免子模块版本冲突:
xml复制<dependencyManagement>
<dependencies>
<!-- Spring AI Alibaba BOM -->
<dependency>
<groupId>com.alibaba.cloud.ai</groupId>
<artifactId>spring-ai-alibaba-bom</artifactId>
<version>1.1.2.2</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<!-- Spring Cloud BOM -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>2023.0.3</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
2.2 AI服务核心依赖
AI服务需要引入以下关键依赖:
xml复制<dependencies>
<!-- Spring AI Alibaba 核心 -->
<dependency>
<groupId>com.alibaba.cloud.ai</groupId>
<artifactId>spring-ai-alibaba-starter</artifactId>
</dependency>
<!-- RAG 向量存储 -->
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-milvus-store-spring-boot-starter</artifactId>
</dependency>
<!-- 熔断降级 -->
<dependency>
<groupId>io.github.resilience4j</groupId>
<artifactId>resilience4j-spring-boot3</artifactId>
<version>2.2.0</version>
</dependency>
<!-- 监控指标 -->
<dependency>
<groupId>io.micrometer</groupId>
<artifactId>micrometer-registry-prometheus</artifactId>
</dependency>
</dependencies>
2.3 关键配置详解
application.yml中需要配置以下核心参数:
yaml复制spring:
ai:
dashscope:
api-key: ${DASHSCOPE_API_KEY}
chat:
options:
model: qwen-max
temperature: 0.3 # 客服场景需要确定性更高的回复
max-tokens: 2048
# Milvus向量数据库配置
milvus:
host: ${MILVUS_HOST:localhost}
port: 19530
collection-name: customer_knowledge
dimension: 1536 # 与text-embedding-v3模型维度一致
# 熔断配置
resilience4j:
circuitbreaker:
instances:
aiService:
sliding-window-size: 10
failure-rate-threshold: 50
wait-duration-in-open-state: 30s
3. 知识库构建与管理
3.1 知识库构建流程
知识库质量直接影响客服系统的回答准确性,我们采用以下流程构建高质量知识库:
-
文档加载:支持PDF、Word、HTML等多种格式
- 使用TikaDocumentReader解析通用文档
- 使用PagePdfDocumentReader处理PDF文件,保留页码信息
-
文档清洗:
- 去除页眉页脚、特殊字符
- 过滤广告和无关内容
- 处理文档中的表格和图片
-
文本切分:
- 采用TokenTextSplitter进行语义切分
- 设置chunk_size=512,overlap=64
- 确保每个chunk包含完整语义
-
元数据增强:
- 添加文档来源、分类标签
- 记录文档版本和更新时间
- 添加业务相关元数据
-
向量化入库:
- 使用text-embedding-v3模型生成向量
- 存入Milvus向量数据库
- 建立高效索引(HNSW)
3.2 知识库服务实现
KnowledgeIngestionService负责知识库的构建和维护:
java复制@Service
public class KnowledgeIngestionService {
private final VectorStore vectorStore;
private final TokenTextSplitter textSplitter;
public void importFAQ(List<FAQItem> faqList) {
List<Document> documents = faqList.stream()
.map(faq -> {
String content = String.format(
"问题:%s\n答案:%s\n相关标签:%s",
faq.getQuestion(), faq.getAnswer(), String.join("、", faq.getTags())
);
return new Document(content, Map.of(
"type", "faq",
"category", faq.getCategory(),
"faq_id", faq.getId()
));
})
.collect(Collectors.toList());
ingestDocuments(documents);
}
private void ingestDocuments(List<Document> documents) {
// 去重检查
List<Document> newDocs = deduplicate(documents);
if (!newDocs.isEmpty()) {
vectorStore.add(newDocs);
}
}
}
3.3 多轮对话设计
对于复杂业务流程,我们设计对话树引导用户:
yaml复制refund_dialog_tree:
- nodeId: "start"
question: "请提供您的订单号"
type: QUESTION
branches:
- condition: "\\d{10,20}"
nextNodeId: "verify_order"
slotName: "order_id"
- nodeId: "verify_order"
type: ACTION
toolToCall: "queryOrderTool"
branches:
- condition: "found"
nextNodeId: "ask_reason"
每个对话节点包含:
- nodeId:唯一标识
- question:询问用户的问题
- type:节点类型(QUESTION/ACTION/END)
- branches:根据用户回答的分支
4. 意图识别与路由
4.1 意图识别服务
IntentRecognitionService使用大模型进行意图分类:
java复制@Service
public class IntentRecognitionService {
private final ChatClient chatClient;
private static final String PROMPT = """
你是一个意图识别引擎。请分析用户输入,识别其意图。
支持的意图:
- ORDER_QUERY:查询订单
- REFUND_REQUEST:申请退款
- PRODUCT_INQUIRY:产品咨询
- ACCOUNT_ISSUE:账户问题
- HUMAN_TRANSFER:转人工
请以JSON格式输出,包含:
- intent: 意图名称
- confidence: 置信度(0-1)
- slots: 提取到的槽位
""";
public IntentResult recognize(String userInput) {
String response = chatClient.prompt()
.user(u -> u.text(PROMPT).param("userInput", userInput))
.call()
.content();
return parseResponse(response);
}
}
4.2 智能路由实现
RequestRouter根据意图结果决定处理流程:
java复制@Service
public class RequestRouter {
private final IntentRecognitionService intentService;
private final CustomerServiceRAG ragService;
private final CustomerServiceAgent agentService;
public Flux<String> route(String userInput, String sessionId) {
IntentResult intent = intentService.recognize(userInput);
return switch (intent.getIntent()) {
case "ORDER_QUERY", "REFUND_REQUEST" ->
agentService.processWithTools(userInput, sessionId);
case "PRODUCT_INQUIRY" ->
ragService.queryWithContext(userInput, sessionId);
default ->
ragService.queryWithContext(userInput, sessionId);
};
}
}
5. RAG问答系统实现
5.1 RAG服务核心逻辑
CustomerServiceRAG整合向量检索与大模型:
java复制@Service
public class CustomerServiceRAG {
private final ChatClient chatClient;
private final VectorStore vectorStore;
private static final String SYSTEM_PROMPT = """
你是一位专业客服助手。请遵循以下原则:
1. 优先使用知识库中的信息回答
2. 答案要准确具体
3. 语气友好,避免技术术语
""";
public Flux<String> queryWithContext(String userInput, String sessionId) {
return chatClient.prompt()
.defaultSystem(SYSTEM_PROMPT)
.user(userInput)
.advisors(
QuestionAnswerAdvisor.builder(vectorStore)
.searchRequest(SearchRequest.builder()
.topK(5)
.similarityThreshold(0.72)
.build())
.build()
)
.stream()
.content();
}
}
5.2 检索增强配置
QuestionAnswerAdvisor关键参数:
- topK:检索最相关的5条知识
- similarityThreshold:相似度阈值0.72
- filterExpression:可按分类过滤
6. Agent工具调用实现
6.1 客服工具集定义
使用@Tool注解定义客服工具:
java复制@Component
public class CustomerServiceTools {
@Tool(description = "查询订单信息")
public OrderInfo queryOrder(@ToolParam(description = "订单号") String orderId) {
return orderService.getOrderById(orderId);
}
@Tool(description = "提交退款申请")
public RefundResult submitRefund(
@ToolParam(description = "订单号") String orderId,
@ToolParam(description = "退款原因") String reason) {
return orderService.submitRefund(orderId, reason);
}
}
6.2 Agent服务实现
CustomerServiceAgent整合工具调用与对话管理:
java复制@Service
public class CustomerServiceAgent {
private final ChatClient agentClient;
private static final String SYSTEM_PROMPT = """
你是一位智能客服,拥有查询订单、处理退款等能力。
工作原则:
1. 优先使用工具获取实时数据
2. 工具调用前确认必要信息
3. 操作后告知用户结果
""";
public Flux<String> processWithTools(String userInput, String sessionId) {
return agentClient.prompt()
.defaultSystem(SYSTEM_PROMPT)
.user(userInput)
.stream()
.content();
}
}
7. 生产环境考量
7.1 熔断降级配置
使用Resilience4j实现熔断:
yaml复制resilience4j:
circuitbreaker:
instances:
aiService:
sliding-window-size: 10
failure-rate-threshold: 50
wait-duration-in-open-state: 30s
timelimiter:
instances:
aiService:
timeout-duration: 30s
7.2 监控指标收集
配置Micrometer收集关键指标:
java复制@Autowired
private MeterRegistry meterRegistry;
public void processRequest() {
long start = System.currentTimeMillis();
try {
// 处理请求
meterRegistry.counter("requests.count").increment();
} finally {
meterRegistry.timer("requests.latency")
.record(System.currentTimeMillis() - start, TimeUnit.MILLISECONDS);
}
}
8. 实际应用中的经验分享
在开发智能客服系统过程中,我们积累了一些宝贵经验:
- 知识库质量至关重要
- 定期更新知识库内容,确保信息时效性
- 对知识文档进行严格的质检和审核
- 建立反馈机制,持续优化知识库
- 意图识别优化技巧
- 收集真实用户query优化意图分类
- 对低置信度结果进行人工审核
- 建立意图识别测试集,定期评估效果
- 性能优化建议
- 对高频查询建立缓存机制
- 向量检索使用GPU加速
- 对话历史采用增量更新
- 异常处理经验
- 对工具调用设置合理超时
- 准备多种fallback方案
- 关键操作添加确认环节
这个智能客服系统架构已经在多个企业项目中得到验证,能够稳定支持日均百万级的客服请求。系统设计充分考虑了扩展性,可以方便地接入新的AI能力和业务工具。
