一、案例背景

某电商平台日均咨询量 12 万+,客服团队 500 人,面临以下痛点:

  • 渠道割裂:Web 在线客服、App 内消息、微信公众号、小程序、电话热线各自独立,用户重复描述问题
  • 重复咨询占比高:约 65% 的咨询是常见问题(物流查询、退换货流程、优惠券使用等)
  • 高峰期人力不足:大促期间咨询量暴涨 5-8 倍,排队时长超过 30 分钟
  • 知识库更新滞后:运营政策频繁调整,客服培训跟不上,回答口径不统一
  • 坐席流动率高:新人培训周期长(3 周),上岗后前两个月质检合格率仅 62%

目标:构建全渠道智能客服 Agent,实现:

  1. 常见问题自动解决率 ≥ 70%
  2. 平均响应时间 < 5 秒
  3. 坐席辅助模式下人均处理效率提升 50%
  4. 全渠道用户会话无缝衔接

二、需求分析

# requirements/customer_service_requirements.py

class CustomerServiceRequirements:
    """
    智能客服 Agent 需求分析
    """

    # 渠道接入
    CHANNELS = {
        "web_chat": {
            "protocol": "WebSocket",
            "auth": "Session Cookie",
            "features": ["文本", "图片", "表情包", "商品卡片"],
        },
        "app_chat": {
            "protocol": "MQTT",
            "auth": "Token",
            "features": ["文本", "图片", "语音消息", "订单链接"],
        },
        "wechat_official": {
            "protocol": "HTTP (WeChat API)",
            "auth": "OAuth2.0",
            "features": ["文本", "图片", "模板消息", "菜单点击"],
        },
        "wechat_miniprogram": {
            "protocol": "WebSocket",
            "auth": "Code + Session Key",
            "features": ["文本", "图片", "小程序卡片", "订阅消息"],
        },
        "phone_hotline": {
            "protocol": "SIP/VoIP",
            "auth": "来电号码 + 会员验证",
            "features": ["语音 -> ASR -> 文本", "TTS 播报", "按键导航"],
        },
    }

    # 意图分类体系(三级)
    INTENT_CLASSIFICATION = {
        "order": {
            "name": "订单相关",
            "sub_intents": {
                "query_status": "查询订单状态",
                "cancel_order": "取消订单",
                "modify_address": "修改收货地址",
                "confirm_receipt": "确认收货",
                "track_logistics": "物流查询",
            },
        },
        "after_sale": {
            "name": "售后服务",
            "sub_intents": {
                "return_request": "申请退货",
                "exchange_request": "申请换货",
                "refund_inquiry": "退款进度查询",
                "complaint": "投诉",
                "repair": "维修申请",
            },
        },
        "product": {
            "name": "商品咨询",
            "sub_intents": {
                "spec_inquiry": "规格参数咨询",
                "stock_inquiry": "库存查询",
                "price_inquiry": "价格咨询",
                "recommendation": "商品推荐",
                "comparison": "商品对比",
            },
        },
        "account": {
            "name": "账户问题",
            "sub_intents": {
                "login_issue": "登录问题",
                "password_reset": "密码重置",
                "binding": "账号绑定",
                "security": "安全问题",
            },
        },
        "promotion": {
            "name": "营销活动",
            "sub_intents": {
                "coupon": "优惠券相关",
                "points": "积分查询/兑换",
                "flash_sale": "秒杀活动",
                "group_buy": "拼团活动",
            },
        },
        "general": {
            "name": "通用咨询",
            "sub_intents": {
                "greeting": "问候/寒暄",
                "thanks": "感谢/表扬",
                "feedback": "意见建议",
                "human": "要求转人工",
            },
        },
    }

    # 自动解决能力要求
    AUTO_RESOLUTION = {
        "faq_match": {
            "description": "FAQ 精准匹配",
            "target_rate": 0.35,
            "response_type": "直接回复答案",
        },
        "knowledge_graph": {
            "description": "知识图谱推理问答",
            "target_rate": 0.20,
            "response_type": "多跳推理后回复",
        },
        "api_call": {
            "description": "调用业务 API 查询",
            "target_rate": 0.25,
            "response_type": "查询后回复(如物流、订单状态)",
        },
        "multi_turn": {
            "description": "多轮对话完成任务",
            "target_rate": 0.20,
            "response_type": "引导式交互完成(如退货申请)",
        },
    }

    # 非功能需求
    NON_FUNCTIONAL = {
        "response_time": {
            "simple_query": "< 1 秒",
            "api_query": "< 3 秒",
            "complex_reasoning": "< 8 秒",
        },
        "concurrency": "支持 5000 并发会话",
        "availability": "99.95%(月宕机 < 22 分钟)",
        "sentiment_detection": "负面情绪识别准确率 > 90%",
        "escalation": "自动识别需人工介入的场景,转接准确率 > 95%",
        "compliance": "对话记录保存 3 年,敏感信息脱敏展示",
    }

三、架构设计

智能客服 Agent 架构:

┌──────────────────────────────────────────────────────────────────┐
│                          接入层                                    │
│  Web Chat  │  App Chat  │  微信公众号  │  小程序  │  电话热线     │
│  (WS)      │  (MQTT)    │  (HTTP)      │  (WS)    │  (SIP/ASR)   │
└──────────────────────────────┬───────────────────────────────────┘
                               │
                               ▼
┌──────────────────────────────────────────────────────────────────┐
│                      会话管理层                                    │
│  ┌──────────────┐  ┌──────────────┐  ┌──────────────────────┐   │
│  │ 渠道适配器    │  │ 会话路由     │  │ 上下文管理           │   │
│  │ (协议转换)    │  │ (渠道->统一) │  │ (历史/状态/实体)     │   │
│  └──────────────┘  └──────────────┘  └──────────────────────┘   │
└──────────────────────────────┬───────────────────────────────────┘
                               │
                               ▼
┌──────────────────────────────────────────────────────────────────┐
│                      理解层                                        │
│  ┌──────────────┐  ┌──────────────┐  ┌──────────────┐           │
│  │ 意图识别      │  │ 实体抽取     │  │ 情绪检测     │           │
│  │ (BERT分类)   │  │ (NER/BIO)    │  │ (情感分析)   │           │
│  └──────────────┘  └──────────────┘  └──────────────┘           │
└──────────────────────────────┬───────────────────────────────────┘
                               │
                               ▼
┌──────────────────────────────────────────────────────────────────┐
│                      决策层                                        │
│                                                                   │
│  ┌──────────────────────────────────────────────────────────┐    │
│  │                   对话管理器 (Dialog Manager)              │    │
│  │   ┌──────────┐  ┌──────────┐  ┌──────────┐  ┌────────┐ │    │
│  │   │ FAQ 匹配 │  │ 知识图谱 │  │ 任务型   │  │ 转人工 │ │    │
│  │   │ (向量检索)│  │ (推理)   │  │ (Slot填充)│  │ (条件) │ │    │
│  │   └──────────┘  └──────────┘  └──────────┘  └────────┘ │    │
│  └──────────────────────────────────────────────────────────┘    │
│                                                                   │
│  ┌──────────────────────────────────────────────────────────┐    │
│  │                策略引擎 (Policy Engine)                    │    │
│  │  自动回复 / 反问澄清 / 多轮引导 / 转人工 / 等待 / 结束    │    │
│  └──────────────────────────────────────────────────────────┘    │
└──────────────────────────────┬───────────────────────────────────┘
                               │
                               ▼
