feat: 添加 AI Agent 对话测试工具 + 代码优化

主要变更:

- 新增 tests/test_ai_chat.py: AI Agent 对话测试工具

- 优化 core/pydantic_ai_agent.py 和 db/chat_log_db.py

- 清理归档文件,更新文档

Made-with: Cursor
This commit is contained in:
2026-02-28 16:19:35 +08:00
parent a6c42d505a
commit c39840fe15
49 changed files with 2453 additions and 8556 deletions

View File

@@ -1,91 +1,228 @@
# AI 客服系统 - 天网协作版部署文档
# AI 客服系统 - 部署与运维文档
## 📋 系统架构
**版本**: v1.0 | **更新日期**: 2026-02-28
---
## 目录
1. [系统架构](#系统架构)
2. [快速部署](#快速部署)
3. [启动方式](#启动方式)
4. [生产环境部署](#生产环境部署)
5. [多进程架构](#多进程架构)
6. [API 接口文档](#api-接口文档)
7. [触发条件详解](#触发条件详解)
8. [数据库](#数据库)
9. [配置说明](#配置说明)
10. [监控与日志](#监控与日志)
11. [故障排查](#故障排查)
---
## 系统架构
```
┌─────────────┐ ┌──────────────┐ ┌─────────────┐
│ 天网服务器 │ ───→ │ AI 客服 API │ ───→ │ 企业微信 │
│ (公网 IP) │ │ (127.0.0.1:6060)│ │ (轻简软件) │
│ (公网 IP) │ │ (127.0.0.1:6060)│ │ (轻简软件) │
└─────────────┘ └──────────────┘ └─────────────┘
↑ │
│ ↓
──────────────┐
┌──────────────┐
SQLite
任务数据库 │
└──────────────┘
└─────────────────────┘
──────────────┐
│ SQLite │
│ 任务数据库
└──────────────┘
```
### 核心组件
| 组件 | 地址 | 说明 |
|------|------|------|
| **AI 客服 HTTP API** | http://127.0.0.1:6060 | 接收天网任务 |
| **天网服务器** | 你的公网 IP | 任务调度中心 |
| **轻简软件** | ws://127.0.0.1:9528 | 企业微信连接 |
| **任务数据库** | SQLite | 本地存储 |
| AI 客服 HTTP API | `http://127.0.0.1:6060` | 接收天网任务 |
| 天网服务器 | 公网 IP | 任务调度中心 |
| 轻简软件 | `ws://127.0.0.1:9528` | 企业微信连接 |
| 任务数据库 | SQLite 本地存储 | 任务持久化 |
---
## 🚀 快速部署
## 快速部署
### 步骤 1环境检查
```bash
# 检查 Python 版本
python3 --version # 需要 3.8+
# 检查依赖
pip3 list | grep -E "flask|pydantic|sqlite"
cd /root/ai_customer_service/ai_cs
pip3 install -r requirements.txt
```
### 步骤 2启动 AI 客服 API
### 步骤 2启动服务
```bash
cd /root/ai_customer_service/ai_cs
# 前台运行(测试用)
python3 run_tianwang_simple.py
python3 run.py --api-only
# 后台运行(生产用)
nohup python3 run_tianwang_simple.py > /tmp/tianwang.log 2>&1 &
# 查看进程
ps aux | grep run_tianwang
# 查看日志
tail -f /tmp/tianwang.log
nohup python3 run.py --api-only > /tmp/tianwang.log 2>&1 &
```
### 步骤 3测试 API
### 步骤 3验证
```bash
# 健康检查
curl http://localhost:6060/api/health
# 预期输出:
# {"code":200,"data":{"service":"ai-cs-tianwang-bridge","timestamp":"..."},"message":"OK"}
# 预期: {"code":200,"data":{"service":"ai-cs-tianwang-bridge",...},"message":"OK"}
```
---
## 📝 API 接口说明
## 启动方式
统一入口 `run.py`,通过参数切换模式:
```bash
# 仅 HTTP API天网简化版推荐
python3 run.py --api-only
# 完整版HTTP API + WebSocket + AI Agent
python3 run.py --tianwang
# WebSocket 客服模式(默认)
python3 run.py
# 多进程模式
python3 run.py --multi --workers 4
# 不启用 AI Agent
python3 run.py --no-agent
# 指定 HTTP 端口
python3 run.py --api-only --port 8080
```
---
## 生产环境部署
### 方式 1systemd 服务(推荐)
```bash
cat > /etc/systemd/system/ai-cs-tianwang.service << 'SERVICE'
[Unit]
Description=AI Customer Service with Tianwang
After=network.target
[Service]
Type=simple
User=root
WorkingDirectory=/root/ai_customer_service/ai_cs
ExecStart=/usr/bin/python3 run.py --api-only
Restart=always
RestartSec=10
LimitNOFILE=65535
Environment="HTTP_API_PORT=6060"
StandardOutput=journal
StandardError=journal
SyslogIdentifier=ai-cs-tianwang
[Install]
WantedBy=multi-user.target
SERVICE
systemctl daemon-reload
systemctl enable ai-cs-tianwang
systemctl start ai-cs-tianwang
systemctl status ai-cs-tianwang
journalctl -u ai-cs-tianwang -f
```
### 方式 2Docker 部署
```dockerfile
FROM python:3.11-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
EXPOSE 6060
CMD ["python3", "run.py", "--api-only"]
```
```bash
docker build -t ai-cs-tianwang .
docker run -d \
--name ai-cs \
-p 6060:6060 \
-v /root/ai_customer_service/ai_cs/db:/app/db \
--restart unless-stopped \
ai-cs-tianwang
```
### 方式 3后台运行简单场景
```bash
nohup python3 run.py --api-only > /tmp/tianwang.log 2>&1 &
ps aux | grep "run.py"
tail -f /tmp/tianwang.log
pkill -f "run.py" # 停止
```
---
## 多进程架构
### 架构说明
```
单进程(默认) 多进程(可选)
┌─────────────────┐ ┌─────────┐ ┌─────────┐ ┌─────────┐
│ Python 进程 │ │进程 1 │ │进程 2 │ │进程 3 │
│ asyncio Loop │ │客户 A,B │ │客户 C,D │ │客户 E,F │
│ 所有客户 + Agent │ └─────────┘ └─────────┘ └─────────┘
└─────────────────┘
```
### 使用方法
```bash
# 多进程模式(默认 CPU 核心数)
python3 run.py --multi
# 指定进程数
python3 run.py --multi --workers 4
# 或使用专用启动器
python3 scripts/multi_process_launcher.py --workers 4
```
### 分片算法
客户按 `acc_id:from_id` 的 MD5 hash 值分配到不同进程,同一客户始终在同一进程。
### 性能对比
| 指标 | 单进程 | 多进程 (4 核) |
|------|--------|-------------|
| 并发客户数 | ~50 | ~200 |
| CPU 使用率 | 25% | 80% |
| 故障影响 | 全局 | 局部 |
---
## API 接口文档
### 1. 接收任务
**接口**: `POST /api/task/receive`
**POST** `/api/task/receive`
**请求示例**:
```bash
curl -X POST http://localhost:6060/api/task/receive \
-H "Content-Type: application/json" \
-d '{
"task_id": "TASK_20260227_001",
"type": "send_file_after_reply",
"customer": {
"id": "customer_123",
"name": "小明"
},
"customer": {"id": "customer_123", "name": "小明"},
"trigger": {
"type": "specified_customer_reply",
"customer_id": "customer_123",
@@ -93,133 +230,61 @@ curl -X POST http://localhost:6060/api/task/receive \
"keyword": "好的",
"exact_match": false
},
"action": {
"type": "send_message",
"message": "这是您要的文件"
},
"action": {"type": "send_message", "message": "这是您要的文件"},
"priority": "normal",
"timeout_hours": 24,
"created_by": "设计师 lz"
}'
```
**响应示例**:
**响应**:
```json
{
"code": 200,
"message": "任务接收成功",
"data": {
"task_id": "TASK_20260227_001",
"status": "pending"
}
}
{"code": 200, "message": "任务接收成功", "data": {"task_id": "TASK_20260227_001", "status": "pending"}}
```
---
### 2. 查询任务状态
**接口**: `GET /api/task/status/:task_id`
**GET** `/api/task/status/:task_id`
**请求示例**:
```bash
curl http://localhost:6060/api/task/status/TASK_20260227_001
```
**响应示例**:
```json
{
"code": 200,
"data": {
"task_id": "TASK_20260227_001",
"type": "send_file_after_reply",
"status": "pending",
"priority": "normal",
"retry_count": 0,
"created_at": "2026-02-27T18:00:00",
"created_by": "设计师 lz",
"triggered_at": null,
"completed_at": null,
"error_message": null
}
}
```
---
### 3. 取消任务
**接口**: `POST /api/task/cancel`
**POST** `/api/task/cancel`
**请求示例**:
```bash
curl -X POST http://localhost:6060/api/task/cancel \
-H "Content-Type: application/json" \
-d '{
"task_id": "TASK_20260227_001",
"reason": "客户取消订单"
}'
-d '{"task_id": "TASK_20260227_001", "reason": "客户取消订单"}'
```
**响应示例**:
```json
{
"code": 200,
"message": "任务已取消",
"data": {
"task_id": "TASK_20260227_001",
"status": "cancelled"
}
}
```
### 4. 任务列表
---
**GET** `/api/task/list`
### 4. 查询任务列表
参数: `customer_id`(可选)、`status`(可选)、`page`(默认1)、`page_size`(默认20)
**接口**: `GET /api/task/list`
**请求参数**:
- `customer_id` (可选): 客户 ID
- `status` (可选): 任务状态
- `page` (可选): 页码,默认 1
- `page_size` (可选): 每页数量,默认 20
**请求示例**:
```bash
curl "http://localhost:6060/api/task/list?status=pending&page=1&page_size=10"
```
---
### 5. 健康检查
**接口**: `GET /api/health`
**GET** `/api/health`
**请求示例**:
```bash
curl http://localhost:6060/api/health
```
**响应示例**:
```json
{
"code": 200,
"message": "OK",
"data": {
"timestamp": "2026-02-27T18:00:00",
"service": "ai-cs-tianwang-bridge"
}
}
```
---
## 📊 触发条件类型
## 触发条件详解
### 1. specified_customer_reply推荐
**指定客户回复指定内容**
指定客户回复指定内容时触发。
```json
{
@@ -233,105 +298,62 @@ curl http://localhost:6060/api/health
}
```
**匹配逻辑**:
- ✅ 客户 ID 匹配
- ✅ 客户名称匹配(可选)
- ✅ 消息包含关键词
| 字段 | 必填 | 说明 |
|------|------|------|
| `customer_id` | 是 | 指定客户 ID |
| `customer_name` | 否 | 指定客户名称 |
| `keyword` | 是 | 回复关键词 |
| `exact_match` | 否 | 是否精确匹配(默认 false|
---
**exact_match 说明**:
- `false`: 消息**包含**关键词即触发("好的谢谢" 匹配 "好的"
- `true`: 消息**完全等于**关键词才触发
**匹配逻辑**:
```
客户发送消息 → 检查客户 ID → 检查客户名称(可选) → 检查关键词 → 触发
```
### 2. customer_reply
**任意客户回复指定内容**
任意客户回复指定内容
```json
{
"trigger": {
"type": "customer_reply",
"keyword": "好的"
}
}
{"trigger": {"type": "customer_reply", "keyword": "好的"}}
```
---
### 3. customer_keyword
**任意客户说某关键词**
任意客户说某关键词(支持多个)。
```json
{
"trigger": {
"type": "customer_keyword",
"keywords": ["好的", "可以", "行"]
}
}
{"trigger": {"type": "customer_keyword", "keywords": ["好的", "可以", "行"]}}
```
---
### 4. customer_payment
**客户付款**
客户付款时触发。
```json
{
"trigger": {
"type": "customer_payment",
"keywords": ["已付款", "拍下了", "已下单"]
}
}
{"trigger": {"type": "customer_payment", "keywords": ["已付款", "拍下了"]}}
```
---
### 5. time_reach
**到达指定时间**
到达指定时间触发。
```json
{
"trigger": {
"type": "time_reach",
"time": "2026-02-27 09:00:00"
}
}
{"trigger": {"type": "time_reach", "time": "2026-02-28 09:00:00"}}
```
---
## 🔧 配置说明
## 数据库
### 环境变量文件
### 天网任务数据库
位置:`/root/ai_customer_service/ai_cs/.env.tianwang`
路径: `db/task_db/tasks.db`
```bash
# AI 客服配置
AI_CS_HOST=127.0.0.1
AI_CS_PORT=6060
# AI 客服 HTTP API 地址(本地)
AI_CS_API_URL=http://127.0.0.1:6060
# 天网回调地址
TIANWANG_CALLBACK_URL=http://127.0.0.1:6060/api/task/callback
# API 接口
TASK_RECEIVE=/api/task/receive
TASK_STATUS=/api/task/status
TASK_CANCEL=/api/task/cancel
TASK_LIST=/api/task/list
HEALTH=/api/health
```
---
### 数据库配置
位置:`/root/ai_customer_service/ai_cs/db/task_db/tasks.db`
**数据库结构**:
```sql
CREATE TABLE tasks (
task_id TEXT PRIMARY KEY,
@@ -360,281 +382,144 @@ CREATE TABLE tasks (
);
```
**任务状态流转**: `pending → waiting → running → completed / failed`
### 图片任务数据库
路径: `db/image_tasks.db`(详见 **项目功能汇总.md - 图片任务数据库**
---
## 📖 使用场景
## 配置说明
### 场景 1客户说"好的"后发送文件
### 环境变量
**天网下发任务**:
```json
{
"task_id": "TASK_001",
"type": "send_file_after_reply",
"customer": {
"id": "customer_123",
"name": "小明"
},
"trigger": {
"type": "specified_customer_reply",
"customer_id": "customer_123",
"customer_name": "小明",
"keyword": "好的"
},
"action": {
"type": "send_message",
"message": "这是您要的文件"
},
"priority": "normal",
"timeout_hours": 24,
"created_by": "设计师 lz"
}
文件: `.env.tianwang`
```bash
AI_CS_HOST=127.0.0.1
AI_CS_PORT=6060
AI_CS_API_URL=http://127.0.0.1:6060
TIANWANG_CALLBACK_URL=http://127.0.0.1:6060/api/task/callback
```
**流程**:
1. 天网下发任务 → AI 客服 API
2. 客户在群里说"好的"
3. AI 客服检测到匹配任务
4. 自动发送消息给客户
5. 任务标记为 completed
6. 回调通知天网
### 天网回调配置
---
`core/task_scheduler.py` 中修改回调 URL:
### 场景 2客户付款后发送教程
```python
await client.post('http://tianwang-server/api/task/callback', json={...})
```
**天网下发任务**:
```json
{
"task_id": "TASK_002",
"type": "send_tutorial_after_payment",
"customer": {
"id": "customer_456",
"name": "小红"
},
"trigger": {
"type": "customer_payment"
},
"action": {
"type": "send_message",
"message": "感谢购买!这是使用教程:..."
},
"created_by": "设计师 lz"
}
### 端口说明
| 端口 | 用途 |
|------|------|
| 6060 | HTTP API 服务器 |
| 9528 | 轻简软件 WebSocket外部|
**防火墙**:
```bash
firewall-cmd --add-port=6060/tcp --permanent && firewall-cmd --reload
```
---
### 场景 3定时发送问候
**天网下发任务**:
```json
{
"task_id": "TASK_003",
"type": "send_greeting",
"customer": {
"id": "customer_789"
},
"trigger": {
"type": "time_reach",
"time": "2026-02-28 09:00:00"
},
"action": {
"type": "send_message",
"message": "早上好!有什么可以帮您?"
},
"created_by": "设计师 lz"
}
```
---
## 🔍 监控与日志
## 监控与日志
### 查看进程状态
```bash
# 查看进程
ps aux | grep run_tianwang
# 查看端口
ps aux | grep "run.py"
netstat -tlnp | grep 6060
systemctl status ai-cs-tianwang # systemd 方式
```
### 查看日志
```bash
# 实时日志
tail -f /tmp/tianwang.log
# 最近 100 行
tail -100 /tmp/tianwang.log
# 搜索关键词
grep "任务" /tmp/tianwang.log
tail -f /tmp/tianwang.log # 文件方式
journalctl -u ai-cs-tianwang -f # systemd 方式
grep "任务" /tmp/tianwang.log # 搜索任务日志
grep "派单" /tmp/tianwang.log # 搜索派单日志
grep "转接人工" /tmp/tianwang.log # 搜索转接日志
```
### 查看数据库
```bash
# 进入 SQLite
sqlite3 /root/ai_customer_service/ai_cs/db/task_db/tasks.db
# 查看所有任务
SELECT task_id, type, status, created_at FROM tasks ORDER BY created_at DESC LIMIT 10;
# 查看待触发任务
SELECT * FROM tasks WHERE status='pending';
# 查看失败任务
SELECT task_id, error_message FROM tasks WHERE status='failed';
# 查看统计数据
SELECT status, COUNT(*) as count FROM tasks GROUP BY status;
# 退出
.exit
```
---
## ⚠️ 故障排查
## 故障排查
### 问题 1API 无法访问
### API 无法访问
**症状**: `curl http://localhost:6060/api/health` 无响应
**解决**:
```bash
# 1. 检查进程
ps aux | grep run_tianwang
# 2. 检查端口
netstat -tlnp | grep 6060
# 3. 重启服务
pkill -f run_tianwang
cd /root/ai_customer_service/ai_cs
nohup python3 run_tianwang_simple.py > /tmp/tianwang.log 2>&1 &
# 4. 查看日志
tail -f /tmp/tianwang.log
ps aux | grep "run.py" # 检查进程
netstat -tlnp | grep 6060 # 检查端口
pkill -f "run.py" # 停止
nohup python3 run.py --api-only > /tmp/tianwang.log 2>&1 &
tail -f /tmp/tianwang.log # 查看日志
```
---
### 任务接收失败500 错误)
### 问题 2任务接收失败
**症状**: POST /api/task/receive 返回 500 错误
**解决**:
```bash
# 1. 查看日志
tail -f /tmp/tianwang.log | grep "ERROR"
# 2. 检查数据库
sqlite3 /root/ai_customer_service/ai_cs/db/task_db/tasks.db ".schema tasks"
# 3. 测试数据库
sqlite3 /root/ai_customer_service/ai_cs/db/task_db/tasks.db "SELECT 1;"
# 4. 如果数据库损坏,删除重建
rm /root/ai_customer_service/ai_cs/db/task_db/tasks.db
# 重启服务后会自动创建
sqlite3 db/task_db/tasks.db ".schema tasks" # 检查数据库
# 如果数据库损坏rm db/task_db/tasks.db 然后重启(自动重建)
```
---
### 任务未触发
### 问题 3任务未触发
**症状**: 任务一直是 pending 状态
**解决**:
```bash
# 1. 检查任务状态
curl http://localhost:6060/api/task/status/TASK_ID
# 2. 查看触发日志
grep "任务触发" /tmp/tianwang.log
# 3. 检查触发条件
curl http://localhost:6060/api/task/status/TASK_ID # 检查状态
grep "任务触发" /tmp/tianwang.log # 查看触发日志
# 确认客户消息包含触发关键词
# 4. 手动触发测试
sqlite3 /root/ai_customer_service/ai_cs/db/task_db/tasks.db \
"UPDATE tasks SET status='pending' WHERE task_id='TASK_ID';"
```
---
### 内存占用过高
### 问题 4内存占用过高
**症状**: 进程内存持续增长
**解决**:
```bash
# 1. 查看内存使用
ps aux | grep run_tianwang | awk '{print $6/1024 " MB"}'
# 2. 定期重启(建议每天)
# 建议每天定时重启
crontab -e
# 添加0 3 * * * pkill -f run_tianwang && sleep 2 && nohup python3 /root/ai_customer_service/ai_cs/run_tianwang_simple.py > /tmp/tianwang.log 2>&1 &
# 添加: 0 3 * * * pkill -f "run.py" && sleep 2 && nohup python3 /root/ai_customer_service/ai_cs/run.py --api-only > /tmp/tianwang.log 2>&1 &
```
### Worker 进程退出(多进程模式)
```bash
journalctl -u ai-cs-multi -f | grep "Worker.*退出"
systemctl restart ai-cs-multi
```
---
## 📞 技术支持
### 文件位置
## 文件位置速查
| 文件 | 路径 |
|------|------|
| **启动脚本** | `/root/ai_customer_service/ai_cs/run_tianwang_simple.py` |
| **HTTP API** | `/root/ai_customer_service/ai_cs/api/http_server.py` |
| **任务调度** | `/root/ai_customer_service/ai_cs/core/task_scheduler.py` |
| **数据模型** | `/root/ai_customer_service/ai_cs/db/task_db/task_model.py` |
| **配置文件** | `/root/ai_customer_service/ai_cs/.env.tianwang` |
| **日志文件** | `/tmp/tianwang.log` |
| **数据库** | `/root/ai_customer_service/ai_cs/db/task_db/tasks.db` |
### 文档位置
| 文档 | 路径 |
|------|------|
| **部署文档** | `/root/ai_customer_service/ai_cs/部署文档.md` |
| **功能文档** | `/root/ai_customer_service/ai_cs/TIANWANG_INTEGRATION.md` |
| **使用示例** | `/root/ai_customer_service/ai_cs/SPECIFIED_CUSTOMER_REPLY_EXAMPLE.md` |
| 启动脚本 | `run.py`(通过 `--api-only` / `--tianwang` 切换模式)|
| HTTP API | `api/http_server.py` |
| 任务调度 | `core/task_scheduler.py` |
| 数据模型 | `db/task_db/task_model.py` |
| 配置文件 | `.env.tianwang` |
| 日志文件 | `/tmp/tianwang.log` |
| 任务数据库 | `db/task_db/tasks.db` |
---
## 📧 发送文档
如需发送此文档,可以:
### 方式 1复制内容
```bash
# 复制文档内容
cat /root/ai_customer_service/ai_cs/部署文档.md
```
### 方式 2生成 PDF
```bash
# 安装 pandoc
apt-get install pandoc
# 转换为 PDF
pandoc /root/ai_customer_service/ai_cs/部署文档.md -o 部署文档.pdf
```
### 方式 3发送邮件
```bash
# 使用 mail 命令
mail -s "AI 客服系统部署文档" recipient@example.com < /root/ai_customer_service/ai_cs/部署文档.md
```
---
## 🎯 快速参考卡片
## 快速参考
```
┌─────────────────────────────────────────────┐
@@ -648,15 +533,8 @@ mail -s "AI 客服系统部署文档" recipient@example.com < /root/ai_customer_
│ GET /api/task/list - 任务列表 │
│ GET /api/health - 健康检查 │
│ │
│ 启动python3 run_tianwang_simple.py
│ 启动python3 run.py --api-only
│ 日志tail -f /tmp/tianwang.log │
│ 数据库sqlite3 db/task_db/tasks.db │
└─────────────────────────────────────────────┘
```
---
**文档版本**: v1.0
**更新日期**: 2026-02-27
**维护者**: AI 客服系统团队