Files
knowledge-base/2 - Projects/Smart Support.md

13 KiB
Raw Permalink Blame History

created, updated, type, status, deadline, tags
created updated type status deadline tags
2026-03-29 2026-04-07 project active
ai-agent
multi-agent
langgraph
python
fastapi
mcp
architecture
customer-support
websocket
postgresql
react
docker

Smart Support

AI 客服行动层框架。粘贴你的 API获得一个能执行真实操作的智能客服。

目标

解决现有客服工具Zendesk、Intercom自动化率卡在 20-30% 的问题。这些工具能回答 FAQ但无法执行内部系统操作。Smart Support 作为「行动层」补充,让 AI 直接调用客户的内部系统完成查订单、取消订单、发优惠券等操作。

架构

客户 → React Chat UI → FastAPI WebSocket → LangGraph Supervisor → Agent → MCP Tools → 客户内部系统

核心组件:

  • langgraph-supervisor v0.0.31 -- 多 Agent 编排
  • langchain-mcp-adapters -- MCP 工具集成
  • langgraph-checkpoint-postgres v3.0.5 -- 会话状态持久化
  • interrupt() -- 写操作人工确认30 分钟 TTL 自动取消)

技术栈

组件 技术 版本/说明
后端 Python 3.11+ / FastAPI Web 框架 + WebSocket
Agent 编排 LangGraph 1.x Supervisor 模式多 Agent 路由
检查点 langgraph-checkpoint-postgres PostgreSQL 持久化
MCP langchain-mcp-adapters MultiServerMCPClient
数据库 PostgreSQL 16 Docker Compose 部署
DB 迁移 Alembic 自动运行 migrations
LLM Claude Sonnet 4.6(默认) 支持 Anthropic/OpenAI/Azure/Google 切换
前端 React 19 + TypeScript + Vite 6 React Router 7.x
测试 pytest 8.3+ / vitest 4.1.2 后端 516+ 测试 94%+ 覆盖率
部署 Docker Compose PostgreSQL + FastAPI + nginx
日志 structlog 结构化日志console/json 模式)
代码质量 ruff 0.9+ Python linting + formatting
认证 API Key X-API-Key header / ?token= for WS

核心特性

  • 多 Agent 协作YAML 驱动配置
  • 意图分类(单意图/多意图/模糊检测LLM 结构化输出
  • OpenAPI 规范自动生成 @tool 函数 + Agent YAMLLLM 辅助分类 + 人工审核)
  • 写操作人工确认interrupt()30 分钟 TTL 超时自动取消)
  • 对话回放 + 数据分析仪表盘解决率、Agent 使用率、升级率、成本)
  • Webhook 升级通知(指数退避重试)
  • 垂直行业模板电商、SaaS、金融科技
  • SSRF 防护(私有 IP 拦截、DNS 重绑定防御、重定向链验证)
  • WebSocket 流式输出 + 速率限制10 msg/10s per thread
  • 错误分类 + 自动重试ErrorCategory 枚举,可重试错误指数退避)

开发阶段

阶段 周期 内容 状态 详情
Phase 1 第 1-3 周 核心框架 COMPLETED (2026-03-30) Smart Support/Phase 1 - 核心框架
Phase 2 第 3-4 周 多 Agent + 安全 COMPLETED (2026-03-30) Smart Support/Phase 2 - 多 Agent + 安全
Phase 3 第 4-6 周 OpenAPI 自动发现 COMPLETED (2026-03-30) Smart Support/Phase 3 - OpenAPI 自动发现
Phase 4 第 6-7 周 分析 + 回放 COMPLETED (2026-03-31) Smart Support/Phase 4 - 分析 + 回放
Phase 5 缓冲周 打磨 + 演示 COMPLETED (2026-03-31) Smart Support/Phase 5 - 打磨 + 演示
Post 2026-04 架构修复 + 工程改进 进行中 API v1 版本化、structlog、Alembic、认证、GraphContext/WebSocketContext