┌──────────────────────────────────────────────────────────────────┐
│                      执行层                                        │
│  ┌──────────────┐  ┌──────────────┐  ┌──────────────┐           │
│  │ 答案生成      │  │ API 网关     │  │ 模板渲染     │           │
│  │ (LLM/模板)   │  │ (订单/物流)  │  │ (卡片/按钮)  │           │
│  └──────────────┘  └──────────────┘  └──────────────┘           │
└──────────────────────────────┬───────────────────────────────────┘
                               │
                               ▼
┌──────────────────────────────────────────────────────────────────┐
│                      坐席辅助层                                    │
│  ┌──────────────┐  ┌──────────────┐  ┌──────────────┐           │
│  │ 实时建议      │  │ 快捷回复     │  │ 知识弹窗     │           │
│  │ (下一步操作)  │  │ (一键发送)   │  │ (关联知识)   │           │
│  └──────────────┘  └──────────────┘  └──────────────┘           │
└──────────────────────────────────────────────────────────────────┘

四、核心代码实现

4.1 多渠道接入适配器
# channels/channel_adapter.py

import asyncio
import json
from abc import ABC, abstractmethod
from typing import Dict, List, Optional, Callable
from dataclasses import dataclass, field
from enum import Enum
import time


class MessageType(Enum):
    TEXT = "text"
    IMAGE = "image"
    VOICE = "voice"
    PRODUCT_CARD = "product_card"
    ORDER_LINK = "order_link"
    EVENT = "event"  # 菜单点击、模板消息回调等


class ChannelType(Enum):
    WEB_CHAT = "web_chat"
    APP_CHAT = "app_chat"
    WECHAT_OFFICIAL = "wechat_official"
    WECHAT_MINI = "wechat_mini"
    PHONE_HOTLINE = "phone_hotline"


@dataclass
class UnifiedMessage:
    """统一消息格式"""
    msg_id: str
    channel: ChannelType
    channel_user_id: str
    platform_user_id: str       # 统一用户 ID(跨渠道识别)
    session_id: str
    type: MessageType
    content: str                 # 文本内容(语音转文字后的结果)
    raw_content: Dict            # 原始消息内容
    timestamp: float
    extra: Dict = field(default_factory=dict)

    @property
    def age_seconds(self) -> float:
        return time.time() - self.timestamp


@dataclass
class UnifiedResponse:
    """统一回复格式"""
    text: str = ""
    cards: List[Dict] = field(default_factory=list)  # 富媒体卡片
    quick_replies: List[str] = field(default_factory=list)  # 快捷回复选项
    actions: List[Dict] = field(default_factory=list)  # 按钮动作
    transfer_to_agent: bool = False
    end_conversation: bool = False
    wait_for_input: bool = True


class BaseChannelAdapter(ABC):
    """渠道适配器基类"""

    def __init__(self, channel: ChannelType, 
                 message_handler: Callable[[UnifiedMessage], None]):
        self.channel = channel
        self.message_handler = message_handler

    @abstractmethod
    async def send_message(self, user_id: str, 
                            response: UnifiedResponse) -> bool:
        """发送消息到用户"""
        pass

    @abstractmethod
    async def start(self):
        """启动渠道监听"""
        pass

    @abstractmethod
    async def stop(self):
        """停止渠道监听"""
        pass

    def _to_unified(self, raw_msg: Dict) -> UnifiedMessage:
        """子类实现:将原始消息转为统一格式"""
        raise NotImplementedError


class WebChatAdapter(BaseChannelAdapter):
    """Web 在线客服适配器"""

    def __init__(self, message_handler):
        super().__init__(ChannelType.WEB_CHAT, message_handler)
        self.connections: Dict[str, asyncio.Queue] = {}
        self.server = None

    async def start(self):
        """启动 WebSocket 服务器"""
        import websockets
        
        async def handler(websocket, path):
            user_id = path.split("/")[-1]  # /ws/{user_id}
            self.connections[user_id] = asyncio.Queue()
            
            try:
                async for raw_msg in websocket:
                    data = json.loads(raw_msg)
                    unified = self._to_unified(data)
                    unified.channel_user_id = user_id
                    await self.message_handler(unified)
                    
                    # 等待回复
                    response = await self.connections[user_id].get()
                    await websocket.send(json.dumps(self._from_unified(response)))
            finally:
                self.connections.pop(user_id, None)
        
        self.server = await websockets.serve(handler, "0.0.0.0", 8765)

    async def send_message(self, user_id: str, 
                            response: UnifiedResponse) -> bool:
        if user_id in self.connections:
            await self.connections[user_id].put(response)
            return True
        return False

    def _to_unified(self, raw: Dict) -> UnifiedMessage:
        return UnifiedMessage(
            msg_id=raw.get("msg_id", ""),
            channel=self.channel,
            channel_user_id="",
            platform_user_id=raw.get("user_id", ""),
            session_id=raw.get("session_id", ""),
            type=MessageType(raw.get("type", "text")),
            content=raw.get("content", ""),
            raw_content=raw,
            timestamp=time.time(),
        )

    def _from_unified(self, resp: UnifiedResponse) -> Dict:
        result = {"type": "text", "content": resp.text}
        if resp.cards:
            result["cards"] = resp.cards
        if resp.quick_replies:
            result["quick_replies"] = resp.quick_replies
        if resp.transfer_to_agent:
            result["transfer_to_agent"] = True
        return result

    async def stop(self):
        if self.server:
            self.server.close()


