Files
shop-platform/docs/api_kefu.md

665 lines
16 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 智能客服API接口文档
## 一、接口说明
本接口用于连接微信小程序与Dify聊天机器人实现智能客服功能。所有接口都采用事件驱动架构支持高并发和模块化扩展。
## 二、配置说明
### 1. 安装插件
在ThinkPHP后台的插件管理页面中找到智能客服插件aikefu并点击安装按钮。
### 2. 配置插件
1. 进入智能客服配置页面
2. 输入从Dify平台获取的API密钥
3. 配置API基础地址默认https://api.dify.ai/v1
4. 配置聊天接口端点(默认:/chat-messages
5. 启用智能客服功能
### 3. 获取Dify API密钥
1. 登录Dify平台
2. 进入工作台
3. 选择您的聊天机器人项目
4. 点击"发布"按钮
5. 在API访问页面获取API密钥
## 三、接口列表
### 1. 系统健康检查
**接口地址**`/api/kefu/health`
**请求方式**GET
**请求参数**
| 参数名 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| uniacid | int | 是 | 站点ID |
| check_type | string | 否 | 检查类型full完整、basic基础、ai_serviceAI服务默认full |
**响应示例**
```json
{
"code": 0,
"message": "healthy",
"data": {
"status": "healthy",
"check_id": "health_63a8f9c1234abcd",
"timestamp": "2023-12-25 10:30:45",
"total_checks": 4,
"passed_checks": 4,
"failed_checks": 0,
"response_time_ms": 156.78,
"components": {
"database": {
"status": "healthy",
"message": "数据库连接正常",
"response_time_ms": 12.34,
"details": {
"connection": "success",
"query_test": "passed"
}
},
"ai_service_config": {
"status": "healthy",
"message": "AI服务配置正常",
"response_time_ms": 8.56,
"details": {
"configured": true,
"complete": true,
"enabled": true,
"base_url": "https://api.example.com"
}
},
"ai_service_connection": {
"status": "healthy",
"message": "AI服务连接正常",
"response_time_ms": 45.67,
"details": {
"http_status": 200,
"url": "https://api.example.com"
}
},
"system_resources": {
"status": "healthy",
"message": "系统资源正常",
"response_time_ms": 2.34,
"details": {
"php_version": "8.1.0",
"memory_usage": "45.67 MB",
"memory_limit": "512.00 MB",
"memory_usage_percent": "8.92%",
"max_execution_time": "30s"
}
}
},
"warnings": [],
"errors": []
}
}
```
### 2. 获取服务配置信息
**接口地址**`/api/kefu/info`
**请求方式**GET
**请求参数**
| 参数名 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| uniacid | int | 否 | 站点ID |
| member_id | int | 否 | 会员ID |
| token | string | 否 | 访问令牌 |
**响应示例**
```json
{
"code": 0,
"message": "success",
"data": {
"service_info": {
"name": "智能客服",
"version": "1.0.0",
"enabled": true,
"status": "enabled"
},
"features": {
"chat": true,
"chat_stream": true,
"conversation_management": true,
"history_management": true
},
"limits": {
"max_message_length": 4000,
"max_conversation_history": 100,
"rate_limit": {
"requests_per_minute": 60,
"requests_per_hour": 1000
}
},
"endpoints": {
"chat": "/api/kefu/chat",
"chat_stream": "/api/kefu/chatStream",
"create_conversation": "/api/kefu/createConversation",
"get_history": "/api/kefu/getHistory",
"clear_conversation": "/api/kefu/clearConversation",
"health": "/api/kefu/health",
"info": "/api/kefu/info"
},
"api_config": {
"base_url": "https://api.dify.ai/v1",
"chat_endpoint": "/chat-messages",
"supports_streaming": true,
"authentication": "bearer_token"
},
"client_info": {
"user_agent": "Mozilla/5.0...",
"ip": "192.168.1.100",
"timestamp": 1703505845
},
"server_info": {
"php_version": "8.1.0",
"server_time": "2023-12-25 10:30:45",
"timezone": "Asia/Shanghai"
},
"user_stats": {
"can_use_service": true,
"member_id": 123,
"site_id": 1
}
}
}
```
### 3. 智能客服聊天接口
**接口地址**`/api/kefu/chat`
**请求方式**POST
**请求参数**
| 参数名 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| uniacid | int | 是 | 站点ID |
| message | string | 是 | 用户输入的消息内容 |
| user_id | string | 否 | 用户ID默认使用当前登录会员ID |
| conversation_id | string | 否 | 会话ID第一次聊天可不传系统会自动创建 |
| stream | bool | 否 | 是否使用流式响应默认false |
| member_id | int | 否 | 会员ID |
| token | string | 否 | 访问令牌 |
**响应示例**
```json
{
"code": 0,
"message": "success",
"data": {
"conversation_id": "conv_123456789",
"reply": "您好,我是智能客服,有什么可以帮助您的?",
"message_id": "msg_123456789",
"finish_reason": "stop",
"usage": {
"prompt_tokens": 10,
"completion_tokens": 20,
"total_tokens": 30
}
}
}
```
### 4. 智能客服流式聊天接口
**接口地址**`/api/kefu/chatStream`
**请求方式**POST
**请求参数**:同 `/api/kefu/chat` 接口
**响应格式**Server-Sent Events (SSE)
**响应示例**
```javascript
// 开始事件
event: start
data: {
"id": "unique_id",
"event": "start",
"timestamp": 1703505845,
"data": {
"request_id": "stream_123",
"message": "开始处理请求"
}
}
// 内容块事件
event: message
data: {
"id": "unique_id",
"event": "message",
"timestamp": 1703505845,
"data": {
"content": "您",
"conversation_id": "conv_123",
"finished": false
}
}
// 完成事件
event: complete
data: {
"id": "unique_id",
"event": "complete",
"timestamp": 1703505845,
"data": {
"conversation_id": "conv_123",
"message_id": "msg_456",
"usage": {},
"finish_reason": "stop"
}
}
// 结束事件
event: end
data: {
"id": "unique_id",
"event": "end",
"timestamp": 1703505845,
"data": {
"request_id": "stream_123",
"status": "completed"
}
}
```
### 5. 创建新会话
**接口地址**`/api/kefu/createConversation`
**请求方式**POST
**请求参数**
| 参数名 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| uniacid | int | 是 | 站点ID |
| user_id | string | 否 | 用户ID默认使用当前登录会员ID |
| member_id | int | 否 | 会员ID |
| token | string | 否 | 访问令牌 |
**响应示例**
```json
{
"code": 0,
"message": "success",
"data": {
"conversation_id": "conv_123456789",
"name": "智能客服会话",
"created_at": "2023-12-25 10:30:45"
}
}
```
### 6. 获取会话历史
**接口地址**`/api/kefu/getHistory`
**请求方式**POST
**请求参数**
| 参数名 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| uniacid | int | 是 | 站点ID |
| conversation_id | string | 是 | 会话ID |
| user_id | string | 否 | 用户ID默认使用当前登录会员ID |
| limit | int | 否 | 每页条数默认20 |
| offset | int | 否 | 偏移量默认0 |
| member_id | int | 否 | 会员ID |
| token | string | 否 | 访问令牌 |
**响应示例**
```json
{
"code": 0,
"message": "success",
"data": {
"messages": [
{
"id": 1,
"role": "user",
"content": "你好",
"create_time": "2023-12-25 10:30:45"
},
{
"id": 2,
"role": "assistant",
"content": "您好,我是智能客服,有什么可以帮助您的?",
"create_time": "2023-12-25 10:30:46"
}
],
"total": 2,
"limit": 20,
"offset": 0
}
}
```
### 7. 清除会话历史
**接口地址**`/api/kefu/clearConversation`
**请求方式**POST
**请求参数**
| 参数名 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| uniacid | int | 是 | 站点ID |
| conversation_id | string | 否 | 会话ID与user_id二选一 |
| user_id | string | 否 | 用户ID用于清除该用户所有会话与conversation_id二选一 |
| member_id | int | 否 | 会员ID |
| token | string | 否 | 访问令牌 |
**响应示例**
```json
{
"code": 0,
"message": "success",
"data": {
"deleted_messages": 15,
"deleted_conversations": 3
}
}
```
## 四、前端调用示例
### Uniapp调用示例
```javascript
// 引入请求封装(根据项目实际情况调整)
import { request } from '@/utils/request';
// 1. 获取服务配置信息
async function getAIInfo() {
try {
const res = await request({
url: '/api/kefu/info',
method: 'GET',
data: {
uniacid: 1
}
});
if (res.code === 0) {
console.log('AI服务状态:', res.data.service_info);
console.log('可用功能:', res.data.features);
return res.data;
} else {
console.error('获取配置失败:', res.message);
return null;
}
} catch (error) {
console.error('获取配置请求失败:', error);
return null;
}
}
// 2. 智能客服聊天(普通模式)
async function chatWithAI(message, conversationId = '') {
try {
const res = await request({
url: '/api/kefu/chat',
method: 'POST',
data: {
uniacid: 1,
message: message,
conversation_id: conversationId
// user_id: 'your-user-id', // 可选
// stream: false // 可选
}
});
if (res.code === 0) {
return res.data;
} else {
console.error('聊天失败:', res.message);
return null;
}
} catch (error) {
console.error('聊天请求失败:', error);
return null;
}
}
// 3. 智能客服聊天(流式模式)
async function chatWithAIStream(message, conversationId = '', onMessage, onComplete, onError) {
try {
const response = await uni.request({
url: '/api/kefu/chatStream',
method: 'POST',
data: {
uniacid: 1,
message: message,
conversation_id: conversationId
},
responseType: 'text'
});
// 处理流式响应
if (response.statusCode === 200) {
const lines = response.data.split('\n');
for (const line of lines) {
if (line.startsWith('data: ')) {
try {
const data = JSON.parse(line.substring(6));
if (data.event === 'message' && onMessage) {
onMessage(data.data);
} else if (data.event === 'complete' && onComplete) {
onComplete(data.data);
} else if (data.event === 'error' && onError) {
onError(data.data);
}
} catch (e) {
console.warn('解析流式数据失败:', e);
}
}
}
}
} catch (error) {
console.error('流式聊天请求失败:', error);
if (onError) onError({ error: error.message });
}
}
// 4. 创建新会话
async function createNewConversation() {
try {
const res = await request({
url: '/api/kefu/createConversation',
method: 'POST',
data: {
uniacid: 1
// user_id: 'your-user-id', // 可选
}
});
if (res.code === 0) {
return res.data.conversation_id;
} else {
console.error('创建会话失败:', res.message);
return null;
}
} catch (error) {
console.error('创建会话请求失败:', error);
return null;
}
}
// 5. 获取会话历史
async function getChatHistory(conversationId, limit = 20, offset = 0) {
try {
const res = await request({
url: '/api/kefu/getHistory',
method: 'POST',
data: {
uniacid: 1,
conversation_id: conversationId,
limit: limit,
offset: offset
// user_id: 'your-user-id', // 可选
}
});
if (res.code === 0) {
return res.data;
} else {
console.error('获取历史记录失败:', res.message);
return null;
}
} catch (error) {
console.error('获取历史记录请求失败:', error);
return null;
}
}
// 6. 清除会话历史
async function clearConversation(conversationId = '', userId = '') {
try {
const res = await request({
url: '/api/kefu/clearConversation',
method: 'POST',
data: {
uniacid: 1,
conversation_id: conversationId,
user_id: userId
}
});
if (res.code === 0) {
return res.data;
} else {
console.error('清除会话失败:', res.message);
return null;
}
} catch (error) {
console.error('清除会话请求失败:', error);
return null;
}
}
// 7. 健康检查
async function checkHealth(checkType = 'full') {
try {
const res = await request({
url: '/api/kefu/health',
method: 'GET',
data: {
uniacid: 1,
check_type: checkType
}
});
if (res.code === 0) {
return res.data;
} else {
console.error('健康检查失败:', res.message);
return null;
}
} catch (error) {
console.error('健康检查请求失败:', error);
return null;
}
}
```
## 五、使用流程
1. **初始化检查**:小程序端启动时,调用`health``info`接口检查服务状态
2. **创建会话**:进入客服页面时,调用`createConversation`接口创建新会话或使用本地存储的会话ID
3. **发送消息**:用户输入消息后,调用`chat``chatStream`接口发送消息,获取机器人回复
4. **显示消息**:将用户消息和机器人回复显示在聊天界面
5. **加载历史记录**:需要时调用`getHistory`接口加载历史消息
6. **维护会话**保持会话ID用于后续消息交流
7. **清理数据**:根据用户需求调用`clearConversation`接口清理历史数据
## 六、注意事项
1. **必填参数**:所有接口都需要`uniacid`站点ID参数
2. **事件驱动**:后端采用事件驱动架构,所有业务逻辑通过事件处理器执行
3. **安全性**请确保Dify API密钥的安全性不要泄露给前端
4. **用户标识**建议对用户ID进行加密处理避免直接使用敏感信息
5. **流式支持**:推荐使用`chatStream`接口获得更好的用户体验
6. **会话管理**:建议实现会话管理机制,定期清理过期会话
7. **频率限制**:建议添加请求频率限制,防止恶意请求
8. **生产环境**在生产环境中建议关闭DEBUG模式
## 七、测试建议
1. **基础检查**:首先调用`health`接口检查系统状态
2. **配置验证**:调用`info`接口验证配置信息
3. **接口测试**使用Postman或类似工具测试各个API接口
4. **流式测试**:测试`chatStream`接口的流式响应
5. **完整流程**:在小程序端集成并测试完整流程
6. **边界测试**:模拟不同场景下的用户输入,测试机器人回复效果
7. **压力测试**:测试接口在高并发情况下的表现
## 八、常见问题
### 1. 接口返回400错误
**原因**:缺少必填参数`uniacid`或参数格式错误
**解决方法**确保请求中包含有效的站点ID
### 2. 健康检查返回503错误
**原因**AI服务配置不完整或服务异常
**解决方法**检查插件配置和Dify API服务状态
### 3. 接口返回401错误
**原因**Dify API密钥无效或过期
**解决方法**重新获取有效的API密钥并更新插件配置
### 4. 接口返回500错误
**原因**后端服务器错误或Dify API服务异常
**解决方法**查看服务器日志检查Dify API服务状态
### 5. 机器人回复为空
**原因**Dify聊天机器人配置问题或请求参数错误
**解决方法**检查Dify机器人配置验证请求参数是否正确
### 6. 流式响应无法解析
**原因**客户端不支持SSE或解析方式错误
**解决方法**使用正确的方式解析Server-Sent Events格式
### 7. 会话ID无效
**原因**:会话已过期或不存在
**解决方法**创建新会话获取新的会话ID
## 九、性能优化建议
1. **缓存配置**:可对`info`接口返回的配置信息进行客户端缓存
2. **连接复用**HTTP请求使用连接池减少建立连接的开销
3. **压缩传输**启用gzip压缩减少传输数据量
4. **分页加载**:历史记录使用分页加载,避免一次性加载大量数据
5. **CDN加速**静态资源使用CDN加速访问
6. **监控告警**:建立接口性能监控和告警机制