{"id":"e813f05c-ea82-455e-a819-006c77eb5361","entityType":"agent","slug":"clawhub-jerryang-cool-trtc-ai-customer-service","name":"TRTC AI Customer Service","canonicalUrl":"https://www.xpersona.co/agent/clawhub-jerryang-cool-trtc-ai-customer-service","canonicalPath":"/agent/clawhub-jerryang-cool-trtc-ai-customer-service","generatedAt":"2026-10-11T05:43:22.642Z","source":"CLAWHUB","claimStatus":"UNCLAIMED","verificationTier":"NONE","summary":{"evidence":{"source":"CLAWHUB","verified":false,"confidence":"medium","updatedAt":"2026-10-11T03:02:55.006Z","emptyReason":null},"description":"Build an AI e-commerce customer service Web app with TRTC ConversationAI — real-time voice/text dual-mode, trilingual (Chinese/English/Cantonese), digital av...","descriptionLabel":"Source description","evidenceSummary":"Capability contract not published. No trust telemetry is available yet. 1.2K downloads reported by the source. Last updated 10/11/2026.","installCommand":"clawhub skill install s17asvpk3b23w8deqmbkaxf4cn86swf9:trtc-ai-customer-service","sourceUrl":"https://clawhub.ai/jerryang-cool/trtc-ai-customer-service","homepage":"https://clawhub.ai/jerryang-cool/skills/trtc-ai-customer-service","primaryLinks":[{"label":"View on ClawHub","url":"https://clawhub.ai/jerryang-cool/trtc-ai-customer-service","kind":"source"},{"label":"Homepage","url":"https://clawhub.ai/jerryang-cool/skills/trtc-ai-customer-service","kind":"homepage"}],"safetyScore":84,"overallRank":62,"popularityScore":61,"trustScore":null,"claimedByName":null,"isOwner":false,"seoDescription":"TRTC AI Customer Service technical dossier on Xpersona with agent coverage, OPENCLEW support, and live trust metadata."},"coverage":{"evidence":{"source":"public-profile","verified":false,"confidence":"medium","updatedAt":"2026-10-11T03:02:55.006Z","emptyReason":null},"protocols":[{"protocol":"OPENCLEW","label":"OpenClaw","status":"self-declared","notes":"Declared in the public agent profile."}],"capabilities":[],"verifiedCount":0,"selfDeclaredCount":1,"capabilityMatrix":{"rows":[{"key":"OPENCLEW","type":"protocol","support":"unknown","confidenceSource":"profile","notes":"Listed on profile"}],"flattenedTokens":"protocol:OPENCLEW|unknown|profile"}},"adoption":{"evidence":{"source":"CLAWHUB","verified":false,"confidence":"medium","updatedAt":"2026-10-11T03:02:55.006Z","emptyReason":null},"stars":null,"forks":null,"downloads":1179,"packageName":null,"latestVersion":"1.2.5","tractionLabel":"1.2K downloads"},"release":{"evidence":{"source":"CLAWHUB","verified":false,"confidence":"medium","updatedAt":"2026-10-11T03:02:54.945Z","emptyReason":null},"lastUpdatedAt":"2026-10-11T03:02:55.006Z","lastCrawledAt":"2026-10-11T03:02:54.945Z","lastIndexedAt":null,"nextCrawlAt":"2026-10-12T03:02:54.945Z","lastVerifiedAt":null,"highlights":[{"version":"1.2.5","createdAt":"2026-05-26T13:10:12.564Z","changelog":"trtc-ai-customer-service v1.2.5 - Updated documentation (SKILL.md) for improved clarity and completeness. - Minor improvements or fixes applied to source/script files. - No breaking changes in APIs or workflows. - All instructions and reference guides are now up to date for new users.","fileCount":15,"zipByteSize":88408},{"version":"1.2.4","createdAt":"2026-05-26T12:00:37.223Z","changelog":"Version 1.2.4 - Refined trigger logic: Only activates when users express a clear intent to build, integrate, or set up an e-commerce AI customer service app, rather than on all customer service keyword mentions. - Updated documentation to clarify supported and unsupported trigger scenarios. - Improved instructions for configuration and customization steps. - Added or updated references for integration guides and configuration documentation. - Minor enhancements to scripts and static assets to streamline setup and deployment.","fileCount":15,"zipByteSize":87959},{"version":"1.2.3","createdAt":"2026-05-26T09:39:13.011Z","changelog":"trtc-ai-customer-service v1.2.3 - 推荐 LLM 接入方式更新为腾讯云 TokenHub，脚本/文档默认优先 TokenHub 配置，并给出国际站与中国站 API 网关、模型和 key 获取入口 - 指南文档 references/config-guide.md 针对 LLM 配置及官方推荐开放平台进行了同步说明 - start.sh 脚本及说明文本优化：“TokenHub”为首选入口，便于零门槛开箱即用 - 常规文档细节润色，部分说明表述更加清晰","fileCount":15,"zipByteSize":87561},{"version":"1.2.2","createdAt":"2026-05-26T09:08:49.169Z","changelog":"trtc-ai-customer-service 1.2.2 - Documentation improvements: updated SKILL.md usage and instructions for clarity and completeness. - Small internal script and frontend code adjustments. - No breaking changes to public interfaces.","fileCount":15,"zipByteSize":86828},{"version":"1.2.1","createdAt":"2026-05-18T13:00:53.083Z","changelog":"trtc-ai-customer-service v1.2.1 - Updated SKILL.md: version bump from 1.2.0 to 1.2.1 and minor documentation adjustments. - No functional or code logic changes; update focuses on documentation consistency.","fileCount":14,"zipByteSize":84868},{"version":"1.2.0","createdAt":"2026-05-18T12:24:44.949Z","changelog":"Version 1.2.0 of trtc-ai-customer-service: - Added a Chinese documentation file (`README_ZH.md`), removed the English README. - Revised and reorganized documentation for clearer workflows, especially the setup and customization process. - Enhanced startup script and onboarding experience: now supports selecting deployment region (Intl/CN), with context-sensitive steps and links. - Streamlined multi-language support—default trilingual (Chinese, English, Cantonese) without language flags. - Improved skill integration guidance: direct code snippets for non-Python stacks, more reference and troubleshooting details. - Various improvements to configuration setup, customization, and FAQ sections for greater clarity and regional compatibility.","fileCount":14,"zipByteSize":83152},{"version":"1.1.1","createdAt":"2026-05-18T07:46:23.496Z","changelog":"- Updated assets/static/app.js. - No user-facing or documentation changes. - Internal or implementation-only update; all user docs remain the same.","fileCount":14,"zipByteSize":81867},{"version":"1.1.0","createdAt":"2026-05-18T06:56:20.675Z","changelog":"- Improved customer service UI and user experience in customer_service.html. - Enhanced JavaScript in app.js for better interaction and bug fixes. - No changes to overall Skill usage or backend APIs.","fileCount":14,"zipByteSize":81760}]},"execution":{"evidence":{"source":"CLAWHUB","verified":false,"confidence":"low","updatedAt":null,"emptyReason":"No published capability contract is available yet."},"installCommand":"clawhub skill install s17asvpk3b23w8deqmbkaxf4cn86swf9:trtc-ai-customer-service","setupComplexity":"low","setupSteps":["Install using `clawhub skill install s17asvpk3b23w8deqmbkaxf4cn86swf9:trtc-ai-customer-service` in an isolated environment before connecting it to live workloads.","No published capability contract is available yet, so validate auth and request/response behavior manually.","Review the upstream CLAWHUB listing at https://clawhub.ai/jerryang-cool/trtc-ai-customer-service before using production credentials."],"contract":{"contractStatus":"missing","authModes":[],"requires":[],"forbidden":[],"supportsMcp":false,"supportsA2a":false,"supportsStreaming":false,"inputSchemaRef":null,"outputSchemaRef":null,"dataRegion":null,"contractUpdatedAt":null,"sourceUpdatedAt":null,"freshnessSeconds":null},"invocationGuide":{"preferredApi":{"snapshotUrl":"https://www.xpersona.co/api/v1/agents/clawhub-jerryang-cool-trtc-ai-customer-service/snapshot","contractUrl":"https://www.xpersona.co/api/v1/agents/clawhub-jerryang-cool-trtc-ai-customer-service/contract","trustUrl":"https://www.xpersona.co/api/v1/agents/clawhub-jerryang-cool-trtc-ai-customer-service/trust"},"curlExamples":["curl -s \"https://www.xpersona.co/api/v1/agents/clawhub-jerryang-cool-trtc-ai-customer-service/snapshot\"","curl -s \"https://www.xpersona.co/api/v1/agents/clawhub-jerryang-cool-trtc-ai-customer-service/contract\"","curl -s \"https://www.xpersona.co/api/v1/agents/clawhub-jerryang-cool-trtc-ai-customer-service/trust\""],"jsonRequestTemplate":{"query":"summarize this repo","constraints":{"maxLatencyMs":2000,"protocolPreference":["OPENCLEW"]}},"jsonResponseTemplate":{"ok":true,"result":{"summary":"...","confidence":0.9},"meta":{"source":"CLAWHUB","generatedAt":"2026-10-11T05:43:22.639Z"}},"retryPolicy":{"maxAttempts":3,"backoffMs":[500,1500,3500],"retryableConditions":["HTTP_429","HTTP_503","NETWORK_TIMEOUT"]}},"endpoints":{"dossierUrl":"https://www.xpersona.co/api/v1/agents/clawhub-jerryang-cool-trtc-ai-customer-service/dossier","snapshotUrl":"https://www.xpersona.co/api/v1/agents/clawhub-jerryang-cool-trtc-ai-customer-service/snapshot","contractUrl":"https://www.xpersona.co/api/v1/agents/clawhub-jerryang-cool-trtc-ai-customer-service/contract","trustUrl":"https://www.xpersona.co/api/v1/agents/clawhub-jerryang-cool-trtc-ai-customer-service/trust"}},"reliability":{"evidence":{"source":"runtime-metrics","verified":false,"confidence":"low","updatedAt":null,"emptyReason":"No trust, reliability, or runtime telemetry is available."},"trust":{"status":"unavailable","handshakeStatus":"UNKNOWN","verificationFreshnessHours":null,"reputationScore":null,"p95LatencyMs":null,"successRate30d":null,"fallbackRate":null,"attempts30d":null,"trustUpdatedAt":null,"trustConfidence":"unknown","sourceUpdatedAt":null,"freshnessSeconds":null},"decisionGuardrails":{"doNotUseIf":["Contract metadata is missing or unavailable for deterministic execution."],"safeUseWhen":[],"riskFlags":["missing_or_unavailable_contract","trust_data_unavailable","schema_references_missing"],"operationalConfidence":"low"},"executionMetrics":{"observedLatencyMsP50":null,"observedLatencyMsP95":null,"estimatedCostUsd":null,"uptime30d":null,"rateLimitRpm":null,"rateLimitBurst":null,"lastVerifiedAt":null,"verificationSource":null},"runtimeMetrics":{"successRate":null,"avgLatencyMs":null,"avgCostUsd":null,"hallucinationRate":null,"retryRate":null,"disputeRate":null,"p50Latency":null,"p95Latency":null,"lastUpdated":null}},"benchmarks":{"evidence":{"source":"no-benchmark-data","verified":false,"confidence":"low","updatedAt":null,"emptyReason":"No benchmark suites or observed failure patterns are available."},"suites":[],"failurePatterns":[]},"artifacts":{"evidence":{"source":"CLAWHUB","verified":false,"confidence":"medium","updatedAt":"2026-10-11T03:02:55.006Z","emptyReason":null},"readme":"Skill: TRTC AI Customer Service\n\nOwner: jerryang-cool\n\nSummary: Build an AI e-commerce customer service Web app with TRTC ConversationAI — real-time voice/text dual-mode, trilingual (Chinese/English/Cantonese), digital av...\n\nTags: latest:1.2.5\n\nVersion history:\n\nv1.2.5 | 2026-05-26T13:10:12.564Z | auto\n\ntrtc-ai-customer-service v1.2.5\n\n- Updated documentation (SKILL.md) for improved clarity and completeness.\n- Minor improvements or fixes applied to source/script files.\n- No breaking changes in APIs or workflows.\n- All instructions and reference guides are now up to date for new users.\n\nv1.2.4 | 2026-05-26T12:00:37.223Z | auto\n\nVersion 1.2.4\n\n- Refined trigger logic: Only activates when users express a clear intent to build, integrate, or set up an e-commerce AI customer service app, rather than on all customer service keyword mentions.\n- Updated documentation to clarify supported and unsupported trigger scenarios.\n- Improved instructions for configuration and customization steps.\n- Added or updated references for integration guides and configuration documentation.\n- Minor enhancements to scripts and static assets to streamline setup and deployment.\n\nv1.2.3 | 2026-05-26T09:39:13.011Z | auto\n\ntrtc-ai-customer-service v1.2.3\n\n- 推荐 LLM 接入方式更新为腾讯云 TokenHub，脚本/文档默认优先 TokenHub 配置，并给出国际站与中国站 API 网关、模型和 key 获取入口\n- 指南文档 references/config-guide.md 针对 LLM 配置及官方推荐开放平台进行了同步说明\n- start.sh 脚本及说明文本优化：“TokenHub”为首选入口，便于零门槛开箱即用\n- 常规文档细节润色，部分说明表述更加清晰\n\nv1.2.2 | 2026-05-26T09:08:49.169Z | auto\n\ntrtc-ai-customer-service 1.2.2\n\n- Documentation improvements: updated SKILL.md usage and instructions for clarity and completeness.\n- Small internal script and frontend code adjustments. \n- No breaking changes to public interfaces.\n\nv1.2.1 | 2026-05-18T13:00:53.083Z | auto\n\ntrtc-ai-customer-service v1.2.1\n\n- Updated SKILL.md: version bump from 1.2.0 to 1.2.1 and minor documentation adjustments.\n- No functional or code logic changes; update focuses on documentation consistency.\n\nv1.2.0 | 2026-05-18T12:24:44.949Z | auto\n\nVersion 1.2.0 of trtc-ai-customer-service:\n\n- Added a Chinese documentation file (`README_ZH.md`), removed the English README.\n- Revised and reorganized documentation for clearer workflows, especially the setup and customization process.\n- Enhanced startup script and onboarding experience: now supports selecting deployment region (Intl/CN), with context-sensitive steps and links.\n- Streamlined multi-language support—default trilingual (Chinese, English, Cantonese) without language flags.\n- Improved skill integration guidance: direct code snippets for non-Python stacks, more reference and troubleshooting details.\n- Various improvements to configuration setup, customization, and FAQ sections for greater clarity and regional compatibility.\n\nv1.1.1 | 2026-05-18T07:46:23.496Z | auto\n\n- Updated assets/static/app.js.\n- No user-facing or documentation changes.\n- Internal or implementation-only update; all user docs remain the same.\n\nv1.1.0 | 2026-05-18T06:56:20.675Z | auto\n\n- Improved customer service UI and user experience in customer_service.html.\n- Enhanced JavaScript in app.js for better interaction and bug fixes.\n- No changes to overall Skill usage or backend APIs.\n\nv1.0.1 | 2026-05-15T10:35:29.853Z | auto\n\n- Added troubleshooting guidance for activating chmod permissions if the start.sh script cannot be executed directly.\n- Updated the configuration documentation to clarify handling of start.sh execution errors and to recommend the use of `chmod +x start.sh` on macOS/Linux systems.\n\nv1.0.0 | 2026-05-15T10:07:57.364Z | auto\n\n- Initial release of TRTC AI e-commerce customer service skill.\n- Provides step-by-step guidance for creating a trilingual (Mandarin, Cantonese, English), voice/text dual-mode customer service web app with TRTC ConversationAI.\n- Features detailed project scaffolding, key integration points for both new and existing projects, and extensive troubleshooting documentation.\n- Includes configuration guides for deployment, AI avatar, LLM/TTS setup, security tips, and extensibility for real or mock e-commerce data.\n- Supports digital avatar integration and offers fallback to pure voice-based mode.\n- Designed for quick onboarding and rich customization of customer service flows and branding.\n\nArchive index:\n\nArchive v1.2.5: 15 files, 88408 bytes\n\nFiles: assets/start.sh (30549b), assets/static/app.js (54183b), assets/static/i18n.js (14766b), assets/static/mock-orders.json (1525b), assets/templates/customer_service.html (62687b), assets/TLSSigAPIv2.py (16022b), README_ZH.md (6090b), README.md (6281b), references/architecture.md (12223b), references/config-guide.md (11425b), references/frontend-guide.md (14226b), scripts/scaffold.py (38041b), skill-card.md (3245b), SKILL.md (13938b), _meta.json (143b)\n\nFile v1.2.5:SKILL.md\n\n---\nname: trtc-ai-customer-service\nversion: 1.2.5\ndescription: |\n  Build an AI e-commerce customer service Web app with TRTC ConversationAI — real-time voice/text dual-mode, trilingual (Chinese/English/Cantonese), digital avatar optional. Covers order inquiry, returns, shipping tracking, and promotions.\n  基于腾讯云 TRTC Conversational AI 快速构建 AI 电商客服 Web 应用 — 实时语音/文字双模、中英粤三语、数字人可选。覆盖订单查询、退换货、物流追踪、商品咨询等场景。\nhomepage: https://github.com/jerryang-cool/trtc-ai-customer-service-skill\nmetadata:\n  openclaw:\n    emoji: \"🛍️\"\n    requires:\n      bins:\n        - python3\n---\n\n# TRTC AI 电商客服 Skill\n\n本 Skill 指导你基于腾讯云 TRTC Conversational AI 能力，快速构建 AI 电商客服 Web 应用。\n场景预置了订单查询、退换货处理、商品咨询、物流追踪、优惠活动等电商业务模块。\n\n## 触发条件\n\n当用户**表达构建/搭建/集成意图**时使用此 Skill：\n- \"做一个 AI 客服\" \"搭建电商客服\" \"帮我做个智能客服系统\" \"语音客服 demo\"\n- \"build an AI customer service\" \"e-commerce customer service app\"\n- \"TRTC ConversationAI\" \"TRTC + AI 客服\" \"TRTC e-commerce support\"\n- \"StartAIConversation\" \"StopAIConversation\" \"ControlAIConversation\"（TRTC API 名称）\n- \"数字人客服\" \"avatar customer service\"\n- \"实时语音 AI 对话\" \"ASR + LLM + TTS 客服\"\n\n**不应触发的场景**：\n- 用户仅在讨论客服概念，没有构建/开发意图\n- 用户询问通用 chat bot 方案，不需要语音能力或电商场景\n- 关键词如 \"voice bot\" \"chat bot\" 单独出现且无构建上下文\n\n## 架构总览\n\n```\n浏览器 (TRTC Web SDK v5)\n     ↕ 音频 (WebRTC) + 自定义消息 (字幕/状态/文字输入)\nTRTC Room\n     ↕ 内置 ASR → LLM → TTS → 推回房间\nTRTC AI Bot (云端)\n     ↕ OpenAPI (TC3-HMAC-SHA256)\nFlask 后端 (app.py)  —— 仅 UserSig 签发 + OpenAPI 中转\n```\n\n| 平面 | 通道 | 内容 |\n|------|------|------|\n| **媒体面** | WebRTC 音频流 | 用户麦克风 ↔ TRTC 房间 ↔ AI Bot |\n| **控制面** | HTTP `/action` | 前端 → Flask → TRTC OpenAPI |\n| **数据面** | TRTC 自定义消息 | 字幕(10000) / AI 状态(10001) / 文字输入(20000) / 打断(20001) |\n\n后端**完全不调用 LLM**——LLM 由 TRTC 云端 AI Bot 内部调用，后端只负责签发 UserSig 和中转 OpenAPI 请求。\n\n---\n\n## 工作流程\n\n根据用户需求选择合适的路径。\n\n### 路径 A：从零创建新项目（推荐）\n\n#### Step 1: 生成项目\n\n运行脚手架脚本：\n\n```bash\npython {baseDir}/scripts/scaffold.py <项目目录> [--name <商城名称>] [--name-en <English name>]\n```\n\n- `{baseDir}`：本 Skill 所在目录的绝对路径（由 Agent 自动替换为实际路径）\n- `--name`：商城名称（默认\"云尚商城\"），用于中文/粤语的 SystemPrompt、欢迎语、告别语、前端 UI\n- `--name-en`：英文商城名称（默认自动推导：中文名时为\"CloudShop Mall\"，英文名时与 `--name` 相同），用于英文 SystemPrompt、英文欢迎语/告别语\n- 默认支持中文/英文/粤语三语，无需手动指定语言\n- 脚本自动生成全部文件：后端 + 前端 + 头像 + 鉴权库 + 启动脚本，无需手动复制任何文件\n\n**检查点**：确认用户看到 `✅ 电商客服项目已生成到: xxx` 和完整文件列表，再继续。\n\n#### Step 2: 配置密钥\n\n引导用户运行启动脚本（**根据操作系统自动选择**：macOS/Linux 用 `./start.sh`，Windows 用 `start.bat`），首次运行会进入交互式引导：\n\n- [0/4] 选择部署区域（默认 `intl` 国际站，可选 `cn` 中国站）— 后续步骤会根据所选区域展示对应的控制台链接\n- [1/4] 腾讯云 API 密钥 → 脚本会展示对应区域的 [CAM 控制台](https://console.intl.cloud.tencent.com/cam/capi) 链接\n- [2/4] TRTC 应用凭据 → 脚本会展示对应区域的 [TRTC 控制台](https://console.trtc.io/app) 链接\n- [3/4] LLM 配置 → **建议优先使用 TokenHub**（腾讯云统一 LLM 网关，开箱即用）：\n  - `LLMConfig.LLMType`：`openai`（固定）\n  - `LLMConfig.Model`：`deepseek-v4-flash`（推荐）\n  - `LLMConfig.APIUrl`：\n    - 国际站：`https://tokenhub-intl.tencentcloudmaas.com/v1/chat/completions`\n    - 中国站：`https://tokenhub.tencentmaas.com/v1/chat/completions`\n  - `LLMConfig.APIKey`：在 TokenHub 控制台获取（[国际站](https://console.intl.cloud.tencent.com/tokenhub) | [中国站](https://console.cloud.tencent.com/tokenhub)）\n  - 也支持其他兼容 OpenAI 协议的 LLM，参考配置指南：[国际站](https://trtc.io/document/68338?product=conversationalai) | [中国站](https://cloud.tencent.com/document/product/647/115413)\n\n**检查点**：确认用户看到 `✓ 所有密钥已配置完成！`。如果有跳过项，提醒手动编辑 `env.yaml`。\n\n> **提示用户**：以上为最小必填项，启动成功后还有丰富的可定制选项（角色定制、商城名称、欢迎语、TTS 音色、关键词等），详见 Step 4。\n\n#### Step 3: 启动验证\n\n启动脚本会自动创建虚拟环境、安装依赖、启动服务。\n\n**验证标准**（告知用户逐项确认）：\n1. 终端显示 `🚀 启动 TRTC AI 智能客服` + 访问地址（公网服务器会自动检测公网 IP 并启用 HTTPS，显示 `https://<公网IP>:8080`；本地开发则显示 `http://localhost:8080`）\n2. 浏览器打开页面 → 能看到客服头像选择界面\n3. 选择客服 → 点击\"开始对话\" → 听到 AI 播报欢迎语\n4. 说话或打字 → AI 能正常回复\n\n#### Step 4: 定制化（可选）\n\n启动成功后，**主动告知用户**以下所有可定制项，引导按需修改：\n\n| 定制项 | 修改位置 | 说明 |\n|--------|---------|------|\n| **AI 客服角色** | 交互式引导 [4/4]（删除 `env.yaml` 后重新运行 `./start.sh`），或直接编辑 `env.yaml` → `SystemPrompt` / `SystemPromptYue` / `SystemPromptEn` | 预设品类 + 语气快速定制（见下方枚举表），也可手动编辑三语 SystemPrompt 做精细调整 |\n| **商城名称/品牌** | scaffold 的 `--name` / `--name-en` 参数 | 一键替换全链路品牌文案（三语 SystemPrompt、欢迎语、告别语、前端 UI） |\n| **欢迎语 / 告别语** | `env.yaml` → `WelcomeMessage` / `FarewellMessage`（`.zh` / `.yue` / `.en`） | AI 进房首条播报 / 关键词触发结束时播报 |\n| **LLM 模型** | `env.yaml` → `LLMConfig.Model` / `APIUrl` / `APIKey` | LLM 配置指南：[国际站](https://trtc.io/document/68338?product=conversationalai) \\| [中国站](https://cloud.tencent.com/document/product/647/115413) |\n| **TTS 音色** | `config_loader.py` → `TTS_VOICE_MAP` | TTS 音色配置指南：[国际站](https://trtc.io/document/79682?product=conversationalai) \\| [中国站](https://cloud.tencent.com/document/product/647/115414) |\n| **商品/订单数据** | `static/mock-orders.json`，或参考 `references/frontend-guide.md` 对接真实 API | JSON 格式含三语名称和价格，可替换为真实订单系统 |\n| **数字人** | `env.yaml` → `AvatarConfig` 三项 | 三项全填启用数字人视频模式，否则纯语音 |\n| **部署方式** | 自动检测公网 IP 启用 HTTPS；生产环境用 Gunicorn + Nginx + 正式证书 | WebRTC 要求 HTTPS；生产还需添加 `/action` 接口鉴权 |\n\n**AI 客服角色预设枚举值**（`start.sh` 交互式引导 [4/4]）：\n\n商城品类（影响 AI 的专业知识方向）：\n\n| 选项 | 品类 | AI 擅长方向 |\n|------|------|------------|\n| 1 | 综合电商（默认） | 通用电商场景，不修改 SystemPrompt |\n| 2 | 数码产品 | 参数对比、兼容性问题、保修政策、使用教程 |\n| 3 | 服装鞋帽 | 尺码推荐、面料材质、搭配建议、洗涤保养、退换尺码 |\n| 4 | 食品生鲜 | 保质期、储存方式、配送时效、食材产地、过敏原信息 |\n| 5 | 家居百货 | 商品尺寸规格、安装方式、材质说明、配送安装服务 |\n\n客服语气风格（影响 AI 的表达方式）：\n\n| 选项 | 风格 | 效果 |\n|------|------|------|\n| 1 | 亲切自然（默认） | 像朋友聊天，已内置于默认 SystemPrompt |\n| 2 | 专业严谨 | 用词准确规范，适合高端品牌/B2B |\n| 3 | 活泼可爱 | 轻松表达方式，适合年轻用户群体 |\n\n> 选择后自动注入三语 SystemPrompt（中文/粤语/英文同步）。如需更精细定制，直接编辑 `env.yaml` 中的 SystemPrompt 即可。\n\n### 路径 B：为现有项目集成 TRTC AI 对话\n\n#### Step 1: 了解现有架构\n\n询问并确认：\n- 后端语言和框架（Python/Node/Go/Java？）\n- 前端技术栈（React/Vue/原生 JS？已有 TRTC SDK？）\n- 集成范围：仅后端 API？还是含前端 UI？\n\n#### Step 2: 按需读取参考文档并输出代码\n\n根据用户技术栈，读取对应文档并**直接输出可集成的代码片段**：\n\n| 需求 | 读取文档 | 输出内容 |\n|------|----------|----------|\n| 后端 API | `references/architecture.md` | 用户语言的 5 个 Action 处理器代码（join / Start / Stop / Farewell / Transfer） |\n| 配置体系 | `references/config-guide.md` | 生成 `env.yaml` 模板 + 配置加载代码 |\n| 前端对话 UI | `references/frontend-guide.md` | TRTC SDK 进房 + 消息监听 + 字幕渲染代码 |\n\n**关键**：如果用户不是 Python 技术栈，需要将参考文档中的 Python 逻辑**翻译为用户的语言**（如 Node.js / Go / Java），核心逻辑不变。\n\n#### Step 3: 验证集成\n\n引导用户完成最小可用流程并逐步确认：\n1. 后端 `/action` 接口能正常响应（`curl -X POST /action -H \"Action: join\"` 返回 UserSig）\n2. 前端成功进入 TRTC 房间（控制台无报错）\n3. `StartAIConversation` 调用成功返回 TaskId\n4. 用户说话 → 听到 AI 回复（完整链路跑通）\n\n**如果卡在某一步**，参照下方 FAQ 表逐条排查。\n\n---\n\n## 常见问题排查\n\n当用户遇到问题时，按以下清单排查：\n\n| 现象 | 原因 | 解决方案 |\n|------|------|----------|\n| scaffold.py 报错退出 | Python 版本或参数错误 | 确认 Python 3.8+；检查输出目录路径是否合法 |\n| `start.sh` 报 Python 版本不够 | Python < 3.8 | 安装 Python 3.8+ |\n| venv 创建失败 | 缺少 `python3-venv` 包 | Ubuntu/Debian: `sudo apt install python3-venv`；macOS 自带 |\n| 依赖安装失败 | 网络问题 | `start.sh` 会自动 fallback 官方源；或手动 `pip install -r requirements.txt` |\n| `env.yaml` 解析报错 | YAML 缩进或格式错误 | 用在线 YAML 校验器检查；常见：冒号后缺空格、中文引号 |\n| 页面打开空白 | 静态文件缺失 | 确认 `static/app.js` 和 `templates/customer_service.html` 存在 |\n| 点\"开始对话\"无反应 | 密钥未填或填错 | 检查 `env.yaml` 中 SDKAPPID 不为 0、SECRET_ID/KEY 正确 |\n| 点\"开始对话\"提示**进房失败** | TRTC 进房参数异常 | 检查 `SDKAPPID` 是否正确填写；UserSig 是否校验失败（核对 `TRTC.SECRET`） |\n| 说话**无任何响应**（语音不可用） | 浏览器麦克风权限未授予或设备异常 | 检查浏览器地址栏麦克风权限；测试系统设备：录音机能否录到声音 |\n| 仅显示**本地字幕，AI 无回应** | LLM 服务异常 | 检查 `LLMConfig.APIKey` / `APIUrl` / `Model` 是否正确；确认 LLM 账户额度充足 |\n| AI 有字幕但**无语音播报** | TTS 服务异常 | 核对 TTS 参数（VoiceId、Language）；确认 TTS 套餐包资源充足 |\n| LLM **长时间不回复**或超时报错 | LLM Timeout | 调大 `env.yaml` → `LLMConfig.Timeout`（如 5.0 → 10.0） |\n| 进房成功但无欢迎语 | LLM APIKey 错误或 TRTC 服务未开通 | 检查 `LLMConfig.APIKey`；确认 TRTC 控制台已开通 AI 对话能力 |\n| 非 localhost 访问**无声音或麦克风不可用** | WebRTC 安全策略要求 HTTPS | 运行 `./start.sh --https` 自动生成自签证书并启用 HTTPS；首次访问浏览器点击\"高级→继续前往\" |\n| 公网 IP 访问**页面打不开** | 防火墙未放行端口 | 确认服务器防火墙/安全组已放行 8080 端口（TCP）|\n| 端口 8080 被占用 | 其他进程占用 | `start.sh` 会自动检测并询问是否终止 |\n| 浏览器控制台报 CORS 错误 | 前后端不同源 | 确保前端页面由 Flask 提供（同源）；不要用 `file://` 打开 HTML |\n\n---\n\n## 速查参考\n\n### 后端 API（`POST /action` + `Action` 请求头）\n\n| Action | 职责 |\n|--------|------|\n| `join` | 签发 UserSig（用户/机器人/数字人），下发关键词/告别语/数字人开关 |\n| `StartAIConversation` | 组装参数调用 TRTC OpenAPI 启动 AI 对话 |\n| `StopAIConversation` | 兜底停止（正常走 FarewellAndStop） |\n| `FarewellAndStop` | 推送告别语 + StopAfterPlay 一站式结束 |\n| `TransferAndStop` | 推送转接提示语 + StopAfterPlay 一站式结束 |\n\n### 核心设计模式（详见 `references/architecture.md`）\n\n| 模式 | 要点 |\n|------|------|\n| StopAfterPlay 一站式结束 | `ControlAIConversation` + `StopAfterPlay=true`，TTS 播完自动停止 |\n| 文字输入跳过 ASR | `type: 20000` 自定义消息直送 LLM |\n| 中英文词边界匹配 | 中文用非中文字符边界，英文用 `\\b` |\n| 增量/累积自适应字幕 | 自动检测 TRTC 下发模式 |\n| 机器人退房 + AI 状态双保险 | `REMOTE_USER_LEAVE` + `state=5` |\n| 数字人可选降级 | `AvatarConfig` 三项齐全启用，否则纯语音 |\n\n### 技术栈\n\nPython 3.8+ · Flask · tencentcloud-sdk-python · 原生 JS · TRTC Web SDK v5 · YAML（envyaml）\n\n### 安全\n\n- `env.yaml` 含密钥，加入 `.gitignore`，切勿提交\n- UserSig 服务端签发，密钥不暴露给前端\n- 生产环境添加 `/action` 接口鉴权\n- 非 localhost 部署必须 HTTPS（WebRTC 安全策略）\n\nFile v1.2.5:README.md\n\n# TRTC AI Customer Service Skill\n\nEnglish | [简体中文](README_ZH.md)\n\n> Rapidly scaffold a production-ready AI customer service Web application powered by [Tencent RTC Conversational AI](https://trtc.io/solutions/conversational-ai) — voice & text dual-mode, trilingual, with built-in e-commerce workflows.\n\n## Highlights\n\n| Capability | Description |\n|-----------|-------------|\n| **Real-time Voice** | Bidirectional WebRTC audio between end-user and cloud-hosted AI Bot |\n| **Text Fallback** | Bypass ASR — send typed messages directly to the LLM pipeline |\n| **Trilingual i18n** | Chinese / Cantonese / English across UI, STT, TTS, and SystemPrompt |\n| **E-commerce Workflows** | Order inquiry, returns & exchanges, shipping tracking, promotions |\n| **Digital Avatar** | Optional virtual human rendering; graceful degradation to pure voice |\n| **Session Lifecycle** | Keyword-triggered farewell, human agent transfer, auto-idle timeout |\n| **Service Rating** | 4-dimension post-session evaluation |\n\n## Installation\n\nThis is a **portable Agent Skill** (a `SKILL.md` + `scripts/` + `references/` + `assets/` bundle). Install it to your tool's skills directory and the agent will auto-discover it.\n\n### OpenClaw\n\nChoose the install location based on your needs:\n\n| Location | Scope | Command |\n|----------|-------|---------|\n| `<workspace>/skills/` | Current workspace, highest priority | `git clone https://github.com/jerryang-cool/trtc-ai-customer-service-skill.git skills/trtc-ai-customer-service` |\n| `~/.agents/skills/` | Personal, effective across workspaces | `git clone https://github.com/jerryang-cool/trtc-ai-customer-service-skill.git ~/.agents/skills/trtc-ai-customer-service` |\n| `~/.openclaw/skills/` | Global, visible to all agents | `git clone https://github.com/jerryang-cool/trtc-ai-customer-service-skill.git ~/.openclaw/skills/trtc-ai-customer-service` |\n\nInvoke via natural language (\"help me build an AI customer service\") or slash command `/trtc-ai-customer-service`.\n\n> See [OpenClaw Skills documentation](https://docs.openclaw.ai/tools/skills) for more details.\n\n### CodeBuddy\n\nSettings → Skills → **Import Skill**, then point to this repository's directory. Once imported, mention keywords such as *\"AI customer service\"*, *\"e-commerce support\"*, or *\"TRTC + AI\"* to activate.\n\n### Claude Code\n\n```bash\n# User-level (available across all projects)\ngit clone <repo-url> ~/.claude/skills/trtc-ai-customer-service\n\n# OR project-level (commit to repo, share with team)\ngit clone <repo-url> .claude/skills/trtc-ai-customer-service\n```\n\nClaude Code auto-discovers skills via `description` matching. Invoke implicitly (\"help me build an AI customer service\") or explicitly via `/trtc-ai-customer-service`.\n\n### OpenAI Codex CLI\n\n```bash\n# User-level\ngit clone <repo-url> ~/.codex/skills/trtc-ai-customer-service\n\n# OR project-level\ngit clone <repo-url> .agents/skills/trtc-ai-customer-service\n```\n\nCodex auto-detects new skills on next session. Invoke implicitly via natural language, or explicitly via `$trtc-ai-customer-service`.\n\n### Cursor\n\n```bash\n# Skill bundle: drop into Cursor's skills directory\ngit clone <repo-url> ~/.cursor/skills/trtc-ai-customer-service\n```\n\nThe `.cursor/rules/trtc-ai-customer-service.mdc` inside this repo follows the 2026 MDC format (Agent Requested mode) — Cursor's Agent loads it on demand based on the description.\n\n> **Legacy `.cursorrules` users**: Cursor silently ignores `.cursorrules` in Agent mode since 2026. This skill ships only the modern `.cursor/rules/*.mdc` format.\n\n## Quick Start\n\n```bash\n# 1. Generate a new project\npython scripts/scaffold.py ./my-shop --name \"CloudShop\" --name-en \"CloudShop Mall\"\n\n# 2. Launch (first run enters interactive credential wizard)\ncd ./my-shop && ./start.sh\n\n# 3. Open http://localhost:8080\n```\n\n## Architecture\n\n```\n┌─────────────────────────────────┐\n│  Browser  (TRTC Web SDK v5)     │\n│  WebRTC audio + custom messages │\n└──────────────┬──────────────────┘\n               │\n       ┌───────▼───────┐\n       │   TRTC Room   │\n       │  ASR → LLM →  │  Cloud-hosted AI pipeline\n       │      TTS       │  (zero LLM calls on your server)\n       └───────┬────────┘\n               │ OpenAPI (TC3-HMAC-SHA256)\n       ┌───────▼────────┐\n       │  Flask Backend  │  UserSig signing\n       │   (app.py)      │  + OpenAPI relay only\n       └─────────────────┘\n```\n\n## Tech Stack\n\n| Layer | Technology |\n|-------|-----------|\n| Backend | Python 3.8+ · Flask · tencentcloud-sdk-python |\n| Frontend | Vanilla JS · TRTC Web SDK v5 · CSS custom properties |\n| AI Engine | TRTC ConversationAI (cloud ASR → LLM → TTS) |\n| Auth | HMAC-SHA256 UserSig (server-side only) |\n| Config | YAML via `envyaml` with env-var interpolation |\n\n## Project Layout\n\n```\ntrtc-ai-customer-service-skill/\n├── SKILL.md              # Skill entry — used by CodeBuddy / Claude Code / Codex CLI\n├── .cursor/\n│   └── rules/\n│       └── trtc-ai-customer-service.mdc  # Cursor 2026 MDC format\n├── LICENSE               # MIT\n├── CHANGELOG.md          # Version history\n├── README.md             # English documentation (this file)\n├── README_ZH.md          # 中文文档\n├── scripts/\n│   └── scaffold.py       # One-command project generator\n├── references/\n│   ├── architecture.md   # System design & backend integration\n│   ├── config-guide.md   # Full configuration reference\n│   └── frontend-guide.md # TRTC Web SDK integration guide\n└── assets/               # Template files shipped by scaffold\n```\n\n## References\n\n- [Tencent RTC Console](https://console.trtc.io/)\n- [Conversational AI Solution](https://trtc.io/solutions/conversational-ai)\n- [LLM Configuration Guide](https://trtc.io/document/68338?product=conversationalai)\n- [TTS Voice Configuration](https://trtc.io/document/79682?product=conversationalai)\n\n## License\n\nReleased under the [MIT License](LICENSE).\n\nFile v1.2.5:_meta.json\n\n{\n  \"ownerId\": \"kn7c55va424ew234devca4r09186sb9y\",\n  \"slug\": \"trtc-ai-customer-service\",\n  \"version\": \"1.2.5\",\n  \"publishedAt\": 1779801012564\n}\n\nFile v1.2.5:references/architecture.md\n\n# TRTC AI 智能客服 - 架构设计参考\n\n## 目录\n\n1. [系统架构](#系统架构)\n2. [项目结构](#项目结构)\n3. [后端实现详解](#后端实现详解)\n4. [认证流程](#认证流程)\n5. [核心设计模式](#核心设计模式)\n6. [依赖清单](#依赖清单)\n7. [启动与部署](#启动与部署)\n\n---\n\n## 系统架构\n\n### 三平面模型\n\n```\n┌─────────────────────────────────────────────────┐\n│              浏览器 (TRTC Web SDK v5)              │\n│                                                   │\n│   音频流 (WebRTC)   自定义消息 (字幕/状态/文字)       │\n└───────────┬─────────────────┬─────────────────────┘\n            │                 │\n            ▼                 ▼\n┌───────────────────────────────────────────────────┐\n│                  TRTC Room (云端)                   │\n│                                                     │\n│   ASR ──► LLM ──► TTS ──► 推回房间                  │\n│                                                     │\n│              TRTC AI Bot (云端实例)                   │\n└───────────┬─────────────────────────────────────────┘\n            │ OpenAPI (TC3-HMAC-SHA256)\n            ▼\n┌───────────────────────────────────────────────────┐\n│   Flask 后端 (app.py)                               │\n│   - UserSig 签发                                    │\n│   - TRTC OpenAPI 中转                               │\n│   - 零 LLM 调用                                     │\n└─────────────────────────────────────────────────────┘\n```\n\n关键洞察：**后端完全不调用 LLM**。LLM 推理由 TRTC 云端 AI Bot 内部完成。后端只做两件事：\n1. 签发 UserSig（用于 TRTC 房间鉴权）\n2. 中转 TRTC OpenAPI 请求（启动/停止/控制 AI 对话）\n\n### 消息类型\n\n| type | 方向 | 内容 |\n|------|------|------|\n| `10000` | 云→端 | 字幕（用户 ASR 结果 + AI 回复文本） |\n| `10001` | 云→端 | AI 状态（聆听/思考/说话/打断/结束） |\n| `20000` | 端→云 | 文字输入（跳过 ASR 直送 LLM） |\n| `20001` | 端→云 | 手动打断 |\n\n---\n\n## 项目结构\n\n```\nproject/\n├── app.py                        # Flask 主入口（~296 行，5 个 Action 处理器）\n├── config_loader.py              # 配置加载器（Region/TTS/STT 映射）\n├── trtc_signer.py                # UserSig 三套签发封装\n├── TLSSigAPIv2.py                # 腾讯云官方 TRTC HMAC 鉴权库（不修改）\n├── env.example.yaml              # 配置模板\n├── env.yaml                      # 实际配置（.gitignore 排除）\n├── requirements.txt              # 4 个 Python 依赖\n├── start.sh / start.bat          # 一键启动脚本\n├── templates/\n│   └── customer_service.html     # 主页面（配置侧边栏 + 聊天区 + 评分弹窗）\n├── static/\n│   ├── app.js                    # 前端核心交互逻辑\n│   ├── i18n.js                   # 国际化字典（zh/yue/en）\n│   └── avatars/                  # 客服头像\n└── docs/\n    └── PARAMS.md                 # 参数配置详解\n```\n\n---\n\n## 后端实现详解\n\n### 初始化\n\n```python\n# 加载配置\nconfig = AppConfig(\"env.yaml\")\nsigner = TRTCSigner(config.sdkappid, config.trtc_secret)\n\n# 初始化 TRTC OpenAPI 客户端\n_cred = credential.Credential(config.secret_id, config.secret_key)\n_http = HttpProfile()\n_http.endpoint = config.trtc_endpoint  # 按 Region 自动切换\n_client_profile = ClientProfile()\n_client_profile.httpProfile = _http\ntrtc_api = trtc_client.TrtcClient(_cred, config.trtc_region, _client_profile)\n```\n\n### 路由设计\n\n仅 2 个路由，极简：\n- `GET /` → 渲染主页面\n- `POST /action` → 统一 API 调度，通过 `Action` 请求头区分\n\n### Action 处理器详解\n\n#### handle_join(data)\n\n签发三套 UserSig 并下发配置：\n\n```python\ndef handle_join(data):\n    user_id = data.get(\"userid\")\n    sigs = signer.sign_trio(user_id)     # 用户 + 机器人 + 数字人\n    avatar_enabled = config.is_avatar_enabled()\n    return {\n        \"sdkappid\": sigs[\"sdkappid\"],\n        \"userid\": sigs[\"user_id\"],\n        \"usersig\": sigs[\"user_sig\"],\n        \"robot_userid\": sigs[\"robot_user_id\"],\n        \"robot_usersig\": sigs[\"robot_user_sig\"],\n        \"avatar_userid\": sigs[\"avatar_user_id\"] if avatar_enabled else \"\",\n        \"avatar_usersig\": sigs[\"avatar_user_sig\"] if avatar_enabled else \"\",\n        \"avatar_available\": avatar_enabled,\n        \"end_keywords\": config.all_end_keywords(),        # 三语结束关键词\n        \"farewell_message\": {...},                         # 三语告别语\n        \"transfer_keywords\": config.all_transfer_keywords(),  # 三语转人工关键词\n        \"transfer_message\": {...},                         # 三语转接提示\n    }\n```\n\n#### handle_start_ai_conversation(body)\n\n组装 5 大配置块并调用 TRTC OpenAPI：\n\n```python\ndef handle_start_ai_conversation(body):\n    lang = body[\"AgentConfig\"][\"Lang\"]          # zh/yue/en\n    use_avatar = body.get(\"UseAvatar\", False)\n\n    # 1. AgentConfig：机器人身份 + 对话参数\n    agent_cfg = {\n        \"UserId\": body[\"AgentConfig\"][\"UserId\"],\n        \"UserSig\": body[\"AgentConfig\"][\"UserSig\"],\n        \"TargetUserId\": body[\"AgentConfig\"][\"TargetUserId\"],\n        \"MaxIdleTime\": 60,\n        \"WelcomeMessage\": config.welcome_message(lang),\n        \"TurnDetectionMode\": 3,                 # 语义断句\n        \"TurnDetection\": {\"SemanticEagerness\": \"auto\"},\n        \"SubtitleMode\": 1,                      # 句子级字幕\n        \"InterruptMode\": interrupt_mode,         # 0=智能/1=手动\n        \"InterruptSpeechDuration\": interrupt_speech_duration,\n    }\n\n    # 2. STTConfig：语音识别\n    stt_cfg = {\n        \"Language\": get_stt_language(lang),      # zh / zh-TW / en\n        \"VadLevel\": vad_level,\n        \"VadSilenceTime\": vad_silence_time,\n    }\n\n    # 3. LLMConfig：从 env.yaml 读取\n    llm_cfg = config.llm_config(lang)            # 按语言切换 SystemPrompt\n\n    # 4. TTSConfig\n    if use_avatar:\n        tts_cfg = {\"TTSType\": \"dummy\"}           # 数字人模式：TTS 由数字人引擎处理\n    else:\n        tts_cfg = {\n            \"TTSType\": \"flow\",\n            \"Model\": \"flow_01_turbo\",\n            \"VoiceId\": get_voice_id(lang, gender),  # 6 种组合\n        }\n\n    # 5. AvatarConfig（可选）\n    if use_avatar:\n        params[\"AvatarConfig\"] = json.dumps({...})\n\n    # 调用 TRTC OpenAPI\n    req = models.StartAIConversationRequest()\n    req.from_json_string(json.dumps(params))\n    resp = trtc_api.StartAIConversation(req)\n    return json.loads(resp.to_json_string())     # 包含 TaskId\n```\n\n#### handle_farewell_and_stop(body)\n\n一站式结束的核心实现：\n\n```python\ndef handle_farewell_and_stop(body):\n    params = {\n        \"TaskId\": task_id,\n        \"Command\": \"ServerPushText\",\n        \"ServerPushText\": {\n            \"Text\": farewell_text,           # 告别语\n            \"Interrupt\": True,               # 打断当前播报\n            \"StopAfterPlay\": True,           # TTS 播完后自动停止任务\n            \"AddHistory\": True,\n            \"Priority\": 0,\n        },\n    }\n    req = models.ControlAIConversationRequest()\n    req.from_json_string(json.dumps(params))\n    resp = trtc_api.ControlAIConversation(req)\n```\n\n`StopAfterPlay=True` 的优势：\n- 不需要前端估算 TTS 播报时长\n- 不需要 setTimeout 轮询\n- 服务端确保播报完整后才停止任务\n\n#### handle_transfer_and_stop(body)\n\n与 FarewellAndStop 结构相同，只是文本换成转接提示语。\n\n### 错误处理\n\n```python\nclass ErrorCode(enum.Enum):\n    InvalidParameter = \"InvalidParameter\"\n\ndef err(code: ErrorCode, msg: str):\n    return {\"Response\": {\"Error\": {\"Code\": code.name, \"Message\": msg}}}\n```\n\n所有异常统一返回腾讯云 API 风格的错误结构。`TaskNotExist` 错误被静默处理（幂等设计）。\n\n---\n\n## 认证流程\n\n### UserSig 签发\n\n```python\nclass TRTCSigner:\n    def sign_trio(self, user_id):\n        # 一次签发 3 套 UserSig：\n        # - user_id           → 真人用户\n        # - {user_id}_robot   → AI 机器人\n        # - {user_id}_avatar  → 数字人\n        robot_id = f\"{user_id}_robot\"\n        avatar_id = f\"{user_id}_avatar\"\n        return {\n            \"user_sig\": self.sign(user_id),\n            \"robot_user_sig\": self.sign(robot_id),\n            \"avatar_user_sig\": self.sign(avatar_id),\n        }\n```\n\n底层使用 `TLSSigAPIv2`（HMAC-SHA256 + zlib 压缩 + Base64URL 编码），这是腾讯云官方库，无需修改。\n\n### 认证流程\n\n1. 前端调用 `join` → 后端用 TRTC SECRET 签发 UserSig\n2. UserSig 随响应返回前端 → 前端用于 TRTC SDK 鉴权进房\n3. 同时签发机器人的 UserSig → 传递给 `StartAIConversation` API\n4. TRTC SECRET 和 CloudAPI 密钥永远不暴露给前端\n\n---\n\n## 核心设计模式\n\n### 1. ServerPushText + StopAfterPlay\n\n这是最重要的设计模式。通过一次 `ControlAIConversation` 调用实现\"播报告别语后自动结束\"：\n\n```\n前端: FarewellAndStop(TaskId, Lang)\n  → 后端: ControlAIConversation(ServerPushText + StopAfterPlay=true)\n    → TRTC 云端: 打断当前播报 → TTS 播报告别语 → 自动 StopAIConversation\n      → 机器人退房\n        → 前端: onRobotLeave → 用户退房 → 显示评分\n```\n\n### 2. 语音/文字双模混合\n\n同一个对话中可以无缝切换：\n- **语音模式**：麦克风 → TRTC 音频流 → 云端 ASR → LLM\n- **文字模式**：输入框 → `sendCustomMessage(type: 20000)` → 直接 LLM（跳过 ASR）\n\n### 3. 配置驱动的多语言\n\n一份配置文件 (`env.yaml`) 驱动全链路国际化：\n- `LLMConfig.SystemPrompt` / `SystemPromptYue` / `SystemPromptEn`\n- `WelcomeMessage.zh/yue/en`\n- `EndKeywords.zh/yue/en`\n- `FarewellMessage.zh/yue/en`\n- `TransferKeywords.zh/yue/en`\n- `TransferMessage.zh/yue/en`\n\n后端根据前端传入的 `lang` 参数自动切换。\n\n### 4. 数字人可选降级\n\n```python\ndef is_avatar_enabled(self):\n    avatar = self.env.get(\"AvatarConfig\")\n    return bool(avatar.get(\"Appkey\")) and bool(avatar.get(\"AccessToken\")) \\\n        and bool(avatar.get(\"VirtualmanProjectId\"))\n```\n\n三项全填 → 启用数字人，TTSConfig 设为 `dummy`（由数字人引擎处理 TTS）\n任一为空 → 降级为纯语音 + `flow` TTS\n\n---\n\n## 依赖清单\n\n```\nFlask==3.0.3                     # Web 框架\nenvyaml==1.10.211231             # YAML 配置加载（支持环境变量）\nloguru==0.7.3                    # 结构化日志\ntencentcloud-sdk-python==3.1.93  # 腾讯云 OpenAPI SDK（含 TRTC 模块）\n```\n\n极简：仅 4 个直接依赖。\n\n---\n\n## 启动与部署\n\n### 开发环境\n\n```bash\n# 一键启动（推荐）\n./start.sh\n\n# 手动启动\npython3 -m venv venv\nsource venv/bin/activate\npip install -r requirements.txt\npython app.py\n```\n\n`start.sh` 自动完成：\n1. 检测 Python >= 3.8\n2. 首次从 `env.example.yaml` 生成 `env.yaml` 并暂停提示填密钥\n3. 创建 venv 虚拟环境\n4. 检测并安装依赖（清华镜像优先）\n5. 端口冲突检测\n6. 启动 Flask 服务（端口 8080）\n\n### 生产部署建议\n\n| 项目 | 开发 | 生产 |\n|------|------|------|\n| 服务器 | Flask 内置 | Gunicorn + Nginx |\n| 协议 | HTTP | HTTPS（必须，WebRTC 要求） |\n| 鉴权 | 无 | `/action` 添加 Token/Session 鉴权 |\n| 日志 | loguru 文件 | 接入 ELK / 腾讯云 CLS |\n| 配置 | env.yaml | 环境变量或密钥管理服务 |\n\nFile v1.2.5:references/config-guide.md\n\n# TRTC AI 智能客服 - 配置参数完全指南\n\n## 目录\n\n1. [配置文件结构](#配置文件结构)\n2. [部署区域](#部署区域)\n3. [腾讯云 API 密钥](#腾讯云-api-密钥)\n4. [TRTC 应用凭据](#trtc-应用凭据)\n5. [LLM 配置](#llm-配置)\n6. [欢迎语](#欢迎语)\n7. [数字人配置](#数字人配置)\n8. [关键词与告别语](#关键词与告别语)\n9. [转人工关键词与提示语](#转人工关键词与提示语)\n10. [TTS 音色映射表](#tts-音色映射表)\n11. [STT 引擎映射表](#stt-引擎映射表)\n12. [固定默认参数](#固定默认参数)\n13. [UI 可调参数](#ui-可调参数)\n14. [Region 切换机制](#region-切换机制)\n\n---\n\n## 配置文件结构\n\n配置使用 YAML 格式，通过 `envyaml` 库加载（支持环境变量替换）。\n\n```yaml\n# env.yaml 完整模板\nDeployment:\n  Region: intl\n\nCloudAPI:\n  SECRET_ID: your-secret-id\n  SECRET_KEY: your-secret-key\n\nTRTC:\n  SDKAPPID: 0\n  SECRET: your-trtc-secret\n\nLLMConfig:\n  LLMType: openai\n  Model: your-model-name\n  APIKey: your-api-key\n  APIUrl: your-llm-api-url\n  Timeout: 5.0\n  History: 20\n  Temperature: 0.3\n  SystemPrompt: |\n    你是一名专业的客服助手...\n  SystemPromptYue: |\n    你係一名專業嘅客服助手...\n  SystemPromptEn: |\n    You are a professional customer service assistant...\n\nWelcomeMessage:\n  zh: 您好，我是AI客服小助手...\n  yue: 您好，我係AI客服小助手...\n  en: \"Hello! I'm your AI assistant...\"\n\nAvatarConfig:\n  AvatarType: tencent\n  Appkey: \"\"\n  AccessToken: \"\"\n  VirtualmanProjectId: \"\"\n\nEndKeywords:\n  zh: [拜拜, 再见, 挂了, ...]\n  yue: [拜拜, 再見, 收線啦, ...]\n  en: [bye, goodbye, see you, ...]\n\nFarewellMessage:\n  zh: 感谢您的咨询，再见！\n  yue: 多謝您嘅諮詢，再見！\n  en: Thank you for your inquiry. Goodbye!\n\nTransferKeywords:\n  zh: [转人工, 人工客服, 找人工, ...]\n  yue: [轉人工, 人工客服, 搵人工, ...]\n  en: [transfer, human agent, real person, ...]\n\nTransferMessage:\n  zh: 好的，正在为您转接人工客服，请稍候...\n  yue: 好嘅，正在為您轉接人工客服，請稍候...\n  en: Sure, transferring you to a human agent, please wait...\n```\n\n---\n\n## 部署区域\n\n```yaml\nDeployment:\n  Region: intl   # intl / cn\n```\n\n| 值 | 说明 | TRTC Endpoint | TRTC Region |\n|----|------|---------------|-------------|\n| `intl` | 国际站账号（默认） | `trtc.intl.tencentcloudapi.com` | `ap-singapore` |\n| `cn` | 中国大陆账号 | `trtc.tencentcloudapi.com` | `ap-guangzhou` |\n\nRegion 决定了 TRTC OpenAPI 的请求域名和地域参数。\n\n---\n\n## 腾讯云 API 密钥\n\n```yaml\nCloudAPI:\n  SECRET_ID: your-secret-id\n  SECRET_KEY: your-secret-key\n```\n\n用于 TRTC OpenAPI 的 TC3-HMAC-SHA256 签名。在腾讯云控制台获取（[国际站](https://console.intl.cloud.tencent.com/cam/capi) | [中国站](https://console.cloud.tencent.com/cam/capi)）。\n\n**安全提醒**：这是主账号密钥，生产环境建议使用子账号并限制权限。\n\n---\n\n## TRTC 应用凭据\n\n```yaml\nTRTC:\n  SDKAPPID: 0\n  SECRET: your-trtc-secret\n```\n\n- `SDKAPPID`：TRTC 应用 ID，在 TRTC 控制台创建（[国际站](https://console.trtc.io/app) | [中国站](https://console.cloud.tencent.com/trtc/app)）\n- `SECRET`：用于生成 UserSig 的密钥\n\n---\n\n## LLM 配置\n\n```yaml\nLLMConfig:\n  LLMType: openai             # LLM 协议类型（目前仅支持 openai）\n  Model: your-model-name      # 模型名称\n  APIKey: your-api-key        # LLM API Key\n  APIUrl: your-llm-api-url    # LLM API 端点（兼容 OpenAI /v1/chat/completions 协议）\n  Timeout: 5.0                # 超时时间（秒）\n  History: 20                 # 上下文轮数\n  Temperature: 0.3            # 温度参数（越低越确定）\n  SystemPrompt: |             # 中文系统提示词\n    你是一名专业的客服助手...\n  SystemPromptYue: |          # 粤语系统提示词（可选，默认用中文）\n    你係一名專業嘅客服助手...\n  SystemPromptEn: |           # 英文系统提示词（可选，默认用中文）\n    You are a professional customer service assistant...\n```\n\n**重要**：LLM 由 TRTC 云端 AI Bot 调用，不是本项目后端调用。配置会通过 `StartAIConversation` API 传递给 TRTC 服务端。\n\n> ⚠️ **数据隐私提示**：您的 LLM 配置（包括 APIKey、APIUrl、SystemPrompt）以及用户对话内容将通过 TRTC 云端服务转发给 LLM 提供商。请确保：\n> 1. 了解所选 LLM 提供商的数据处理政策\n> 2. 不要在 SystemPrompt 中包含敏感的业务数据\n> 3. 在生产环境中评估是否需要数据脱敏措施\n\n### 支持的 LLM 提供商\n\n任何兼容 OpenAI 协议的 LLM 均可使用，详见官方 LLM 配置指南（[国际站](https://trtc.io/document/68338?product=conversationalai) | [中国站](https://cloud.tencent.com/document/product/647/115413)）：\n\n**推荐：TokenHub（腾讯云统一 LLM 网关，开箱即用）**\n\n| 配置项 | 国际站 (intl) | 中国站 (cn) |\n|--------|-------------|------------|\n| LLMType | `openai` | `openai` |\n| APIUrl | `https://tokenhub-intl.tencentcloudmaas.com/v1/chat/completions` | `https://tokenhub.tencentmaas.com/v1/chat/completions` |\n| Model | `deepseek-v4-flash`（推荐） | `deepseek-v4-flash`（推荐） |\n| APIKey | [国际站 TokenHub 控制台](https://console.intl.cloud.tencent.com/tokenhub) 获取 | [中国站 TokenHub 控制台](https://console.cloud.tencent.com/tokenhub) 获取 |\n\n也支持其他兼容 OpenAI 协议的 LLM：\n- OpenAI / Azure OpenAI\n- DeepSeek\n- 通义千问\n- 其他支持 `/v1/chat/completions` 的服务\n\n### SystemPrompt 编写建议\n\n1. 明确角色定位和服务范围\n2. 限制回复长度（语音场景建议 3 句以内）\n3. 要求纯文本输出（不使用 Markdown、括号注释等）\n4. 说明何时建议转人工\n5. 如有订单等结构化信息，说明如何使用\n\n---\n\n## 欢迎语\n\n```yaml\nWelcomeMessage:\n  zh: 您好，欢迎来到云尚商城！我是AI客服小助手...\n  yue: 您好，歡迎嚟到雲尚商城！我係AI客服小助手...\n  en: \"Welcome to CloudShop Mall! I'm your AI assistant...\"\n```\n\nAI Bot 进入房间后自动播报的第一条消息。\n\n---\n\n## 数字人配置\n\n```yaml\nAvatarConfig:\n  AvatarType: tencent                    # 数字人类型\n  Appkey: \"\"                             # 数字人 Appkey\n  AccessToken: \"\"                        # 数字人 Access Token\n  VirtualmanProjectId: \"\"                # 数字人项目 ID\n```\n\n**启用条件**：`Appkey`、`AccessToken`、`VirtualmanProjectId` 三项全部非空。\n\n**降级机制**：任一为空 → 自动降级为纯语音模式。UI 上\"数字人\"选项会变为灰色不可选。\n\n启用数字人后：\n- `TTSConfig.TTSType` 自动设为 `dummy`（TTS 由数字人引擎处理）\n- 前端会显示数字人视频流\n\n---\n\n## 关键词与告别语\n\n```yaml\nEndKeywords:\n  zh: [拜拜, 再见, 先挂了, 先这样, 就这样吧, 没事了, 挂了, 不需要了, 不用了]\n  yue: [拜拜, 再見, 收線啦, 咁先啦, 唔使啦, 冇事啦, 掛啦]\n  en: [bye, goodbye, see you, that's all, thanks bye, gotta go, i'm done]\n\nFarewellMessage:\n  zh: 感谢您光临云尚商城，祝您购物愉快，再见！\n  yue: 多謝您光臨雲尚商城，祝您購物愉快，再見！\n  en: Thank you for visiting CloudShop Mall. Happy shopping and goodbye!\n```\n\n**匹配机制**：前端实时检测用户 ASR 文本，命中关键词后触发 `FarewellAndStop`。\n\n**词边界匹配**：\n- 英文：`\\b关键词\\b`（标准词边界）\n- 中文：`(^|[^\\u4e00-\\u9fa5A-Za-z0-9])关键词(?=[^\\u4e00-\\u9fa5A-Za-z0-9]|$)`\n\n这样\"再见面\"不会误触发\"再见\"，\"我没事了\"不会误触发\"没事了\"。\n\n---\n\n## 转人工关键词与提示语\n\n```yaml\nTransferKeywords:\n  zh: [转人工, 人工客服, 找人工, 转接人工, 真人客服, 找真人]\n  yue: [轉人工, 人工客服, 搵人工, 轉接人工, 真人客服]\n  en: [transfer, human agent, real person, talk to a person, speak to someone]\n\nTransferMessage:\n  zh: 好的，正在为您转接人工客服，请稍候...\n  yue: 好嘅，正在為您轉接人工客服，請稍候...\n  en: Sure, transferring you to a human agent, please wait...\n```\n\n命中转人工关键词后：\n1. 调用 `TransferAndStop` 播报转接提示语\n2. 前端显示模拟排队进度\n3. 排队\"失败\"后恢复 AI 对话（MVP 中为模拟，生产环境对接真实呼叫中心）\n\n---\n\n## TTS 音色映射表\n\n| 语言 | 性别 | VoiceId | 描述 |\n|------|------|---------|------|\n| zh（中文） | female | `female-kefu-xiaoyue` | 客服小悦 |\n| zh（中文） | male | `male-kefu-xiaoxu` | 客服小徐 |\n| yue（粤语） | female | `v-female-k3P8sL0Q` | 粤语女声 |\n| yue（粤语） | male | `v-male-L4s7PqZ9` | 粤语男声 |\n| en（英文） | female | `v-female-Z3x9LmQ2` | 理性女讲解 |\n| en（英文） | male | `v-male-Q6p8ZxL3` | 阳光男演讲 |\n\nTTS 引擎：`flow` 类型 + `flow_01_turbo` 模型（延迟最低）。\n\n> 如需自定义 TTS 音色（更换声线、调整语速语调等），请参考官方 TTS 音色配置指南（[国际站](https://trtc.io/document/79682?product=conversationalai) | [中国站](https://cloud.tencent.com/document/product/647/115414)）。\n\n---\n\n## STT 引擎映射表\n\n| 语言 | STTConfig.Language | 说明 |\n|------|-------------------|------|\n| zh（中文） | `zh` | 中文识别 |\n| yue（粤语） | `zh-TW` | 粤语识别 |\n| en（英文） | `en` | 英文识别 |\n\n后端根据前端传入的 `lang` 参数自动选择 STT 引擎。\n\n---\n\n## 固定默认参数\n\n这些参数在后端代码中硬编码，用户无需配置：\n\n| 参数 | 值 | 理由 |\n|------|------|------|\n| `TurnDetection.SemanticEagerness` | `auto` | 平衡响应速度与耐心 |\n| `FilterOneWord` | `false` | 保留\"嗯\"\"好\"等应答词 |\n| `WelcomeMessagePriority` | `0` | 欢迎语可被打断 |\n| `MaxIdleTime` | `60s` | 客服标准空闲超时 |\n| `SubtitleMode` | `1` | 句子级同步下发（非逐字） |\n| `FilterBracketsContent` | `1`(zh) / `2`(en) | 过滤 LLM 输出的舞台说明 |\n| `LLMConfig.Streaming` | `true` | 流式输出，首字延迟最优 |\n\n---\n\n## UI 可调参数\n\n用户可通过前端 UI 调整：\n\n| 参数 | 控件 | 取值 | 默认 | 含义 |\n|------|------|------|------|------|\n| 语言 | 顶部栏切换 | zh/yue/en | 跟随浏览器 | 联动 STT/TTS/Prompt/UI 文案 |\n| 对话模式 | Pill 切换 | voice/avatar | voice | 需 AvatarConfig 三项全填 |\n| 客服角色 | 头像卡片 | female/male | female | 影响 TTS VoiceId |\n| 断句模式 | Pill 切换 | 3(语义)/0(VAD) | 3 | 语义断句用 LLM 判断 |\n| 打断模式 | Pill 切换 | 0(智能)/1(手动) | 0 | 智能=自动检测打断 |\n| VAD 时长 | 滑块 | 240-2000ms | 600ms | 越小响应越快 |\n| 远场人声抑制 | 滑块 | 0-5 | 3 | 越高抑制越强 |\n| 打断时长 | 滑块 | 240-2000ms | 600ms | 仅智能打断模式 |\n\n---\n\n## Region 切换机制\n\n`config_loader.py` 中的实现：\n\n```python\nREGION_PROFILES = {\n    \"cn\": {\n        \"trtc_endpoint\": \"trtc.tencentcloudapi.com\",\n        \"trtc_region\": \"ap-guangzhou\",\n    },\n    \"intl\": {\n        \"trtc_endpoint\": \"trtc.intl.tencentcloudapi.com\",\n        \"trtc_region\": \"ap-singapore\",\n    },\n}\n```\n\n配置加载时根据 `Deployment.Region` 自动选择对应的 endpoint 和 region。未知 region 值会回退到 `intl`。\n\nFile v1.2.5:references/frontend-guide.md\n\n# TRTC AI 智能客服 - 前端集成指南\n\n## 目录\n\n1. [TRTC Web SDK 集成](#trtc-web-sdk-集成)\n2. [对话生命周期](#对话生命周期)\n3. [消息处理协议](#消息处理协议)\n4. [文字输入（跳过 ASR）](#文字输入跳过-asr)\n5. [关键词检测](#关键词检测)\n6. [字幕增量/累积自适应](#字幕增量累积自适应)\n7. [转人工流程](#转人工流程)\n8. [UI 组件结构](#ui-组件结构)\n9. [国际化系统](#国际化系统)\n10. [状态管理](#状态管理)\n\n---\n\n## TRTC Web SDK 集成\n\n### 引入 SDK\n\n```html\n<script src=\"https://web.sdk.qcloud.com/trtc/webrtc/v5/dist/trtc.js\"></script>\n```\n\n### 初始化与进房\n\n```javascript\n// 创建 TRTC 客户端\nconst trtcClient = TRTC.create();\n\n// 绑定事件\ntrtcClient.on(TRTC.EVENT.CUSTOM_MESSAGE, handleMessage);           // 字幕 + AI 状态\ntrtcClient.on(TRTC.EVENT.REMOTE_USER_LEAVE, onRobotLeave);         // 机器人退房\ntrtcClient.on(TRTC.EVENT.REMOTE_VIDEO_AVAILABLE, onVideoAvailable); // 数字人视频流\n\n// 进房\nawait trtcClient.enterRoom({\n    roomId: roomId,        // 房间号（数字）\n    scene: 'rtc',\n    sdkAppId: sdkAppId,\n    userId: userId,\n    userSig: userSig,\n});\n\n// 开麦克风（纯语音场景）\nawait trtcClient.startLocalAudio();\n```\n\n### 退房\n\n```javascript\nawait trtcClient.stopLocalAudio();\nawait trtcClient.exitRoom();\ntrtcClient.destroy();\n```\n\n---\n\n## 对话生命周期\n\n```\nidle → connecting → active → ending → idle\n                              ↓\n                         transferring → idle\n```\n\n### 启动流程（startCall）\n\n```javascript\nasync function startCall() {\n    STATE.callState = 'connecting';\n\n    // 1. join：获取 UserSig\n    const joinData = await postAction('join', { userid: STATE.userId });\n    STATE.sdkAppId = joinData.sdkappid;\n    STATE.userSig = joinData.usersig;\n    STATE.robotUserId = joinData.robot_userid;\n    STATE.robotUserSig = joinData.robot_usersig;\n    STATE.endKeywords = joinData.end_keywords;\n    STATE.farewellMessage = joinData.farewell_message;\n    STATE.transferKeywords = joinData.transfer_keywords;\n    STATE.avatarAvailable = joinData.avatar_available;\n\n    // 2. 创建 TRTC 客户端并进房\n    trtcClient = TRTC.create();\n    bindEvents(trtcClient);\n    await trtcClient.enterRoom({ roomId, scene: 'rtc', sdkAppId, userId, userSig });\n    await trtcClient.startLocalAudio();\n\n    // 3. StartAIConversation\n    const startData = await postAction('StartAIConversation', {\n        RoomId: STATE.roomId,\n        AgentConfig: {\n            UserId: STATE.robotUserId,\n            UserSig: STATE.robotUserSig,\n            TargetUserId: STATE.userId,\n            Lang: USER_CFG.lang,\n        },\n        UserConfig: {\n            InterruptMode: USER_CFG.interruptMode,\n            InterruptSpeechDuration: USER_CFG.interruptSpeechDuration,\n            VadLevel: USER_CFG.vadLevel,\n            VadSilenceTime: USER_CFG.vadSilenceTime,\n            Gender: STATE.gender,\n        },\n        UseAvatar: STATE.useAvatar,\n        AvatarConfig: STATE.useAvatar ? {\n            AvatarUserID: STATE.avatarUserId,\n            AvatarUserSig: STATE.avatarUserSig,\n        } : undefined,\n    });\n    STATE.taskId = startData.TaskId;\n    STATE.callState = 'active';\n}\n```\n\n### 结束流程（farewellAndEnd）\n\n```javascript\nasync function farewellAndEnd() {\n    STATE.callState = 'ending';\n\n    // 1. 发送 FarewellAndStop\n    await postAction('FarewellAndStop', {\n        TaskId: STATE.taskId,\n        Lang: USER_CFG.lang,\n    });\n\n    // 2. 等待机器人退房（onRobotLeave 回调）\n    // 3. 退房\n    await cleanupRoom();\n\n    // 4. 显示评分弹窗\n    showRatingOverlay();\n}\n```\n\n### 机器人退房回调\n\n```javascript\nfunction onRobotLeave(event) {\n    const { userId } = event;\n    if (userId === STATE.robotUserId || userId === STATE.avatarUserId) {\n        if (STATE.callState === 'ending' || STATE.callState === 'transferring') {\n            cleanupRoom();\n        }\n    }\n}\n```\n\n---\n\n## 消息处理协议\n\n所有云端消息通过 `TRTC.EVENT.CUSTOM_MESSAGE` 事件接收：\n\n```javascript\nfunction handleMessage(event) {\n    const { data } = event;\n    const msg = JSON.parse(new TextDecoder().decode(data));\n\n    switch (msg.type) {\n        case 10000:  // 字幕\n            handleSubtitle(msg);\n            break;\n        case 10001:  // AI 状态\n            handleAIState(msg);\n            break;\n    }\n}\n```\n\n### type: 10000 - 字幕消息\n\n```json\n{\n    \"type\": 10000,\n    \"sender\": \"user_xxx_robot\",\n    \"payload\": {\n        \"roundid\": \"round_123\",\n        \"userid\": \"user_xxx\",       // 发言者\n        \"text\": \"你好，请问...\",\n        \"end\": false                 // true=该轮结束\n    }\n}\n```\n\n**区分用户和 AI**：\n- `payload.userid === STATE.userId` → 用户的 ASR 文本\n- `payload.userid !== STATE.userId` → AI 的回复文本\n\n### type: 10001 - AI 状态\n\n```json\n{\n    \"type\": 10001,\n    \"payload\": {\n        \"state\": 1,         // 1=聆听 2=思考 3=说话 4=打断 5=结束\n        \"roundid\": \"round_123\"\n    }\n}\n```\n\n| state | 含义 | 前端响应 |\n|-------|------|----------|\n| 1 | 聆听 | 显示\"聆听中...\" |\n| 2 | 思考 | 显示 typing 动画 |\n| 3 | 说话 | 更新语音状态指示 |\n| 4 | 打断 | 标记当前回复被打断 |\n| 5 | 结束 | 触发结束流程 |\n\n---\n\n## 文字输入（跳过 ASR）\n\n使用 `type: 20000` 自定义消息协议，文字直接发送到 LLM：\n\n```javascript\nfunction sendTextMessage(text) {\n    const message = {\n        type: 20000,\n        sender: STATE.userId,\n        receiver: [STATE.robotUserId],\n        payload: {\n            id: crypto.randomUUID(),\n            message: text,\n            timestamp: Date.now(),\n        },\n    };\n\n    trtcClient.sendCustomMessage({\n        cmdId: 2,\n        data: new TextEncoder().encode(JSON.stringify(message)).buffer,\n    });\n}\n```\n\n**关键点**：\n- `cmdId: 2` 是固定值\n- `receiver` 指定机器人 userId\n- 文本跳过 ASR 引擎，直接送入 LLM，适合不便说话场景\n- 用户发送文字后可无缝切回语音模式\n\n---\n\n## 关键词检测\n\n### 构建正则\n\n```javascript\nfunction buildKeywordRegex(keywords) {\n    if (!keywords || keywords.length === 0) return null;\n\n    const patterns = keywords.map(kw => {\n        const escaped = kw.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n        const hasChineseChar = /[\\u4e00-\\u9fa5]/.test(kw);\n\n        if (hasChineseChar) {\n            // 中文：两侧非中文字母数字边界\n            return `(^|[^\\\\u4e00-\\\\u9fa5A-Za-z0-9])${escaped}(?=[^\\\\u4e00-\\\\u9fa5A-Za-z0-9]|$)`;\n        } else {\n            // 英文：标准词边界\n            return `\\\\b${escaped}\\\\b`;\n        }\n    });\n\n    return new RegExp(patterns.join('|'), 'i');\n}\n```\n\n### 检测触发\n\n```javascript\nfunction detectEndKeyword(text) {\n    const lang = USER_CFG.lang;\n    const keywords = STATE.endKeywords[lang] || [];\n    const regex = buildKeywordRegex(keywords);\n    return regex && regex.test(text);\n}\n\n// 在用户 ASR 文本结束时检测\nif (payload.end && payload.userid === STATE.userId) {\n    if (detectEndKeyword(payload.text)) {\n        farewellAndEnd();\n    } else if (detectTransferKeyword(payload.text)) {\n        triggerTransfer();\n    }\n}\n```\n\n---\n\n## 字幕增量/累积自适应\n\nTRTC 下发字幕可能是增量或累积模式，前端自动适配：\n\n```javascript\nfunction processSubtitleText(roundId, newText) {\n    const accumulated = STATE.aiRoundText[roundId] || '';\n\n    if (newText.startsWith(accumulated)) {\n        // 累积模式：新文本是旧文本的超集\n        STATE.aiRoundText[roundId] = newText;\n    } else {\n        // 增量模式：新文本是新增部分\n        STATE.aiRoundText[roundId] = accumulated + newText;\n    }\n\n    return STATE.aiRoundText[roundId];\n}\n```\n\n---\n\n## 转人工流程\n\n```javascript\nasync function triggerTransfer() {\n    STATE.callState = 'transferring';\n\n    // 1. 播报转接提示语\n    await postAction('TransferAndStop', {\n        TaskId: STATE.taskId,\n        Lang: USER_CFG.lang,\n    });\n\n    // 2. 等待机器人退房\n    // 3. 显示排队进度弹窗\n    showTransferOverlay();\n\n    // 4. 模拟排队（MVP）\n    await simulateQueueProgress();\n\n    // 5. 排队失败 → 恢复 AI 对话（或对接真实呼叫中心）\n    restartAIConversation();\n}\n```\n\n---\n\n## UI 组件结构\n\n```\n┌─────────────────────────────────────────────────┐\n│  Top Bar                                          │\n│  [☰ 侧边栏] [AI 电商客服]      [🌐 简体中文 ▼]     │\n├──────────┬──────────────────────────────────────┤\n│          │                                       │\n│ Sidebar  │  Main Area                            │\n│          │                                       │\n│ ┌──────┐ │  ┌────────────────────────────────┐  │\n│ │对话模式│ │  │  Agent Select Area              │  │\n│ │断句模式│ │  │  [👩 女客服]  [👨 男客服]         │  │\n│ │打断模式│ │  │       [开始对话]                 │  │\n│ │VAD设置│ │  └────────────────────────────────┘  │\n│ │       │ │                                      │\n│ └──────┘ │  ┌────────────────────────────────┐  │\n│          │  │  Chat Messages                   │  │\n│          │  │  [AI] 您好，请问有什么...          │  │\n│          │  │          [User] 查询订单          │  │\n│          │  │  [AI] 好的，请提供订单号...        │  │\n│          │  └────────────────────────────────┘  │\n│          │                                      │\n│          │  ┌────────────────────────────────┐  │\n│          │  │  Input Bar                       │  │\n│          │  │  [⌨️/🎤] [📦订单] [🔁转人工] [📞挂断] │  │\n│          │  └────────────────────────────────┘  │\n├──────────┴──────────────────────────────────────┤\n│  Overlays: 评分弹窗 / 订单面板 / 转人工弹窗      │\n└─────────────────────────────────────────────────┘\n```\n\n### CSS 设计要点\n\n- **CSS 变量系统**：`--primary`、`--bg`、`--surface` 等统一管理主题色\n- **响应式**：768px 断点移动端适配，侧边栏可折叠\n- **动效**：消息入场 `fadeInUp`、typing dots、评分弹窗滑入\n- **无外部依赖**：纯 CSS + 内联 SVG 图标\n\n---\n\n## 国际化系统\n\n### 架构\n\n```javascript\n// i18n.js - IIFE 模式\n(function() {\n    const DICT = {\n        zh: { appName: 'AI 电商客服', ... },\n        yue: { appName: 'AI 電商客服', ... },\n        en: { appName: 'AI Customer Service', ... },\n    };\n\n    window.I18N = {\n        getLang() { ... },           // 从 localStorage 读取\n        setLang(lang) { ... },       // 保存到 localStorage + 广播事件\n        t(key, params) { ... },      // 翻译（支持 {param} 模板替换）\n    };\n})();\n```\n\n### 使用\n\n```javascript\n// HTML 中\n<span data-i18n=\"appName\"></span>\n\n// JS 中\nconst text = I18N.t('tipConnecting');  // \"正在连接...\"\nconst text = I18N.t('duration', { time: '5:30' });  // \"通话时长: 5:30\"\n\n// 语言切换监听\nwindow.addEventListener('langChange', (e) => {\n    const lang = e.detail.lang;\n    updateAllTexts();\n});\n```\n\n### 语言存储\n\n- `localStorage` key: `cs_lang`\n- 默认值：跟随浏览器 `navigator.language`\n- 切换通过 `CustomEvent('langChange')` 事件广播\n\n---\n\n## 状态管理\n\n前端使用简单的全局对象管理状态：\n\n```javascript\nconst STATE = {\n    // 连接状态\n    userId: '',\n    roomId: 0,\n    sdkAppId: 0,\n    userSig: '',\n    robotUserId: '',\n    robotUserSig: '',\n    avatarUserId: '',\n    avatarUserSig: '',\n\n    // 功能开关\n    avatarAvailable: false,\n    useAvatar: false,\n    gender: 'female',\n\n    // 通话状态\n    callState: 'idle',       // idle | connecting | active | ending | transferring\n    taskId: null,\n    startTime: null,\n    muted: false,\n    aiSpeaking: false,\n\n    // 关键词（从 join 响应获取）\n    endKeywords: { zh: [], yue: [], en: [] },\n    farewellMessage: { zh: '', yue: '', en: '' },\n    transferKeywords: { zh: [], yue: [], en: [] },\n    transferMessage: { zh: '', yue: '', en: '' },\n\n    // 消息管理\n    messages: [],             // 消息气泡列表\n    typingMsgId: null,        // AI typing 状态\n    aiRoundText: {},          // roundid → 累积文本\n    aiRoundLast: {},          // roundid → 上一次文本（去重）\n    aiRoundMsgId: {},         // roundid → 消息气泡 ID\n};\n\nconst USER_CFG = {\n    lang: I18N.getLang(),\n    mode: 'voice',            // voice | avatar\n    inputMode: 'voice',       // voice | text\n    interruptMode: 0,         // 0=智能打断 1=手动打断\n    interruptSpeechDuration: 600,\n    vadLevel: 3,\n    vadSilenceTime: 600,\n    turnDetectionMode: 3,     // 3=语义断句 0=VAD断句\n};\n```\n\n### HTTP 请求封装\n\n```javascript\nasync function postAction(action, body = {}) {\n    const resp = await fetch('/action', {\n        method: 'POST',\n        headers: {\n            'Content-Type': 'application/json',\n            'Action': action,\n        },\n        body: JSON.stringify(body),\n    });\n    const data = await resp.json();\n    if (data.Response?.Error) {\n        throw new Error(data.Response.Error.Message);\n    }\n    return data;\n}\n```\n\nFile v1.2.5:README_ZH.md\n\n# TRTC AI 电商客服 Skill\n\n[English](README.md) | 简体中文\n\n> 基于 [腾讯云 TRTC Conversational AI 解决方案](https://cloud.tencent.com/document/product/647/110584) 快速搭建生产级 AI 电商客服 Web 应用 — 语音与文字双通道、三语国际化、内置电商业务流程。\n\n## 核心能力\n\n| 能力 | 说明 |\n|------|------|\n| **实时语音** | 终端用户与云端 AI Bot 之间的双向 WebRTC 音频通信 |\n| **文字降级** | 跳过 ASR，将键盘输入直接送达 LLM 处理链路 |\n| **三语国际化** | 中文 / 粤语 / 英文全覆盖：UI、STT、TTS、SystemPrompt |\n| **电商业务流** | 订单查询、退换货处理、物流追踪、优惠活动咨询 |\n| **数字人可选** | 可选虚拟形象渲染，未配置时优雅降级为纯语音 |\n| **会话生命周期** | 关键词触发告别、转人工、空闲超时自动结束 |\n| **服务评分** | 会话结束后 4 维度评价 |\n\n## 安装方式\n\n本项目是一个**便携式 Agent Skill**（包含 `SKILL.md` + `scripts/` + `references/` + `assets/` 的标准结构）。安装到对应工具的 skills 目录即可被自动发现。\n\n### OpenClaw\n\n根据需要选择安装位置：\n\n| 位置 | 作用域 | 命令 |\n|------|--------|------|\n| `<workspace>/skills/` | 当前工作区，优先级最高 | `git clone https://github.com/jerryang-cool/trtc-ai-customer-service-skill.git skills/trtc-ai-customer-service` |\n| `~/.agents/skills/` | 个人级，跨工作区生效 | `git clone https://github.com/jerryang-cool/trtc-ai-customer-service-skill.git ~/.agents/skills/trtc-ai-customer-service` |\n| `~/.openclaw/skills/` | 全局共享，所有 agent 可见 | `git clone https://github.com/jerryang-cool/trtc-ai-customer-service-skill.git ~/.openclaw/skills/trtc-ai-customer-service` |\n\n安装后通过自然语言（如\"帮我做个 AI 客服\"）或斜杠命令 `/trtc-ai-customer-service` 调用。\n\n> 更多信息参见 [OpenClaw Skills 官方文档](https://docs.openclaw.ai/zh-CN/tools/skills)。\n\n### CodeBuddy\n\n设置 → Skills → **导入 Skill**，选择本仓库目录。导入后，在对话中提及 *\"AI 客服\"*、*\"电商客服\"*、*\"TRTC + AI\"* 等关键词即自动激活。\n\n### Claude Code\n\n```bash\n# 用户级（跨项目可用）\ngit clone <repo-url> ~/.claude/skills/trtc-ai-customer-service\n\n# 或项目级（提交到仓库，团队共享）\ngit clone <repo-url> .claude/skills/trtc-ai-customer-service\n```\n\nClaude Code 通过 `description` 字段自动匹配触发。隐式调用（如\"帮我做个 AI 客服\"）或显式调用 `/trtc-ai-customer-service` 均可。\n\n### OpenAI Codex CLI\n\n```bash\n# 用户级\ngit clone <repo-url> ~/.codex/skills/trtc-ai-customer-service\n\n# 或项目级\ngit clone <repo-url> .agents/skills/trtc-ai-customer-service\n```\n\nCodex 在下次会话启动时自动检测新 skill。隐式调用（自然语言）或显式调用 `$trtc-ai-customer-service` 均可。\n\n### Cursor\n\n```bash\n# 投放到 Cursor skills 目录\ngit clone <repo-url> ~/.cursor/skills/trtc-ai-customer-service\n```\n\n仓库内 `.cursor/rules/trtc-ai-customer-service.mdc` 遵循 2026 MDC 格式（Agent Requested 模式），Cursor 的 Agent 模式会按 description 按需加载。\n\n> **从 `.cursorrules` 升级**：Cursor 自 2026 年起在 Agent 模式下静默忽略 `.cursorrules`。本 Skill 仅提供新的 `.cursor/rules/*.mdc` 格式。\n\n## 快速开始\n\n```bash\n# 1. 生成新项目\npython scripts/scaffold.py ./my-shop --name \"云尚商城\"\n\n# 2. 启动（首次运行进入交互式密钥配置向导）\ncd ./my-shop && ./start.sh\n\n# 3. 浏览器访问 http://localhost:8080\n```\n\n## 架构\n\n```\n┌─────────────────────────────────┐\n│  浏览器  (TRTC Web SDK v5)       │\n│  WebRTC 音频 + 自定义消息         │\n└──────────────┬──────────────────┘\n               │\n       ┌───────▼───────┐\n       │   TRTC 房间    │\n       │  ASR → LLM →  │  云端 AI 处理链路\n       │      TTS       │  (后端零 LLM 调用)\n       └───────┬────────┘\n               │ OpenAPI (TC3-HMAC-SHA256)\n       ┌───────▼────────┐\n       │  Flask 后端     │  UserSig 签发\n       │   (app.py)      │  + OpenAPI 中转\n       └─────────────────┘\n```\n\n## 技术栈\n\n| 层 | 技术 |\n|----|------|\n| 后端 | Python 3.8+ · Flask · tencentcloud-sdk-python |\n| 前端 | 原生 JS · TRTC Web SDK v5 · CSS 自定义属性 |\n| AI 引擎 | TRTC ConversationAI（云端 ASR → LLM → TTS） |\n| 鉴权 | HMAC-SHA256 UserSig（仅服务端签发） |\n| 配置 | YAML，通过 `envyaml` 支持环境变量插值 |\n\n## 项目结构\n\n```\ntrtc-ai-customer-service-skill/\n├── SKILL.md              # Skill 入口 — 供 CodeBuddy / Claude Code / Codex CLI 识别\n├── .cursor/\n│   └── rules/\n│       └── trtc-ai-customer-service.mdc  # Cursor 2026 MDC 格式\n├── LICENSE               # MIT 许可证\n├── CHANGELOG.md          # 版本历史\n├── README.md             # English documentation\n├── README_ZH.md          # 中文文档（本文件）\n├── scripts/\n│   └── scaffold.py       # 一键项目生成器\n├── references/\n│   ├── architecture.md   # 系统设计与后端集成\n│   ├── config-guide.md   # 完整配置参考\n│   └── frontend-guide.md # TRTC Web SDK 集成指南\n└── assets/               # 脚手架附带的模板文件\n```\n\n## 参考链接\n\n- [TRTC 控制台](https://console.cloud.tencent.com/trtc/app)\n- [Conversational AI 解决方案](https://cloud.tencent.com/document/product/647/110584)\n- [LLM 配置指南](https://cloud.tencent.com/document/product/647/115413)\n- [TTS 音色配置指南](https://cloud.tencent.com/document/product/647/115414)\n\n## 许可证\n\n基于 [MIT 许可证](LICENSE) 发布。\n\nFile v1.2.5:skill-card.md\n\n## Description:\n\nBuilds an AI e-commerce customer service web app with TRTC Conversational AI, real-time voice and text modes, Chinese, English, and Cantonese support, order workflows, shipping tracking, returns, promotions, and optional digital avatar support.\n\nThis skill is ready for commercial/non-commercial use.\n\n## Publisher:\n\n[jerryang-cool](https://clawhub.ai/user/jerryang-cool)\n\n### License/Terms of Use:\n\nMIT-0\n\n## Use Case:\n\nDevelopers and engineers use this skill to scaffold or integrate a TRTC Conversational AI e-commerce customer service web app with voice, text, multilingual UI, order workflows, and optional digital avatar support.\n\n### Deployment Geography for Use:\n\nGlobal\n\n## Known Risks and Mitigations:\n\nRisk: The generated app exposes unauthenticated cloud-control and credential-issuing endpoints.\n\nMitigation: Add authentication, rate limits, and room or task ownership checks before customer-facing deployment.\n\nRisk: The generated configuration uses cloud API keys, TRTC secrets, and LLM keys that can affect billing and access if exposed.\n\nMitigation: Protect env.yaml, use least-privilege cloud credentials, and move production secrets into an approved secret-management system.\n\nRisk: The startup flow can offer to kill the process listening on port 8080.\n\nMitigation: Inspect the displayed PID and command before approving termination, and decline when the process is unknown.\n\nRisk: External SDKs and package dependencies may change over time.\n\nMitigation: Pin or self-host SDK assets and review dependency versions before deployment.\n\nRisk: LLM configuration and user conversation content may be routed through TRTC cloud services and the configured LLM provider.\n\nMitigation: Review provider data handling policies and apply data minimization or redaction for sensitive customer information.\n\n## Reference(s):\n\n- [ClawHub skill page](https://clawhub.ai/jerryang-cool/skills/trtc-ai-customer-service)\n- [Architecture reference](artifact/references/architecture.md)\n- [Configuration guide](artifact/references/config-guide.md)\n- [Frontend integration guide](artifact/references/frontend-guide.md)\n- [Tencent RTC console](https://console.trtc.io/)\n- [TRTC Conversational AI solution](https://trtc.io/solutions/conversational-ai)\n- [TRTC LLM configuration guide](https://trtc.io/document/68338?product=conversationalai)\n- [TRTC TTS voice configuration](https://trtc.io/document/79682?product=conversationalai)\n\n## Skill Output:\n\n**Output Type(s):** [text, markdown, code, shell commands, configuration, guidance, files]\n\n**Output Format:** [Markdown guidance with code snippets and shell commands, plus generated project files when scaffolding.]\n\n**Output Parameters:** [1D]\n\n**Other Properties Related to Output:** [May generate a Python Flask and vanilla JavaScript TRTC customer-service app, configuration templates, startup scripts, and integration guidance.]\n\n## Skill Version(s):\n\n1.2.5 (source: server evidence and SKILL.md frontmatter)\n\n## Ethical Considerations:\n\nUsers should evaluate whether this skill is appropriate for their environment, review any generated or modified files before relying on them, and apply their organization's safety, security, and compliance requirements before deployment.\n\nFile v1.2.5:assets/static/mock-orders.json\n\n[\n    {\n        \"id\": \"CS20260510001\",\n        \"name\": { \"zh\": \"无线降噪耳机 Pro\", \"yue\": \"無線降噪耳機 Pro\", \"en\": \"Wireless ANC Headphones Pro\" },\n        \"price\": { \"zh\": \"¥699\", \"yue\": \"HK$759\", \"en\": \"$96\" },\n        \"status\": \"shipped\",\n        \"date\": \"2026-05-10\",\n        \"emoji\": \"🎧\"\n    },\n    {\n        \"id\": \"CS20260508002\",\n        \"name\": { \"zh\": \"轻薄笔记本电脑 14寸\", \"yue\": \"輕薄筆記本電腦 14吋\", \"en\": \"Ultra-slim Laptop 14\\\"\" },\n        \"price\": { \"zh\": \"¥5,299\", \"yue\": \"HK$5,749\", \"en\": \"$729\" },\n        \"status\": \"delivered\",\n        \"date\": \"2026-05-08\",\n        \"emoji\": \"💻\"\n    },\n    {\n        \"id\": \"CS20260507003\",\n        \"name\": { \"zh\": \"智能手表 S9\", \"yue\": \"智能手錶 S9\", \"en\": \"Smart Watch S9\" },\n        \"price\": { \"zh\": \"¥1,299\", \"yue\": \"HK$1,409\", \"en\": \"$179\" },\n        \"status\": \"pending\",\n        \"date\": \"2026-05-07\",\n        \"emoji\": \"⌚\"\n    },\n    {\n        \"id\": \"CS20260505004\",\n        \"name\": { \"zh\": \"真皮双肩包\", \"yue\": \"真皮雙肩包\", \"en\": \"Genuine Leather Backpack\" },\n        \"price\": { \"zh\": \"¥399\", \"yue\": \"HK$433\", \"en\": \"$55\" },\n        \"status\": \"refunding\",\n        \"date\": \"2026-05-05\",\n        \"emoji\": \"🎒\"\n    },\n    {\n        \"id\": \"CS20260501005\",\n        \"name\": { \"zh\": \"空气炸锅 5L\", \"yue\": \"空氣炸鍋 5L\", \"en\": \"Air Fryer 5L\" },\n        \"price\": { \"zh\": \"¥259\", \"yue\": \"HK$281\", \"en\": \"$36\" },\n        \"status\": \"delivered\",\n        \"date\": \"2026-05-01\",\n        \"emoji\": \"🍳\"\n    }\n]\n\nArchive v1.2.4: 15 files, 87959 bytes\n\nFiles: assets/start.sh (30549b), assets/static/app.js (52830b), assets/static/i18n.js (14766b), assets/static/mock-orders.json (1525b), assets/templates/customer_service.html (62687b), assets/TLSSigAPIv2.py (16022b), README_ZH.md (6090b), README.md (6281b), references/architecture.md (12223b), references/config-guide.md (11425b), references/frontend-guide.md (14226b), scripts/scaffold.py (37555b), skill-card.md (2933b), SKILL.md (13938b), _meta.json (143b)\n\nFile v1.2.4:SKILL.md\n\n---\nname: trtc-ai-customer-service\nversion: 1.2.4\ndescription: |\n  Build an AI e-commerce customer service Web app with TRTC ConversationAI — real-time voice/text dual-mode, trilingual (Chinese/English/Cantonese), digital avatar optional. Covers order inquiry, returns, shipping tracking, and promotions.\n  基于腾讯云 TRTC Conversational AI 快速构建 AI 电商客服 Web 应用 — 实时语音/文字双模、中英粤三语、数字人可选。覆盖订单查询、退换货、物流追踪、商品咨询等场景。\nhomepage: https://github.com/jerryang-cool/trtc-ai-customer-service-skill\nmetadata:\n  openclaw:\n    emoji: \"🛍️\"\n    requires:\n      bins:\n        - python3\n---\n\n# TRTC AI 电商客服 Skill\n\n本 Skill 指导你基于腾讯云 TRTC Conversational AI 能力，快速构建 AI 电商客服 Web 应用。\n场景预置了订单查询、退换货处理、商品咨询、物流追踪、优惠活动等电商业务模块。\n\n## 触发条件\n\n当用户**表达构建/搭建/集成意图**时使用此 Skill：\n- \"做一个 AI 客服\" \"搭建电商客服\" \"帮我做个智能客服系统\" \"语音客服 demo\"\n- \"build an AI customer service\" \"e-commerce customer service app\"\n- \"TRTC ConversationAI\" \"TRTC + AI 客服\" \"TRTC e-commerce support\"\n- \"StartAIConversation\" \"StopAIConversation\" \"ControlAIConversation\"（TRTC API 名称）\n- \"数字人客服\" \"avatar customer service\"\n- \"实时语音 AI 对话\" \"ASR + LLM + TTS 客服\"\n\n**不应触发的场景**：\n- 用户仅在讨论客服概念，没有构建/开发意图\n- 用户询问通用 chat bot 方案，不需要语音能力或电商场景\n- 关键词如 \"voice bot\" \"chat bot\" 单独出现且无构建上下文\n\n## 架构总览\n\n```\n浏览器 (TRTC Web SDK v5)\n     ↕ 音频 (WebRTC) + 自定义消息 (字幕/状态/文字输入)\nTRTC Room\n     ↕ 内置 ASR → LLM → TTS → 推回房间\nTRTC AI Bot (云端)\n     ↕ OpenAPI (TC3-HMAC-SHA256)\nFlask 后端 (app.py)  —— 仅 UserSig 签发 + OpenAPI 中转\n```\n\n| 平面 | 通道 | 内容 |\n|------|------|------|\n| **媒体面** | WebRTC 音频流 | 用户麦克风 ↔ TRTC 房间 ↔ AI Bot |\n| **控制面** | HTTP `/action` | 前端 → Flask → TRTC OpenAPI |\n| **数据面** | TRTC 自定义消息 | 字幕(10000) / AI 状态(10001) / 文字输入(20000) / 打断(20001) |\n\n后端**完全不调用 LLM**——LLM 由 TRTC 云端 AI Bot 内部调用，后端只负责签发 UserSig 和中转 OpenAPI 请求。\n\n---\n\n## 工作流程\n\n根据用户需求选择合适的路径。\n\n### 路径 A：从零创建新项目（推荐）\n\n#### Step 1: 生成项目\n\n运行脚手架脚本：\n\n```bash\npython {baseDir}/scripts/scaffold.py <项目目录> [--name <商城名称>] [--name-en <English name>]\n```\n\n- `{baseDir}`：本 Skill 所在目录的绝对路径（由 Agent 自动替换为实际路径）\n- `--name`：商城名称（默认\"云尚商城\"），用于中文/粤语的 SystemPrompt、欢迎语、告别语、前端 UI\n- `--name-en`：英文商城名称（默认自动推导：中文名时为\"CloudShop Mall\"，英文名时与 `--name` 相同），用于英文 SystemPrompt、英文欢迎语/告别语\n- 默认支持中文/英文/粤语三语，无需手动指定语言\n- 脚本自动生成全部文件：后端 + 前端 + 头像 + 鉴权库 + 启动脚本，无需手动复制任何文件\n\n**检查点**：确认用户看到 `✅ 电商客服项目已生成到: xxx` 和完整文件列表，再继续。\n\n#### Step 2: 配置密钥\n\n引导用户运行启动脚本（**根据操作系统自动选择**：macOS/Linux 用 `./start.sh`，Windows 用 `start.bat`），首次运行会进入交互式引导：\n\n- [0/4] 选择部署区域（默认 `intl` 国际站，可选 `cn` 中国站）— 后续步骤会根据所选区域展示对应的控制台链接\n- [1/4] 腾讯云 API 密钥 → 脚本会展示对应区域的 [CAM 控制台](https://console.intl.cloud.tencent.com/cam/capi) 链接\n- [2/4] TRTC 应用凭据 → 脚本会展示对应区域的 [TRTC 控制台](https://console.trtc.io/app) 链接\n- [3/4] LLM 配置 → **建议优先使用 TokenHub**（腾讯云统一 LLM 网关，开箱即用）：\n  - `LLMConfig.LLMType`：`openai`（固定）\n  - `LLMConfig.Model`：`deepseek-v4-flash`（推荐）\n  - `LLMConfig.APIUrl`：\n    - 国际站：`https://tokenhub-intl.tencentcloudmaas.com/v1/chat/completions`\n    - 中国站：`https://tokenhub.tencentmaas.com/v1/chat/completions`\n  - `LLMConfig.APIKey`：在 TokenHub 控制台获取（[国际站](https://console.intl.cloud.tencent.com/tokenhub) | [中国站](https://console.cloud.tencent.com/tokenhub)）\n  - 也支持其他兼容 OpenAI 协议的 LLM，参考配置指南：[国际站](https://trtc.io/document/68338?product=conversationalai) | [中国站](https://cloud.tencent.com/document/product/647/115413)\n\n**检查点**：确认用户看到 `✓ 所有密钥已配置完成！`。如果有跳过项，提醒手动编辑 `env.yaml`。\n\n> **提示用户**：以上为最小必填项，启动成功后还有丰富的可定制选项（角色定制、商城名称、欢迎语、TTS 音色、关键词等），详见 Step 4。\n\n#### Step 3: 启动验证\n\n启动脚本会自动创建虚拟环境、安装依赖、启动服务。\n\n**验证标准**（告知用户逐项确认）：\n1. 终端显示 `🚀 启动 TRTC AI 智能客服` + 访问地址（公网服务器会自动检测公网 IP 并启用 HTTPS，显示 `https://<公网IP>:8080`；本地开发则显示 `http://localhost:8080`）\n2. 浏览器打开页面 → 能看到客服头像选择界面\n3. 选择客服 → 点击\"开始对话\" → 听到 AI 播报欢迎语\n4. 说话或打字 → AI 能正常回复\n\n#### Step 4: 定制化（可选）\n\n启动成功后，**主动告知用户**以下所有可定制项，引导按需修改：\n\n| 定制项 | 修改位置 | 说明 |\n|--------|---------|------|\n| **AI 客服角色** | 交互式引导 [4/4]（删除 `env.yaml` 后重新运行 `./start.sh`），或直接编辑 `env.yaml` → `SystemPrompt` / `SystemPromptYue` / `SystemPromptEn` | 预设品类 + 语气快速定制（见下方枚举表），也可手动编辑三语 SystemPrompt 做精细调整 |\n| **商城名称/品牌** | scaffold 的 `--name` / `--name-en` 参数 | 一键替换全链路品牌文案（三语 SystemPrompt、欢迎语、告别语、前端 UI） |\n| **欢迎语 / 告别语** | `env.yaml` → `WelcomeMessage` / `FarewellMessage`（`.zh` / `.yue` / `.en`） | AI 进房首条播报 / 关键词触发结束时播报 |\n| **LLM 模型** | `env.yaml` → `LLMConfig.Model` / `APIUrl` / `APIKey` | LLM 配置指南：[国际站](https://trtc.io/document/68338?product=conversationalai) \\| [中国站](https://cloud.tencent.com/document/product/647/115413) |\n| **TTS 音色** | `config_loader.py` → `TTS_VOICE_MAP` | TTS 音色配置指南：[国际站](https://trtc.io/document/79682?product=conversationalai) \\| [中国站](https://cloud.tencent.com/document/product/647/115414) |\n| **商品/订单数据** | `static/mock-orders.json`，或参考 `references/frontend-guide.md` 对接真实 API | JSON 格式含三语名称和价格，可替换为真实订单系统 |\n| **数字人** | `env.yaml` → `AvatarConfig` 三项 | 三项全填启用数字人视频模式，否则纯语音 |\n| **部署方式** | 自动检测公网 IP 启用 HTTPS；生产环境用 Gunicorn + Nginx + 正式证书 | WebRTC 要求 HTTPS；生产还需添加 `/action` 接口鉴权 |\n\n**AI 客服角色预设枚举值**（`start.sh` 交互式引导 [4/4]）：\n\n商城品类（影响 AI 的专业知识方向）：\n\n| 选项 | 品类 | AI 擅长方向 |\n|------|------|------------|\n| 1 | 综合电商（默认） | 通用电商场景，不修改 SystemPrompt |\n| 2 | 数码产品 | 参数对比、兼容性问题、保修政策、使用教程 |\n| 3 | 服装鞋帽 | 尺码推荐、面料材质、搭配建议、洗涤保养、退换尺码 |\n| 4 | 食品生鲜 | 保质期、储存方式、配送时效、食材产地、过敏原信息 |\n| 5 | 家居百货 | 商品尺寸规格、安装方式、材质说明、配送安装服务 |\n\n客服语气风格（影响 AI 的表达方式）：\n\n| 选项 | 风格 | 效果 |\n|------|------|------|\n| 1 | 亲切自然（默认） | 像朋友聊天，已内置于默认 SystemPrompt |\n| 2 | 专业严谨 | 用词准确规范，适合高端品牌/B2B |\n| 3 | 活泼可爱 | 轻松表达方式，适合年轻用户群体 |\n\n> 选择后自动注入三语 SystemPrompt（中文/粤语/英文同步）。如需更精细定制，直接编辑 `env.yaml` 中的 SystemPrompt 即可。\n\n### 路径 B：为现有项目集成 TRTC AI 对话\n\n#### Step 1: 了解现有架构\n\n询问并确认：\n- 后端语言和框架（Python/Node/Go/Java？）\n- 前端技术栈（React/Vue/原生 JS？已有 TRTC SDK？）\n- 集成范围：仅后端 API？还是含前端 UI？\n\n#### Step 2: 按需读取参考文档并输出代码\n\n根据用户技术栈，读取对应文档并**直接输出可集成的代码片段**：\n\n| 需求 | 读取文档 | 输出内容 |\n|------|----------|----------|\n| 后端 API | `references/architecture.md` | 用户语言的 5 个 Action 处理器代码（join / Start / Stop / Farewell / Transfer） |\n| 配置体系 | `references/config-guide.md` | 生成 `env.yaml` 模板 + 配置加载代码 |\n| 前端对话 UI | `references/frontend-guide.md` | TRTC SDK 进房 + 消息监听 + 字幕渲染代码 |\n\n**关键**：如果用户不是 Python 技术栈，需要将参考文档中的 Python 逻辑**翻译为用户的语言**（如 Node.js / Go / Java），核心逻辑不变。\n\n#### Step 3: 验证集成\n\n引导用户完成最小可用流程并逐步确认：\n1. 后端 `/action` 接口能正常响应（`curl -X POST /action -H \"Action: join\"` 返回 UserSig）\n2. 前端成功进入 TRTC 房间（控制台无报错）\n3. `StartAIConversation` 调用成功返回 TaskId\n4. 用户说话 → 听到 AI 回复（完整链路跑通）\n\n**如果卡在某一步**，参照下方 FAQ 表逐条排查。\n\n---\n\n## 常见问题排查\n\n当用户遇到问题时，按以下清单排查：\n\n| 现象 | 原因 | 解决方案 |\n|------|------|----------|\n| scaffold.py 报错退出 | Python 版本或参数错误 | 确认 Python 3.8+；检查输出目录路径是否合法 |\n| `start.sh` 报 Python 版本不够 | Python < 3.8 | 安装 Python 3.8+ |\n| venv 创建失败 | 缺少 `python3-venv` 包 | Ubuntu/Debian: `sudo apt install python3-venv`；macOS 自带 |\n| 依赖安装失败 | 网络问题 | `start.sh` 会自动 fallback 官方源；或手动 `pip install -r requirements.txt` |\n| `env.yaml` 解析报错 | YAML 缩进或格式错误 | 用在线 YAML 校验器检查；常见：冒号后缺空格、中文引号 |\n| 页面打开空白 | 静态文件缺失 | 确认 `static/app.js` 和 `templates/customer_service.html` 存在 |\n| 点\"开始对话\"无反应 | 密钥未填或填错 | 检查 `env.yaml` 中 SDKAPPID 不为 0、SECRET_ID/KEY 正确 |\n| 点\"开始对话\"提示**进房失败** | TRTC 进房参数异常 | 检查 `SDKAPPID` 是否正确填写；UserSig 是否校验失败（核对 `TRTC.SECRET`） |\n| 说话**无任何响应**（语音不可用） | 浏览器麦克风权限未授予或设备异常 | 检查浏览器地址栏麦克风权限；测试系统设备：录音机能否录到声音 |\n| 仅显示**本地字幕，AI 无回应** | LLM 服务异常 | 检查 `LLMConfig.APIKey` / `APIUrl` / `Model` 是否正确；确认 LLM 账户额度充足 |\n| AI 有字幕但**无语音播报** | TTS 服务异常 | 核对 TTS 参数（VoiceId、Language）；确认 TTS 套餐包资源充足 |\n| LLM **长时间不回复**或超时报错 | LLM Timeout | 调大 `env.yaml` → `LLMConfig.Timeout`（如 5.0 → 10.0） |\n| 进房成功但无欢迎语 | LLM APIKey 错误或 TRTC 服务未开通 | 检查 `LLMConfig.APIKey`；确认 TRTC 控制台已开通 AI 对话能力 |\n| 非 localhost 访问**无声音或麦克风不可用** | WebRTC 安全策略要求 HTTPS | 运行 `./start.sh --https` 自动生成自签证书并启用 HTTPS；首次访问浏览器点击\"高级→继续前往\" |\n| 公网 IP 访问**页面打不开** | 防火墙未放行端口 | 确认服务器防火墙/安全组已放行 8080 端口（TCP）|\n| 端口 8080 被占用 | 其他进程占用 | `start.sh` 会自动检测并询问是否终止 |\n| 浏览器控制台报 CORS 错误 | 前后端不同源 | 确保前端页面由 Flask 提供（同源）；不要用 `file://` 打开 HTML |\n\n---\n\n## 速查参考\n\n### 后端 API（`POST /action` + `Action` 请求头）\n\n| Action | 职责 |\n|--------|------|\n| `join` | 签发 UserSig（用户/机器人/数字人），下发关键词/告别语/数字人开关 |\n| `StartAIConversation` | 组装参数调用 TRTC OpenAPI 启动 AI 对话 |\n| `StopAIConversation` | 兜底停止（正常走 FarewellAndStop） |\n| `FarewellAndStop` | 推送告别语 + StopAfterPlay 一站式结束 |\n| `TransferAndStop` | 推送转接提示语 + StopAfterPlay 一站式结束 |\n\n### 核心设计模式（详见 `references/architecture.md`）\n\n| 模式 | 要点 |\n|------|------|\n| StopAfterPlay 一站式结束 | `ControlAIConversation` + `StopAfterPlay=true`，TTS 播完自动停止 |\n| 文字输入跳过 ASR | `type: 20000` 自定义消息直送 LLM |\n| 中英文词边界匹配 | 中文用非中文字符边界，英文用 `\\b` |\n| 增量/累积自适应字幕 | 自动检测 TRTC 下发模式 |\n| 机器人退房 + AI 状态双保险 | `REMOTE_USER_LEAVE` + `state=5` |\n| 数字人可选降级 | `AvatarConfig` 三项齐全启用，否则纯语音 |\n\n### 技术栈\n\nPython 3.8+ · Flask · tencentcloud-sdk-python · 原生 JS · TRTC Web SDK v5 · YAML（envyaml）\n\n### 安全\n\n- `env.yaml` 含密钥，加入 `.gitignore`，切勿提交\n- UserSig 服务端签发，密钥不暴露给前端\n- 生产环境添加 `/action` 接口鉴权\n- 非 localhost 部署必须 HTTPS（WebRTC 安全策略）\n\nFile v1.2.4:README.md\n\n# TRTC AI Customer Service Skill\n\nEnglish | [简体中文](README_ZH.md)\n\n> Rapidly scaffold a production-ready AI customer service Web application powered by [Tencent RTC Conversational AI](https://trtc.io/solutions/conversational-ai) — voice & text dual-mode, trilingual, with built-in e-commerce workflows.\n\n## Highlights\n\n| Capability | Description |\n|-----------|-------------|\n| **Real-time Voice** | Bidirectional WebRTC audio between end-user and cloud-hosted AI Bot |\n| **Text Fallback** | Bypass ASR — send typed messages directly to the LLM pipeline |\n| **Trilingual i18n** | Chinese / Cantonese / English across UI, STT, TTS, and SystemPrompt |\n| **E-commerce Workflows** | Order inquiry, returns & exchanges, shipping tracking, promotions |\n| **Digital Avatar** | Optional virtual human rendering; graceful degradation to pure voice |\n| **Session Lifecycle** | Keyword-triggered farewell, human agent transfer, auto-idle timeout |\n| **Service Rating** | 4-dimension post-session evaluation |\n\n## Installation\n\nThis is a **portable Agent Skill** (a `SKILL.md` + `scripts/` + `references/` + `assets/` bundle). Install it to your tool's skills directory and the agent will auto-discover it.\n\n### OpenClaw\n\nChoose the install location based on your needs:\n\n| Location | Scope | Command |\n|----------|-------|---------|\n| `<workspace>/skills/` | Current workspace, highest priority | `git clone https://github.com/jerryang-cool/trtc-ai-customer-service-skill.git skills/trtc-ai-customer-service` |\n| `~/.agents/skills/` | Personal, effective across workspaces | `git clone https://github.com/jerryang-cool/trtc-ai-customer-service-skill.git ~/.agents/skills/trtc-ai-customer-service` |\n| `~/.openclaw/skills/` | Global, visible to all agents | `git clone https://github.com/jerryang-cool/trtc-ai-customer-service-skill.git ~/.openclaw/skills/trtc-ai-customer-service` |\n\nInvoke via natural language (\"help me build an AI customer service\") or slash command `/trtc-ai-customer-service`.\n\n> See [OpenClaw Skills documentation](https://docs.openclaw.ai/tools/skills) for more details.\n\n### CodeBuddy\n\nSettings → Skills → **Import Skill**, then point to this repository's directory. Once imported, mention keywords such as *\"AI customer service\"*, *\"e-commerce support\"*, or *\"TRTC + AI\"* to activate.\n\n### Claude Code\n\n```bash\n# User-level (available across all projects)\ngit clone <repo-url> ~/.claude/skills/trtc-ai-customer-service\n\n# OR project-level (commit to repo, share with team)\ngit clone <repo-url> .claude/skills/trtc-ai-customer-service\n```\n\nClaude Code auto-discovers skills via `description` matching. Invoke implicitly (\"help me build an AI customer service\") or explicitly via `/trtc-ai-customer-service`.\n\n### OpenAI Codex CLI\n\n```bash\n# User-level\ngit clone <repo-url> ~/.codex/skills/trtc-ai-customer-service\n\n# OR project-level\ngit clone <repo-url> .agents/skills/trtc-ai-customer-service\n```\n\nCodex auto-detects new skills on next session. Invoke implicitly via natural language, or explicitly via `$trtc-ai-customer-service`.\n\n### Cursor\n\n```bash\n# Skill bundle: drop into Cursor's skills directory\ngit clone <repo-url> ~/.cursor/skills/trtc-ai-customer-service\n```\n\nThe `.cursor/rules/trtc-ai-customer-service.mdc` inside this repo follows the 2026 MDC format (Agent Requested mode) — Cursor's Agent loads it on demand based on the description.\n\n> **Legacy `.cursorrules` users**: Cursor silently ignores `.cursorrules` in Agent mode since 2026. This skill ships only the modern `.cursor/rules/*.mdc` format.\n\n## Quick Start\n\n```bash\n# 1. Generate a new project\npython scripts/scaffold.py ./my-shop --name \"CloudShop\" --name-en \"CloudShop Mall\"\n\n# 2. Launch (first run enters interactive credential wizard)\ncd ./my-shop && ./start.sh\n\n# 3. Open http://localhost:8080\n```\n\n## Architecture\n\n```\n┌─────────────────────────────────┐\n│  Browser  (TRTC Web SDK v5)     │\n│  WebRTC audio + custom messages │\n└──────────────┬──────────────────┘\n               │\n       ┌───────▼───────┐\n       │   TRTC Room   │\n       │  ASR → LLM →  │  Cloud-hosted AI pipeline\n       │      TTS       │  (zero LLM calls on your server)\n       └───────┬────────┘\n               │ OpenAPI (TC3-HMAC-SHA256)\n       ┌───────▼────────┐\n       │  Flask Backend  │  UserSig signing\n       │   (app.py)      │  + OpenAPI relay only\n       └─────────────────┘\n```\n\n## Tech Stack\n\n| Layer | Technology |\n|-------|-----------|\n| Backend | Python 3.8+ · Flask · tencentcloud-sdk-python |\n| Frontend | Vanilla JS · TRTC Web SDK v5 · CSS custom properties |\n| AI Engine | TRTC ConversationAI (cloud ASR → LLM → TTS) |\n| Auth | HMAC-SHA256 UserSig (server-side only) |\n| Config | YAML via `envyaml` with env-var interpolation |\n\n## Project Layout\n\n```\ntrtc-ai-customer-service-skill/\n├── SKILL.md              # Skill entry — used by CodeBuddy / Claude Code / Codex CLI\n├── .cursor/\n│   └── rules/\n│       └── trtc-ai-customer-service.mdc  # Cursor 2026 MDC format\n├── LICENSE               # MIT\n├── CHANGELOG.md          # Version history\n├── README.md             # English documentation (this file)\n├── README_ZH.md          # 中文文档\n├── scripts/\n│   └── scaffold.py       # One-command project generator\n├── references/\n│   ├── architecture.md   # System design & backend integration\n│   ├── config-guide.md   # Full configuration reference\n│   └── frontend-guide.md # TRTC Web SDK integration guide\n└── assets/               # Template files shipped by scaffold\n```\n\n## References\n\n- [Tencent RTC Console](https://console.trtc.io/)\n- [Conversational AI Solution](https://trtc.io/solutions/conversational-ai)\n- [LLM Configuration Guide](https://trtc.io/document/68338?product=conversationalai)\n- [TTS Voice Configuration](https://trtc.io/document/79682?product=conversationalai)\n\n## License\n\nReleased under the [MIT License](LICENSE).\n\nFile v1.2.4:_meta.json\n\n{\n  \"ownerId\": \"kn7c55va424ew234devca4r09186sb9y\",\n  \"slug\": \"trtc-ai-customer-service\",\n  \"version\": \"1.2.4\",\n  \"publishedAt\": 1779796837223\n}\n\nFile v1.2.4:references/architecture.md\n\n# TRTC AI 智能客服 - 架构设计参考\n\n## 目录\n\n1. [系统架构](#系统架构)\n2. [项目结构](#项目结构)\n3. [后端实现详解](#后端实现详解)\n4. [认证流程](#认证流程)\n5. [核心设计模式](#核心设计模式)\n6. [依赖清单](#依赖清单)\n7. [启动与部署](#启动与部署)\n\n---\n\n## 系统架构\n\n### 三平面模型\n\n```\n┌─────────────────────────────────────────────────┐\n│              浏览器 (TRTC Web SDK v5)              │\n│                                                   │\n│   音频流 (WebRTC)   自定义消息 (字幕/状态/文字)       │\n└───────────┬─────────────────┬─────────────────────┘\n            │                 │\n            ▼                 ▼\n┌───────────────────────────────────────────────────┐\n│                  TRTC Room (云端)                   │\n│                                                     │\n│   ASR ──► LLM ──► TTS ──► 推回房间                  │\n│                                                     │\n│              TRTC AI Bot (云端实例)                   │\n└───────────┬─────────────────────────────────────────┘\n            │ OpenAPI (TC3-HMAC-SHA256)\n            ▼\n┌───────────────────────────────────────────────────┐\n│   Flask 后端 (app.py)                               │\n│   - UserSig 签发                                    │\n│   - TRTC OpenAPI 中转                               │\n│   - 零 LLM 调用                                     │\n└─────────────────────────────────────────────────────┘\n```\n\n关键洞察：**后端完全不调用 LLM**。LLM 推理由 TRTC 云端 AI Bot 内部完成。后端只做两件事：\n1. 签发 UserSig（用于 TRTC 房间鉴权）\n2. 中转 TRTC OpenAPI 请求（启动/停止/控制 AI 对话）\n\n### 消息类型\n\n| type | 方向 | 内容 |\n|------|------|------|\n| `10000` | 云→端 | 字幕（用户 ASR 结果 + AI 回复文本） |\n| `10001` | 云→端 | AI 状态（聆听/思考/说话/打断/结束） |\n| `20000` | 端→云 | 文字输入（跳过 ASR 直送 LLM） |\n| `20001` | 端→云 | 手动打断 |\n\n---\n\n## 项目结构\n\n```\nproject/\n├── app.py                        # Flask 主入口（~296 行，5 个 Action 处理器）\n├── config_loader.py              # 配置加载器（Region/TTS/STT 映射）\n├── trtc_signer.py                # UserSig 三套签发封装\n├── TLSSigAPIv2.py                # 腾讯云官方 TRTC HMAC 鉴权库（不修改）\n├── env.example.yaml              # 配置模板\n├── env.yaml                      # 实际配置（.gitignore 排除）\n├── requirements.txt              # 4 个 Python 依赖\n├── start.sh / start.bat          # 一键启动脚本\n├── templates/\n│   └── customer_service.html     # 主页面（配置侧边栏 + 聊天区 + 评分弹窗）\n├── static/\n│   ├── app.js                    # 前端核心交互逻辑\n│   ├── i18n.js                   # 国际化字典（zh/yue/en）\n│   └── avatars/                  # 客服头像\n└── docs/\n    └── PARAMS.md                 # 参数配置详解\n```\n\n---\n\n## 后端实现详解\n\n### 初始化\n\n```python\n# 加载配置\nconfig = AppConfig(\"env.yaml\")\nsigner = TRTCSigner(config.sdkappid, config.trtc_secret)\n\n# 初始化 TRTC OpenAPI 客户端\n_cred = credential.Credential(config.secret_id, config.secret_key)\n_http = HttpProfile()\n_http.endpoint = config.trtc_endpoint  # 按 Region 自动切换\n_client_profile = ClientProfile()\n_client_profile.httpProfile = _http\ntrtc_api = trtc_client.TrtcClient(_cred, config.trtc_region, _client_profile)\n```\n\n### 路由设计\n\n仅 2 个路由，极简：\n- `GET /` → 渲染主页面\n- `POST /action` → 统一 API 调度，通过 `Action` 请求头区分\n\n### Action 处理器详解\n\n#### handle_join(data)\n\n签发三套 UserSig 并下发配置：\n\n```python\ndef handle_join(data):\n    user_id = data.get(\"userid\")\n    sigs = signer.sign_trio(user_id)     # 用户 + 机器人 + 数字人\n    avatar_enabled = config.is_avatar_enabled()\n    return {\n        \"sdkappid\": sigs[\"sdkappid\"],\n        \"userid\": sigs[\"user_id\"],\n        \"usersig\": sigs[\"user_sig\"],\n        \"robot_userid\": sigs[\"robot_user_id\"],\n        \"robot_usersig\": sigs[\"robot_user_sig\"],\n        \"avatar_userid\": sigs[\"avatar_user_id\"] if avatar_enabled else \"\",\n        \"avatar_usersig\": sigs[\"avatar_user_sig\"] if avatar_enabled else \"\",\n        \"avatar_available\": avatar_enabled,\n        \"end_keywords\": config.all_end_keywords(),        # 三语结束关键词\n        \"farewell_message\": {...},                         # 三语告别语\n        \"transfer_keywords\": config.all_transfer_keywords(),  # 三语转人工关键词\n        \"transfer_message\": {...},                         # 三语转接提示\n    }\n```\n\n#### handle_start_ai_conversation(body)\n\n组装 5 大配置块并调用 TRTC OpenAPI：\n\n```python\ndef handle_start_ai_conversation(body):\n    lang = body[\"AgentConfig\"][\"Lang\"]          # zh/yue/en\n    use_avatar = body.get(\"UseAvatar\", False)\n\n    # 1. AgentConfig：机器人身份 + 对话参数\n    agent_cfg = {\n        \"UserId\": body[\"AgentConfig\"][\"UserId\"],\n        \"UserSig\": body[\"AgentConfig\"][\"UserSig\"],\n        \"TargetUserId\": body[\"AgentConfig\"][\"TargetUserId\"],\n        \"MaxIdleTime\": 60,\n        \"WelcomeMessage\": config.welcome_message(lang),\n        \"TurnDetectionMode\": 3,                 # 语义断句\n        \"TurnDetection\": {\"SemanticEagerness\": \"auto\"},\n        \"SubtitleMode\": 1,                      # 句子级字幕\n        \"InterruptMode\": interrupt_mode,         # 0=智能/1=手动\n        \"InterruptSpeechDuration\": interrupt_speech_duration,\n    }\n\n    # 2. STTConfig：语音识别\n    stt_cfg = {\n        \"Language\": get_stt_language(lang),      # zh / zh-TW / en\n        \"VadLevel\": vad_level,\n        \"VadSilenceTime\": vad_silence_time,\n    }\n\n    # 3. LLMConfig：从 env.yaml 读取\n    llm_cfg = config.llm_config(lang)            # 按语言切换 SystemPrompt\n\n    # 4. TTSConfig\n    if use_avatar:\n        tts_cfg = {\"TTSType\": \"dummy\"}           # 数字人模式：TTS 由数字人引擎处理\n    else:\n        tts_cfg = {\n            \"TTSType\": \"flow\",\n            \"Model\": \"flow_01_turbo\",\n            \"VoiceId\": get_voice_id(lang, gender),  # 6 种组合\n        }\n\n    # 5. AvatarConfig（可选）\n    if use_avatar:\n        params[\"AvatarConfig\"] = json.dumps({...})\n\n    # 调用 TRTC OpenAPI\n    req = models.StartAIConversationRequest()\n    req.from_json_string(json.dumps(params))\n    resp = trtc_api.StartAIConversation(req)\n    return json.loads(resp.to_json_string())     # 包含 TaskId\n```\n\n#### handle_farewell_and_stop(body)\n\n一站式结束的核心实现：\n\n```python\ndef handle_farewell_and_stop(body):\n    params = {\n        \"TaskId\": task_id,\n        \"Command\": \"ServerPushText\",\n        \"ServerPushText\": {\n            \"Text\": farewell_text,           # 告别语\n            \"Interrupt\": True,               # 打断当前播报\n            \"StopAfterPlay\": True,           # TTS 播完后自动停止任务\n            \"AddHistory\": True,\n            \"Priority\": 0,\n        },\n    }\n    req = models.ControlAIConversationRequest()\n    req.from_json_string(json.dumps(params))\n    resp = trtc_api.ControlAIConversation(req)\n```\n\n`StopAfterPlay=True` 的优势：\n- 不需要前端估算 TTS 播报时长\n- 不需要 setTimeout 轮询\n- 服务端确保播报完整后才停止任务\n\n#### handle_transfer_and_stop(body)\n\n与 FarewellAndStop 结构相同，只是文本换成转接提示语。\n\n### 错误处理\n\n```python\nclass ErrorCode(enum.Enum):\n    InvalidParameter = \"InvalidParameter\"\n\ndef err(code: ErrorCode, msg: str):\n    return {\"Response\": {\"Error\": {\"Code\": code.name, \"Message\": msg}}}\n```\n\n所有异常统一返回腾讯云 API 风格的错误结构。`TaskNotExist` 错误被静默处理（幂等设计）。\n\n---\n\n## 认证流程\n\n### UserSig 签发\n\n```python\nclass TRTCSigner:\n    def sign_trio(self, user_id):\n        # 一次签发 3 套 UserSig：\n        # - user_id           → 真人用户\n        # - {user_id}_robot   → AI 机器人\n        # - {user_id}_avatar  → 数字人\n        robot_id = f\"{user_id}_robot\"\n        avatar_id = f\"{user_id}_avatar\"\n        return {\n            \"user_sig\": self.sign(user_id),\n            \"robot_user_sig\": self.sign(robot_id),\n            \"avatar_user_sig\": self.sign(avatar_id),\n        }\n```\n\n底层使用 `TLSSigAPIv2`（HMAC-SHA256 + zlib 压缩 + Base64URL 编码），这是腾讯云官方库，无需修改。\n\n### 认证流程\n\n1. 前端调用 `join` → 后端用 TRTC SECRET 签发 UserSig\n2. UserSig 随响应返回前端 → 前端用于 TRTC SDK 鉴权进房\n3. 同时签发机器人的 UserSig → 传递给 `StartAIConversation` API\n4. TRTC SECRET 和 CloudAPI 密钥永远不暴露给前端\n\n---\n\n## 核心设计模式\n\n### 1. ServerPushText + StopAfterPlay\n\n这是最重要的设计模式。通过一次 `ControlAIConversation` 调用实现\"播报告别语后自动结束\"：\n\n```\n前端: FarewellAndStop(TaskId, Lang)\n  → 后端: ControlAIConversation(ServerPushText + StopAfterPlay=true)\n    → TRTC 云端: 打断当前播报 → TTS 播报告别语 → 自动 StopAIConversation\n      → 机器人退房\n        → 前端: onRobotLeave → 用户退房 → 显示评分\n```\n\n### 2. 语音/文字双模混合\n\n同一个对话中可以无缝切换：\n- **语音模式**：麦克风 → TRTC 音频流 → 云端 ASR → LLM\n- **文字模式**：输入框 → `sendCustomMessage(type: 20000)` → 直接 LLM（跳过 ASR）\n\n### 3. 配置驱动的多语言\n\n一份配置文件 (`env.yaml`) 驱动全链路国际化：\n- `LLMConfig.SystemPrompt` / `SystemPromptYue` / `SystemPromptEn`\n- `WelcomeMessage.zh/yue/en`\n- `EndKeywords.zh/yue/en`\n- `FarewellMessage.zh/yue/en`\n- `TransferKeywords.zh/yue/en`\n- `TransferMessage.zh/yue/en`\n\n后端根据前端传入的 `lang` 参数自动切换。\n\n### 4. 数字人可选降级\n\n```python\ndef is_avatar_enabled(self):\n    avatar = self.env.get(\"AvatarConfig\")\n    return bool(avatar.get(\"Appkey\")) and bool(avatar.get(\"AccessToken\")) \\\n        and bool(avatar.get(\"VirtualmanProjectId\"))\n```\n\n三项全填 → 启用数字人，TTSConfig 设为 `dummy`（由数字人引擎处理 TTS）\n任一为空 → 降级为纯语音 + `flow` TTS\n\n---\n\n## 依赖清单\n\n```\nFlask==3.0.3                     # Web 框架\nenvyaml==1.10.211231             # YAML 配置加载（支持环境变量）\nloguru==0.7.3                    # 结构化日志\ntencentcloud-sdk-python==3.1.93  # 腾讯云 OpenAPI SDK（含 TRTC 模块）\n```\n\n极简：仅 4 个直接依赖。\n\n---\n\n## 启动与部署\n\n### 开发环境\n\n```bash\n# 一键启动（推荐）\n./start.sh\n\n# 手动启动\npython3 -m venv venv\nsource venv/bin/activate\npip install -r requirements.txt\npython app.py\n```\n\n`start.sh` 自动完成：\n1. 检测 Python >= 3.8\n2. 首次从 `env.example.yaml` 生成 `env.yaml` 并暂停提示填密钥\n3. 创建 venv 虚拟环境\n4. 检测并安装依赖（清华镜像优先）\n5. 端口冲突检测\n6. 启动 Flask 服务（端口 8080）\n\n### 生产部署建议\n\n| 项目 | 开发 | 生产 |\n|------|------|------|\n| 服务器 | Flask 内置 | Gunicorn + Nginx |\n| 协议 | HTTP | HTTPS（必须，WebRTC 要求） |\n| 鉴权 | 无 | `/action` 添加 Token/Session 鉴权 |\n| 日志 | loguru 文件 | 接入 ELK / 腾讯云 CLS |\n| 配置 | env.yaml | 环境变量或密钥管理服务 |\n\nFile v1.2.4:references/config-guide.md\n\n# TRTC AI 智能客服 - 配置参数完全指南\n\n## 目录\n\n1. [配置文件结构](#配置文件结构)\n2. [部署区域](#部署区域)\n3. [腾讯云 API 密钥](#腾讯云-api-密钥)\n4. [TRTC 应用凭据](#trtc-应用凭据)\n5. [LLM 配置](#llm-配置)\n6. [欢迎语](#欢迎语)\n7. [数字人配置](#数字人配置)\n8. [关键词与告别语](#关键词与告别语)\n9. [转人工关键词与提示语](#转人工关键词与提示语)\n10. [TTS 音色映射表](#tts-音色映射表)\n11. [STT 引擎映射表](#stt-引擎映射表)\n12. [固定默认参数](#固定默认参数)\n13. [UI 可调参数](#ui-可调参数)\n14. [Region 切换机制](#region-切换机制)\n\n---\n\n## 配置文件结构\n\n配置使用 YAML 格式，通过 `envyaml` 库加载（支持环境变量替换）。\n\n```yaml\n# env.yaml 完整模板\nDeployment:\n  Region: intl\n\nCloudAPI:\n  SECRET_ID: your-secret-id\n  SECRET_KEY: your-secret-key\n\nTRTC:\n  SDKAPPID: 0\n  SECRET: your-trtc-secret\n\nLLMConfig:\n  LLMType: openai\n  Model: your-model-name\n  APIKey: your-api-key\n  APIUrl: your-llm-api-url\n  Timeout: 5.0\n  History: 20\n  Temperature: 0.3\n  SystemPrompt: |\n    你是一名专业的客服助手...\n  SystemPromptYue: |\n    你係一名專業嘅客服助手...\n  SystemPromptEn: |\n    You are a professional customer service assistant...\n\nWelcomeMessage:\n  zh: 您好，我是AI客服小助手...\n  yue: 您好，我係AI客服小助手...\n  en: \"Hello! I'm your AI assistant...\"\n\nAvatarConfig:\n  AvatarType: tencent\n  Appkey: \"\"\n  AccessToken: \"\"\n  VirtualmanProjectId: \"\"\n\nEndKeywords:\n  zh: [拜拜, 再见, 挂了, ...]\n  yue: [拜拜, 再見, 收線啦, ...]\n  en: [bye, goodbye, see you, ...]\n\nFarewellMessage:\n  zh: 感谢您的咨询，再见！\n  yue: 多謝您嘅諮詢，再見！\n  en: Thank you for your inquiry. Goodbye!\n\nTransferKeywords:\n  zh: [转人工, 人工客服, 找人工, ...]\n  yue: [轉人工, 人工客服, 搵人工, ...]\n  en: [transfer, human agent, real person, ...]\n\nTransferMessage:\n  zh: 好的，正在为您转接人工客服，请稍候...\n  yue: 好嘅，正在為您轉接人工客服，請稍候...\n  en: Sure, transferring you to a human agent, please wait...\n```\n\n---\n\n## 部署区域\n\n```yaml\nDeployment:\n  Region: intl   # intl / cn\n```\n\n| 值 | 说明 | TRTC Endpoint | TRTC Region |\n|----|------|---------------|-------------|\n| `intl` | 国际站账号（默认） | `trtc.intl.tencentcloudapi.com` | `ap-singapore` |\n| `cn` | 中国大陆账号 | `trtc.tencentcloudapi.com` | `ap-guangzhou` |\n\nRegion 决定了 TRTC OpenAPI 的请求域名和地域参数。\n\n---\n\n## 腾讯云 API 密钥\n\n```yaml\nCloudAPI:\n  SECRET_ID: your-secret-id\n  SECRET_KEY: your-secret-key\n```\n\n用于 TRTC OpenAPI 的 TC3-HMAC-SHA256 签名。在腾讯云控制台获取（[国际站](https://console.intl.cloud.tencent.com/cam/capi) | [中国站](https://console.cloud.tencent.com/cam/capi)）。\n\n**安全提醒**：这是主账号密钥，生产环境建议使用子账号并限制权限。\n\n---\n\n## TRTC 应用凭据\n\n```yaml\nTRTC:\n  SDKAPPID: 0\n  SECRET: your-trtc-secret\n```\n\n- `SDKAPPID`：TRTC 应用 ID，在 TRTC 控制台创建（[国际站](https://console.trtc.io/app) | [中国站](https://console.cloud.tencent.com/trtc/app)）\n- `SECRET`：用于生成 UserSig 的密钥\n\n---\n\n## LLM 配置\n\n```yaml\nLLMConfig:\n  LLMType: openai             # LLM 协议类型（目前仅支持 openai）\n  Model: your-model-name      # 模型名称\n  APIKey: your-api-key        # LLM API Key\n  APIUrl: your-llm-api-url    # LLM API 端点（兼容 OpenAI /v1/chat/completions 协议）\n  Timeout: 5.0                # 超时时间（秒）\n  History: 20                 # 上下文轮数\n  Temperature: 0.3            # 温度参数（越低越确定）\n  SystemPrompt: |             # 中文系统提示词\n    你是一名专业的客服助手...\n  SystemPromptYue: |          # 粤语系统提示词（可选，默认用中文）\n    你係一名專業嘅客服助手...\n  SystemPromptEn: |           # 英文系统提示词（可选，默认用中文）\n    You are a professional customer service assistant...\n```\n\n**重要**：LLM 由 TRTC 云端 AI Bot 调用，不是本项目后端调用。配置会通过 `StartAIConversation` API 传递给 TRTC 服务端。\n\n> ⚠️ **数据隐私提示**：您的 LLM 配置（包括 APIKey、APIUrl、SystemPrompt）以及用户对话内容将通过 TRTC 云端服务转发给 LLM 提供商。请确保：\n> 1. 了解所选 LLM 提供商的数据处理政策\n> 2. 不要在 SystemPrompt 中包含敏感的业务数据\n> 3. 在生产环境中评估是否需要数据脱敏措施\n\n### 支持的 LLM 提供商\n\n任何兼容 OpenAI 协议的 LLM 均可使用，详见官方 LLM 配置指南（[国际站](https://trtc.io/document/68338?product=conversationalai) | [中国站](https://cloud.tencent.com/document/product/647/115413)）：\n\n**推荐：TokenHub（腾讯云统一 LLM 网关，开箱即用）**\n\n| 配置项 | 国际站 (intl) | 中国站 (cn) |\n|--------|-------------|------------|\n| LLMType | `openai` | `openai` |\n| APIUrl | `https://tokenhub-intl.tencentcloudmaas.com/v1/chat/completions` | `https://tokenhub.tencentmaas.com/v1/chat/completions` |\n| Model | `deepseek-v4-flash`（推荐） | `deepseek-v4-flash`（推荐） |\n| APIKey | [国际站 TokenHub 控制台](https://console.intl.cloud.tencent.com/tokenhub) 获取 | [中国站 TokenHub 控制台](https://console.cloud.tencent.com/tokenhub) 获取 |\n\n也支持其他兼容 OpenAI 协议的 LLM：\n- OpenAI / Azure OpenAI\n- DeepSeek\n- 通义千问\n- 其他支持 `/v1/chat/completions` 的服务\n\n### SystemPrompt 编写建议\n\n1. 明确角色定位和服务范围\n2. 限制回复长度（语音场景建议 3 句以内）\n3. 要求纯文本输出（不使用 Markdown、括号注释等）\n4. 说明何时建议转人工\n5. 如有订单等结构化信息，说明如何使用\n\n---\n\n## 欢迎语\n\n```yaml\nWelcomeMessage:\n  zh: 您好，欢迎来到云尚商城！我是AI客服小助手...\n  yue: 您好，歡迎嚟到雲尚商城！我係AI客服小助手...\n  en: \"Welcome to CloudShop Mall! I'm your AI assistant...\"\n```\n\nAI Bot 进入房间后自动播报的第一条消息。\n\n---\n\n## 数字人配置\n\n```yaml\nAvatarConfig:\n  AvatarType: tencent                    # 数字人类型\n  Appkey: \"\"                             # 数字人 Appkey\n  AccessToken: \"\"                        # 数字人 Access Token\n  VirtualmanProjectId: \"\"                # 数字人项目 ID\n```\n\n**启用条件**：`Appkey`、`AccessToken`、`VirtualmanProjectId` 三项全部非空。\n\n**降级机制**：任一为空 → 自动降级为纯语音模式。UI 上\"数字人\"选项会变为灰色不可选。\n\n启用数字人后：\n- `TTSConfig.TTSType` 自动设为 `dummy`（TTS 由数字人引擎处理）\n- 前端会显示数字人视频流\n\n---\n\n## 关键词与告别语\n\n```yaml\nEndKeywords:\n  zh: [拜拜, 再见, 先挂了, 先这样, 就这样吧, 没事了, 挂了, 不需要了, 不用了]\n  yue: [拜拜, 再見, 收線啦, 咁先啦, 唔使啦, 冇事啦, 掛啦]\n  en: [bye, goodbye, see you, that's all, thanks bye, gotta go, i'm done]\n\nFarewellMessage:\n  zh: 感谢您光临云尚商城，祝您购物愉快，再见！\n  yue: 多謝您光臨雲尚商城，祝您購物愉快，再見！\n  en: Thank you for visiting CloudShop Mall. Happy shopping and goodbye!\n```\n\n**匹配机制**：前端实时检测用户 ASR 文本，命中关键词后触发 `FarewellAndStop`。\n\n**词边界匹配**：\n- 英文：`\\b关键词\\b`（标准词边界）\n- 中文：`(^|[^\\u4e00-\\u9fa5A-Za-z0-9])关键词(?=[^\\u4e00-\\u9fa5A-Za-z0-9]|$)`\n\n这样\"再见面\"不会误触发\"再见\"，\"我没事了\"不会误触发\"没事了\"。\n\n---\n\n## 转人工关键词与提示语\n\n```yaml\nTransferKeywords:\n  zh: [转人工, 人工客服, 找人工, 转接人工, 真人客服, 找真人]\n  yue: [轉人工, 人工客服, 搵人工, 轉接人工, 真人客服]\n  en: [transfer, human agent, real person, talk to a person, speak to someone]\n\nTransferMessage:\n  zh: 好的，正在为您转接人工客服，请稍候...\n  yue: 好嘅，正在為您轉接人工客服，請稍候...\n  en: Sure, transferring you to a human agent, please wait...\n```\n\n命中转人工关键词后：\n1. 调用 `TransferAndStop` 播报转接提示语\n2. 前端显示模拟排队进度\n3. 排队\"失败\"后恢复 AI 对话（MVP 中为模拟，生产环境对接真实呼叫中心）\n\n---\n\n## TTS 音色映射表\n\n| 语言 | 性别 | VoiceId | 描述 |\n|------|------|---------|------|\n| zh（中文） | female | `female-kefu-xiaoyue` | 客服小悦 |\n| zh（中文） | male | `male-kefu-xiaoxu` | 客服小徐 |\n| yue（粤语） | female | `v-female-k3P8sL0Q` | 粤语女声 |\n| yue（粤语） | male | `v-male-L4s7PqZ9` | 粤语男声 |\n| en（英文） | female | `v-female-Z3x9LmQ2` | 理性女讲解 |\n| en（英文） | male | `v-male-Q6p8ZxL3` | 阳光男演讲 |\n\nTTS 引擎：`flow` 类型 + `flow_01_turbo` 模型（延迟最低）。\n\n> 如需自定义 TTS 音色（更换声线、调整语速语调等），请参考官方 TTS 音色配置指南（[国际站](https://trtc.io/document/79682?product=conversationalai) | [中国站](https://cloud.tencent.com/document/product/647/115414)）。\n\n---\n\n## STT 引擎映射表\n\n| 语言 | STTConfig.Language | 说明 |\n|------|-------------------|------|\n| zh（中文） | `zh` | 中文识别 |\n| yue（粤语） | `zh-TW` | 粤语识别 |\n| en（英文） | `en` | 英文识别 |\n\n后端根据前端传入的 `lang` 参数自动选择 STT 引擎。\n\n---\n\n## 固定默认参数\n\n这些参数在后端代码中硬编码，用户无需配置：\n\n| 参数 | 值 | 理由 |\n|------|------|------|\n| `TurnDetection.SemanticEagerness` | `auto` | 平衡响应速度与耐心 |\n| `FilterOneWord` | `false` | 保留\"嗯\"\"好\"等应答词 |\n| `WelcomeMessagePriority` | `0` | 欢迎语可被打断 |\n| `MaxIdleTime` | `60s` | 客服标准空闲超时 |\n| `SubtitleMode` | `1` | 句子级同步下发（非逐字） |\n| `FilterBracketsContent` | `1`(zh) / `2`(en) | 过滤 LLM 输出的舞台说明 |\n| `LLMConfig.Streaming` | `true` | 流式输出，首字延迟最优 |\n\n---\n\n## UI 可调参数\n\n用户可通过前端 UI 调整：\n\n| 参数 | 控件 | 取值 | 默认 | 含义 |\n|------|------|------|------|------|\n| 语言 | 顶部栏切换 | zh/yue/en | 跟随浏览器 | 联动 STT/TTS/Prompt/UI 文案 |\n| 对话模式 | Pill 切换 | voice/avatar | voice | 需 AvatarConfig 三项全填 |\n| 客服角色 | 头像卡片 | female/male | female | 影响 TTS VoiceId |\n| 断句模式 | Pill 切换 | 3(语义)/0(VAD) | 3 | 语义断句用 LLM 判断 |\n| 打断模式 | Pill 切换 | 0(智能)/1(手动) | 0 | 智能=自动检测打断 |\n| VAD 时长 | 滑块 | 240-2000ms | 600ms | 越小响应越快 |\n| 远场人声抑制 | 滑块 | 0-5 | 3 | 越高抑制越强 |\n| 打断时长 | 滑块 | 240-2000ms | 600ms | 仅智能打断模式 |\n\n---\n\n## Region 切换机制\n\n`config_loader.py` 中的实现：\n\n```python\nREGION_PROFILES = {\n    \"cn\": {\n        \"trtc_endpoint\": \"trtc.tencentcloudapi.com\",\n        \"trtc_region\": \"ap-guangzhou\",\n    },\n    \"intl\": {\n        \"trtc_endpoint\": \"trtc.intl.tencentcloudapi.com\",\n        \"trtc_region\": \"ap-singapore\",\n    },\n}\n```\n\n配置加载时根据 `Deployment.Region` 自动选择对应的 endpoint 和 region。未知 region 值会回退到 `intl`。\n\nFile v1.2.4:references/frontend-guide.md\n\n# TRTC AI 智能客服 - 前端集成指南\n\n## 目录\n\n1. [TRTC Web SDK 集成](#trtc-web-sdk-集成)\n2. [对话生命周期](#对话生命周期)\n3. [消息处理协议](#消息处理协议)\n4. [文字输入（跳过 ASR）](#文字输入跳过-asr)\n5. [关键词检测](#关键词检测)\n6. [字幕增量/累积自适应](#字幕增量累积自适应)\n7. [转人工流程](#转人工流程)\n8. [UI 组件结构](#ui-组件结构)\n9. [国际化系统](#国际化系统)\n10. [状态管理](#状态管理)\n\n---\n\n## TRTC Web SDK 集成\n\n### 引入 SDK\n\n```html\n<script src=\"https://web.sdk.qcloud.com/trtc/webrtc/v5/dist/trtc.js\"></script>\n```\n\n### 初始化与进房\n\n```javascript\n// 创建 TRTC 客户端\nconst trtcClient = TRTC.create();\n\n// 绑定事件\ntrtcClient.on(TRTC.EVENT.CUSTOM_MESSAGE, handleMessage);           // 字幕 + AI 状态\ntrtcClient.on(TRTC.EVENT.REMOTE_USER_LEAVE, onRobotLeave);         // 机器人退房\ntrtcClient.on(TRTC.EVENT.REMOTE_VIDEO_AVAILABLE, onVideoAvailable); // 数字人视频流\n\n// 进房\nawait trtcClient.enterRoom({\n    roomId: roomId,        // 房间号（数字）\n    scene: 'rtc',\n    sdkAppId: sdkAppId,\n    userId: userId,\n    userSig: userSig,\n});\n\n// 开麦克风（纯语音场景）\nawait trtcClient.startLocalAudio();\n```\n\n### 退房\n\n```javascript\nawait trtcClient.stopLocalAudio();\nawait trtcClient.exitRoom();\ntrtcClient.destroy();\n```\n\n---\n\n## 对话生命周期\n\n```\nidle → connecting → active → ending → idle\n                              ↓\n                         transferring → idle\n```\n\n### 启动流程（startCall）\n\n```javascript\nasync function startCall() {\n    STATE.callState = 'connecting';\n\n    // 1. join：获取 UserSig\n    const joinData = await postAction('join', { userid: STATE.userId });\n    STATE.sdkAppId = joinData.sdkappid;\n    STATE.userSig = joinData.usersig;\n    STATE.robotUserId = joinData.robot_userid;\n    STATE.robotUserSig = joinData.robot_usersig;\n    STATE.endKeywords = joinData.end_keywords;\n    STATE.farewellMessage = joinData.farewell_message;\n    STATE.transferKeywords = joinData.transfer_keywords;\n    STATE.avatarAvailable = joinData.avatar_available;\n\n    // 2. 创建 TRTC 客户端并进房\n    trtcClient = TRTC.create();\n    bindEvents(trtcClient);\n    await trtcClient.enterRoom({ roomId, scene: 'rtc', sdkAppId, userId, userSig });\n    await trtcClient.startLocalAudio();\n\n    // 3. StartAIConversation\n    const startData = await postAction('StartAIConversation', {\n        RoomId: STATE.roomId,\n        AgentConfig: {\n            UserId: STATE.robotUserId,\n            UserSig: STATE.robotUserSig,\n            TargetUserId: STATE.userId,\n            Lang: USER_CFG.lang,\n        },\n        UserConfig: {\n            InterruptMode: USER_CFG.interruptMode,\n            InterruptSpeechDuration: USER_CFG.interruptSpeechDuration,\n            VadLevel: USER_CFG.vadLevel,\n            VadSilenceTime: USER_CFG.vadSilenceTime,\n            Gender: STATE.gender,\n        },\n        UseAvatar: STATE.useAvatar,\n        AvatarConfig: STATE.useAvatar ? {\n            AvatarUserID: STATE.avatarUserId,\n            AvatarUserSig: STATE.avatarUserSig,\n        } : undefined,\n    });\n    STATE.taskId = startData.TaskId;\n    STATE.callState = 'active';\n}\n```\n\n### 结束流程（farewellAndEnd）\n\n```javascript\nasync function farewellAndEnd() {\n    STATE.callState = 'ending';\n\n    // 1. 发送 FarewellAndStop\n    await postAction('FarewellAndStop', {\n        TaskId: STATE.taskId,\n        Lang: USER_CFG.lang,\n    });\n\n    // 2. 等待机器人退房（onRobotLeave 回调）\n    // 3. 退房\n    await cleanupRoom();\n\n    // 4. 显示评分弹窗\n    showRatingOverlay();\n}\n```\n\n### 机器人退房回调\n\n```javascript\nfunction onRobotLeave(event) {\n    const { userId } = event;\n    if (userId === STATE.robotUserId || userId === STATE.avatarUserId) {\n        if (STATE.callState === 'ending' || STATE.callState === 'transferring') {\n            cleanupRoom();\n        }\n    }\n}\n```\n\n---\n\n## 消息处理协议\n\n所有云端消息通过 `TRTC.EVENT.CUSTOM_MESSAGE` 事件接收：\n\n```javascript\nfunction handleMessage(event) {\n    const { data } = event;\n    const msg = JSON.parse(new TextDecoder().decode(data));\n\n    switch (msg.type) {\n        case 10000:  // 字幕\n            handleSubtitle(msg);\n            break;\n        case 10001:  // AI 状态\n            handleAIState(msg);\n            break;\n    }\n}\n```\n\n### type: 10000 - 字幕消息\n\n```json\n{\n    \"type\": 10000,\n    \"sender\": \"user_xxx_robot\",\n    \"payload\": {\n        \"roundid\": \"round_123\",\n        \"userid\": \"user_xxx\",       // 发言者\n        \"text\": \"你好，请问...\",\n        \"end\": false                 // true=该轮结束\n    }\n}\n```\n\n**区分用户和 AI**：\n- `payload.userid === STATE.userId` → 用户的 ASR 文本\n- `payload.userid !== STATE.userId` → AI 的回复文本\n\n### type: 10001 - AI 状态\n\n```json\n{\n    \"type\": 10001,\n    \"payload\": {\n        \"state\": 1,         // 1=聆听 2=思考 3=说话 4=打断 5=结束\n        \"roundid\": \"round_123\"\n    }\n}\n```\n\n| state | 含义 | 前端响应 |\n|-------|------|----------|\n| 1 | 聆听 | 显示\"聆听中...\" |\n| 2 | 思考 | 显示 typing 动画 |\n| 3 | 说话 | 更新语音状态指示 |\n| 4 | 打断 | 标记当前回复被打断 |\n| 5 | 结束 | 触发结束流程 |\n\n---\n\n## 文字输入（跳过 ASR）\n\n使用 `type: 20000` 自定义消息协议，文字直接发送到 LLM：\n\n```javascript\nfunction sendTextMessage(text) {\n    const message = {\n        type: 20000,\n        sender: STATE.userId,\n        receiver: [STATE.robotUserId],\n        payload: {\n            id: crypto.randomUUID(),\n            message: text,\n            timestamp: Date.now(),\n        },\n    };\n\n    trtcClient.sendCustomMessage({\n        cmdId: 2,\n        data: new TextEncoder().encode(JSON.stringify(message)).buffer,\n    });\n}\n```\n\n**关键点**：\n- `cmdId: 2` 是固定值\n- `receiver` 指定机器人 userId\n- 文本跳过 ASR 引擎，直接送入 LLM，适合不便说话场景\n- 用户发送文字后可无缝切回语音模式\n\n---\n\n## 关键词检测\n\n### 构建正则\n\n```javascript\nfunction buildKeywordRegex(keywords) {\n    if (!keywords || keywords.length === 0) return null;\n\n    const patterns = keywords.map(kw => {\n        const escaped = kw.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n        const hasChineseChar = /[\\u4e00-\\u9fa5]/.test(kw);\n\n        if (hasChineseChar) {\n            // 中文：两侧非中文字母数字边界\n            return `(^|[^\\\\u4e00-\\\\u9fa5A-Za-z0-9])${escaped}(?=[^\\\\u4e00-\\\\u9fa5A-Za-z0-9]|$)`;\n        } else {\n            // 英文：标准词边界\n            return `\\\\b${escaped}\\\\b`;\n        }\n    });\n\n    return new RegExp(patterns.join('|'), 'i');\n}\n```\n\n### 检测触发\n\n```javascript\nfunction detectEndKeyword(text) {\n    const lang = USER_CFG.lang;\n    const keywords = STATE.endKeywords[lang] || [];\n    const regex = buildKeywordRegex(keywords);\n    return regex && regex.test(text);\n}\n\n// 在用户 ASR 文本结束时检测\nif (payload.end && payload.userid === STATE.userId) {\n    if (detectEndKeyword(payload.text)) {\n        farewellAndEnd();\n    } else if (detectTransferKeyword(payload.text)) {\n        triggerTransfer();\n    }\n}\n```\n\n---\n\n## 字幕增量/累积自适应\n\nTRTC 下发字幕可能是增量或累积模式，前端自动适配：\n\n```javascript\nfunction processSubtitleText(roundId, newText) {\n    const accumulated = STATE.aiRoundText[roundId] || '';\n\n    if (newText.startsWith(accumulated)) {\n        // 累积模式：新文本是旧文本的超集\n        STATE.aiRoundText[roundId] = newText;\n    } else {\n        // 增量模式：新文本是新增部分\n        STATE.aiRoundText[roundId] = accumulated + newText;\n    }\n\n    return STATE.aiRoundText[roundId];\n}\n```\n\n---\n\n## 转人工流程\n\n```javascript\nasync function triggerTransfer() {\n    STATE.callState = 'transferring';\n\n    // 1. 播报转接提示语\n    await postAction('TransferAndStop', {\n        TaskId: STATE.taskId,\n        Lang: USER_CFG.lang,\n    });\n\n    // 2. 等待机器人退房\n    // 3. 显示排队进度弹窗\n    showTransferOverlay();\n\n    // 4. 模拟排队（MVP）\n    await simulateQueueProgress();\n\n    // 5. 排队失败 → 恢复 AI 对话（或对接真实呼叫中心）\n    restartAIConversation();\n}\n```\n\n---\n\n## UI 组件结构\n\n```\n┌─────────────────────────────────────────────────┐\n│  Top Bar                                          │\n│  [☰ 侧边栏] [AI 电商客服]      [🌐 简体中文 ▼]     │\n├──────────┬──────────────────────────────────────┤\n│          │                                       │\n│ Sidebar  │  Main Area                            │\n│          │                                       │\n│ ┌──────┐ │  ┌────────────────────────────────┐  │\n│ │对话模式│ │  │  Agent Select Area              │  │\n│ │断句模式│ │  │  [👩 女客服]  [👨 男客服]         │  │\n│ │打断模式│ │  │       [开始对话]                 │  │\n│ │VAD设置│ │  └────────────────────────────────┘  │\n│ │       │ │                                      │\n│ └──────┘ │  ┌────────────────────────────────┐  │\n│          │  │  Chat Messages                   │  │\n│          │  │  [AI] 您好，请问有什么...          │  │\n│          │  │          [User] 查询订单          │  │\n│          │  │  [AI] 好的，请提供订单号...        │  │\n│          │  └────────────────────────────────┘  │\n│          │                                      │\n│          │  ┌────────────────────────────────┐  │\n│          │  │  Input Bar                       │  │\n│          │  │  [⌨️/🎤] [📦订单] [🔁转人工] [📞挂断] │  │\n│          │  └────────────────────────────────┘  │\n├──────────┴──────────────────────────────────────┤\n│  Overlays: 评分弹窗 / 订单面板 / 转人工弹窗      │\n└─────────────────────────────────────────────────┘\n```\n\n### CSS 设计要点\n\n- **CSS 变量系统**：`--primary`、`--bg`、`--surface` 等统一管理主题色\n- **响应式**：768px 断点移动端适配，侧边栏可折叠\n- **动效**：消息入场 `fadeInUp`、typing dots、评分弹窗滑入\n- **无外部依赖**：纯 CSS + 内联 SVG 图标\n\n---\n\n## 国际化系统\n\n### 架构\n\n```javascript\n// i18n.js - IIFE 模式\n(function() {\n    const DICT = {\n        zh: { appName: 'AI 电商客服', ... },\n        yue: { appName: 'AI 電商客服', ... },\n        en: { appName: 'AI Customer Service', ... },\n    };\n\n    window.I18N = {\n        getLang() { ... },           // 从 localStorage 读取\n        setLang(lang) { ... },       // 保存到 localStorage + 广播事件\n        t(key, params) { ... },      // 翻译（支持 {param} 模板替换）\n    };\n})();\n```\n\n### 使用\n\n```javascript\n// HTML 中\n<span data-i18n=\"appName\"></span>\n\n// JS 中\nconst text = I18N.t('tipConnecting');  // \"正在连接...\"\nconst text = I18N.t('duration', { time: '5:30' });  // \"通话时长: 5:30\"\n\n// 语言切换监听\nwindow.addEventListener('langChange', (e) => {\n    const lang = e.detail.lang;\n    updateAllTexts();\n});\n```\n\n### 语言存储\n\n- `localStorage` key: `cs_lang`\n- 默认值：跟随浏览器 `navigator.language`\n- 切换通过 `CustomEvent('langChange')` 事件广播\n\n---\n\n## 状态管理\n\n前端使用简单的全局对象管理状态：\n\n```javascript\nconst STATE = {\n    // 连接状态\n    userId: '',\n    roomId: 0,\n    sdkAppId: 0,\n    userSig: '',\n    robotUserId: '',\n    robotUserSig: '',\n    avatarUserId: '',\n    avatarUserSig: '',\n\n    // 功能开关\n    avatarAvailable: false,\n    useAvatar: false,\n    gender: 'female',\n\n    // 通话状态\n    callState: 'idle',       // idle | connecting | active | ending | transferring\n    taskId: null,\n    startTime: null,\n    muted: false,\n    aiSpeaking: false,\n\n    // 关键词（从 join 响应获取）\n    endKeywords: { zh: [], yue: [], en: [] },\n    farewellMessage: { zh: '', yue: '', en: '' },\n    transferKeywords: { zh: [], yue: [], en: [] },\n    transferMessage: { zh: '', yue: '', en: '' },\n\n    // 消息管理\n    messages: [],             // 消息气泡列表\n    typingMsgId: null,        // AI typing 状态\n    aiRoundText: {},          // roundid → 累积文本\n    aiRoundLast: {},          // roundid → 上一次文本（去重）\n    aiRoundMsgId: {},         // roundid → 消息气泡 ID\n};\n\nconst USER_CFG = {\n    lang: I18N.getLang(),\n    mode: 'voice',            // voice | avatar\n    inputMode: 'voice',       // voice | text\n    interruptMode: 0,         // 0=智能打断 1=手动打断\n    interruptSpeechDuration: 600,\n    vadLevel: 3,\n    vadSilenceTime: 600,\n    turnDetectionMode: 3,     // 3=语义断句 0=VAD断句\n};\n```\n\n### HTTP 请求封装\n\n```javascript\nasync function postAction(action, body = {}) {\n    const resp = await fetch('/action', {\n        method: 'POST',\n        headers: {\n            'Content-Type': 'application/json',\n            'Action': action,\n        },\n        body: JSON.stringify(body),\n    });\n    const data = await resp.json();\n    if (data.Response?.Error) {\n        throw new Error(data.Response.Error.Message);\n    }\n    return data;\n}\n```\n\nFile v1.2.4:README_ZH.md\n\n# TRTC AI 电商客服 Skill\n\n[English](README.md) | 简体中文\n\n> 基于 [腾讯云 TRTC Conversational AI 解决方案](https://cloud.tencent.com/document/product/647/110584) 快速搭建生产级 AI 电商客服 Web 应用 — 语音与文字双通道、三语国际化、内置电商业务流程。\n\n## 核心能力\n\n| 能力 | 说明 |\n|------|------|\n| **实时语音** | 终端用户与云端 AI Bot 之间的双向 WebRTC 音频通信 |\n| **文字降级** | 跳过 ASR，将键盘输入直接送达 LLM 处理链路 |\n| **三语国际化** | 中文 / 粤语 / 英文全覆盖：UI、STT、TTS、SystemPrompt |\n| **电商业务流** | 订单查询、退换货处理、物流追踪、优惠活动咨询 |\n| **数字人可选** | 可选虚拟形象渲染，未配置时优雅降级为纯语音 |\n| **会话生命周期** | 关键词触发告别、转人工、空闲超时自动结束 |\n| **服务评分** | 会话结束后 4 维度评价 |\n\n## 安装方式\n\n本项目是一个**便携式 Agent Skill**（包含 `SKILL.md` + `scripts/` + `references/` + `assets/` 的标准结构）。安装到对应工具的 skills 目录即可被自动发现。\n\n### OpenClaw\n\n根据需要选择安装位置：\n\n| 位置 | 作用域 | 命令 |\n|------|--------|------|\n| `<workspace>/skills/` | 当前工作区，优先级最高 | `git clone https://github.com/jerryang-cool/trtc-ai-customer-service-skill.git skills/trtc-ai-customer-service` |\n| `~/.agents/skills/` | 个人级，跨工作区生效 | `git clone https://github.com/jerryang-cool/trtc-ai-customer-service-skill.git ~/.agents/skills/trtc-ai-customer-service` |\n| `~/.openclaw/skills/` | 全局共享，所有 agent 可见 | `git clone https://github.com/jerryang-cool/trtc-ai-customer-service-skill.git ~/.openclaw/skills/trtc-ai-customer-service` |\n\n安装后通过自然语言（如\"帮我做个 AI 客服\"）或斜杠命令 `/trtc-ai-customer-service` 调用。\n\n> 更多信息参见 [OpenClaw Skills 官方文档](https://docs.openclaw.ai/zh-CN/tools/skills)。\n\n### CodeBuddy\n\n设置 → Skills → **导入 Skill**，选择本仓库目录。导入后，在对话中提及 *\"AI 客服\"*、*\"电商客服\"*、*\"TRTC + AI\"* 等关键词即自动激活。\n\n### Claude Code\n\n```bash\n# 用户级（跨项目可用）\ngit clone <repo-url> ~/.claude/skills/trtc-ai-customer-service\n\n# 或项目级（提交到仓库，团队共享）\ngit clone <repo-url> .claude/skills/trtc-ai-customer-service\n```\n\nClaude Code 通过 `description` 字段自动匹配触发。隐式调用（如\"帮我做个 AI 客服\"）或显式调用 `/trtc-ai-customer-service` 均可。\n\n### OpenAI Codex CLI\n\n```bash\n# 用户级\ngit clone <repo-url> ~/.codex/skills/trtc-ai-customer-service\n\n# 或项目级\ngit clone <repo-url> .agents/skills/trtc-ai-customer-service\n```\n\nCodex 在下次会话启动时自动检测新 skill。隐式调用（自然语言）或显式调用 `$trtc-ai-customer-service` 均可。\n\n### Cursor\n\n```bash\n# 投放到 Cursor skills 目录\ngit clone <repo-url> ~/.cursor/skills/trtc-ai-customer-service\n```\n\n仓库内 `.cursor/rules/trtc-ai-customer-service.mdc` 遵循 2026 MDC 格式（Agent Requested 模式），Cursor 的 Agent 模式会按 description 按需加载。\n\n> **从 `.cursorrules` 升级**：Cursor 自 2026 年起在 Agent 模式下静默忽略 `.cursorrules`。本 Skill 仅提供新的 `.cursor/rules/*.mdc` 格式。\n\n## 快速开始\n\n```bash\n# 1. 生成新项目\npython scripts/scaffold.py ./my-shop --name \"云尚商城\"\n\n# 2. 启动（首次运行进入交互式密钥配置向导）\ncd ./my-shop && ./start.sh\n\n# 3. 浏览器访问 http://localhost:8080\n```\n\n## 架构\n\n```\n┌─────────────────────────────────┐\n│  浏览器  (TRTC Web SDK v5)       │\n│  WebRTC 音频 + 自定义消息         │\n└──────────────┬──────────────────┘\n               │\n       ┌───────▼───────┐\n       │   TRTC 房间    │\n       │  ASR → LLM →  │  云端 AI 处理链路\n       │      TTS       │  (后端零 LLM 调用)\n       └───────┬────────┘\n               │ OpenAPI (TC3-HMAC-SHA256)\n       ┌───────▼────────┐\n       │  Flask 后端     │  UserSig 签发\n       │   (app.py)      │  + OpenAPI 中转\n       └─────────────────┘\n```\n\n## 技术栈\n\n| 层 | 技术 |\n|----|------|\n| 后端 | Python 3.8+ · Flask · tencentcloud-sdk-python |\n| 前端 | 原生 JS · TRTC Web SDK v5 · CSS 自定义属性 |\n| AI 引擎 | TRTC ConversationAI（云端 ASR → LLM → TTS） |\n| 鉴权 | HMAC-SHA256 UserSig（仅服务端签发） |\n| 配置 | YAML，通过 `envyaml` 支持环境变量插值 |\n\n## 项目结构\n\n```\ntrtc-ai-customer-service-skill/\n├── SKILL.md              # Skill 入口 — 供 CodeBuddy / Claude Code / Codex CLI 识别\n├── .cursor/\n│   └── rules/\n│       └── trtc-ai-customer-service.mdc  # Cursor 2026 MDC 格式\n├── LICENSE               # MIT 许可证\n├── CHANGELOG.md          # 版本历史\n├── README.md             # English documentation\n├── README_ZH.md          # 中文文档（本文件）\n├── scripts/\n│   └── scaffold.py       # 一键项目生成器\n├── references/\n│   ├── architecture.md   # 系统设计与后端集成\n│   ├── config-guide.md   # 完整配置参考\n│   └── frontend-guide.md # TRTC Web SDK 集成指南\n└── assets/               # 脚手架附带的模板文件\n```\n\n## 参考链接\n\n- [TRTC 控制台](https://console.cloud.tencent.com/trtc/app)\n- [Conversational AI 解决方案](https://cloud.tencent.com/document/product/647/110584)\n- [LLM 配置指南](https://cloud.tencent.com/document/product/647/115413)\n- [TTS 音色配置指南](https://cloud.tencent.com/document/product/647/115414)\n\n## 许可证\n\n基于 [MIT 许可证](LICENSE) 发布。\n\nFile v1.2.4:skill-card.md\n\n## Description: <br>\nBuild an AI e-commerce customer service Web app with TRTC ConversationAI for real-time voice and text support, trilingual interactions, optional digital avatar support, and common commerce workflows such as order inquiry, returns, shipping tracking, and promotions. <br>\n\nThis skill is ready for commercial/non-commercial use. <br>\n\n## Publisher: <br>\n[jerryang-cool](https://clawhub.ai/user/jerryang-cool) <br>\n\n### License/Terms of Use: <br>\nMIT-0 <br>\n\n\n## Use Case: <br>\nDevelopers use this skill to scaffold or integrate a Tencent TRTC ConversationAI customer-service application for e-commerce support. It guides setup, credential configuration, launch validation, customization, and integration with existing backends or frontends. <br>\n\n### Deployment Geography for Use: <br>\nGlobal <br>\n\n## Known Risks and Mitigations: <br>\nRisk: The generated application uses Tencent Cloud, TRTC, and LLM credentials. <br>\nMitigation: Use least-privilege credentials, avoid broad main-account keys where possible, and keep env.yaml out of source control. <br>\nRisk: The application handles microphone audio and customer-service conversations. <br>\nMitigation: Use appropriate user consent, access controls, and retention policies before handling real customer interactions. <br>\nRisk: The generated Flask app may be exposed publicly during testing or deployment. <br>\nMitigation: Add authentication and rate limiting before public exposure, and avoid first launch on sensitive networks unless the public-IP lookup behavior is acceptable. <br>\n\n\n## Reference(s): <br>\n- [ClawHub Skill Page](https://clawhub.ai/jerryang-cool/trtc-ai-customer-service) <br>\n- [Architecture Reference](references/architecture.md) <br>\n- [Configuration Guide](references/config-guide.md) <br>\n- [Frontend Integration Guide](references/frontend-guide.md) <br>\n- [Tencent RTC Conversational AI](https://trtc.io/solutions/conversational-ai) <br>\n- [LLM Configuration Guide](https://trtc.io/document/68338?product=conversationalai) <br>\n- [TTS Voice Configuration](https://trtc.io/document/79682?product=conversationalai) <br>\n\n\n## Skill Output: <br>\n**Output Type(s):** [Text, Markdown, Code, Shell commands, Configuration, Guidance] <br>\n**Output Format:** [Markdown guidance with inline shell commands, code snippets, configuration examples, and generated project files] <br>\n**Output Parameters:** [1D] <br>\n**Other Properties Related to Output:** [May generate a Flask and vanilla JavaScript project scaffold that requires Python 3 and Tencent Cloud/TRTC credentials.] <br>\n\n## Skill Version(s): <br>\n1.2.4 (source: frontmatter and server release evidence) <br>\n\n## Ethical Considerations: <br>\nUsers should evaluate whether this skill is appropriate for their environment, review any generated or modified files before relying on them, and apply their organization's safety, security, and compliance requirements before deployment. <br>\n\nFile v1.2.4:assets/static/mock-orders.json\n\n[\n    {\n        \"id\": \"CS20260510001\",\n        \"name\": { \"zh\": \"无线降噪耳机 Pro\", \"yue\": \"無線降噪耳機 Pro\", \"en\": \"Wireless ANC Headphones Pro\" },\n        \"price\": { \"zh\": \"¥699\", \"yue\": \"HK$759\", \"en\": \"$96\" },\n        \"status\": \"shipped\",\n        \"date\": \"2026-05-10\",\n        \"emoji\": \"🎧\"\n    },\n    {\n        \"id\": \"CS20260508002\",\n        \"name\": { \"zh\": \"轻薄笔记本电脑 14寸\", \"yue\": \"輕薄筆記本電腦 14吋\", \"en\": \"Ultra-slim Laptop 14\\\"\" },\n        \"price\": { \"zh\": \"¥5,299\", \"yue\": \"HK$5,749\", \"en\": \"$729\" },\n        \"status\": \"delivered\",\n        \"date\": \"2026-05-08\",\n        \"emoji\": \"💻\"\n    },\n    {\n        \"id\": \"CS20260507003\",\n        \"name\": { \"zh\": \"智能手表 S9\", \"yue\": \"智能手錶 S9\", \"en\": \"Smart Watch S9\" },\n        \"price\": { \"zh\": \"¥1,299\", \"yue\": \"HK$1,409\", \"en\": \"$179\" },\n        \"status\": \"pending\",\n        \"date\": \"2026-05-07\",\n        \"emoji\": \"⌚\"\n    },\n    {\n        \"id\": \"CS20260505004\",\n        \"name\": { \"zh\": \"真皮双肩包\", \"yue\": \"真皮雙肩包\", \"en\": \"Genuine Leather Backpack\" },\n        \"price\": { \"zh\": \"¥399\", \"yue\": \"HK$433\", \"en\": \"$55\" },\n        \"status\": \"refunding\",\n        \"date\": \"2026-05-05\",\n        \"emoji\": \"🎒\"\n    },\n    {\n        \"id\": \"CS20260501005\",\n        \"name\": { \"zh\": \"空气炸锅 5L\", \"yue\": \"空氣炸鍋 5L\", \"en\": \"Air Fryer 5L\" },\n        \"price\": { \"zh\": \"¥259\", \"yue\": \"HK$281\", \"en\": \"$36\" },\n        \"status\": \"delivered\",\n        \"date\": \"2026-05-01\",\n        \"emoji\": \"🍳\"\n    }\n]\n\nArchive v1.2.3: 15 files, 87561 bytes\n\nFiles: assets/start.sh (29690b), assets/static/app.js (52760b), assets/static/i18n.js (14719b), assets/static/mock-orders.json (1525b), assets/templates/customer_service.html (62687b), assets/TLSSigAPIv2.py (16022b), README_ZH.md (6090b), README.md (6281b), references/architecture.md (12223b), references/config-guide.md (11068b), references/frontend-guide.md (14226b), scripts/scaffold.py (37555b), skill-card.md (3113b), SKILL.md (14219b), _meta.json (143b)\n\nFile v1.2.3:SKILL.md\n\n---\nname: trtc-ai-customer-service\nversion: 1.2.3\ndescription: |\n  Build an AI e-commerce customer service Web app with TRTC ConversationAI — real-time voice/text dual-mode, trilingual (Chinese/English/Cantonese), digital avatar optional. Covers order inquiry, returns, shipping tracking, and promotions.\n  基于腾讯云 TRTC Conversational AI 快速构建 AI 电商客服 Web 应用 — 实时语音/文字双模、中英粤三语、数字人可选。覆盖订单查询、退换货、物流追踪、商品咨询等场景。\nhomepage: https://github.com/jerryang-cool/trtc-ai-customer-service-skill\nmetadata:\n  openclaw:\n    emoji: \"🛍️\"\n    requires:\n      bins:\n        - python3\n---\n\n# TRTC AI 电商客服 Skill\n\n本 Skill 指导你基于腾讯云 TRTC Conversational AI 能力，快速构建 AI 电商客服 Web 应用。\n场景预置了订单查询、退换货处理、商品咨询、物流追踪、优惠活动等电商业务模块。\n\n## 触发条件\n\n当用户提到以下任何场景时使用此 Skill（EN or CN）：\n- \"AI customer service\" \"smart customer support\" \"voice bot\" \"voice agent\" \"chat bot\"\n- \"e-commerce support\" \"online store assistant\" \"shopping assistant\" \"after-sales service\"\n- \"build a customer service app\" \"customer service demo\" \"support chatbot\"\n- \"real-time voice chat\" \"voice-to-text conversation\" \"ASR + LLM + TTS\"\n- \"TRTC conversation\" \"ConversationAI\" \"TRTC + AI\" \"TRTC + LLM\"\n- \"digital human\" \"virtual agent\" \"avatar customer service\"\n- \"StartAIConversation\" \"StopAIConversation\" \"ControlAIConversation\"\n- \"order inquiry\" \"returns and exchanges\" \"shipping tracking\" \"product consultation\"\n- \"AI 客服\" \"智能客服\" \"语音客服\" \"电商客服\" \"商城客服\" \"售后客服\"\n- \"做一个客服系统\" \"搭建客服\" \"客服机器人\" \"数字人客服\"\n- \"订单查询\" \"退换货\" \"物流追踪\" \"商品咨询\"\n\n即使用户只是简单说 \"help me build an AI customer service\" 或 \"帮我做个 AI 客服\" 也应触发。\n\n## 架构总览\n\n```\n浏览器 (TRTC Web SDK v5)\n     ↕ 音频 (WebRTC) + 自定义消息 (字幕/状态/文字输入)\nTRTC Room\n     ↕ 内置 ASR → LLM → TTS → 推回房间\nTRTC AI Bot (云端)\n     ↕ OpenAPI (TC3-HMAC-SHA256)\nFlask 后端 (app.py)  —— 仅 UserSig 签发 + OpenAPI 中转\n```\n\n| 平面 | 通道 | 内容 |\n|------|------|------|\n| **媒体面** | WebRTC 音频流 | 用户麦克风 ↔ TRTC 房间 ↔ AI Bot |\n| **控制面** | HTTP `/action` | 前端 → Flask → TRTC OpenAPI |\n| **数据面** | TRTC 自定义消息 | 字幕(10000) / AI 状态(10001) / 文字输入(20000) / 打断(20001) |\n\n后端**完全不调用 LLM**——LLM 由 TRTC 云端 AI Bot 内部调用，后端只负责签发 UserSig 和中转 OpenAPI 请求。\n\n---\n\n## 工作流程\n\n根据用户需求选择合适的路径。\n\n### 路径 A：从零创建新项目（推荐）\n\n#### Step 1: 生成项目\n\n运行脚手架脚本：\n\n```bash\npython {baseDir}/scripts/scaffold.py <项目目录> [--name <商城名称>] [--name-en <English name>]\n```\n\n- `{baseDir}`：本 Skill 所在目录的绝对路径（由 Agent 自动替换为实际路径）\n- `--name`：商城名称（默认\"云尚商城\"），用于中文/粤语的 SystemPrompt、欢迎语、告别语、前端 UI\n- `--name-en`：英文商城名称（默认自动推导：中文名时为\"CloudShop Mall\"，英文名时与 `--name` 相同），用于英文 SystemPrompt、英文欢迎语/告别语\n- 默认支持中文/英文/粤语三语，无需手动指定语言\n- 脚本自动生成全部文件：后端 + 前端 + 头像 + 鉴权库 + 启动脚本，无需手动复制任何文件\n\n**检查点**：确认用户看到 `✅ 电商客服项目已生成到: xxx` 和完整文件列表，再继续。\n\n#### Step 2: 配置密钥\n\n引导用户运行启动脚本（**根据操作系统自动选择**：macOS/Linux 用 `./start.sh`，Windows 用 `start.bat`），首次运行会进入交互式引导：\n\n- [0/4] 选择部署区域（默认 `intl` 国际站，可选 `cn` 中国站）— 后续步骤会根据所选区域展示对应的控制台链接\n- [1/4] 腾讯云 API 密钥 → 脚本会展示对应区域的 [CAM 控制台](https://console.intl.cloud.tencent.com/cam/capi) 链接\n- [2/4] TRTC 应用凭据 → 脚本会展示对应区域的 [TRTC 控制台](https://console.trtc.io/app) 链接\n- [3/4] LLM 配置 → **建议优先使用 TokenHub**（腾讯云统一 LLM 网关，开箱即用）：\n  - `LLMConfig.LLMType`：`openai`（固定）\n  - `LLMConfig.Model`：`deepseek-v4-flash`（推荐）\n  - `LLMConfig.APIUrl`：\n    - 国际站：`https://tokenhub-intl.tencentcloudmaas.com/v1/chat/completions`\n    - 中国站：`https://tokenhub.tencentmaas.com/v1/chat/completions`\n  - `LLMConfig.APIKey`：在 TokenHub 控制台获取（[国际站](https://console.intl.cloud.tencent.com/tokenhub) | [中国站](https://console.cloud.tencent.com/tokenhub)）\n  - 也支持其他兼容 OpenAI 协议的 LLM，参考配置指南：[国际站](https://trtc.io/document/68338?product=conversationalai) | [中国站](https://cloud.tencent.com/document/product/647/115413)\n\n**检查点**：确认用户看到 `✓ 所有密钥已配置完成！`。如果有跳过项，提醒手动编辑 `env.yaml`。\n\n> **提示用户**：以上为最小必填项，启动成功后还有丰富的可定制选项（角色定制、商城名称、欢迎语、TTS 音色、关键词等），详见 Step 4。\n\n#### Step 3: 启动验证\n\n启动脚本会自动创建虚拟环境、安装依赖、启动服务。\n\n**验证标准**（告知用户逐项确认）：\n1. 终端显示 `🚀 启动 TRTC AI 智能客服` + 访问地址（公网服务器会自动检测公网 IP 并启用 HTTPS，显示 `https://<公网IP>:8080`；本地开发则显示 `http://localhost:8080`）\n2. 浏览器打开页面 → 能看到客服头像选择界面\n3. 选择客服 → 点击\"开始对话\" → 听到 AI 播报欢迎语\n4. 说话或打字 → AI 能正常回复\n\n#### Step 4: 定制化（可选）\n\n启动成功后，**主动告知用户**以下所有可定制项，引导按需修改：\n\n| 定制项 | 修改位置 | 说明 |\n|--------|---------|------|\n| **AI 客服角色** | 交互式引导 [4/4]（删除 `env.yaml` 后重新运行 `./start.sh`），或直接编辑 `env.yaml` → `SystemPrompt` / `SystemPromptYue` / `SystemPromptEn` | 预设品类 + 语气快速定制（见下方枚举表），也可手动编辑三语 SystemPrompt 做精细调整 |\n| **商城名称/品牌** | scaffold 的 `--name` / `--name-en` 参数 | 一键替换全链路品牌文案（三语 SystemPrompt、欢迎语、告别语、前端 UI） |\n| **欢迎语 / 告别语** | `env.yaml` → `WelcomeMessage` / `FarewellMessage`（`.zh` / `.yue` / `.en`） | AI 进房首条播报 / 关键词触发结束时播报 |\n| **LLM 模型** | `env.yaml` → `LLMConfig.Model` / `APIUrl` / `APIKey` | LLM 配置指南：[国际站](https://trtc.io/document/68338?product=conversationalai) \\| [中国站](https://cloud.tencent.com/document/product/647/115413) |\n| **TTS 音色** | `config_loader.py` → `TTS_VOICE_MAP` | TTS 音色配置指南：[国际站](https://trtc.io/document/79682?product=conversationalai) \\| [中国站](https://cloud.tencent.com/document/product/647/115414) |\n| **商品/订单数据** | `static/mock-orders.json`，或参考 `references/frontend-guide.md` 对接真实 API | JSON 格式含三语名称和价格，可替换为真实订单系统 |\n| **数字人** | `env.yaml` → `AvatarConfig` 三项 | 三项全填启用数字人视频模式，否则纯语音 |\n| **部署方式** | 自动检测公网 IP 启用 HTTPS；生产环境用 Gunicorn + Nginx + 正式证书 | WebRTC 要求 HTTPS；生产还需添加 `/action` 接口鉴权 |\n\n**AI 客服角色预设枚举值**（`start.sh` 交互式引导 [4/4]）：\n\n商城品类（影响 AI 的专业知识方向）：\n\n| 选项 | 品类 | AI 擅长方向 |\n|------|------|------------|\n| 1 | 综合电商（默认） | 通用电商场景，不修改 SystemPrompt |\n| 2 | 数码产品 | 参数对比、兼容性问题、保修政策、使用教程 |\n| 3 | 服装鞋帽 | 尺码推荐、面料材质、搭配建议、洗涤保养、退换尺码 |\n| 4 | 食品生鲜 | 保质期、储存方式、配送时效、食材产地、过敏原信息 |\n| 5 | 家居百货 | 商品尺寸规格、安装方式、材质说明、配送安装服务 |\n\n客服语气风格（影响 AI 的表达方式）：\n\n| 选项 | 风格 | 效果 |\n|------|------|------|\n| 1 | 亲切自然（默认） | 像朋友聊天，已内置于默认 SystemPrompt |\n| 2 | 专业严谨 | 用词准确规范，适合高端品牌/B2B |\n| 3 | 活泼可爱 | 轻松表达方式，适合年轻用户群体 |\n\n> 选择后自动注入三语 SystemPrompt（中文/粤语/英文同步）。如需更精细定制，直接编辑 `env.yaml` 中的 SystemPrompt 即可。\n\n### 路径 B：为现有项目集成 TRTC AI 对话\n\n#### Step 1: 了解现有架构\n\n询问并确认：\n- 后端语言和框架（Python/Node/Go/Java？）\n- 前端技术栈（React/Vue/原生 JS？已有 TRTC SDK？）\n- 集成范围：仅后端 API？还是含前端 UI？\n\n#### Step 2: 按需读取参考文档并输出代码\n\n根据用户技术栈，读取对应文档并**直接输出可集成的代码片段**：\n\n| 需求 | 读取文档 | 输出内容 |\n|------|----------|----------|\n| 后端 API | `references/architecture.md` | 用户语言的 5 个 Action 处理器代码（join / Start / Stop / Farewell / Transfer） |\n| 配置体系 | `references/config-guide.md` | 生成 `env.yaml` 模板 + 配置加载代码 |\n| 前端对话 UI | `references/frontend-guide.md` | TRTC SDK 进房 + 消息监听 + 字幕渲染代码 |\n\n**关键**：如果用户不是 Python 技术栈，需要将参考文档中的 Python 逻辑**翻译为用户的语言**（如 Node.js / Go / Java），核心逻辑不变。\n\n#### Step 3: 验证集成\n\n引导用户完成最小可用流程并逐步确认：\n1. 后端 `/action` 接口能正常响应（`curl -X POST /action -H \"Action: join\"` 返回 UserSig）\n2. 前端成功进入 TRTC 房间（控制台无报错）\n3. `StartAIConversation` 调用成功返回 TaskId\n4. 用户说话 → 听到 AI 回复（完整链路跑通）\n\n**如果卡在某一步**，参照下方 FAQ 表逐条排查。\n\n---\n\n## 常见问题排查\n\n当用户遇到问题时，按以下清单排查：\n\n| 现象 | 原因 | 解决方案 |\n|------|------|----------|\n| scaffold.py 报错退出 | Python 版本或参数错误 | 确认 Python 3.8+；检查输出目录路径是否合法 |\n| `start.sh` 报 Python 版本不够 | Python < 3.8 | 安装 Python 3.8+ |\n| venv 创建失败 | 缺少 `python3-venv` 包 | Ubuntu/Debian: `sudo apt install python3-venv`；macOS 自带 |\n| 依赖安装失败 | 网络问题 | `start.sh` 会自动 fallback 官方源；或手动 `pip install -r requirements.txt` |\n| `env.yaml` 解析报错 | YAML 缩进或格式错误 | 用在线 YAML 校验器检查；常见：冒号后缺空格、中文引号 |\n| 页面打开空白 | 静态文件缺失 | 确认 `static/app.js` 和 `templates/customer_service.html` 存在 |\n| 点\"开始对话\"无反应 | 密钥未填或填错 | 检查 `env.yaml` 中 SDKAPPID 不为 0、SECRET_ID/KEY 正确 |\n| 点\"开始对话\"提示**进房失败** | TRTC 进房参数异常 | 检查 `SDKAPPID` 是否正确填写；UserSig 是否校验失败（核对 `TRTC.SECRET`） |\n| 说话**无任何响应**（语音不可用） | 浏览器麦克风权限未授予或设备异常 | 检查浏览器地址栏麦克风权限；测试系统设备：录音机能否录到声音 |\n| 仅显示**本地字幕，AI 无回应** | LLM 服务异常 | 检查 `LLMConfig.APIKey` / `APIUrl` / `Model` 是否正确；确认 LLM 账户额度充足 |\n| AI 有字幕但**无语音播报** | TTS 服务异常 | 核对 TTS 参数（VoiceId、Language）；确认 TTS 套餐包资源充足 |\n| LLM **长时间不回复**或超时报错 | LLM Timeout | 调大 `env.yaml` → `LLMConfig.Timeout`（如 5.0 → 10.0） |\n| 进房成功但无欢迎语 | LLM APIKey 错误或 TRTC 服务未开通 | 检查 `LLMConfig.APIKey`；确认 TRTC 控制台已开通 AI 对话能力 |\n| 非 localhost 访问**无声音或麦克风不可用** | WebRTC 安全策略要求 HTTPS | 运行 `./start.sh --https` 自动生成自签证书并启用 HTTPS；首次访问浏览器点击\"高级→继续前往\" |\n| 公网 IP 访问**页面打不开** | 防火墙未放行端口 | 确认服务器防火墙/安全组已放行 8080 端口（TCP）|\n| 端口 8080 被占用 | 其他进程占用 | `start.sh` 会自动检测并询问是否终止 |\n| 浏览器控制台报 CORS 错误 | 前后端不同源 | 确保前端页面由 Flask 提供（同源）；不要用 `file://` 打开 HTML |\n\n---\n\n## 速查参考\n\n### 后端 API（`POST /action` + `Action` 请求头）\n\n| Action | 职责 |\n|--------|------|\n| `join` | 签发 UserSig（用户/机器人/数字人），下发关键词/告别语/数字人开关 |\n| `StartAIConversation` | 组装参数调用 TRTC OpenAPI 启动 AI 对话 |\n| `StopAIConversation` | 兜底停止（正常走 FarewellAndStop） |\n| `FarewellAndStop` | 推送告别语 + StopAfterPlay 一站式结束 |\n| `TransferAndStop` | 推送转接提示语 + StopAfterPlay 一站式结束 |\n\n### 核心设计模式（详见 `references/architecture.md`）\n\n| 模式 | 要点 |\n|------|------|\n| StopAfterPlay 一站式结束 | `ControlAIConversation` + `StopAfterPlay=true`，TTS 播完自动停止 |\n| 文字输入跳过 ASR | `type: 20000` 自定义消息直送 LLM |\n| 中英文词边界匹配 | 中文用非中文字符边界，英文用 `\\b` |\n| 增量/累积自适应字幕 | 自动检测 TRTC 下发模式 |\n| 机器人退房 + AI 状态双保险 | `REMOTE_USER_LEAVE` + `state=5` |\n| 数字人可选降级 | `AvatarConfig` 三项齐全启用，否则纯语音 |\n\n### 技术栈\n\nPython 3.8+ · Flask · tencentcloud-sdk-python · 原生 JS · TRTC Web SDK v5 · YAML（envyaml）\n\n### 安全\n\n- `env.yaml` 含密钥，加入 `.gitignore`，切勿提交\n- UserSig 服务端签发，密钥不暴露给前端\n- 生产环境添加 `/action` 接口鉴权\n- 非 localhost 部署必须 HTTPS（WebRTC 安全策略）\n\nFile v1.2.3:README.md\n\n# TRTC AI Customer Service Skill\n\nEnglish | [简体中文](README_ZH.md)\n\n> Rapidly scaffold a production-ready AI customer service Web application powered by [Tencent RTC Conversational AI](https://trtc.io/solutions/conversational-ai) — voice & text dual-mode, trilingual, with built-in e-commerce workflows.\n\n## Highlights\n\n| Capability | Description |\n|-----------|-------------|\n| **Real-time Voice** | Bidirectional WebRTC audio between end-user and cloud-hosted AI Bot |\n| **Text Fallback** | Bypass ASR — send typed messages directly to the LLM pipeline |\n| **Trilingual i18n** | Chinese / Cantonese / English across UI, STT, TTS, and SystemPrompt |\n| **E-commerce Workflows** | Order inquiry, returns & exchanges, shipping tracking, promotions |\n| **Digital Avatar** | Optional virtual human rendering; graceful degradation to pure voice |\n| **Session Lifecycle** | Keyword-triggered farewell, human agent transfer, auto-idle timeout |\n| **Service Rating** | 4-dimension post-session evaluation |\n\n## Installation\n\nThis is a **portable Agent Skill** (a `SKILL.md` + `scripts/` + `references/` + `assets/` bundle). Install it to your tool's skills directory and the agent will auto-discover it.\n\n### OpenClaw\n\nChoose the install location based on your needs:\n\n| Location | Scope | Command |\n|----------|-------|---------|\n| `<workspace>/skills/` | Current workspace, highest priority | `git clone https://github.com/jerryang-cool/trtc-ai-customer-service-skill.git skills/trtc-ai-customer-service` |\n| `~/.agents/skills/` | Personal, effective across workspaces | `git clone https://github.com/jerryang-cool/trtc-ai-customer-service-skill.git ~/.agents/skills/trtc-ai-customer-service` |\n| `~/.openclaw/skills/` | Global, visible to all agents | `git clone https://github.com/jerryang-cool/trtc-ai-customer-service-skill.git ~/.openclaw/skills/trtc-ai-customer-service` |\n\nInvoke via natural language (\"help me build an AI customer service\") or slash command `/trtc-ai-customer-service`.\n\n> See [OpenClaw Skills documentation](https://docs.openclaw.ai/tools/skills) for more details.\n\n### CodeBuddy\n\nSettings → Skills → **Import Skill**, then point to this repository's directory. Once imported, mention keywords such as *\"AI customer service\"*, *\"e-commerce support\"*, or *\"TRTC + AI\"* to activate.\n\n### Claude Code\n\n```bash\n# User-level (available across all projects)\ngit clone <repo-url> ~/.claude/skills/trtc-ai-customer-service\n\n# OR project-level (commit to repo, share with team)\ngit clone <repo-url> .claude/skills/trtc-ai-customer-service\n```\n\nClaude Code auto-discovers skills via `description` matching. Invoke implicitly (\"help me build an AI customer service\") or explicitly via `/trtc-ai-customer-service`.\n\n### OpenAI Codex CLI\n\n```bash\n# User-level\ngit clone <repo-url> ~/.codex/skills/trtc-ai-customer-service\n\n# OR project-level\ngit clone <repo-url> .agents/skills/trtc-ai-customer-service\n```\n\nCodex auto-detects new skills on next session. Invoke implicitly via natural language, or explicitly via `$trtc-ai-customer-service`.\n\n### Cursor\n\n```bash\n# Skill bundle: drop into Cursor's skills directory\ngit clone <repo-url> ~/.cursor/skills/trtc-ai-customer-service\n```\n\nThe `.cursor/rules/trtc-ai-customer-service.mdc` inside this repo follows the 2026 MDC format (Agent Requested mode) — Cursor's Agent loads it on demand based on the description.\n\n> **Legacy `.cursorrules` users**: Cursor silently ignores `.cursorrules` in Agent mode since 2026. This skill ships only the modern `.cursor/rules/*.mdc` format.\n\n## Quick Start\n\n```bash\n# 1. Generate a new project\npython scripts/scaffold.py ./my-shop --name \"CloudShop\" --name-en \"CloudShop Mall\"\n\n# 2. Launch (first run enters interactive credential wizard)\ncd ./my-shop && ./start.sh\n\n# 3. Open http://localhost:8080\n```\n\n## Architecture\n\n```\n┌─────────────────────────────────┐\n│  Browser  (TRTC Web SDK v5)     │\n│  WebRTC audio + custom messages │\n└──────────────┬──────────────────┘\n               │\n       ┌───────▼───────┐\n       │   TRTC Room   │\n       │  ASR → LLM →  │  Cloud-hosted AI pipeline\n       │      TTS       │  (zero LLM calls on your server)\n       └───────┬────────┘\n               │ OpenAPI (TC3-HMAC-SHA256)\n       ┌───────▼────────┐\n       │  Flask Backend  │  UserSig signing\n       │   (app.py)      │  + OpenAPI relay only\n       └─────────────────┘\n```\n\n## Tech Stack\n\n| Layer | Technology |\n|-------|-----------|\n| Backend | Python 3.8+ · Flask · tencentcloud-sdk-python |\n| Frontend | Vanilla JS · TRTC Web SDK v5 · CSS custom properties |\n| AI Engine | TRTC ConversationAI (cloud ASR → LLM → TTS) |\n| Auth | HMAC-SHA256 UserSig (server-side only) |\n| Config | YAML via `envyaml` with env-var interpolation |\n\n## Project Layout\n\n```\ntrtc-ai-customer-service-skill/\n├── SKILL.md              # Skill entry — used by CodeBuddy / Claude Code / Codex CLI\n├── .cursor/\n│   └── rules/\n│       └── trtc-ai-customer-service.mdc  # Cursor 2026 MDC format\n├── LICENSE               # MIT\n├── CHANGELOG.md          # Version history\n├── README.md             # English documentation (this file)\n├── README_ZH.md          # 中文文档\n├── scripts/\n│   └── scaffold.py       # One-command project generator\n├── references/\n│   ├── architecture.md   # System design & backend integration\n│   ├── config-guide.md   # Full configuration reference\n│   └── frontend-guide.md # TRTC Web SDK integration guide\n└── assets/               # Template files shipped by scaffold\n```\n\n## References\n\n- [Tencent RTC Console](https://console.trtc.io/)\n- [Conversational AI Solution](https://trtc.io/solutions/conversational-ai)\n- [LLM Configuration Guide](https://trtc.io/document/68338?product=conversationalai)\n- [TTS Voice Configuration](https://trtc.io/document/79682?product=conversationalai)\n\n## License\n\nReleased under the [MIT License](LICENSE).\n\nFile v1.2.3:_meta.json\n\n{\n  \"ownerId\": \"kn7c55va424ew234devca4r09186sb9y\",\n  \"slug\": \"trtc-ai-customer-service\",\n  \"version\": \"1.2.3\",\n  \"publishedAt\": 1779788353011\n}\n\nFile v1.2.3:references/architecture.md\n\n# TRTC AI 智能客服 - 架构设计参考\n\n## 目录\n\n1. [系统架构](#系统架构)\n2. [项目结构](#项目结构)\n3. [后端实现详解](#后端实现详解)\n4. [认证流程](#认证流程)\n5. [核心设计模式](#核心设计模式)\n6. [依赖清单](#依赖清单)\n7. [启动与部署](#启动与部署)\n\n---\n\n## 系统架构\n\n### 三平面模型\n\n```\n┌─────────────────────────────────────────────────┐\n│              浏览器 (TRTC Web SDK v5)              │\n│                                                   │\n│   音频流 (WebRTC)   自定义消息 (字幕/状态/文字)       │\n└───────────┬─────────────────┬─────────────────────┘\n            │                 │\n            ▼                 ▼\n┌───────────────────────────────────────────────────┐\n│                  TRTC Room (云端)                   │\n│                                                     │\n│   ASR ──► LLM ──► TTS ──► 推回房间                  │\n│                                                     │\n│              TRTC AI Bot (云端实例)                   │\n└───────────┬─────────────────────────────────────────┘\n            │ OpenAPI (TC3-HMAC-SHA256)\n            ▼\n┌───────────────────────────────────────────────────┐\n│   Flask 后端 (app.py)                               │\n│   - UserSig 签发                                    │\n│   - TRTC OpenAPI 中转                               │\n│   - 零 LLM 调用                                     │\n└─────────────────────────────────────────────────────┘\n```\n\n关键洞察：**后端完全不调用 LLM**。LLM 推理由 TRTC 云端 AI Bot 内部完成。后端只做两件事：\n1. 签发 UserSig（用于 TRTC 房间鉴权）\n2. 中转 TRTC OpenAPI 请求（启动/停止/控制 AI 对话）\n\n### 消息类型\n\n| type | 方向 | 内容 |\n|------|------|------|\n| `10000` | 云→端 | 字幕（用户 ASR 结果 + AI 回复文本） |\n| `10001` | 云→端 | AI 状态（聆听/思考/说话/打断/结束） |\n| `20000` | 端→云 | 文字输入（跳过 ASR 直送 LLM） |\n| `20001` | 端→云 | 手动打断 |\n\n---\n\n## 项目结构\n\n```\nproject/\n├── app.py                        # Flask 主入口（~296 行，5 个 Action 处理器）\n├── config_loader.py              # 配置加载器（Region/TTS/STT 映射）\n├── trtc_signer.py                # UserSig 三套签发封装\n├── TLSSigAPIv2.py                # 腾讯云官方 TRTC HMAC 鉴权库（不修改）\n├── env.example.yaml              # 配置模板\n├── env.yaml                      # 实际配置（.gitignore 排除）\n├── requirements.txt              # 4 个 Python 依赖\n├── start.sh / start.bat          # 一键启动脚本\n├── templates/\n│   └── customer_service.html     # 主页面（配置侧边栏 + 聊天区 + 评分弹窗）\n├── static/\n│   ├── app.js                    # 前端核心交互逻辑\n│   ├── i18n.js                   # 国际化字典（zh/yue/en）\n│   └── avatars/                  # 客服头像\n└── docs/\n    └── PARAMS.md                 # 参数配置详解\n```\n\n---\n\n## 后端实现详解\n\n### 初始化\n\n```python\n# 加载配置\nconfig = AppConfig(\"env.yaml\")\nsigner = TRTCSigner(config.sdkappid, config.trtc_secret)\n\n# 初始化 TRTC OpenAPI 客户端\n_cred = credential.Credential(config.secret_id, config.secret_key)\n_http = HttpProfile()\n_http.endpoint = config.trtc_endpoint  # 按 Region 自动切换\n_client_profile = ClientProfile()\n_client_profile.httpProfile = _http\ntrtc_api = trtc_client.TrtcClient(_cred, config.trtc_region, _client_profile)\n```\n\n### 路由设计\n\n仅 2 个路由，极简：\n- `GET /` → 渲染主页面\n- `POST /action` → 统一 API 调度，通过 `Action` 请求头区分\n\n### Action 处理器详解\n\n#### handle_join(data)\n\n签发三套 UserSig 并下发配置：\n\n```python\ndef handle_join(data):\n    user_id = data.get(\"userid\")\n    sigs = signer.sign_trio(user_id)     # 用户 + 机器人 + 数字人\n    avatar_enabled = config.is_avatar_enabled()\n    return {\n        \"sdkappid\": sigs[\"sdkappid\"],\n        \"userid\": sigs[\"user_id\"],\n        \"usersig\": sigs[\"user_sig\"],\n        \"robot_userid\": sigs[\"robot_user_id\"],\n        \"robot_usersig\": sigs[\"robot_user_sig\"],\n        \"avatar_userid\": sigs[\"avatar_user_id\"] if avatar_enabled else \"\",\n        \"avatar_usersig\": sigs[\"avatar_user_sig\"] if avatar_enabled else \"\",\n        \"avatar_available\": avatar_enabled,\n        \"end_keywords\": config.all_end_keywords(),        # 三语结束关键词\n        \"farewell_message\": {...},                         # 三语告别语\n        \"transfer_keywords\": config.all_transfer_keywords(),  # 三语转人工关键词\n        \"transfer_message\": {...},                         # 三语转接提示\n    }\n```\n\n#### handle_start_ai_conversation(body)\n\n组装 5 大配置块并调用 TRTC OpenAPI：\n\n```python\ndef handle_start_ai_conversation(body):\n    lang = body[\"AgentConfig\"][\"Lang\"]          # zh/yue/en\n    use_avatar = body.get(\"UseAvatar\", False)\n\n    # 1. AgentConfig：机器人身份 + 对话参数\n    agent_cfg = {\n        \"UserId\": body[\"AgentConfig\"][\"UserId\"],\n        \"UserSig\": body[\"AgentConfig\"][\"UserSig\"],\n        \"TargetUserId\": body[\"AgentConfig\"][\"TargetUserId\"],\n        \"MaxIdleTime\": 60,\n        \"WelcomeMessage\": config.welcome_message(lang),\n        \"TurnDetectionMode\": 3,                 # 语义断句\n        \"TurnDetection\": {\"SemanticEagerness\": \"auto\"},\n        \"SubtitleMode\": 1,                      # 句子级字幕\n        \"InterruptMode\": interrupt_mode,         # 0=智能/1=手动\n        \"InterruptSpeechDuration\": interrupt_speech_duration,\n    }\n\n    # 2. STTConfig：语音识别\n    stt_cfg = {\n        \"Language\": get_stt_language(lang),      # zh / zh-TW / en\n        \"VadLevel\": vad_level,\n        \"VadSilenceTime\": vad_silence_time,\n    }\n\n    # 3. LLMConfig：从 env.yaml 读取\n    llm_cfg = config.llm_config(lang)            # 按语言切换 SystemPrompt\n\n    # 4. TTSConfig\n    if use_avatar:\n        tts_cfg = {\"TTSType\": \"dummy\"}           # 数字人模式：TTS 由数字人引擎处理\n    else:\n        tts_cfg = {\n            \"TTSType\": \"flow\",\n            \"Model\": \"flow_01_turbo\",\n            \"VoiceId\": get_voice_id(lang, gender),  # 6 种组合\n        }\n\n    # 5. AvatarConfig（可选）\n    if use_avatar:\n        params[\"AvatarConfig\"] = json.dumps({...})\n\n    # 调用 TRTC OpenAPI\n    req = models.StartAIConversationRequest()\n    req.from_json_string(json.dumps(params))\n    resp = trtc_api.StartAIConversation(req)\n    return json.loads(resp.to_json_string())     # 包含 TaskId\n```\n\n#### handle_farewell_and_stop(body)\n\n一站式结束的核心实现：\n\n```python\ndef handle_farewell_and_stop(body):\n    params = {\n        \"TaskId\": task_id,\n        \"Command\": \"ServerPushText\",\n        \"ServerPushText\": {\n            \"Text\": farewell_text,           # 告别语\n            \"Interrupt\": True,               # 打断当前播报\n            \"StopAfterPlay\": True,           # TTS 播完后自动停止任务\n            \"AddHistory\": True,\n            \"Priority\": 0,\n        },\n    }\n    req = models.ControlAIConversationRequest()\n    req.from_json_string(json.dumps(params))\n    resp = trtc_api.ControlAIConversation(req)\n```\n\n`StopAfterPlay=True` 的优势：\n- 不需要前端估算 TTS 播报时长\n- 不需要 setTimeout 轮询\n- 服务端确保播报完整后才停止任务\n\n#### handle_transfer_and_stop(body)\n\n与 FarewellAndStop 结构相同，只是文本换成转接提示语。\n\n### 错误处理\n\n```python\nclass ErrorCode(enum.Enum):\n    InvalidParameter = \"InvalidParameter\"\n\ndef err(code: ErrorCode, msg: str):\n    return {\"Response\": {\"Error\": {\"Code\": code.name, \"Message\": msg}}}\n```\n\n所有异常统一返回腾讯云 API 风格的错误结构。`TaskNotExist` 错误被静默处理（幂等设计）。\n\n---\n\n## 认证流程\n\n### UserSig 签发\n\n```python\nclass TRTCSigner:\n    def sign_trio(self, user_id):\n        # 一次签发 3 套 UserSig：\n        # - user_id           → 真人用户\n        # - {user_id}_robot   → AI 机器人\n        # - {user_id}_avatar  → 数字人\n        robot_id = f\"{user_id}_robot\"\n        avatar_id = f\"{user_id}_avatar\"\n        return {\n            \"user_sig\": self.sign(user_id),\n            \"robot_user_sig\": self.sign(robot_id),\n            \"avatar_user_sig\": self.sign(avatar_id),\n        }\n```\n\n底层使用 `TLSSigAPIv2`（HMAC-SHA256 + zlib 压缩 + Base64URL 编码），这是腾讯云官方库，无需修改。\n\n### 认证流程\n\n1. 前端调用 `join` → 后端用 TRTC SECRET 签发 UserSig\n2. UserSig 随响应返回前端 → 前端用于 TRTC SDK 鉴权进房\n3. 同时签发机器人的 UserSig → 传递给 `StartAIConversation` API\n4. TRTC SECRET 和 CloudAPI 密钥永远不暴露给前端\n\n---\n\n## 核心设计模式\n\n### 1. ServerPushText + StopAfterPlay\n\n这是最重要的设计模式。通过一次 `ControlAIConversation` 调用实现\"播报告别语后自动结束\"：\n\n```\n前端: FarewellAndStop(TaskId, Lang)\n  → 后端: ControlAIConversation(ServerPushText + StopAfterPlay=true)\n    → TRTC 云端: 打断当前播报 → TTS 播报告别语 → 自动 StopAIConversation\n      → 机器人退房\n        → 前端: onRobotLeave → 用户退房 → 显示评分\n```\n\n### 2. 语音/文字双模混合\n\n同一个对话中可以无缝切换：\n- **语音模式**：麦克风 → TRTC 音频流 → 云端 ASR → LLM\n- **文字模式**：输入框 → `sendCustomMessage(type: 20000)` → 直接 LLM（跳过 ASR）\n\n### 3. 配置驱动的多语言\n\n一份配置文件 (`env.yaml`) 驱动全链路国际化：\n- `LLMConfig.SystemPrompt` / `SystemPromptYue` / `SystemPromptEn`\n- `WelcomeMessage.zh/yue/en`\n- `EndKeywords.zh/yue/en`\n- `FarewellMessage.zh/yue/en`\n- `TransferKeywords.zh/yue/en`\n- `TransferMessage.zh/yue/en`\n\n后端根据前端传入的 `lang` 参数自动切换。\n\n### 4. 数字人可选降级\n\n```python\ndef is_avatar_enabled(self):\n    avatar = self.env.get(\"AvatarConfig\")\n    return bool(avatar.get(\"Appkey\")) and bool(avatar.get(\"AccessToken\")) \\\n        and bool(avatar.get(\"VirtualmanProjectId\"))\n```\n\n三项全填 → 启用数字人，TTSConfig 设为 `dummy`（由数字人引擎处理 TTS）\n任一为空 → 降级为纯语音 + `flow` TTS\n\n---\n\n## 依赖清单\n\n```\nFlask==3.0.3                     # Web 框架\nenvyaml==1.10.211231             # YAML 配置加载（支持环境变量）\nloguru==0.7.3                    # 结构化日志\ntencentcloud-sdk-python==3.1.93  # 腾讯云 OpenAPI SDK（含 TRTC 模块）\n```\n\n极简：仅 4 个直接依赖。\n\n---\n\n## 启动与部署\n\n### 开发环境\n\n```bash\n# 一键启动（推荐）\n./start.sh\n\n# 手动启动\npython3 -m venv venv\nsource venv/bin/activate\npip install -r requirements.txt\npython app.py\n```\n\n`start.sh` 自动完成：\n1. 检测 Python >= 3.8\n2. 首次从 `env.example.yaml` 生成 `env.yaml` 并暂停提示填密钥\n3. 创建 venv 虚拟环境\n4. 检测并安装依赖（清华镜像优先）\n5. 端口冲突检测\n6. 启动 Flask 服务（端口 8080）\n\n### 生产部署建议\n\n| 项目 | 开发 | 生产 |\n|------|------|------|\n| 服务器 | Flask 内置 | Gunicorn + Nginx |\n| 协议 | HTTP | HTTPS（必须，WebRTC 要求） |\n| 鉴权 | 无 | `/action` 添加 Token/Session 鉴权 |\n| 日志 | loguru 文件 | 接入 ELK / 腾讯云 CLS |\n| 配置 | env.yaml | 环境变量或密钥管理服务 |\n\nFile v1.2.3:references/config-guide.md\n\n# TRTC AI 智能客服 - 配置参数完全指南\n\n## 目录\n\n1. [配置文件结构](#配置文件结构)\n2. [部署区域](#部署区域)\n3. [腾讯云 API 密钥](#腾讯云-api-密钥)\n4. [TRTC 应用凭据](#trtc-应用凭据)\n5. [LLM 配置](#llm-配置)\n6. [欢迎语](#欢迎语)\n7. [数字人配置](#数字人配置)\n8. [关键词与告别语](#关键词与告别语)\n9. [转人工关键词与提示语](#转人工关键词与提示语)\n10. [TTS 音色映射表](#tts-音色映射表)\n11. [STT 引擎映射表](#stt-引擎映射表)\n12. [固定默认参数](#固定默认参数)\n13. [UI 可调参数](#ui-可调参数)\n14. [Region 切换机制](#region-切换机制)\n\n---\n\n## 配置文件结构\n\n配置使用 YAML 格式，通过 `envyaml` 库加载（支持环境变量替换）。\n\n```yaml\n# env.yaml 完整模板\nDeployment:\n  Region: intl\n\nCloudAPI:\n  SECRET_ID: your-secret-id\n  SECRET_KEY: your-secret-key\n\nTRTC:\n  SDKAPPID: 0\n  SECRET: your-trtc-secret\n\nLLMConfig:\n  LLMType: openai\n  Model: your-model-name\n  APIKey: your-api-key\n  APIUrl: your-llm-api-url\n  Timeout: 5.0\n  History: 20\n  Temperature: 0.3\n  SystemPrompt: |\n    你是一名专业的客服助手...\n  SystemPromptYue: |\n    你係一名專業嘅客服助手...\n  SystemPromptEn: |\n    You are a professional customer service assistant...\n\nWelcomeMessage:\n  zh: 您好，我是AI客服小助手...\n  yue: 您好，我係AI客服小助手...\n  en: \"Hello! I'm your AI assistant...\"\n\nAvatarConfig:\n  AvatarType: tencent\n  Appkey: \"\"\n  AccessToken: \"\"\n  VirtualmanProjectId: \"\"\n\nEndKeywords:\n  zh: [拜拜, 再见, 挂了, ...]\n  yue: [拜拜, 再見, 收線啦, ...]\n  en: [bye, goodbye, see you, ...]\n\nFarewellMessage:\n  zh: 感谢您的咨询，再见！\n  yue: 多謝您嘅諮詢，再見！\n  en: Thank you for your inquiry. Goodbye!\n\nTransferKeywords:\n  zh: [转人工, 人工客服, 找人工, ...]\n  yue: [轉人工, 人工客服, 搵人工, ...]\n  en: [transfer, human agent, real person, ...]\n\nTransferMessage:\n  zh: 好的，正在为您转接人工客服，请稍候...\n  yue: 好嘅，正在為您轉接人工客服，請稍候...\n  en: Sure, transferring you to a human agent, please wait...\n```\n\n---\n\n## 部署区域\n\n```yaml\nDeployment:\n  Region: intl   # intl / cn\n```\n\n| 值 | 说明 | TRTC Endpoint | TRTC Region |\n|----|------|---------------|-------------|\n| `intl` | 国际站账号（默认） | `trtc.intl.tencentcloudapi.com` | `ap-singapore` |\n| `cn` | 中国大陆账号 | `trtc.tencentcloudapi.com` | `ap-guangzhou` |\n\nRegion 决定了 TRTC OpenAPI 的请求域名和地域参数。\n\n---\n\n## 腾讯云 API 密钥\n\n```yaml\nCloudAPI:\n  SECRET_ID: your-secret-id\n  SECRET_KEY: your-secret-key\n```\n\n用于 TRTC OpenAPI 的 TC3-HMAC-SHA256 签名。在腾讯云控制台获取（[国际站](https://console.intl.cloud.tencent.com/cam/capi) | [中国站](https://console.cloud.tencent.com/cam/capi)）。\n\n**安全提醒**：这是主账号密钥，生产环境建议使用子账号并限制权限。\n\n---\n\n## TRTC 应用凭据\n\n```yaml\nTRTC:\n  SDKAPPID: 0\n  SECRET: your-trtc-secret\n```\n\n- `SDKAPPID`：TRTC 应用 ID，在 TRTC 控制台创建（[国际站](https://console.trtc.io/app) | [中国站](https://console.cloud.tencent.com/trtc/app)）\n- `SECRET`：用于生成 UserSig 的密钥\n\n---\n\n## LLM 配置\n\n```yaml\nLLMConfig:\n  LLMType: openai             # LLM 协议类型（目前仅支持 openai）\n  Model: your-model-name      # 模型名称\n  APIKey: your-api-key        # LLM API Key\n  APIUrl: your-llm-api-url    # LLM API 端点（兼容 OpenAI /v1/chat/completions 协议）\n  Timeout: 5.0                # 超时时间（秒）\n  History: 20                 # 上下文轮数\n  Temperature: 0.3            # 温度参数（越低越确定）\n  SystemPrompt: |             # 中文系统提示词\n    你是一名专业的客服助手...\n  SystemPromptYue: |          # 粤语系统提示词（可选，默认用中文）\n    你係一名專業嘅客服助手...\n  SystemPromptEn: |           # 英文系统提示词（可选，默认用中文）\n    You are a professional customer service assistant...\n```\n\n**重要**：LLM 由 TRTC 云端 AI Bot 调用，不是本项目后端调用。配置会通过 `StartAIConversation` API 传递给 TRTC 服务端。\n\n### 支持的 LLM 提供商\n\n任何兼容 OpenAI 协议的 LLM 均可使用，详见官方 LLM 配置指南（[国际站](https://trtc.io/document/68338?product=conversationalai) | [中国站](https://cloud.tencent.com/document/product/647/115413)）：\n\n**推荐：TokenHub（腾讯云统一 LLM 网关，开箱即用）**\n\n| 配置项 | 国际站 (intl) | 中国站 (cn) |\n|--------|-------------|------------|\n| LLMType | `openai` | `openai` |\n| APIUrl | `https://tokenhub-intl.tencentcloudmaas.com/v1/chat/completions` | `https://tokenhub.tencentmaas.com/v1/chat/completions` |\n| Model | `deepseek-v4-flash`（推荐） | `deepseek-v4-flash`（推荐） |\n| APIKey | [国际站 TokenHub 控制台](https://console.intl.cloud.tencent.com/tokenhub) 获取 | [中国站 TokenHub 控制台](https://console.cloud.tencent.com/tokenhub) 获取 |\n\n也支持其他兼容 OpenAI 协议的 LLM：\n- OpenAI / Azure OpenAI\n- DeepSeek\n- 通义千问\n- 其他支持 `/v1/chat/completions` 的服务\n\n### SystemPrompt 编写建议\n\n1. 明确角色定位和服务范围\n2. 限制回复长度（语音场景建议 3 句以内）\n3. 要求纯文本输出（不使用 Markdown、括号注释等）\n4. 说明何时建议转人工\n5. 如有订单等结构化信息，说明如何使用\n\n---\n\n## 欢迎语\n\n```yaml\nWelcomeMessage:\n  zh: 您好，欢迎来到云尚商城！我是AI客服小助手...\n  yue: 您好，歡迎嚟到雲尚商城！我係AI客服小助手...\n  en: \"Welcome to CloudShop Mall! I'm your AI assistant...\"\n```\n\nAI Bot 进入房间后自动播报的第一条消息。\n\n---\n\n## 数字人配置\n\n```yaml\nAvatarConfig:\n  AvatarType: tencent                    # 数字人类型\n  Appkey: \"\"                             # 数字人 Appkey\n  AccessToken: \"\"                        # 数字人 Access Token\n  VirtualmanProjectId: \"\"                # 数字人项目 ID\n```\n\n**启用条件**：`Appkey`、`AccessToken`、`VirtualmanProjectId` 三项全部非空。\n\n**降级机制**：任一为空 → 自动降级为纯语音模式。UI 上\"数字人\"选项会变为灰色不可选。\n\n启用数字人后：\n- `TTSConfig.TTSType` 自动设为 `dummy`（TTS 由数字人引擎处理）\n- 前端会显示数字人视频流\n\n---\n\n## 关键词与告别语\n\n```yaml\nEndKeywords:\n  zh: [拜拜, 再见, 先挂了, 先这样, 就这样吧, 没事了, 挂了, 不需要了, 不用了]\n  yue: [拜拜, 再見, 收線啦, 咁先啦, 唔使啦, 冇事啦, 掛啦]\n  en: [bye, goodbye, see you, that's all, thanks bye, gotta go, i'm done]\n\nFarewellMessage:\n  zh: 感谢您光临云尚商城，祝您购物愉快，再见！\n  yue: 多謝您光臨雲尚商城，祝您購物愉快，再見！\n  en: Thank you for visiting CloudShop Mall. Happy shopping and goodbye!\n```\n\n**匹配机制**：前端实时检测用户 ASR 文本，命中关键词后触发 `FarewellAndStop`。\n\n**词边界匹配**：\n- 英文：`\\b关键词\\b`（标准词边界）\n- 中文：`(^|[^\\u4e00-\\u9fa5A-Za-z0-9])关键词(?=[^\\u4e00-\\u9fa5A-Za-z0-9]|$)`\n\n这样\"再见面\"不会误触发\"再见\"，\"我没事了\"不会误触发\"没事了\"。\n\n---\n\n## 转人工关键词与提示语\n\n```yaml\nTransferKeywords:\n  zh: [转人工, 人工客服, 找人工, 转接人工, 真人客服, 找真人]\n  yue: [轉人工, 人工客服, 搵人工, 轉接人工, 真人客服]\n  en: [transfer, human agent, real person, talk to a person, speak to someone]\n\nTransferMessage:\n  zh: 好的，正在为您转接人工客服，请稍候...\n  yue: 好嘅，正在為您轉接人工客服，請稍候...\n  en: Sure, transferring you to a human agent, please wait...\n```\n\n命中转人工关键词后：\n1. 调用 `TransferAndStop` 播报转接提示语\n2. 前端显示模拟排队进度\n3. 排队\"失败\"后恢复 AI 对话（MVP 中为模拟，生产环境对接真实呼叫中心）\n\n---\n\n## TTS 音色映射表\n\n| 语言 | 性别 | VoiceId | 描述 |\n|------|------|---------|------|\n| zh（中文） | female | `female-kefu-xiaoyue` | 客服小悦 |\n| zh（中文） | male | `male-kefu-xiaoxu` | 客服小徐 |\n| yue（粤语） | female | `v-female-k3P8sL0Q` | 粤语女声 |\n| yue（粤语） | male | `v-male-L4s7PqZ9` | 粤语男声 |\n| en（英文） | female | `v-female-Z3x9LmQ2` | 理性女讲解 |\n| en（英文） | male | `v-male-Q6p8ZxL3` | 阳光男演讲 |\n\nTTS 引擎：`flow` 类型 + `flow_01_turbo` 模型（延迟最低）。\n\n> 如需自定义 TTS 音色（更换声线、调整语速语调等），请参考官方 TTS 音色配置指南（[国际站](https://trtc.io/document/79682?product=conversationalai) | [中国站](https://cloud.tencent.com/document/product/647/115414)）。\n\n---\n\n## STT 引擎映射表\n\n| 语言 | STTConfig.Language | 说明 |\n|------|-------------------|------|\n| zh（中文） | `zh` | 中文识别 |\n| yue（粤语） | `zh-TW` | 粤语识别 |\n| en（英文） | `en` | 英文识别 |\n\n后端根据前端传入的 `lang` 参数自动选择 STT 引擎。\n\n---\n\n## 固定默认参数\n\n这些参数在后端代码中硬编码，用户无需配置：\n\n| 参数 | 值 | 理由 |\n|------|------|------|\n| `TurnDetection.SemanticEagerness` | `auto` | 平衡响应速度与耐心 |\n| `FilterOneWord` | `false` | 保留\"嗯\"\"好\"等应答词 |\n| `WelcomeMessagePriority` | `0` | 欢迎语可被打断 |\n| `MaxIdleTime` | `60s` | 客服标准空闲超时 |\n| `SubtitleMode` | `1` | 句子级同步下发（非逐字） |\n| `FilterBracketsContent` | `1`(zh) / `2`(en) | 过滤 LLM 输出的舞台说明 |\n| `LLMConfig.Streaming` | `true` | 流式输出，首字延迟最优 |\n\n---\n\n## UI 可调参数\n\n用户可通过前端 UI 调整：\n\n| 参数 | 控件 | 取值 | 默认 | 含义 |\n|------|------|------|------|------|\n| 语言 | 顶部栏切换 | zh/yue/en | 跟随浏览器 | 联动 STT/TTS/Prompt/UI 文案 |\n| 对话模式 | Pill 切换 | voice/avatar | voice | 需 AvatarConfig 三项全填 |\n| 客服角色 | 头像卡片 | female/male | female | 影响 TTS VoiceId |\n| 断句模式 | Pill 切换 | 3(语义)/0(VAD) | 3 | 语义断句用 LLM 判断 |\n| 打断模式 | Pill 切换 | 0(智能)/1(手动) | 0 | 智能=自动检测打断 |\n| VAD 时长 | 滑块 | 240-2000ms | 600ms | 越小响应越快 |\n| 远场人声抑制 | 滑块 | 0-5 | 3 | 越高抑制越强 |\n| 打断时长 | 滑块 | 240-2000ms | 600ms | 仅智能打断模式 |\n\n---\n\n## Region 切换机制\n\n`config_loader.py` 中的实现：\n\n```python\nREGION_PROFILES = {\n    \"cn\": {\n        \"trtc_endpoint\": \"trtc.tencentcloudapi.com\",\n        \"trtc_region\": \"ap-guangzhou\",\n    },\n    \"intl\": {\n        \"trtc_endpoint\": \"trtc.intl.tencentcloudapi.com\",\n        \"trtc_region\": \"ap-singapore\",\n    },\n}\n```\n\n配置加载时根据 `Deployment.Region` 自动选择对应的 endpoint 和 region。未知 region 值会回退到 `intl`。\n\nFile v1.2.3:references/frontend-guide.md\n\n# TRTC AI 智能客服 - 前端集成指南\n\n## 目录\n\n1. [TRTC Web SDK 集成](#trtc-web-sdk-集成)\n2. [对话生命周期](#对话生命周期)\n3. [消息处理协议](#消息处理协议)\n4. [文字输入（跳过 ASR）](#文字输入跳过-asr)\n5. [关键词检测](#关键词检测)\n6. [字幕增量/累积自适应](#字幕增量累积自适应)\n7. [转人工流程](#转人工流程)\n8. [UI 组件结构](#ui-组件结构)\n9. [国际化系统](#国际化系统)\n10. [状态管理](#状态管理)\n\n---\n\n## TRTC Web SDK 集成\n\n### 引入 SDK\n\n```html\n<script src=\"https://web.sdk.qcloud.com/trtc/webrtc/v5/dist/trtc.js\"></script>\n```\n\n### 初始化与进房\n\n```javascript\n// 创建 TRTC 客户端\nconst trtcClient = TRTC.create();\n\n// 绑定事件\ntrtcClient.on(TRTC.EVENT.CUSTOM_MESSAGE, handleMessage);           // 字幕 + AI 状态\ntrtcClient.on(TRTC.EVENT.REMOTE_USER_LEAVE, onRobotLeave);         // 机器人退房\ntrtcClient.on(TRTC.EVENT.REMOTE_VIDEO_AVAILABLE, onVideoAvailable); // 数字人视频流\n\n// 进房\nawait trtcClient.enterRoom({\n    roomId: roomId,        // 房间号（数字）\n    scene: 'rtc',\n    sdkAppId: sdkAppId,\n    userId: userId,\n    userSig: userSig,\n});\n\n// 开麦克风（纯语音场景）\nawait trtcClient.startLocalAudio();\n```\n\n### 退房\n\n```javascript\nawait trtcClient.stopLocalAudio();\nawait trtcClient.exitRoom();\ntrtcClient.destroy();\n```\n\n---\n\n## 对话生命周期\n\n```\nidle → connecting → active → ending → idle\n                              ↓\n                         transferring → idle\n```\n\n### 启动流程（startCall）\n\n```javascript\nasync function startCall() {\n    STATE.callState = 'connecting';\n\n    // 1. join：获取 UserSig\n    const joinData = await postAction('join', { userid: STATE.userId });\n    STATE.sdkAppId = joinData.sdkappid;\n    STATE.userSig = joinData.usersig;\n    STATE.robotUserId = joinData.robot_userid;\n    STATE.robotUserSig = joinData.robot_usersig;\n    STATE.endKeywords = joinData.end_keywords;\n    STATE.farewellMessage = joinData.farewell_message;\n    STATE.transferKeywords = joinData.transfer_keywords;\n    STATE.avatarAvailable = joinData.avatar_available;\n\n    // 2. 创建 TRTC 客户端并进房\n    trtcClient = TRTC.create();\n    bindEvents(trtcClient);\n    await trtcClient.enterRoom({ roomId, scene: 'rtc', sdkAppId, userId, userSig });\n    await trtcClient.startLocalAudio();\n\n    // 3. StartAIConversation\n    const startData = await postAction('StartAIConversation', {\n        RoomId: STATE.roomId,\n        AgentConfig: {\n            UserId: STATE.robotUserId,\n            UserSig: STATE.robotUserSig,\n            TargetUserId: STATE.userId,\n            Lang: USER_CFG.lang,\n        },\n        UserConfig: {\n            InterruptMode: USER_CFG.interruptMode,\n            InterruptSpeechDuration: USER_CFG.interruptSpeechDuration,\n            VadLevel: USER_CFG.vadLevel,\n            VadSilenceTime: USER_CFG.vadSilenceTime,\n            Gender: STATE.gender,\n        },\n        UseAvatar: STATE.useAvatar,\n        AvatarConfig: STATE.useAvatar ? {\n            AvatarUserID: STATE.avatarUserId,\n            AvatarUserSig: STATE.avatarUserSig,\n        } : undefined,\n    });\n    STATE.taskId = startData.TaskId;\n    STATE.callState = 'active';\n}\n```\n\n### 结束流程（farewellAndEnd）\n\n```javascript\nasync function farewellAndEnd() {\n    STATE.callState = 'ending';\n\n    // 1. 发送 FarewellAndStop\n    await postAction('FarewellAndStop', {\n        TaskId: STATE.taskId,\n        Lang: USER_CFG.lang,\n    });\n\n    // 2. 等待机器人退房（onRobotLeave 回调）\n    // 3. 退房\n    await cleanupRoom();\n\n    // 4. 显示评分弹窗\n    showRatingOverlay();\n}\n```\n\n### 机器人退房回调\n\n```javascript\nfunction onRobotLeave(event) {\n    const { userId } = event;\n    if (userId === STATE.robotUserId || userId === STATE.avatarUserId) {\n        if (STATE.callState === 'ending' || STATE.callState === 'transferring') {\n            cleanupRoom();\n        }\n    }\n}\n```\n\n---\n\n## 消息处理协议\n\n所有云端消息通过 `TRTC.EVENT.CUSTOM_MESSAGE` 事件接收：\n\n```javascript\nfunction handleMessage(event) {\n    const { data } = event;\n    const msg = JSON.parse(new TextDecoder().decode(data));\n\n    switch (msg.type) {\n        case 10000:  // 字幕\n            handleSubtitle(msg);\n            break;\n        case 10001:  // AI 状态\n            handleAIState(msg);\n            break;\n    }\n}\n```\n\n### type: 10000 - 字幕消息\n\n```json\n{\n    \"type\": 10000,\n    \"sender\": \"user_xxx_robot\",\n    \"payload\": {\n        \"roundid\": \"round_123\",\n        \"userid\": \"user_xxx\",       // 发言者\n        \"text\": \"你好，请问...\",\n        \"end\": false                 // true=该轮结束\n    }\n}\n```\n\n**区分用户和 AI**：\n- `payload.userid === STATE.userId` → 用户的 ASR 文本\n- `payload.userid !== STATE.userId` → AI 的回复文本\n\n### type: 10001 - AI 状态\n\n```json\n{\n    \"type\": 10001,\n    \"payload\": {\n        \"state\": 1,         // 1=聆听 2=思考 3=说话 4=打断 5=结束\n        \"roundid\": \"round_123\"\n    }\n}\n```\n\n| state | 含义 | 前端响应 |\n|-------|------|----------|\n| 1 | 聆听 | 显示\"聆听中...\" |\n| 2 | 思考 | 显示 typing 动画 |\n| 3 | 说话 | 更新语音状态指示 |\n| 4 | 打断 | 标记当前回复被打断 |\n| 5 | 结束 | 触发结束流程 |\n\n---\n\n## 文字输入（跳过 ASR）\n\n使用 `type: 20000` 自定义消息协议，文字直接发送到 LLM：\n\n```javascript\nfunction sendTextMessage(text) {\n    const message = {\n        type: 20000,\n        sender: STATE.userId,\n        receiver: [STATE.robotUserId],\n        payload: {\n         \n\nArchive v1.2.2: 15 files, 86828 bytes\n\nFiles: assets/start.sh (28706b), assets/static/app.js (52760b), assets/static/i18n.js (14719b), assets/static/mock-orders.json (1525b), assets/templates/customer_service.html (62687b), assets/TLSSigAPIv2.py (16022b), README_ZH.md (6090b), README.md (6281b), references/architecture.md (12223b), references/config-guide.md (10431b), references/frontend-guide.md (14226b), scripts/scaffold.py (37555b), skill-card.md (2794b), SKILL.md (13888b), _meta.json (143b)\n\nArchive v1.2.1: 14 files, 84868 bytes\n\nFiles: assets/start.sh (28706b), assets/static/app.js (50869b), assets/static/i18n.js (14719b), assets/static/mock-orders.json (1525b), assets/templates/customer_service.html (62687b), assets/TLSSigAPIv2.py (16022b), README_ZH.md (6090b), README.md (6281b), references/architecture.md (12223b), references/config-guide.md (10431b), references/frontend-guide.md (14226b), scripts/scaffold.py (35942b), SKILL.md (13888b), _meta.json (143b)\n\nArchive v1.2.0: 14 files, 83152 bytes\n\nFiles: assets/start.sh (23457b), assets/static/app.js (50869b), assets/static/i18n.js (14719b), assets/static/mock-orders.json (1525b), assets/templates/customer_service.html (62687b), assets/TLSSigAPIv2.py (16022b), README_ZH.md (6090b), README.md (6281b), references/architecture.md (12223b), references/config-guide.md (10431b), references/frontend-guide.md (14226b), scripts/scaffold.py (35942b), SKILL.md (13888b), _meta.json (143b)\n\nArchive v1.1.1: 14 files, 81867 bytes\n\nFiles: assets/start.sh (22242b), assets/static/app.js (50869b), assets/static/i18n.js (14719b), assets/static/mock-orders.json (1525b), assets/templates/customer_service.html (62687b), assets/TLSSigAPIv2.py (16022b), README_EN.md (6093b), README.md (5912b), references/architecture.md (12223b), references/config-guide.md (10135b), references/frontend-guide.md (14226b), scripts/scaffold.py (36057b), SKILL.md (12009b), _meta.json (143b)\n\nArchive v1.1.0: 14 files, 81760 bytes\n\nFiles: assets/start.sh (22242b), assets/static/app.js (50442b), assets/static/i18n.js (14719b), assets/static/mock-orders.json (1525b), assets/templates/customer_service.html (62687b), assets/TLSSigAPIv2.py (16022b), README_EN.md (6093b), README.md (5912b), references/architecture.md (12223b), references/config-guide.md (10135b), references/frontend-guide.md (14226b), scripts/scaffold.py (36057b), SKILL.md (12009b), _meta.json (143b)\n\nArchive v1.0.1: 14 files, 80840 bytes\n\nFiles: assets/start.sh (22242b), assets/static/app.js (49314b), assets/static/i18n.js (14719b), assets/static/mock-orders.json (1525b), assets/templates/customer_service.html (57984b), assets/TLSSigAPIv2.py (16022b), README_EN.md (6093b), README.md (5912b), references/architecture.md (12223b), references/config-guide.md (10135b), references/frontend-guide.md (14226b), scripts/scaffold.py (36057b), SKILL.md (12009b), _meta.json (143b)\n\nArchive v1.0.0: 14 files, 80831 bytes\n\nFiles: assets/start.sh (22248b), assets/static/app.js (49314b), assets/static/i18n.js (14719b), assets/static/mock-orders.json (1525b), assets/templates/customer_service.html (57984b), assets/TLSSigAPIv2.py (16022b), README_EN.md (6093b), README.md (5912b), references/architecture.md (12223b), references/config-guide.md (10141b), references/frontend-guide.md (14226b), scripts/scaffold.py (36057b), SKILL.md (12009b), _meta.json (143b)","readmeExcerpt":"Skill: TRTC AI Customer Service Owner: jerryang-cool Summary: Build an AI e-commerce customer service Web app with TRTC ConversationAI — real-time voice/text dual-mode, trilingual (Chinese/English/Cantonese), digital av... Tags: latest:1.2.5 Version history: v1.2.5 | 2026-05-26T13:10:12.564Z | auto trtc-ai-customer-service v1.2.5 - Updated documentation (SKILL.md) for improved clarity and completeness. - Minor improv","codeSnippets":[],"executableExamples":[{"language":"text","snippet":"浏览器 (TRTC Web SDK v5)\n     ↕ 音频 (WebRTC) + 自定义消息 (字幕/状态/文字输入)\nTRTC Room\n     ↕ 内置 ASR → LLM → TTS → 推回房间\nTRTC AI Bot (云端)\n     ↕ OpenAPI (TC3-HMAC-SHA256)\nFlask 后端 (app.py)  —— 仅 UserSig 签发 + OpenAPI 中转"},{"language":"bash","snippet":"python {baseDir}/scripts/scaffold.py <项目目录> [--name <商城名称>] [--name-en <English name>]"},{"language":"bash","snippet":"# User-level (available across all projects)\ngit clone <repo-url> ~/.claude/skills/trtc-ai-customer-service\n\n# OR project-level (commit to repo, share with team)\ngit clone <repo-url> .claude/skills/trtc-ai-customer-service"},{"language":"bash","snippet":"# User-level\ngit clone <repo-url> ~/.codex/skills/trtc-ai-customer-service\n\n# OR project-level\ngit clone <repo-url> .agents/skills/trtc-ai-customer-service"},{"language":"bash","snippet":"# Skill bundle: drop into Cursor's skills directory\ngit clone <repo-url> ~/.cursor/skills/trtc-ai-customer-service"},{"language":"bash","snippet":"# 1. Generate a new project\npython scripts/scaffold.py ./my-shop --name \"CloudShop\" --name-en \"CloudShop Mall\"\n\n# 2. Launch (first run enters interactive credential wizard)\ncd ./my-shop && ./start.sh\n\n# 3. Open http://localhost:8080"}],"parameters":null,"dependencies":[],"permissions":[],"extractedFiles":[{"path":"SKILL.md","content":"---\nname: trtc-ai-customer-service\nversion: 1.2.5\ndescription: |\n  Build an AI e-commerce customer service Web app with TRTC ConversationAI — real-time voice/text dual-mode, trilingual (Chinese/English/Cantonese), digital avatar optional. Covers order inquiry, returns, shipping tracking, and promotions.\n  基于腾讯云 TRTC Conversational AI 快速构建 AI 电商客服 Web 应用 — 实时语音/文字双模、中英粤三语、数字人可选。覆盖订单查询、退换货、物流追踪、商品咨询等场景。\nhomepage: https://github.com/jerryang-cool/trtc-ai-customer-service-skill\nmetadata:\n  openclaw:\n    emoji: \"🛍️\"\n    requires:\n      bins:\n        - python3\n---\n\n# TRTC AI 电商客服 Skill\n\n本 Skill 指导你基于腾讯云 TRTC Conversational AI 能力，快速构建 AI 电商客服 Web 应用。\n场景预置了订单查询、退换货处理、商品咨询、物流追踪、优惠活动等电商业务模块。\n\n## 触发条件\n\n当用户**表达构建/搭建/集成意图**时使用此 Skill：\n- \"做一个 AI 客服\" \"搭建电商客服\" \"帮我做个智能客服系统\" \"语音客服 demo\"\n- \"build an AI customer service\" \"e-commerce customer service app\"\n- \"TRTC ConversationAI\" \"TRTC + AI 客服\" \"TRTC e-commerce support\"\n- \"StartAIConversation\" \"StopAIConversation\" \"ControlAIConversation\"（TRTC API 名称）\n- \"数字人客服\" \"avatar customer service\"\n- \"实时语音 AI 对话\" \"ASR + LLM + TTS 客服\"\n\n**不应触发的场景**：\n- 用户仅在讨论客服概念，没有构建/开发意图\n- 用户询问通用 chat bot 方案，不需要语音能力或电商场景\n- 关键词如 \"voice bot\" \"chat bot\" 单独出现且无构建上下文\n\n## 架构总览\n\n```\n浏览器 (TRTC Web SDK v5)\n     ↕ 音频 (WebRTC) + 自定义消息 (字幕/状态/文字输入)\nTRTC Room\n     ↕ 内置 ASR → LLM → TTS → 推回房间\nTRTC AI Bot (云端)\n     ↕ OpenAPI (TC3-HMAC-SHA256)\nFlask 后端 (app.py)  —— 仅 UserSig 签发 + OpenAPI 中转\n```\n\n| 平面 | 通道 | 内容 |\n|------|------|------|\n| **媒体面** | WebRTC 音频流 | 用户麦克风 ↔ TRTC 房间 ↔ AI Bot |\n| **控制面** | HTTP `/action` | 前端 → Flask → TRTC OpenAPI |\n| **数据面** | TRTC 自定义消息 | 字幕(10000) / AI 状态(10001) / 文字输入(20000) / 打断(20001) |\n\n后端**完全不调用 LLM**——LLM 由 TRTC 云端 AI Bot 内部调用，后端只负责签发 UserSig 和中转 OpenAPI 请求。\n\n---\n\n## 工作流程\n\n根据用户需求选择合适的路径。\n\n### 路径 A：从零创建新项目（推荐）\n\n#### Step 1: 生成项目\n\n运行脚手架脚本：\n\n```bash\npython {baseDir}/scripts/scaffold.py <项目目录> [--name <商城名称>] [--name-en <English name>]\n```\n\n- `{baseDir}`：本 Skill 所在目录的绝对路径（由 Agent 自动替换为实际路径）\n- `--name`：商城名称（默认\"云尚商城\"），用于中文/粤语的 SystemPrompt、欢迎语、告别语、前端 UI\n- `--name-en`：英文商城名称（默认自动推导：中文名时为\"CloudShop Mall\"，英文名时与 `--name` 相同），用于英文 SystemPrompt、英文欢迎语/告别语\n- 默认支持中文/英文/粤语三语，无需手动指定语言\n- 脚本自动生成全部文件：后端 + 前端 + 头像 + 鉴权库 + 启动脚本，无需手动复制任何文件\n\n**检查点**：确认用户看到 `✅ 电商客服项目已生成到: xxx` 和完整文件列表，再继续。\n\n#### Step 2: 配置密钥\n\n引导用户运行启动脚本（**根据操作系统自动选择**：macOS/Linux 用 `./start.sh`，Windows 用 `start.bat`），首次运行会进入交互式引导：\n\n- [0/4] 选择部署区域（默认 `intl` 国际站，可选 `cn` 中国站）— 后续步骤会根据所选区域展示对应的控制台链接\n- [1/4] 腾讯云 API 密钥 → 脚本会展示对应区域的 [CAM 控制台](https://console.intl.cloud.tencent.com/cam/capi) 链接\n- [2/4] TRTC 应用凭据 → 脚本会展示对应区域的 [TRTC 控制台](https://console.trtc.io/app) 链接\n- [3/4] LLM 配置 → **建议优先使用 TokenHub**（腾讯云统一 LLM 网关，开箱即用）：\n  - `LLMConfig.LLMType`：`openai`（固定）\n  - `LLMConfig.Model`：`deepseek-v4-flash`（推荐）\n  - `LLMConfig.APIUrl`：\n    - 国际站：`https://tokenhub-intl.tencentcloudmaas.com/v1/chat/completions`\n    - 中国站：`https://tokenhub.tencentmaas.com/v1/chat/completions`\n  - `LLMConfig.APIKey`：在 TokenHub 控制台获取（[国际站](https://console.intl.cloud.tencent.com/tokenhub) | [中国站](https://console.cloud.tence"},{"path":"README.md","content":"# TRTC AI Customer Service Skill\n\nEnglish | [简体中文](README_ZH.md)\n\n> Rapidly scaffold a production-ready AI customer service Web application powered by [Tencent RTC Conversational AI](https://trtc.io/solutions/conversational-ai) — voice & text dual-mode, trilingual, with built-in e-commerce workflows.\n\n## Highlights\n\n| Capability | Description |\n|-----------|-------------|\n| **Real-time Voice** | Bidirectional WebRTC audio between end-user and cloud-hosted AI Bot |\n| **Text Fallback** | Bypass ASR — send typed messages directly to the LLM pipeline |\n| **Trilingual i18n** | Chinese / Cantonese / English across UI, STT, TTS, and SystemPrompt |\n| **E-commerce Workflows** | Order inquiry, returns & exchanges, shipping tracking, promotions |\n| **Digital Avatar** | Optional virtual human rendering; graceful degradation to pure voice |\n| **Session Lifecycle** | Keyword-triggered farewell, human agent transfer, auto-idle timeout |\n| **Service Rating** | 4-dimension post-session evaluation |\n\n## Installation\n\nThis is a **portable Agent Skill** (a `SKILL.md` + `scripts/` + `references/` + `assets/` bundle). Install it to your tool's skills directory and the agent will auto-discover it.\n\n### OpenClaw\n\nChoose the install location based on your needs:\n\n| Location | Scope | Command |\n|----------|-------|---------|\n| `<workspace>/skills/` | Current workspace, highest priority | `git clone https://github.com/jerryang-cool/trtc-ai-customer-service-skill.git skills/trtc-ai-customer-service` |\n| `~/.agents/skills/` | Personal, effective across workspaces | `git clone https://github.com/jerryang-cool/trtc-ai-customer-service-skill.git ~/.agents/skills/trtc-ai-customer-service` |\n| `~/.openclaw/skills/` | Global, visible to all agents | `git clone https://github.com/jerryang-cool/trtc-ai-customer-service-skill.git ~/.openclaw/skills/trtc-ai-customer-service` |\n\nInvoke via natural language (\"help me build an AI customer service\") or slash command `/trtc-ai-customer-service`.\n\n> See [OpenClaw Skills documentation](https://docs.openclaw.ai/tools/skills) for more details.\n\n### CodeBuddy\n\nSettings → Skills → **Import Skill**, then point to this repository's directory. Once imported, mention keywords such as *\"AI customer service\"*, *\"e-commerce support\"*, or *\"TRTC + AI\"* to activate.\n\n### Claude Code\n\n```bash\n# User-level (available across all projects)\ngit clone <repo-url> ~/.claude/skills/trtc-ai-customer-service\n\n# OR project-level (commit to repo, share with team)\ngit clone <repo-url> .claude/skills/trtc-ai-customer-service\n```\n\nClaude Code auto-discovers skills via `description` matching. Invoke implicitly (\"help me build an AI customer service\") or explicitly via `/trtc-ai-customer-service`.\n\n### OpenAI Codex CLI\n\n```bash\n# User-level\ngit clone <repo-url> ~/.codex/skills/trtc-ai-customer-service\n\n# OR project-level\ngit clone <repo-url> .agents/skills/trtc-ai-customer-service\n```\n\nCodex auto-detects new skills on next session. Invoke implicitly via natural language, "},{"path":"_meta.json","content":"{\n  \"ownerId\": \"kn7c55va424ew234devca4r09186sb9y\",\n  \"slug\": \"trtc-ai-customer-service\",\n  \"version\": \"1.2.5\",\n  \"publishedAt\": 1779801012564\n}"},{"path":"references/architecture.md","content":"# TRTC AI 智能客服 - 架构设计参考\n\n## 目录\n\n1. [系统架构](#系统架构)\n2. [项目结构](#项目结构)\n3. [后端实现详解](#后端实现详解)\n4. [认证流程](#认证流程)\n5. [核心设计模式](#核心设计模式)\n6. [依赖清单](#依赖清单)\n7. [启动与部署](#启动与部署)\n\n---\n\n## 系统架构\n\n### 三平面模型\n\n```\n┌─────────────────────────────────────────────────┐\n│              浏览器 (TRTC Web SDK v5)              │\n│                                                   │\n│   音频流 (WebRTC)   自定义消息 (字幕/状态/文字)       │\n└───────────┬─────────────────┬─────────────────────┘\n            │                 │\n            ▼                 ▼\n┌───────────────────────────────────────────────────┐\n│                  TRTC Room (云端)                   │\n│                                                     │\n│   ASR ──► LLM ──► TTS ──► 推回房间                  │\n│                                                     │\n│              TRTC AI Bot (云端实例)                   │\n└───────────┬─────────────────────────────────────────┘\n            │ OpenAPI (TC3-HMAC-SHA256)\n            ▼\n┌───────────────────────────────────────────────────┐\n│   Flask 后端 (app.py)                               │\n│   - UserSig 签发                                    │\n│   - TRTC OpenAPI 中转                               │\n│   - 零 LLM 调用                                     │\n└─────────────────────────────────────────────────────┘\n```\n\n关键洞察：**后端完全不调用 LLM**。LLM 推理由 TRTC 云端 AI Bot 内部完成。后端只做两件事：\n1. 签发 UserSig（用于 TRTC 房间鉴权）\n2. 中转 TRTC OpenAPI 请求（启动/停止/控制 AI 对话）\n\n### 消息类型\n\n| type | 方向 | 内容 |\n|------|------|------|\n| `10000` | 云→端 | 字幕（用户 ASR 结果 + AI 回复文本） |\n| `10001` | 云→端 | AI 状态（聆听/思考/说话/打断/结束） |\n| `20000` | 端→云 | 文字输入（跳过 ASR 直送 LLM） |\n| `20001` | 端→云 | 手动打断 |\n\n---\n\n## 项目结构\n\n```\nproject/\n├── app.py                        # Flask 主入口（~296 行，5 个 Action 处理器）\n├── config_loader.py              # 配置加载器（Region/TTS/STT 映射）\n├── trtc_signer.py                # UserSig 三套签发封装\n├── TLSSigAPIv2.py                # 腾讯云官方 TRTC HMAC 鉴权库（不修改）\n├── env.example.yaml              # 配置模板\n├── env.yaml                      # 实际配置（.gitignore 排除）\n├── requirements.txt              # 4 个 Python 依赖\n├── start.sh / start.bat          # 一键启动脚本\n├── templates/\n│   └── customer_service.html     # 主页面（配置侧边栏 + 聊天区 + 评分弹窗）\n├── static/\n│   ├── app.js                    # 前端核心交互逻辑\n│   ├── i18n.js                   # 国际化字典（zh/yue/en）\n│   └── avatars/                  # 客服头像\n└── docs/\n    └── PARAMS.md                 # 参数配置详解\n```\n\n---\n\n## 后端实现详解\n\n### 初始化\n\n```python\n# 加载配置\nconfig = AppConfig(\"env.yaml\")\nsigner = TRTCSigner(config.sdkappid, config.trtc_secret)\n\n# 初始化 TRTC OpenAPI 客户端\n_cred = credential.Credential(config.secret_id, config.secret_key)\n_http = HttpProfile()\n_http.endpoint = config.trtc_endpoint  # 按 Region 自动切换\n_client_profile = ClientProfile()\n_client_profile.httpProfile = _http\ntrtc_api = trtc_client.TrtcClient(_cred, config.trtc_region, _client_profile)\n```\n\n### 路由设计\n\n仅 2 个路由，极简：\n- `GET /` → 渲染主页面\n- `POST /action` → 统一 API 调度，通过 `Action` 请求头区分\n\n### Action 处理器详解\n\n#### handle_join(data)\n\n签发三套 UserSig 并下发配置：\n\n```python\ndef handle_join(data):\n    user_id = da"},{"path":"references/config-guide.md","content":"# TRTC AI 智能客服 - 配置参数完全指南\n\n## 目录\n\n1. [配置文件结构](#配置文件结构)\n2. [部署区域](#部署区域)\n3. [腾讯云 API 密钥](#腾讯云-api-密钥)\n4. [TRTC 应用凭据](#trtc-应用凭据)\n5. [LLM 配置](#llm-配置)\n6. [欢迎语](#欢迎语)\n7. [数字人配置](#数字人配置)\n8. [关键词与告别语](#关键词与告别语)\n9. [转人工关键词与提示语](#转人工关键词与提示语)\n10. [TTS 音色映射表](#tts-音色映射表)\n11. [STT 引擎映射表](#stt-引擎映射表)\n12. [固定默认参数](#固定默认参数)\n13. [UI 可调参数](#ui-可调参数)\n14. [Region 切换机制](#region-切换机制)\n\n---\n\n## 配置文件结构\n\n配置使用 YAML 格式，通过 `envyaml` 库加载（支持环境变量替换）。\n\n```yaml\n# env.yaml 完整模板\nDeployment:\n  Region: intl\n\nCloudAPI:\n  SECRET_ID: your-secret-id\n  SECRET_KEY: your-secret-key\n\nTRTC:\n  SDKAPPID: 0\n  SECRET: your-trtc-secret\n\nLLMConfig:\n  LLMType: openai\n  Model: your-model-name\n  APIKey: your-api-key\n  APIUrl: your-llm-api-url\n  Timeout: 5.0\n  History: 20\n  Temperature: 0.3\n  SystemPrompt: |\n    你是一名专业的客服助手...\n  SystemPromptYue: |\n    你係一名專業嘅客服助手...\n  SystemPromptEn: |\n    You are a professional customer service assistant...\n\nWelcomeMessage:\n  zh: 您好，我是AI客服小助手...\n  yue: 您好，我係AI客服小助手...\n  en: \"Hello! I'm your AI assistant...\"\n\nAvatarConfig:\n  AvatarType: tencent\n  Appkey: \"\"\n  AccessToken: \"\"\n  VirtualmanProjectId: \"\"\n\nEndKeywords:\n  zh: [拜拜, 再见, 挂了, ...]\n  yue: [拜拜, 再見, 收線啦, ...]\n  en: [bye, goodbye, see you, ...]\n\nFarewellMessage:\n  zh: 感谢您的咨询，再见！\n  yue: 多謝您嘅諮詢，再見！\n  en: Thank you for your inquiry. Goodbye!\n\nTransferKeywords:\n  zh: [转人工, 人工客服, 找人工, ...]\n  yue: [轉人工, 人工客服, 搵人工, ...]\n  en: [transfer, human agent, real person, ...]\n\nTransferMessage:\n  zh: 好的，正在为您转接人工客服，请稍候...\n  yue: 好嘅，正在為您轉接人工客服，請稍候...\n  en: Sure, transferring you to a human agent, please wait...\n```\n\n---\n\n## 部署区域\n\n```yaml\nDeployment:\n  Region: intl   # intl / cn\n```\n\n| 值 | 说明 | TRTC Endpoint | TRTC Region |\n|----|------|---------------|-------------|\n| `intl` | 国际站账号（默认） | `trtc.intl.tencentcloudapi.com` | `ap-singapore` |\n| `cn` | 中国大陆账号 | `trtc.tencentcloudapi.com` | `ap-guangzhou` |\n\nRegion 决定了 TRTC OpenAPI 的请求域名和地域参数。\n\n---\n\n## 腾讯云 API 密钥\n\n```yaml\nCloudAPI:\n  SECRET_ID: your-secret-id\n  SECRET_KEY: your-secret-key\n```\n\n用于 TRTC OpenAPI 的 TC3-HMAC-SHA256 签名。在腾讯云控制台获取（[国际站](https://console.intl.cloud.tencent.com/cam/capi) | [中国站](https://console.cloud.tencent.com/cam/capi)）。\n\n**安全提醒**：这是主账号密钥，生产环境建议使用子账号并限制权限。\n\n---\n\n## TRTC 应用凭据\n\n```yaml\nTRTC:\n  SDKAPPID: 0\n  SECRET: your-trtc-secret\n```\n\n- `SDKAPPID`：TRTC 应用 ID，在 TRTC 控制台创建（[国际站](https://console.trtc.io/app) | [中国站](https://console.cloud.tencent.com/trtc/app)）\n- `SECRET`：用于生成 UserSig 的密钥\n\n---\n\n## LLM 配置\n\n```yaml\nLLMConfig:\n  LLMType: openai             # LLM 协议类型（目前仅支持 openai）\n  Model: your-model-name      # 模型名称\n  APIKey: your-api-key        # LLM API Key\n  APIUrl: your-llm-api-url    # LLM API 端点（兼容 OpenAI /v1/chat/completions 协议）\n  Timeout: 5.0                # 超时时间（秒）\n  History: 20                 # 上下文轮数\n  Temperature: 0.3            # 温度参数（越低越确定）\n  SystemPrompt: |             # 中文系统提示词\n    你是一名专业的客服助手...\n  SystemPromptYue: |          # 粤语系统提示词（可选，默认用中文）\n    你係一名專業嘅客服助手...\n  SystemPromptEn: |           # 英文系统提示词（可选，默认用中文）\n    You are a professional customer s"}],"languages":[],"docsSourceLabel":"CLAWHUB","editorialOverview":null,"editorialQuality":{"score":100,"threshold":65,"status":"thin","wordCount":1458,"uniquenessScore":44,"reasons":["uniqueness-below-45"]}},"media":{"evidence":{"source":"no-media","verified":false,"confidence":"low","updatedAt":"2026-10-11T03:02:55.006Z","emptyReason":"No screenshots, media assets, or demo links are available."},"primaryImageUrl":null,"mediaAssetCount":0,"assets":[],"demoUrl":null},"ownerResources":{"evidence":{"source":"unclaimed","verified":false,"confidence":"low","updatedAt":"2026-10-11T03:02:55.006Z","emptyReason":"This page has not been claimed by the agent owner."},"hasCustomPage":false,"customPageUpdatedAt":null,"customLinks":[],"structuredLinks":{"docsUrl":null,"demoUrl":null,"supportUrl":null,"pricingUrl":null,"statusUrl":null},"customPage":null},"relatedAgents":{"evidence":{"source":"protocol-neighbors","verified":false,"confidence":"medium","updatedAt":"2026-10-11T05:43:22.642Z","emptyReason":null},"items":[{"id":"8ebccd8e-3863-4187-8355-c3f14e1f9edf","entityType":"agent","canonicalPath":"/agent/iofficeai-aionui","slug":"iofficeai-aionui","name":"AionUi","description":"Free, local, open-source 24/7 Cowork app and OpenClaw for Gemini CLI, Claude Code, Codex, OpenCode, Qwen Code, Goose CLI, Auggie, and more | 🌟 Star if you like it!","url":"https://github.com/iOfficeAI/AionUi","homepage":"https://www.aionui.com","source":"GITHUB_REPOS","protocols":["MCP","OPENCLAW"],"capabilities":[],"safetyScore":100,"overallRank":70,"updatedAt":"2026-10-09T19:11:12.944Z","createdAt":"2026-02-25T03:38:16.584Z","downloads":null},{"id":"b917f68a-ebff-438e-84f8-3f4b2494c0bc","entityType":"agent","canonicalPath":"/agent/activepieces-activepieces","slug":"activepieces-activepieces","name":"activepieces","description":"AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents","url":"https://github.com/activepieces/activepieces","homepage":"https://www.activepieces.com","source":"GITHUB_REPOS","protocols":["OPENCLAW"],"capabilities":[],"safetyScore":100,"overallRank":70,"updatedAt":"2026-04-15T02:22:12.426Z","createdAt":"2026-02-25T03:38:12.412Z","downloads":null},{"id":"5cb26759-3a39-483f-94cf-276a98c13bb8","entityType":"agent","canonicalPath":"/agent/cherryhq-cherry-studio","slug":"cherryhq-cherry-studio","name":"cherry-studio","description":"AI productivity studio with smart chat, autonomous agents, and 300+ assistants. Unified access to frontier LLMs","url":"https://github.com/CherryHQ/cherry-studio","homepage":"https://cherry-ai.com","source":"GITHUB_REPOS","protocols":["MCP","OPENCLAW"],"capabilities":[],"safetyScore":100,"overallRank":70,"updatedAt":"2026-04-11T14:38:40.986Z","createdAt":"2026-02-25T03:38:19.379Z","downloads":null},{"id":"6f6582d0-5d76-4f0f-b81d-86520247950b","entityType":"agent","canonicalPath":"/agent/copilotkit-copilotkit","slug":"copilotkit-copilotkit","name":"CopilotKit","description":"The Frontend for Agents & Generative UI. React + Angular","url":"https://github.com/CopilotKit/CopilotKit","homepage":"https://docs.copilotkit.ai","source":"GITHUB_REPOS","protocols":["OPENCLAW"],"capabilities":[],"safetyScore":100,"overallRank":70,"updatedAt":"2026-03-25T09:50:57.846Z","createdAt":"2026-02-25T03:39:14.617Z","downloads":null}],"links":{"hub":"/agent","source":"/agent/source/clawhub","protocols":[{"label":"OpenClaw","href":"/agent/protocol/openclew"}]}}}