class WeChatOfficialAdapter(BaseChannelAdapter):
    """微信公众号适配器"""

    def __init__(self, message_handler, app_id: str, app_secret: str):
        super().__init__(ChannelType.WECHAT_OFFICIAL, message_handler)
        self.app_id = app_id
        self.app_secret = app_secret
        self.access_token = None
        self.token_expires_at = 0

    async def start(self):
        """启动 HTTP 回调服务器"""
        from aiohttp import web
        
        app = web.Application()
        app.router.add_post("/wechat/callback", self.handle_callback)
        app.router.add_get("/wechat/callback", self.handle_verify)
        
        runner = web.AppRunner(app)
        await runner.setup()
        site = web.TCPSite(runner, "0.0.0.0", 8080)
        await site.start()

    async def handle_verify(self, request):
        """微信服务器验证"""
        query = request.query
        # 验证 signature
        return web.Response(text=query.get("echostr", ""))

    async def handle_callback(self, request):
        """处理微信消息回调"""
        import xml.etree.ElementTree as ET
        
        body = await request.text()
        root = ET.fromstring(body)
        
        msg_type = root.find("MsgType").text
        from_user = root.find("FromUserName").text
        
        if msg_type == "text":
            content = root.find("Content").text
            unified = UnifiedMessage(
                msg_id=root.find("MsgId").text,
                channel=self.channel,
                channel_user_id=from_user,
                platform_user_id=from_user,
                session_id=from_user,
                type=MessageType.TEXT,
                content=content,
                raw_content={"xml": body},
                timestamp=float(root.find("CreateTime").text),
            )
            await self.message_handler(unified)
        
        return web.Response(text="success")

    async def send_message(self, user_id: str,
                            response: UnifiedResponse) -> bool:
        """通过客服接口发送消息"""
        token = await self._get_access_token()
        
        import aiohttp
        url = f"https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token={token}"
        
        payload = {
            "touser": user_id,
            "msgtype": "text",
            "text": {"content": response.text},
        }
        
        async with aiohttp.ClientSession() as session:
            async with session.post(url, json=payload) as resp:
                result = await resp.json()
                return result.get("errcode") == 0

    async def _get_access_token(self) -> str:
        """获取 access_token(带缓存)"""
        if self.access_token and time.time() < self.token_expires_at:
            return self.access_token
        
        import aiohttp
        url = (
            f"https://api.weixin.qq.com/cgi-bin/token"
            f"?grant_type=client_credential"
            f"&appid={self.app_id}&secret={self.app_secret}"
        )
        
        async with aiohttp.ClientSession() as session:
            async with session.get(url) as resp:
                data = await resp.json()
                self.access_token = data["access_token"]
                self.token_expires_at = time.time() + data["expires_in"] - 60
                return self.access_token

    async def stop(self):
        pass


class PhoneHotlineAdapter(BaseChannelAdapter):
    """电话热线适配器(ASR + TTS)"""

    def __init__(self, message_handler):
        super().__init__(ChannelType.PHONE_HOTLINE, message_handler)
        self.active_calls: Dict[str, Dict] = {}

    async def start(self):
        """启动 SIP 服务器监听(简化版)"""
        # 实际项目中会对接 FreeSWITCH / Asterisk
        pass

    async def handle_voice_input(self, call_id: str, 
                                   transcribed_text: str):
        """处理 ASR 转写的文本"""
        unified = UnifiedMessage(
            msg_id=f"call_{call_id}_{time.time()}",
            channel=self.channel,
            channel_user_id=call_id,
            platform_user_id=call_id,
            session_id=call_id,
            type=MessageType.TEXT,
            content=transcribed_text,
            raw_content={"call_id": call_id, "transcript": transcribed_text},
            timestamp=time.time(),
        )
        await self.message_handler(unified)

    async def send_message(self, user_id: str,
                            response: UnifiedResponse) -> bool:
        """TTS 播报回复"""
        if user_id in self.active_calls:
            # 调用 TTS 服务将 text 转为语音播放
            # tts_url = await self.tts_service.synthesize(response.text)
            # await self.play_audio(user_id, tts_url)
            return True
        return False

    async def stop(self):
        pass
4.2 意图识别与实体抽取
# nlu/intent_classifier.py

import re
import json
from typing import Dict, List, Optional, Tuple
from dataclasses import dataclass


@dataclass
class IntentResult:
    """意图识别结果"""
    intent: str                    # order.query_status
    category: str                  # order
    sub_intent: str                # query_status
    confidence: float
    entities: Dict[str, str]       # {"order_id": "123456"}
    utterance: str                 # 原始用户输入