项目数据

  • 后端测试516+ 个(单元 ~439 + 集成 ~51 + E2E ~26
  • 前端测试:~23 个vitest + happy-dom
  • 代码覆盖率:~94%
  • 应用版本v0.6.0
  • Git 最新提交:f069943 refactor: engineering improvements -- API versioning, structured logging, Alembic, error standardization

目标用户

中型电商公司(日均 500-5000 订单5-20 名客服)的客户体验负责人。

仓库

  • 代码:git@git.colacoder.com:kai/smart-support.git
  • 分支:main
  • 本地路径WindowsC:\Users\yaoji\git\ColaCoder\smart-support

WebSocket 协议

客户端 -> 服务器:

  • {"type": "message", "thread_id": "...", "content": "..."}
  • {"type": "interrupt_response", "thread_id": "...", "approved": true/false}

服务器 -> 客户端8 种消息类型):

  • {"type": "token", "agent": "...", "content": "..."} -- 流式 token
  • {"type": "interrupt", "thread_id": "...", "action": "...", "params": {...}} -- 人工确认提示
  • {"type": "clarification", "thread_id": "...", "message": "..."} -- 意图模糊,请求澄清
  • {"type": "interrupt_expired", "thread_id": "...", "action": "...", "message": "..."} -- 审批超时
  • {"type": "tool_call", "agent": "...", "tool": "...", "args": {...}} -- 工具调用
  • {"type": "tool_result", "agent": "...", "tool": "...", "result": ...} -- 工具返回
  • {"type": "message_complete", "thread_id": "..."} -- 消息完成
  • {"type": "error", "message": "..."} -- 错误

WebSocket 连接需 ?token=<ADMIN_API_KEY> 认证(未配置 key 时跳过)。

REST API

所有端点使用 /api/v1/ 前缀。管理端点需 X-API-Key headerADMIN_API_KEY 未配置时跳过认证)。

