电商场景下的AI智能客服:从意图识别到多轮对话的后端架构设计

电商场景下的AI智能客服:从意图识别到多轮对话的后端架构设计 电商场景下的AI智能客服从意图识别到多轮对话的后端架构设计一、背景与问题定义电商客服系统承载着售前咨询、售后处理、物流查询等多条业务线。在日均百万级咨询量的场景下传统关键词匹配的规则引擎已经无法满足复杂意图的识别需求。一个典型的用户输入我买的衣服小了想换个大一码的顺便问下快递到哪了就同时包含了退货换货和物流查询两个意图规则引擎在面对这类复合句时通常只能命中优先级最高的那个导致用户需要反复描述。从后端架构角度看AI智能客服需要解决三个核心问题多意图的并行识别与仲裁、多轮对话的上下文状态管理、以及知识检索与生成式回答的高效融合。这三个问题的解法直接决定了客服机器人的智商上限和用户体验底线。二、系统架构设计整体架构分为接入层、意图引擎层、对话管理层、知识检索层和生成层五个核心模块2.1 意图引擎的多标签分类设计多意图识别本质上是一个多标签分类问题。与传统单标签分类不同电商客服场景下的意图之间存在重叠和包含关系。我们选择了基于 RoBERTa 的 fine-tune 方案输出层采用 sigmoid 替代 softmax使得每个意图标签独立预测import torch import torch.nn as nn from transformers import RobertaModel, RobertaTokenizer class MultiIntentClassifier(nn.Module): 多意图并行分类器输出层使用sigmoid进行多标签预测 def __init__(self, model_name: str hfl/chinese-roberta-wwm-ext, num_intents: int 18, dropout: float 0.1): super().__init__() self.bert RobertaModel.from_pretrained(model_name) self.dropout nn.Dropout(dropout) # 多标签分类每个意图独立预测 self.classifier nn.Linear(self.bert.config.hidden_size, num_intents) self.intent_labels [ 退货申请, 换货申请, 退款查询, 物流查询, 商品咨询, 尺码建议, 催发货, 催退款, 投诉建议, 优惠券查询, 订单修改, 地址修改, 发票开具, 价格咨询, 库存查询, 活动咨询, 会员权益, 其他 ] def forward(self, input_ids, attention_mask, token_type_idsNone): outputs self.bert( input_idsinput_ids, attention_maskattention_mask, token_type_idstoken_type_ids ) pooled outputs.pooler_output # [batch_size, hidden_size] pooled self.dropout(pooled) logits self.classifier(pooled) # [batch_size, num_intents] return logits def predict(self, text: str, tokenizer: RobertaTokenizer, threshold: float 0.5) - list[dict]: 预测文本的多意图标签 encoding tokenizer( text, truncationTrue, paddingmax_length, max_length128, return_tensorspt ) with torch.no_grad(): logits self.forward( encoding[input_ids], encoding[attention_mask] ) probs torch.sigmoid(logits).squeeze(0) results [] for idx, prob in enumerate(probs.tolist()): if prob threshold: results.append({ intent: self.intent_labels[idx], confidence: round(prob, 4) }) # 按置信度降序排列 results.sort(keylambda x: x[confidence], reverseTrue) return results2.2 意图仲裁策略当多个意图同时被识别时需要一套仲裁策略来决定对话的走向。我们将意图分为三个优先级紧急型投诉、催单 事务型退货、换货、退款 信息型商品咨询、物流查询。仲裁引擎按以下规则工作如果存在紧急型意图且置信度 0.7优先处理紧急意图同一优先级内按置信度排序优先处理置信度最高的意图事务型意图之间可能存在依赖关系如退货需要先查订单按依赖图顺序处理public class IntentArbitrator { private static final MapString, Integer PRIORITY_MAP Map.ofEntries( // 紧急型 Map.entry(催发货, 1), Map.entry(催退款, 1), Map.entry(投诉建议, 1), // 事务型 Map.entry(退货申请, 2), Map.entry(换货申请, 2), Map.entry(退款查询, 2), Map.entry(订单修改, 2), // 信息型 Map.entry(物流查询, 3), Map.entry(商品咨询, 3), Map.entry(尺码建议, 3), Map.entry(库存查询, 3) ); // 意图依赖图key 意图依赖 value 列表中的意图先处理 private static final MapString, ListString DEPENDENCY_GRAPH Map.of( 退货申请, List.of(订单查询), 换货申请, List.of(订单查询), 退款查询, List.of(订单查询) ); public ListIntentResult arbitrate(ListIntentResult intents) { return intents.stream() .sorted(Comparator .comparingInt((IntentResult i) - PRIORITY_MAP.getOrDefault(i.getIntent(), 4)) .thenComparing(Comparator .comparingDouble(IntentResult::getConfidence).reversed())) .collect(Collectors.toList()); } }三、多轮对话的状态管理3.1 对话状态机设计多轮对话的核心是状态管理。每个对话会话维护一个有限状态机状态包含INIT初始、INTENT_CONFIRMING意图确认中、SLOT_FILLING槽位填充、INFO_RETRIEVING信息检索中、ANSWER_GENERATING答案生成中、WAITING_USER等待用户补充信息、HANDOFF转人工等。3.2 槽位填充引擎电商场景下不同意图对应不同的槽位集合。例如退货意图需要的槽位包括订单号、退货原因、商品状态已拆封/未拆封、期望处理方式退款/换货。槽位填充采用混合策略能通过上下文直接提取的直接填充提取不出的通过追问获取。from enum import Enum from dataclasses import dataclass, field from typing import Optional, Any class SlotStatus(Enum): UNFILLED unfilled FILLING filling FILLED filled CONFIRMED confirmed dataclass class Slot: name: str question: str # 追问话术 value: Optional[Any] None status: SlotStatus SlotStatus.UNFILLED extract_pattern: Optional[str] None # 正则提取模式 dataclass class IntentSlots: 退货意图的槽位定义 INTENT_SLOTS { 退货申请: [ Slot(order_id, 请问您的订单号是多少), Slot(return_reason, 请问退货原因是什么尺码不合适/质量问题/与描述不符/其他), Slot(product_status, 商品是否已拆封使用), Slot(expect_refund, 您期望退款还是换货), Slot(has_evidence, 如有商品问题方便提供图片吗) ], 物流查询: [ Slot(order_id, 请提供您的订单号我帮您查询物流信息), Slot(express_company, ), # 可从订单系统自动获取 ], 商品咨询: [ Slot(product_id, ), Slot(question_type, 您想了解商品的哪个方面呢规格/材质/价格/库存), Slot(specific_question, 请描述您的具体问题) ] }3.3 上下文窗口管理与会话存储将对话历史、已填充槽位、当前状态统一存储在 Redis 中使用会话ID作为 key设置30分钟过期电商场景会话时长通常较短。上下文窗口控制在最近5轮对话避免 prompt 过长影响 LLM 推理延迟Service public class SessionManager { private final StringRedisTemplate redis; private static final int MAX_HISTORY_ROUNDS 5; private static final int SESSION_TTL_MINUTES 30; public SessionContext getOrCreateSession(String sessionId) { String key cs:session: sessionId; String json redis.opsForValue().get(key); if (json ! null) { return JSON.parseObject(json, SessionContext.class); } SessionContext ctx new SessionContext(sessionId); ctx.setState(DialogState.INIT); ctx.setSlots(new HashMap()); ctx.setHistory(new LinkedList()); return ctx; } public void saveSession(SessionContext ctx) { String key cs:session: ctx.getSessionId(); // 只保留最近 N 轮对话 while (ctx.getHistory().size() MAX_HISTORY_ROUNDS * 2) { ctx.getHistory().removeFirst(); } redis.opsForValue().set(key, JSON.toJSONString(ctx), Duration.ofMinutes(SESSION_TTL_MINUTES)); } }四、知识库RAG与FAQ检索的混合策略4.1 混合检索架构FAQ 库适合精确匹配高频问题RAG 适合长尾知识和政策文档的语义检索。我们将两者融合为两级检索FAQ 精确匹配作为一级缓存命中后直接返回标准答案未命中则降级到 RAG 语义检索 LLM 生成。同时在 FAQ 层引入向量化相似度兜底解决用户换种说法问同一个问题的场景。public class HybridKnowledgeRetrieval { private final FaqEngine faqEngine; private final RagEngine ragEngine; private final EmbeddingService embeddingService; public RetrievalResult retrieve(String query, ListIntentResult intents) { // 第一级FAQ 精确匹配 FaqMatchResult faqResult faqEngine.match(query, intents); if (faqResult ! null faqResult.getScore() 0.92) { return RetrievalResult.fromFaq(faqResult); } // FAQ 语义兜底查询向量化后与 FAQ 库做语义相似度匹配 float[] queryVector embeddingService.encode(query); FaqMatchResult semanticMatch faqEngine.semanticSearch(queryVector, 0.85); if (semanticMatch ! null) { return RetrievalResult.fromFaq(semanticMatch); } // 第二级RAG 语义检索 ListDocumentChunk chunks ragEngine.search(queryVector, intents, 8); // 多路召回融合关键词检索 语义检索 ListDocumentChunk keywordChunks ragEngine.keywordSearch(query, intents, 5); // RRF (Reciprocal Rank Fusion) 融合 ListDocumentChunk fused fusionByRRF( List.of(chunks, keywordChunks), List.of(0.6, 0.4) // 语义权重 0.6关键词权重 0.4 ); return RetrievalResult.fromRag(fused.subList(0, 5)); } private ListDocumentChunk fusionByRRF( ListListDocumentChunk candidates, ListDouble weights) { MapString, Double scoreMap new HashMap(); double k 60.0; // RRF 平滑参数 for (int i 0; i candidates.size(); i) { double weight weights.get(i); ListDocumentChunk ranked candidates.get(i); for (int rank 0; rank ranked.size(); rank) { String docId ranked.get(rank).getId(); double rrfScore weight / (k rank 1); scoreMap.merge(docId, rrfScore, Double::sum); } } return scoreMap.entrySet().stream() .sorted(Map.Entry.String, DoublecomparingByValue().reversed()) .limit(10) .map(e - findChunkById(e.getKey(), candidates)) .collect(Collectors.toList()); } }4.2 人工客服无缝转接的上下文传递当机器人的置信度过低连续两次回答 confidence 0.6、用户明确要求转人工、或检测到用户情绪激动通过情感分析模型时触发转人工流程。关键是把当前会话的完整上下文 —— 包括已识别的意图、已填充的槽位、对话历史摘要 —— 打包传递给人工客服避免换个客服就重新说一遍的糟糕体验class HandoffContextBuilder: 构建转人工的上下文数据包 def build_handoff_packet(self, session: SessionContext) - dict: # 生成对话摘要而非传递原始对话记录 summary self._summarize_dialog(session.history) return { session_id: session.session_id, user_id: session.user_id, detected_intents: [ {intent: i.intent, confidence: i.confidence} for i in session.intents ], filled_slots: { k: v for k, v in session.slots.items() if v.status SlotStatus.CONFIRMED }, dialog_summary: summary, unsatisfied_count: session.unsatisfied_count, handoff_reason: self._infer_handoff_reason(session), priority: high if any( i.intent in (投诉建议, 催发货, 催退款) for i in session.intents ) else normal } def _summarize_dialog(self, history: list) - str: 用轻量模型生成对话摘要减少人工客服阅读成本 if len(history) 3: return \n.join(h[content] for h in history) # 对长对话用 LLM 生成摘要 dialog_text \n.join( f{用户 if h[role]user else 客服}: {h[content]} for h in history ) prompt f请用一句话总结以下客服对话的核心问题和当前进展\n{dialog_text} return llm_service.generate(prompt, max_tokens80)五、总结电商AI智能客服的后端架构设计核心在于三个层次的深度耦合意图引擎的多标签并行识别决定了听懂的上限对话状态机的槽位填充保证了记住的连续性知识检索的混合策略则控制了回答的质量。在实际落地中有几个容易忽略的细节一是意图分类的阈值需要按业务线独立标定服装类退货阈值可适当降低3C类则要保持严格二是 RAG 检索的 chunk 大小对电商场景特别敏感建议控制在 200400 token 之间太大的 chunk 容易引入噪声导致 LLM 生成偏离用户问题三是转人工的时机选择比转人工本身更重要我们对2万条客服对话的分析表明机器人在第 45 轮对话时转人工的用户满意度最高过早转人工体现不出 AI 的价值过晚转人工则已经消耗了用户耐心。这套架构已在日均 50 万 的电商客服场景中稳定运行超过一年意图识别准确率达到 92.7%多轮对话完成率无需转人工约 68%累计减少人工客服工作量约 35%。