class IntentClassifier:
    """
    意图识别器
    
    分层策略:
    1. 正则规则快速匹配(高频、确定性问题)
    2. 关键词 + 模板匹配
    3. LLM 深度理解(复杂、模糊问题)
    """

    # 高频正则规则
    REGEX_RULES = {
        "order.query_status": [
            r"订单.*?(状态|到哪|进度|怎么样了|在哪里)",
            r"(查|看|问).*?订单",
            r"我的订单.*?(怎么|如何|哪里)",
        ],
        "order.track_logistics": [
            r"(快递|物流|包裹|发货).*?(到哪|状态|跟踪|查询|到哪里了)",
            r"物流信息",
            r"什么时候.*?(到|收到|送达)",
        ],
        "order.cancel_order": [
            r"取消.*?订单",
            r"不想要了",
            r"退单",
        ],
        "after_sale.return_request": [
            r"(退货|退回去|退回).*?(怎么|如何|申请|流程)",
            r"我要退货",
            r"退货退款",
        ],
        "after_sale.refund_inquiry": [
            r"(退款|退钱).*?(进度|到哪|多久|什么时候|状态)",
            r"退款还没到",
            r"钱什么时候退",
        ],
        "account.login_issue": [
            r"(登录|登陆).*?(不上|不了|失败|错误|问题)",
            r"登不上去",
            r"忘记密码",
        ],
        "promotion.coupon": [
            r"(优惠券|券|红包).*?(怎么用|领取|在哪|过期|规则)",
            r"领优惠券",
            r"优惠券.*?(没用|失效)",
        ],
        "general.human": [
            r"(转人工|人工客服|真人|活人|客服人员)",
            r"我要投诉",
            r"找你们经理",
        ],
    }

    # 关键词权重
    KEYWORD_WEIGHTS = {
        "order": {
            "订单": 0.8, "下单": 0.7, "购买": 0.6, "付款": 0.6,
            "发货": 0.7, "物流": 0.8, "快递": 0.7, "签收": 0.6,
        },
        "after_sale": {
            "退货": 0.9, "换货": 0.9, "退款": 0.8, "维修": 0.8,
            "投诉": 0.7, "赔偿": 0.6, "售后": 0.7,
        },
        "product": {
            "多少钱": 0.8, "价格": 0.7, "尺寸": 0.6, "颜色": 0.6,
            "推荐": 0.5, "怎么样": 0.5, "好用吗": 0.5,
        },
        "account": {
            "密码": 0.8, "账号": 0.7, "登录": 0.7, "注册": 0.6,
            "绑定": 0.6, "解绑": 0.6, "安全": 0.5,
        },
        "promotion": {
            "优惠券": 0.9, "满减": 0.8, "折扣": 0.7, "秒杀": 0.8,
            "拼团": 0.7, "积分": 0.6, "活动": 0.5,
        },
    }

    def __init__(self, llm_client=None):
        self.llm = llm_client
        self.entity_patterns = self._build_entity_patterns()

    def _build_entity_patterns(self) -> Dict[str, str]:
        """构建实体抽取正则"""
        return {
            "order_id": r"[A-Za-z0-9]{10,20}",
            "phone": r"1[3-9]\d{9}",
            "amount": r"\d+(?:\.\d{1,2})?",
            "sku_id": r"\d{6,12}",
            "express_no": r"[A-Za-z0-9]{8,20}",
        }

    async def classify(self, utterance: str, 
                        context: Dict = None) -> IntentResult:
        """意图识别主入口"""
        
        # Step 1: 正则快速匹配
        regex_result = self._match_regex(utterance)
        if regex_result and regex_result.confidence > 0.9:
            return regex_result
        
        # Step 2: 关键词加权匹配
        keyword_result = self._match_keywords(utterance)
        
        # Step 3: 实体抽取
        entities = self._extract_entities(utterance)
        
        # Step 4: 如果置信度不够,走 LLM
        if (not keyword_result or keyword_result.confidence < 0.6) and self.llm:
            llm_result = await self._llm_classify(utterance, context)
            if llm_result.confidence > keyword_result.confidence:
                llm_result.entities.update(entities)
                return llm_result
        
        if keyword_result:
            keyword_result.entities.update(entities)
            return keyword_result
        
        # 兜底:返回未知意图
        return IntentResult(
            intent="general.unknown",
            category="general",
            sub_intent="unknown",
            confidence=0.0,
            entities=entities,
            utterance=utterance,
        )

    def _match_regex(self, utterance: str) -> Optional[IntentResult]:
        """正则规则匹配"""
        
        for intent, patterns in self.REGEX_RULES.items():
            for pattern in patterns:
                match = re.search(pattern, utterance)
                if match:
                    category, sub_intent = intent.split(".", 1)
                    return IntentResult(
                        intent=intent,
                        category=category,
                        sub_intent=sub_intent,
                        confidence=0.95,
                        entities={},
                        utterance=utterance,
                    )
        return None

    def _match_keywords(self, utterance: str) -> Optional[IntentResult]:
        """关键词加权匹配"""
        
        category_scores = {}
        
        for category, keywords in self.KEYWORD_WEIGHTS.items():
            score = 0.0
            for keyword, weight in keywords.items():
                if keyword in utterance:
                    score += weight
            if score > 0:
                category_scores[category] = score
        
        if not category_scores:
            return None
        
        # 取最高分的类别
        best_category = max(category_scores, key=category_scores.get)
        best_score = category_scores[best_category]
        
        # 归一化置信度
        confidence = min(best_score / 2.0, 0.85)
        
        # 二级意图用 LLM 或者简单规则
        sub_intent = self._infer_sub_intent(utterance, best_category)
        
        return IntentResult(
            intent=f"{best_category}.{sub_intent}",
            category=best_category,
            sub_intent=sub_intent,
            confidence=confidence,
            entities={},
            utterance=utterance,
        )

    def _infer_sub_intent(self, utterance: str, 
                            category: str) -> str:
        """推断二级意图(基于关键词)"""
        
        sub_keywords = {
            "order": {
                "query_status": ["状态", "到哪", "进度", "查询", "查看"],
                "track_logistics": ["物流", "快递", "发货"],
                "cancel_order": ["取消", "退单"],
                "modify_address": ["地址", "改地址", "换地址"],
                "confirm_receipt": ["确认收货", "签收"],
            },
            "after_sale": {
                "return_request": ["退货", "退回去"],
                "exchange_request": ["换货", "换一个"],
                "refund_inquiry": ["退款", "退钱"],
                "complaint": ["投诉", "举报"],
                "repair": ["维修", "修"],
            },
        }
        
        sub_map = sub_keywords.get(category, {})
        for sub_intent, keywords in sub_map.items():
            for kw in keywords:
                if kw in utterance:
                    return sub_intent
        
        return "general"

    def _extract_entities(self, utterance: str) -> Dict[str, str]:
        """实体抽取"""
        
        entities = {}
        
        for entity_name, pattern in self.entity_patterns.items():
            match = re.search(pattern, utterance)
            if match:
                entities[entity_name] = match.group()
        
        return entities

    async def _llm_classify(self, utterance: str,
                              context: Dict = None) -> IntentResult:
        """LLM 意图识别"""
        
        context_str = ""
        if context and "last_intent" in context:
            context_str = f"上一轮意图: {context['last_intent']}"
        
        prompt = f"""你是一个电商客服的意图识别系统。请识别用户输入的意图。

{context_str}

可选意图列表(格式:类别.子意图):
- order.query_status: 查询订单状态
- order.track_logistics: 物流查询
- order.cancel_order: 取消订单
- order.modify_address: 修改地址
- after_sale.return_request: 申请退货
- after_sale.exchange_request: 申请换货
- after_sale.refund_inquiry: 退款进度
- after_sale.complaint: 投诉
- product.spec_inquiry: 商品规格咨询
- product.price_inquiry: 价格咨询
- account.login_issue: 登录问题
- account.password_reset: 密码重置
- promotion.coupon: 优惠券相关
- general.human: 要求转人工
- general.unknown: 无法识别

用户输入:{utterance}

输出 JSON 格式:{{"intent": "类别.子意图", "confidence": 0.95, "entities": {{}}}}
只输出 JSON。"""
        
        try:
            response = await self.llm.chat(prompt, temperature=0.1, max_tokens=200)
            response = response.strip().replace("```json", "").replace("```", "").strip()
            result = json.loads(response)
            
            intent = result.get("intent", "general.unknown")
            confidence = result.get("confidence", 0.0)
            entities = result.get("entities", {})
            
            parts = intent.split(".", 1)
            category = parts[0] if len(parts) > 0 else "general"
            sub_intent = parts[1] if len(parts) > 1 else "unknown"
            
            return IntentResult(
                intent=intent,
                category=category,
                sub_intent=sub_intent,
                confidence=confidence,
                entities=entities,
                utterance=utterance,
            )
        except Exception as e:
            print(f"LLM classification failed: {e}")
            return IntentResult(
                intent="general.unknown",
                category="general",
                sub_intent="unknown",
                confidence=0.0,
                entities={},
                utterance=utterance,
            )
4.3 对话管理器
# dialog/dialog_manager.py

import json
import time
from typing import Dict, List, Optional, Any
from dataclasses import dataclass, field
from collections import deque


@dataclass
class DialogState:
    """对话状态"""
    session_id: str
    user_id: str
    channel: str
    current_intent: str = ""
    current_step: str = "initial"      # initial / collecting / confirming / completed
    slots: Dict[str, Any] = field(default_factory=dict)
    missing_slots: List[str] = field(default_factory=list)
    history: List[Dict] = field(default_factory=lambda: deque(maxlen=20))
    last_activity: float = 0.0
    turn_count: int = 0
    sentiment: str = "neutral"          # positive / neutral / negative / angry
    escalation_reason: str = ""


class TaskTemplate:
    """任务型对话模板"""
    
    def __init__(self, name: str, required_slots: List[Dict],
                 api_call: str = None, confirmation_required: bool = True):
        self.name = name
        self.required_slots = required_slots  # [{"name": "order_id", "question": "请问您的订单号是多少?"}, ...]
        self.api_call = api_call
        self.confirmation_required = confirmation_required