方法 路径 认证 说明
WS /ws Token WebSocket 聊天(?token=<key>
GET /api/v1/health 健康检查
GET /api/v1/conversations API Key 对话列表(分页)
GET /api/v1/replay/{thread_id} API Key 回放时间线(分页)
GET /api/v1/analytics?range=7d API Key 分析摘要
POST /api/v1/openapi/import API Key 开始 OpenAPI 导入
GET /api/v1/openapi/jobs/{id} API Key 导入任务状态
GET /api/v1/openapi/jobs/{id}/classifications API Key 获取端点分类
PUT /api/v1/openapi/jobs/{id}/classifications/{idx} API Key 修改端点分类
POST /api/v1/openapi/jobs/{id}/approve API Key 审核通过,生成工具代码 + Agent YAML

数据库表

用途
checkpoints LangGraph 状态快照(自动管理)
checkpoint_writes 检查点写入记录
conversations 对话元数据(状态、解决类型、使用 Agent、Token、成本
active_interrupts 人工确认记录interrupt_id, action, params, resolved_at
sessions 会话状态持久化last_activity, has_pending_interrupt供 PgSessionManager 使用
analytics_events 分析事件流事件类型、Agent、工具、Token、成本、耗时

数据库迁移通过 Alembic 管理,应用启动时自动执行 run_alembic_migrations()

架构决策ADR

ADR 决策 理由
ADR-001 LangGraph Supervisor 多 Agent 内置编排,无需自定义
ADR-002 PostgresSaver 从第一天起 Phase 4 分析需要可查询的检查点数据
ADR-003 WebSocket + astream_events() 双向低延迟流式
ADR-004 YAML 声明式 Agent 注册 非开发者可配置 Agent
ADR-005 LangGraph interrupt() HITL 框架内置,深度集成检查点
ADR-006 OpenAPI: 解析 -> LLM 分类 -> 人工审核 平衡自动化与安全
ADR-007 SSRF 独立模块 可复用,可独立测试

安全架构

  • L1 输入验证消息格式、长度限制10k 字符、Agent YAML 启动验证
  • L2 SSRF 防护:私有 IP 拦截、DNS 重绑定防御、重定向链验证
  • L3 HITL:写操作 interrupt()、30 分钟 TTL 自动取消
  • L4 权限隔离Agent 级工具集、读 Agent 无法调写工具
  • L5 审计追踪全操作记录、PostgreSQL 存储、回放 API

完整文档(已同步)

项目模块结构

backend/app/
  main.py              -- FastAPI 入口 (v0.6.0), 全局异常处理, 中断清理循环
  config.py            -- Pydantic Settings含 admin_api_key, log_format
  db.py                -- AsyncPostgreSQL + AsyncPostgresSaver + Alembic runner
  llm.py               -- LLM 提供商工厂Anthropic/OpenAI/Azure/Google
  graph.py             -- LangGraph Supervisor 构建,返回 GraphContext
  graph_context.py     -- GraphContext: 图 + 分类器 + 注册表的类型化封装
  ws_handler.py        -- WebSocket 消息分发 + 流式 + 速率限制
  ws_context.py        -- WebSocketContext: WS 处理依赖打包
  auth.py              -- API Key 认证中间件X-API-Key / ?token= for WS
  api_utils.py         -- 共享 envelope() 响应格式
  logging_config.py    -- structlog 配置console/json
  registry.py          -- YAML Agent 注册表 + 模板支持
  intent.py            -- LLM 意图分类器
  session_manager.py   -- Session TTL30m 滑动窗口)+ PgSessionManager
  interrupt_manager.py -- 中断 TTL 追踪 + 自动取消 + PgInterruptManager
  escalation.py        -- Webhook 升级(指数退避)
  conversation_tracker.py -- 对话生命周期追踪
  callbacks.py         -- Token 用量回调
  safety.py            -- 确认策略规则 + MCP 错误分类
  agents/              -- Agent 定义order_lookup, order_actions, discount, fallback
  openapi/             -- OpenAPI 解析 + 分类 + 生成ssrf, fetcher, parser, classifier, generator, review_api
  replay/              -- 回放模型 + 转换器 + API
  analytics/           -- 分析模型 + 事件记录 + 查询 + API

架构模式

  • Protocol 接口:所有跨模块边界使用 ProtocolSessionManagerProtocol, InterruptManagerProtocol 等)
  • Frozen dataclassesGraphContext, WebSocketContext, SessionState, InterruptRecord 等全部不可变
  • Composition Rootmain.py lifespan() 统一组装所有依赖
  • Envelope 响应{"success": bool, "data": T, "error": str | null} 统一格式
  • 双实现状态管理:内存版(开发)+ PostgreSQL 版(生产多 Worker

计划文档

项目根目录下:

  • design-doc.md -- 设计文档(问题定义、约束、方案选择)
  • ceo-plan.md -- CEO 计划(产品愿景、范围决策)
  • eng-review-plan.md -- 工程评审(架构决策、测试策略、失败模式)
  • TODOS.md -- 待办事项

快速启动

# 1. 克隆 + 配置
git clone <repo-url> && cd smart-support
cp .env.example .env && cp backend/.env.example backend/.env
# 编辑 .env 设置 ANTHROPIC_API_KEY

# 2. 启动
docker compose up -d
# PostgreSQL: localhost:5433 | Backend: localhost:8000 | Frontend: localhost:80

# 3. 测试
cd backend && pytest --cov=app --cov-report=term-missing
cd ../frontend && npm test

自动编排脚本

项目 scripts/ 目录下有基于 autonomous-agent-harness 模式的自动化脚本:

脚本 用途 模式
auto-pilot.sh 多阶段自动执行(每阶段独立 claude -p session Sequential Pipeline
dev-sequential.sh 单功能开发plan → TDD → de-sloppify → verify → commit Sequential Pipeline
de-sloppify.sh 独立清理 pass新上下文 = 无作者偏见) De-Sloppify
full-verify.sh 全套质量门(测试、安全、模块独立性、代码质量) Verification Pipeline
pr-review-loop.sh 自动审查 open PRs Continuous PR Loop
health-monitor.sh 服务健康检查(可配 Windows Task Scheduler Scheduled Monitor
phases.json 声明式阶段定义(任务、验收标准、模式、依赖) 配置文件

大部分时候不需要外部脚本 — 在 Claude Code 内直接用:

  • /ecc:feature-dev "描述" — 单功能全流程
  • /gsd:autonomous — 全项目多阶段自动

脚本只在以下场景使用:上下文窗口不够、无人值守运行、需要 Santa Method 消除作者偏见。

CLAUDE.md 已更新Step 2 从 /ecc:orchestratelegacy迁移到 /ecc:feature-dev + GSD。

已知技术债务

  • 认证/授权系统 -- 已实现 API Key 认证(auth.pyADMIN_API_KEY
  • 中断清理未定时调度 -- 已实现 _interrupt_cleanup_loop 后台任务60s 间隔)
  • 猴子补丁 -- 已替换为 GraphContext 类型化封装
  • dispatch_message 参数膨胀 -- 已替换为 WebSocketContext
  • _envelope 重复定义 -- 已提取到 api_utils.py
  • 前端缺失消息类型 -- 已添加 clarification/interrupt_expired/tool_result 处理
  • 多租户架构(第一个付费客户后)
  • CI/CD 流水线(原型阶段手动部署)
  • 速率限制进程全局状态 -- 多 Worker 需 Redis
  • 生产环境切换到 PgSessionManager/PgInterruptManager
  • OpenAPI approve 后的工具尚未运行时注入到 _TOOL_MAP仅生成代码 + YAML
  • SSRF DNS 重绑定 TOCTOU 窗口(实践中利用难度大)
  • SaaS/Fintech 模板工具仅为桩(无实现)
  • 工具生成基于字符串模板 -- 复杂场景可能需 AST