class DialogManager:
    """
    对话管理器
    
    管理多轮对话的状态流转、槽位填充、策略选择
    """

    # 预定义任务模板
    TASK_TEMPLATES = {
        "order.query_status": TaskTemplate(
            name="查询订单状态",
            required_slots=[
                {"name": "order_id", "question": "请问您的订单号是多少?"},
            ],
            api_call="query_order_status",
            confirmation_required=False,
        ),
        "order.track_logistics": TaskTemplate(
            name="查询物流",
            required_slots=[
                {"name": "order_id", "question": "请问您的订单号是多少?"},
            ],
            api_call="track_logistics",
            confirmation_required=False,
        ),
        "order.cancel_order": TaskTemplate(
            name="取消订单",
            required_slots=[
                {"name": "order_id", "question": "请问您想取消哪个订单?请提供订单号。"},
                {"name": "reason", "question": "请问取消的原因是?"},
            ],
            api_call="cancel_order",
            confirmation_required=True,
        ),
        "after_sale.return_request": TaskTemplate(
            name="申请退货",
            required_slots=[
                {"name": "order_id", "question": "请问您的订单号是多少?"},
                {"name": "sku_id", "question": "请问您要退哪个商品?(提供商品编号或名称)"},
                {"name": "reason", "question": "请问退货的原因是什么?"},
                {"name": "quantity", "question": "请问要退几件?"},
            ],
            api_call="create_return",
            confirmation_required=True,
        ),
        "after_sale.refund_inquiry": TaskTemplate(
            name="查询退款进度",
            required_slots=[
                {"name": "order_id", "question": "请问您的订单号是多少?"},
            ],
            api_call="query_refund",
            confirmation_required=False,
        ),
    }

    def __init__(self, llm_client=None, api_gateway=None):
        self.llm = llm_client
        self.api_gateway = api_gateway
        self.sessions: Dict[str, DialogState] = {}

    def get_or_create_session(self, session_id: str, 
                                user_id: str, channel: str) -> DialogState:
        """获取或创建会话"""
        if session_id not in self.sessions:
            self.sessions[session_id] = DialogState(
                session_id=session_id,
                user_id=user_id,
                channel=channel,
            )
        return self.sessions[session_id]

    async def process(self, session: DialogState,
                       intent: IntentResult,
                       utterance: str) -> Dict:
        """处理用户输入,决定下一步动作"""
        
        session.last_activity = time.time()
        session.turn_count += 1
        
        # 记录历史
        session.history.append({
            "role": "user",
            "text": utterance,
            "intent": intent.intent,
            "timestamp": time.time(),
        })
        
        # 如果是转人工,直接处理
        if intent.intent == "general.human":
            return self._escalate_to_human(session, "用户主动要求转人工")
        
        # 检查是否需要开启新的任务
        if not session.current_intent or session.current_step == "completed":
            # 新任务开始
            template = self.TASK_TEMPLATES.get(intent.intent)
            if template:
                session.current_intent = intent.intent
                session.current_step = "collecting"
                session.slots = {}
                session.missing_slots = [s["name"] for s in template.required_slots]
                
                # 尝试从当前输入中提取槽位
                self._fill_slots_from_utterance(session, utterance, template)
                
                if not session.missing_slots:
                    # 所有槽位已齐,进入确认或执行
                    return await self._execute_task(session, template)
                else:
                    # 询问第一个缺失的槽位
                    first_missing = next(
                        s for s in template.required_slots 
                        if s["name"] == session.missing_slots[0]
                    )
                    return {
                        "action": "ask_slot",
                        "slot_name": first_missing["name"],
                        "text": first_missing["question"],
                        "wait_for_input": True,
                    }
            else:
                # 没有匹配的任务模板,走 FAQ 或 LLM 闲聊
                return await self._fallback_response(session, utterance)
        
        # 已有进行中的任务
        elif session.current_step == "collecting":
            template = self.TASK_TEMPLATES.get(session.current_intent)
            if template:
                # 尝试从本次输入中提取缺失的槽位
                self._fill_slots_from_utterance(session, utterance, template)
                
                if not session.missing_slots:
                    # 所有槽位已齐
                    if template.confirmation_required:
                        session.current_step = "confirming"
                        return self._build_confirmation(session, template)
                    else:
                        return await self._execute_task(session, template)
                else:
                    # 继续询问下一个缺失槽位
                    next_missing = next(
                        s for s in template.required_slots 
                        if s["name"] == session.missing_slots[0]
                    )
                    return {
                        "action": "ask_slot",
                        "slot_name": next_missing["name"],
                        "text": next_missing["question"],
                        "wait_for_input": True,
                    }
        
        elif session.current_step == "confirming":
            # 处理用户的确认/否认
            if self._is_confirmation(utterance):
                template = self.TASK_TEMPLATES.get(session.current_intent)
                return await self._execute_task(session, template)
            elif self._is_denial(utterance):
                # 用户否认,回到收集状态
                session.current_step = "collecting"
                return {
                    "action": "restart_collecting",
                    "text": "好的,请您重新告诉我需要的信息。",
                    "wait_for_input": True,
                }
            else:
                # 可能是修改某个槽位
                modified = await self._handle_modification(session, utterance, template)
                if modified:
                    return self._build_confirmation(session, template)
                else:
                    return {
                        "action": "reconfirm",
                        "text": "请确认以上信息是否正确?回复「确认」或「修改xxx为yyy」。",
                        "wait_for_input": True,
                    }
        
        return {
            "action": "fallback",
            "text": "抱歉,我没有理解您的意思,请换个方式描述您的问题。",
            "wait_for_input": True,
        }

    def _fill_slots_from_utterance(self, session: DialogState,
                                     utterance: str,
                                     template: TaskTemplate):
        """从用户输入中提取槽位"""
        
        # 遍历所有缺失槽位,尝试从输入中提取
        still_missing = []
        for slot_def in template.required_slots:
            slot_name = slot_def["name"]
            if slot_name not in session.missing_slots:
                continue
            
            value = self._extract_slot_value(utterance, slot_name)
            if value:
                session.slots[slot_name] = value
                session.missing_slots.remove(slot_name)
            else:
                still_missing.append(slot_name)
        
        session.missing_slots = still_missing

    def _extract_slot_value(self, utterance: str, slot_name: str) -> Optional[str]:
        """从文本中提取特定槽位的值"""
        
        extractors = {
            "order_id": lambda u: re.search(r"[A-Za-z0-9]{10,20}", u),
            "phone": lambda u: re.search(r"1[3-9]\d{9}", u),
            "sku_id": lambda u: re.search(r"\d{6,12}", u),
            "quantity": lambda u: re.search(r"(\d+)\s*(件|个|台|双)", u),
            "reason": lambda u: u if len(u) > 2 else None,
        }
        
        extractor = extractors.get(slot_name)
        if extractor:
            match = extractor(utterance)
            if match:
                if isinstance(match, re.Match):
                    return match.group()
                return match
        
        return None

    async def _execute_task(self, session: DialogState,
                              template: TaskTemplate) -> Dict:
        """执行任务(调用 API 或查询)"""
        
        session.current_step = "executing"
        
        if template.api_call and self.api_gateway:
            try:
                result = await self.api_gateway.call(
                    template.api_call,
                    session.slots
                )
                
                session.current_step = "completed"
                session.history.append({
                    "role": "system",
                    "text": json.dumps(result, ensure_ascii=False),
                    "timestamp": time.time(),
                })
                
                return {
                    "action": "show_result",
                    "text": self._format_api_result(template.api_call, result),
                    "data": result,
                    "wait_for_input": True,
                    "end_conversation": False,
                }
            except Exception as e:
                return {
                    "action": "error",
                    "text": f"查询时遇到问题:{str(e)},请稍后再试或联系人工客服。",
                    "wait_for_input": True,
                }
        
        return {
            "action": "completed",
            "text": "已为您处理完成,还有其他问题吗?",
            "wait_for_input": True,
        }

    def _build_confirmation(self, session: DialogState,
                              template: TaskTemplate) -> Dict:
        """构建确认信息"""
        
        slot_descriptions = []
        for slot_def in template.required_slots:
            name = slot_def["name"]
            value = session.slots.get(name, "")
            slot_descriptions.append(f"{name}: {value}")
        
        return {
            "action": "confirm",
            "text": f"请确认以下信息:\n" + "\n".join(slot_descriptions) + "\n\n回复「确认」或「修改xxx为yyy」。",
            "slots": session.slots,
            "wait_for_input": True,
        }

    def _is_confirmation(self, utterance: str) -> bool:
        """判断是否为确认"""
        confirm_words = ["确认", "是的", "对", "没错", "可以", "好", "嗯", "ok", "yes", "确定"]
        return any(w in utterance.lower() for w in confirm_words)

    def _is_denial(self, utterance: str) -> bool:
        """判断是否为否认"""
        deny_words = ["不对", "不是", "错了", "不对", "不是这个", "重来", "重新", "no"]
        return any(w in utterance.lower() for w in deny_words)

async def _handle_modification(self, session: DialogState,
                                     utterance: str,
                                     template: TaskTemplate) -> bool:
        """处理用户对槽位的修改"""
        
        # 匹配「修改xxx为yyy」或「xxx改成yyy」
        pattern = r"(?:修改|改成|改为|更正)\s*(\S+)\s*(?:为|成|是)\s*(\S+)"
        match = re.search(pattern, utterance)
        if match:
            slot_name = match.group(1)
            new_value = match.group(2)
            if slot_name in [s["name"] for s in template.required_slots]:
                session.slots[slot_name] = new_value
                return True
        
        # 也支持直接给出新值(如用户说「订单号是 123456」)
        for slot_def in template.required_slots:
            name = slot_def["name"]
            value = self._extract_slot_value(utterance, name)
            if value and value != session.slots.get(name):
                session.slots[name] = value
                return True
        
        return False

    def _format_api_result(self, api_name: str, result: Dict) -> str:
        """格式化 API 返回结果"""
        
        if api_name == "query_order_status":
            status_map = {
                "pending": "待付款",
                "paid": "已付款",
                "shipped": "已发货",
                "delivered": "已签收",
                "cancelled": "已取消",
                "refunding": "退款中",
                "refunded": "已退款",
            }
            status = result.get("status", "unknown")
            return (
                f"您的订单 {result.get('order_id', '')} 当前状态为:{status_map.get(status, status)}\n"
                f"下单时间:{result.get('created_at', '')}\n"
                f"预计送达:{result.get('estimated_delivery', '暂无')}"
            )
        
        elif api_name == "track_logistics":
            tracking = result.get("tracking", [])
            if not tracking:
                return "暂无物流信息,请稍后再查。"
            
            lines = [f"物流公司:{result.get('company', '')}"]
            lines.append(f"运单号:{result.get('express_no', '')}")
            lines.append("--- 物流轨迹 ---")
            for t in tracking[:5]:  # 最多显示5条
                lines.append(f"{t.get('time', '')} {t.get('location', '')} - {t.get('status', '')}")
            return "\n".join(lines)
        
        elif api_name == "create_return":
            return (
                f"退货申请已提交!\n"
                f"退货单号:{result.get('return_id', '')}\n"
                f"请将商品寄回至:{result.get('return_address', '')}\n"
                f"退款将在收到商品后 3-5 个工作日内原路返还。"
            )
        
        elif api_name == "query_refund":
            progress = result.get("progress", 0)
            bar = "█" * (progress // 10) + "░" * (10 - progress // 10)
            return (
                f"退款进度:{progress}%\n{bar}\n"
                f"当前状态:{result.get('status_desc', '处理中')}\n"
                f"预计到账:{result.get('estimated_time', '请耐心等待')}"
            )
        
        return json.dumps(result, ensure_ascii=False, indent=2)

    async def _fallback_response(self, session: DialogState,
                                   utterance: str) -> Dict:
        """兜底回复(FAQ 匹配或 LLM 闲聊)"""
        
        # 先尝试 FAQ 匹配
        faq_answer = self._match_faq(utterance)
        if faq_answer:
            return {
                "action": "faq_reply",
                "text": faq_answer,
                "wait_for_input": True,
            }
        
        # 再尝试 LLM 生成
        if self.llm:
            llm_reply = await self._llm_chat(session, utterance)
            return {
                "action": "llm_reply",
                "text": llm_reply,
                "wait_for_input": True,
            }
        
        return {
            "action": "cannot_understand",
            "text": "抱歉,我暂时无法回答这个问题。您可以尝试换个说法,或者输入「转人工」联系我们的客服人员。",
            "wait_for_input": True,
        }

    def _match_faq(self, utterance: str) -> Optional[str]:
        """FAQ 匹配(简化版:关键词匹配)"""
        
        faq_db = {
            "退货流程": "退货流程如下:1. 在我的订单中选择要退货的商品;2. 填写退货原因并提交申请;3. 审核通过后将商品寄回;4. 我们收到商品后 3-5 个工作日退款。",
            "退款时间": "退款一般在以下时间内到账:支付宝/微信支付 1-3 个工作日,银行卡 3-7 个工作日,具体以银行处理时间为准。",
            "运费": "因质量问题退货,运费由我们承担;因个人原因退货,运费由您承担(如有运费险可报销)。",
            "优惠券": "优惠券可在结算页面选择使用,每笔订单限用一张。有效期请在「我的优惠券」中查看。",
        }
        
        for keyword, answer in faq_db.items():
            if keyword in utterance:
                return answer
        
        return None

    async def _llm_chat(self, session: DialogState,
                          utterance: str) -> str:
        """LLM 闲聊回复"""
        
        # 构建上下文
        history_text = ""
        for msg in list(session.history)[-6:-1]:  # 最近几轮
            role = "用户" if msg["role"] == "user" else "客服"
            history_text += f"{role}:{msg['text']}\n"
        
        prompt = f"""你是一个电商平台的智能客服助手,名叫「小帮」。

你的特点:
1. 专业、热情、有耐心
2. 回答简洁明了,不超过 100 字
3. 对于不确定的问题,引导用户转人工
4. 不编造不存在的政策或信息

对话历史:
{history_text}

用户:{utterance}

请给出回复:"""
        
        try:
            response = await self.llm.chat(prompt, temperature=0.7, max_tokens=300)
            return response.strip()
        except Exception:
            return "您好,我是小帮,很高兴为您服务!请问有什么可以帮助您的?"

    def _escalate_to_human(self, session: DialogState,
                             reason: str) -> Dict:
        """转人工处理"""
        
        session.current_step = "escalated"
        session.escalation_reason = reason
        
        return {
            "action": "transfer_to_agent",
            "text": "好的,正在为您转接人工客服,请稍候...",
            "transfer_to_agent": True,
            "reason": reason,
            "session_summary": self._build_session_summary(session),
            "wait_for_input": False,
        }

    def _build_session_summary(self, session: DialogState) -> str:
        """构建会话摘要(给人工客服看的)"""
        
        summary = [
            f"用户ID: {session.user_id}",
            f"渠道: {session.channel}",
            f"对话轮次: {session.turn_count}",
            f"当前意图: {session.current_intent}",
            f"已收集信息: {json.dumps(session.slots, ensure_ascii=False)}",
            f"转人工原因: {session.escalation_reason}",
            "--- 最近对话 ---",
        ]
        
        for msg in list(session.history)[-5:]:
            role = "用户" if msg["role"] == "user" else "系统"
            summary.append(f"{role}: {msg['text'][:100]}")
        
        return "\n".join(summary)

    def check_escalation_conditions(self, session: DialogState) -> Optional[str]:
        """检查是否需要自动转人工"""
        
        # 连续3次无法理解
        recent_actions = [
            h.get("action") for h in list(session.history)[-3:]
            if h.get("role") == "system"
        ]
        if recent_actions.count("cannot_understand") >= 3:
            return "连续3次未能理解用户意图"
        
        # 用户情绪负面
        if session.sentiment in ("negative", "angry"):
            return f"检测到用户情绪{session.sentiment}"
        
        # 对话过长
        if session.turn_count > 20:
            return "对话轮次过多,建议人工接手"
        
        return None
4.4 坐席辅助模块
# agent_assist/agent_assistant.py

from typing import Dict, List, Optional
import json
import time


class AgentAssistant:
    """
    坐席辅助模块
    
    为人工客服提供实时建议、快捷回复、知识弹窗等功能
    """

    def __init__(self, llm_client=None, knowledge_base=None):
        self.llm = llm_client
        self.knowledge_base = knowledge_base
        self.active_sessions: Dict[str, Dict] = {}

    async def on_agent_login(self, agent_id: str):
        """坐席登录"""
        self.active_sessions[agent_id] = {
            "agent_id": agent_id,
            "status": "online",
            "current_session": None,
            "stats": {"handled": 0, "avg_duration": 0},
        }

    async def on_session_transferred(self, session_id: str,
                                       agent_id: str,
                                       session_summary: str):
        """接收到转接的会话"""
        
        self.active_sessions[agent_id]["current_session"] = session_id
        self.active_sessions[agent_id]["session_summary"] = session_summary

    async def generate_reply_suggestions(self, agent_id: str,
                                           user_message: str,
                                           context: Dict) -> List[str]:
        """生成回复建议"""
        
        suggestions = []
        
        # 1. 常用快捷回复
        shortcuts = self._get_shortcuts(context)
        suggestions.extend(shortcuts[:3])
        
        # 2. LLM 生成建议
        if self.llm:
            llm_suggestion = await self._llm_suggest_reply(
                user_message, context
            )
            if llm_suggestion:
                suggestions.insert(0, llm_suggestion)
        
        return suggestions[:5]

    def _get_shortcuts(self, context: Dict) -> List[str]:
        """获取快捷回复"""
        
        intent = context.get("intent", "")
        shortcuts_map = {
            "order.query_status": [
                "亲,我来帮您查询订单状态,请稍等~",
                "已经查到您的订单状态了,目前是【已发货】状态。",
                "预计明天下午送达,请您留意查收哦~",
            ],
            "after_sale.return_request": [
                "亲,退货流程是这样的:...",
                "您可以在「我的订单」中直接申请退货。",
                "请问您退货的原因是什么呢?",
            ],
            "after_sale.refund_inquiry": [
                "亲,我来查一下您的退款进度。",
                "您的退款正在处理中,预计3个工作日内到账。",
                "如果超过预计时间未到账,请提供截图,我帮您催办。",
            ],
            "complaint": [
                "非常抱歉给您带来不好的体验,我会记录您的问题并反馈给相关部门。",
                "请问您方便提供一下相关截图吗?这样我能更好地帮您处理。",
                "我已经记录了您的投诉,会在24小时内给您答复。",
            ],
        }
        
        return shortcuts_map.get(intent, ["好的,我来帮您处理。", "请稍等,我查一下。"])

    async def _llm_suggest_reply(self, user_message: str,
                                   context: Dict) -> Optional[str]:
        """LLM 生成回复建议"""
        
        prompt = f"""你是一个电商客服的回复建议系统。根据用户的消息和上下文,生成一个合适的回复建议。

用户消息:{user_message}

上下文:
- 意图:{context.get('intent', '未知')}
- 用户情绪:{context.get('sentiment', '中性')}
- 对话轮次:{context.get('turn_count', 0)}

要求:
1. 语气友好、专业
2. 简洁明了(不超过80字)
3. 如果是投诉,先道歉再处理
4. 如果是复杂问题,引导用户提供必要信息

回复建议:"""
        
        try:
            response = await self.llm.chat(prompt, temperature=0.5, max_tokens=200)
            return response.strip()
        except Exception:
            return None

    async def search_knowledge(self, agent_id: str,
                                 query: str) -> List[Dict]:
        """搜索知识库"""
        
        if not self.knowledge_base:
            return []
        
        results = await self.knowledge_base.search(query, top_k=3)
        
        return [
            {
                "title": r.get("title", ""),
                "content": r.get("content", "")[:200],
                "url": r.get("url", ""),
                "score": r.get("score", 0),
            }
            for r in results
        ]

    async def analyze_sentiment(self, text: str) -> Dict:
        """情绪分析"""
        
        if self.llm:
            prompt = f"""分析以下用户消息的情绪状态,输出 JSON:

消息:{text}

输出格式:{{"sentiment": "positive|neutral|negative|angry", "urgency": "low|medium|high", "score": 0.95}}
只输出 JSON。"""
            
            try:
                response = await self.llm.chat(prompt, temperature=0.1, max_tokens=100)
                response = response.strip().replace("```json", "").replace("```", "").strip()
                return json.loads(response)
            except Exception:
                pass
        
        return {"sentiment": "neutral", "urgency": "low", "score": 0.5}

    def get_agent_stats(self, agent_id: str) -> Dict:
        """获取坐席统计数据"""
        
        session = self.active_sessions.get(agent_id, {})
        return {
            "status": session.get("status", "offline"),
            "handled_today": session.get("stats", {}).get("handled", 0),
            "avg_duration": session.get("stats", {}).get("avg_duration", 0),
            "current_session": session.get("current_session") is not None,
        }
4.5 FastAPI 服务入口
# main.py

from fastapi import FastAPI, WebSocket, Request
from fastapi.responses import HTMLResponse
import json
import asyncio
from typing import Dict

app = FastAPI(title="智能客服 Agent")


# 全局组件
class CustomerServiceSystem:
    """客服系统主控"""
    
    def __init__(self):
        self.llm_client = None  # 初始化 LLM 客户端
        self.api_gateway = None  # 初始化 API 网关
        self.classifier = IntentClassifier(self.llm_client)
        self.dialog_manager = DialogManager(self.llm_client, self.api_gateway)
        self.agent_assistant = AgentAssistant(self.llm_client)
        self.channels = {}
    
    async def handle_message(self, message: UnifiedMessage):
        """处理用户消息的主入口"""
        
        # 获取或创建会话
        session = self.dialog_manager.get_or_create_session(
            message.session_id,
            message.platform_user_id,
            message.channel.value,
        )
        
        # 意图识别
        intent = await self.classifier.classify(
            message.content,
            {"last_intent": session.current_intent},
        )
        
        # 对话管理
        response = await self.dialog_manager.process(
            session, intent, message.content
        )
        
        # 检查是否需要自动转人工
        if not response.get("transfer_to_agent"):
            escalate_reason = self.dialog_manager.check_escalation_conditions(session)
            if escalate_reason:
                response = self.dialog_manager._escalate_to_human(
                    session, escalate_reason
                )
        
        # 发送回复
        channel_adapter = self.channels.get(message.channel)
        if channel_adapter:
            unified_resp = UnifiedResponse(
                text=response.get("text", ""),
                transfer_to_agent=response.get("transfer_to_agent", False),
                wait_for_input=response.get("wait_for_input", True),
            )
            await channel_adapter.send_message(
                message.channel_user_id, unified_resp
            )


cs_system = CustomerServiceSystem()


@app.on_event("startup")
async def startup():
    """启动时初始化各个渠道"""
    
    # Web 聊天渠道
    web_adapter = WebChatAdapter(cs_system.handle_message)
    await web_adapter.start()
    cs_system.channels[ChannelType.WEB_CHAT] = web_adapter
    
    # 微信公众号渠道
    wechat_adapter = WeChatOfficialAdapter(
        cs_system.handle_message,
        app_id="your_app_id",
        app_secret="your_app_secret",
    )
    await wechat_adapter.start()
    cs_system.channels[ChannelType.WECHAT_OFFICIAL] = wechat_adapter
    
    print("客服系统已启动,监听端口 8765 (WebSocket) 和 8080 (HTTP)")


@app.on_event("shutdown")
async def shutdown():
    """关闭时清理资源"""
    for adapter in cs_system.channels.values():
        await adapter.stop()


@app.get("/health")
async def health_check():
    """健康检查"""
    return {
        "status": "healthy",
        "active_channels": len(cs_system.channels),
        "active_sessions": len(cs_system.dialog_manager.sessions),
    }


@app.get("/agent/sessions")
async def get_active_sessions():
    """获取活跃会话列表(供管理后台使用)"""
    sessions = []
    for sid, state in cs_system.dialog_manager.sessions.items():
        if time.time() - state.last_activity < 300:  # 5分钟内活跃
            sessions.append({
                "session_id": sid,
                "user_id": state.user_id,
                "channel": state.channel,
                "intent": state.current_intent,
                "turn_count": state.turn_count,
                "last_activity": state.last_activity,
            })
    return {"sessions": sessions}


@app.post("/agent/reply/{session_id}")
async def agent_reply(session_id: str, data: Dict):
    """人工客服回复接口"""
    
    text = data.get("text", "")
    agent_id = data.get("agent_id", "")
    
    # 查找会话对应的渠道
    session = cs_system.dialog_manager.sessions.get(session_id)
    if not session:
        return {"error": "Session not found"}
    
    channel = ChannelType(session.channel)
    adapter = cs_system.channels.get(channel)
    if not adapter:
        return {"error": "Channel adapter not found"}
    
    response = UnifiedResponse(text=text)
    await adapter.send_message(session.channel_user_id, response)
    
    return {"status": "sent"}


if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000)

五、实际对话示例

以下是一个完整的退货申请对话流程:

用户:我想退货
🤖:请问您的订单号是多少?
用户:ORD20261126001
🤖:请问您要退哪个商品?(提供商品编号或名称)
用户:那个蓝色卫衣
🤖:请问退货的原因是什么?
用户:尺码太大了,买小了
🤖:请问要退几件?
用户:1件

🤖:请确认以下信息:
订单号:ORD20261126001
商品:蓝色卫衣
原因:尺码太大
数量:1件

回复「确认」或「修改xxx为yyy」。
用户:确认

🤖:退货申请已提交!
退货单号:RTN20261127001
请将商品寄回至:XX省XX市XX区XX路XX号 退货仓
退款将在收到商品后 3-5 个工作日内原路返还。

还有其他问题吗?
用户:没有了,谢谢
🤖:不客气!感谢您的耐心配合,祝您生活愉快~

六、效果数据

指标

实施前

实施后

改善

常见问题自动解决率

0%

74.3%

+74.3pp​

平均响应时间

45 秒

2.3 秒

-94.9%​

高峰期排队时长

30+ 分钟

< 10 秒

-99.4%​

坐席人均日处理量

120 单

210 单

+75%​

坐席培训周期

3 周

1 周

-66.7%​

客服团队规模

500 人

320 人

-36%​

用户满意度评分

3.2/5

4.3/5

+34%​

全渠道会话连贯率

0%(渠道隔离)

87%

基线​


七、本讲坑位

#

坑位

现象

解决方案

1

意图识别与槽位提取耦合​

用户在问 A 问题时顺带说了 B 问题的信息,系统忽略

每次用户输入都尝试提取所有已知槽位,不只是当前任务的

2

多轮对话中的指代消解​

用户说「它」「那个」「这个」,系统不知道指什么

维护实体记忆池 + 指代消解模型 + 必要时反问确认

3

渠道切换导致上下文丢失​

用户在 App 聊了一半,去公众号接着说,系统不认识

统一用户 ID(手机号/UnionID)+ 共享会话状态

4

LLM 回复过于啰嗦​

LLM 生成的回复太长,用户不想看

限制 token + 结构化输出 + 关键信息前置

5

情绪检测误报​

用户只是打字快/用词直接,被判定为负面情绪转人工

多维度判断(关键词+语气+频率)+ 冷却期机制

6

高峰期的 LLM 调用瓶颈​

大促期间 LLM 请求暴增,响应变慢

本地缓存热点问题 + 降级到模板回复 + 异步处理


八、下讲预告

第6讲:内容审核 Agent——从人工审核到 AI 驱动的合规防线

我们将拆解一个内容审核 Agent,它能:

  • 自动审核文本、图片、视频中的违规内容
  • 覆盖色情、暴力、政治敏感、广告垃圾等多维度
  • 实时拦截 + 异步复审双通道
  • 支持自定义审核规则和白名单
  • 审核结果可追溯、可申诉

🧰 博主工具箱

  • JSON 格式化:zz365.top 的 JSON 工具整理意图识别结果和对话状态
  • Base64 编解码:处理图片/音频的 base64 传输
  • 文本差异对比:对比不同版本的 FAQ 答案或话术模板
  • 正则表达式测试:验证意图匹配规则和实体抽取模式

更多效率工具,欢迎访问我的个人主页:zz365.top

Logo

DAMO开发者矩阵,由阿里巴巴达摩院和中国互联网协会联合发起,致力于探讨最前沿的技术趋势与应用成果,搭建高质量的交流与分享平台,推动技术创新与产业应用链接,围绕“人工智能与新型计算”构建开放共享的开发者生态。

更多推荐