Files
schoolNews/schoolNewsServ/ai/前端API接口文档.md
2025-11-04 18:49:37 +08:00

393 lines
15 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.

# AI模块前端API接口文档
> 更新时间2025-11-04
> 作者AI Assistant
## 📁 文件结构
### TypeScript类型定义
```
schoolNewsWeb/src/types/ai/
└── index.ts # 完整的AI模块类型定义含19个接口
```
### API接口文件
```
schoolNewsWeb/src/apis/ai/
├── index.ts # API模块导出
├── agent-config.ts # 智能体配置API10个方法
├── knowledge.ts # 知识库API14个方法
├── file-upload.ts # 文件上传API8个方法
├── chat.ts # 对话API14个方法
└── chat-history.ts # 对话历史API16个方法
```
---
## 📘 类型定义说明
### 核心实体类型
#### 1. AiAgentConfig智能体配置
```typescript
interface AiAgentConfig extends BaseDTO {
name?: string; // 智能体名称
avatar?: string; // 头像
description?: string; // 描述
systemPrompt?: string; // 系统提示词
modelName?: string; // 模型名称
modelProvider?: string; // 模型提供商
temperature?: number; // 温度值0.0-1.0
maxTokens?: number; // 最大tokens
topP?: number; // Top P值
difyAppId?: string; // Dify应用ID
difyApiKey?: string; // Dify API Key
status?: number; // 状态0禁用 1启用
}
```
#### 2. AiKnowledge知识库
```typescript
interface AiKnowledge extends BaseDTO {
name?: string; // 知识库名称
description?: string; // 描述
indexingTechnique?: string; // 索引方式
embeddingModel?: string; // Embedding模型
difyDatasetId?: string; // Dify数据集ID
syncStatus?: number; // 同步状态
documentCount?: number; // 文档数量
characterCount?: number; // 字符数
creatorDept?: string; // 创建者部门
status?: number; // 状态
}
```
#### 3. AiUploadFile上传文件
```typescript
interface AiUploadFile extends BaseDTO {
knowledgeId?: string; // 知识库ID
fileName?: string; // 文件名
filePath?: string; // 文件路径
fileSize?: number; // 文件大小
fileType?: string; // 文件类型
difyDocumentId?: string; // Dify文档ID
uploadStatus?: number; // 上传状态
vectorStatus?: number; // 向量化状态
segmentCount?: number; // 分片数
errorMessage?: string; // 错误信息
}
```
#### 4. AiConversation对话会话
```typescript
interface AiConversation extends BaseDTO {
userID?: string; // 用户ID
agentID?: string; // 智能体ID
title?: string; // 会话标题
summary?: string; // 会话摘要
difyConversationId?: string;// Dify会话ID
status?: number; // 状态
isFavorite?: boolean; // 是否收藏
isPinned?: boolean; // 是否置顶
messageCount?: number; // 消息数量
totalTokens?: number; // Token总数
lastMessageTime?: string; // 最后消息时间
}
```
#### 5. AiMessage对话消息
```typescript
interface AiMessage extends BaseDTO {
conversationID?: string; // 会话ID
userID?: string; // 用户ID
agentID?: string; // 智能体ID
role?: string; // 角色user/assistant/system
content?: string; // 消息内容
fileIDs?: string; // 关联文件ID
knowledgeIDs?: string; // 引用知识ID
knowledgeRefs?: string; // 知识库引用详情
tokenCount?: number; // Token数量
difyMessageId?: string; // Dify消息ID
rating?: number; // 评分1好评/-1差评
feedback?: string; // 反馈内容
}
```
### 请求/响应类型
#### ChatRequest对话请求
```typescript
interface ChatRequest {
agentId: string; // 智能体ID必需
conversationId?: string; // 会话ID可选
query: string; // 用户问题(必需)
knowledgeIds?: string[]; // 知识库ID列表可选
stream?: boolean; // 是否流式返回
}
```
#### ConversationSearchParams会话搜索
```typescript
interface ConversationSearchParams {
agentId?: string; // 智能体ID
keyword?: string; // 关键词
isFavorite?: boolean; // 是否收藏
startDate?: string; // 开始日期
endDate?: string; // 结束日期
pageParam?: PageParam; // 分页参数
}
```
#### StreamCallback流式回调
```typescript
interface StreamCallback {
onMessage?: (message: string) => void; // 接收消息片段
onMessageEnd?: (metadata: string) => void; // 消息结束
onComplete?: () => void; // 完成
onError?: (error: Error) => void; // 错误
}
```
---
## 🔌 API接口说明
### 1. 智能体配置APIaiAgentConfigApi
| 方法 | 说明 | 参数 | 返回值 |
|------|------|------|--------|
| `createAgent` | 创建智能体 | `AiAgentConfig` | `ResultDomain<AiAgentConfig>` |
| `updateAgent` | 更新智能体 | `AiAgentConfig` | `ResultDomain<AiAgentConfig>` |
| `deleteAgent` | 删除智能体 | `agentId: string` | `ResultDomain<boolean>` |
| `getAgentById` | 获取智能体详情 | `agentId: string` | `ResultDomain<AiAgentConfig>` |
| `listEnabledAgents` | 获取启用的智能体列表 | - | `ResultDomain<AiAgentConfig[]>` |
| `listAgents` | 获取智能体列表(支持过滤) | `filter?: Partial<AiAgentConfig>` | `ResultDomain<AiAgentConfig[]>` |
| `pageAgents` | 分页查询智能体 | `filter, pageParam` | `PageDomain<AiAgentConfig>` |
| `updateAgentStatus` | 更新智能体状态 | `agentId, status` | `ResultDomain<boolean>` |
| `updateDifyConfig` | 更新Dify配置 | `agentId, difyAppId, difyApiKey` | `ResultDomain<boolean>` |
| `checkNameExists` | 检查名称是否存在 | `name, excludeId?` | `ResultDomain<boolean>` |
### 2. 知识库APIknowledgeApi
| 方法 | 说明 | 参数 | 返回值 |
|------|------|------|--------|
| `createKnowledge` | 创建知识库 | `AiKnowledge` | `ResultDomain<AiKnowledge>` |
| `updateKnowledge` | 更新知识库 | `AiKnowledge` | `ResultDomain<AiKnowledge>` |
| `deleteKnowledge` | 删除知识库 | `knowledgeId: string` | `ResultDomain<boolean>` |
| `getKnowledgeById` | 获取知识库详情 | `knowledgeId: string` | `ResultDomain<AiKnowledge>` |
| `listUserKnowledges` | 获取用户可见的知识库列表 | - | `ResultDomain<AiKnowledge[]>` |
| `listKnowledges` | 获取知识库列表(支持过滤) | `filter?: Partial<AiKnowledge>` | `ResultDomain<AiKnowledge[]>` |
| `pageKnowledges` | 分页查询知识库 | `filter, pageParam` | `PageDomain<AiKnowledge>` |
| `syncToDify` | 同步知识库到Dify | `knowledgeId: string` | `ResultDomain<boolean>` |
| `syncFromDify` | 从Dify同步知识库状态 | `knowledgeId: string` | `ResultDomain<AiKnowledge>` |
| `setPermissions` | 设置知识库权限 | `KnowledgePermissionParams` | `ResultDomain<boolean>` |
| `getPermissions` | 获取知识库权限 | `knowledgeId: string` | `ResultDomain<any>` |
| `checkPermission` | 检查用户权限 | `knowledgeId: string` | `ResultDomain<boolean>` |
| `getStats` | 获取知识库统计 | `knowledgeId: string` | `ResultDomain<any>` |
### 3. 文件上传APIfileUploadApi
| 方法 | 说明 | 参数 | 返回值 |
|------|------|------|--------|
| `uploadFile` | 上传单个文件 | `knowledgeId, file: File` | `ResultDomain<FileUploadResponse>` |
| `batchUploadFiles` | 批量上传文件 | `knowledgeId, files: File[]` | `ResultDomain<FileUploadResponse[]>` |
| `deleteFile` | 删除文件 | `fileId: string` | `ResultDomain<boolean>` |
| `getFileById` | 获取文件详情 | `fileId: string` | `ResultDomain<AiUploadFile>` |
| `listFilesByKnowledge` | 获取知识库的文件列表 | `knowledgeId: string` | `ResultDomain<AiUploadFile[]>` |
| `pageFiles` | 分页查询文件 | `filter, pageParam` | `PageDomain<AiUploadFile>` |
| `syncFileStatus` | 同步文件状态 | `fileId: string` | `ResultDomain<AiUploadFile>` |
| `batchSyncFileStatus` | 批量同步文件状态 | `fileIds: string[]` | `ResultDomain<number>` |
### 4. 对话APIchatApi
| 方法 | 说明 | 参数 | 返回值 |
|------|------|------|--------|
| `streamChat` | 流式对话SSE | `ChatRequest, StreamCallback?` | `Promise<ResultDomain<AiMessage>>` |
| `blockingChat` | 阻塞式对话 | `ChatRequest` | `ResultDomain<AiMessage>` |
| `stopChat` | 停止对话生成 | `messageId: string` | `ResultDomain<boolean>` |
| `createConversation` | 创建新会话 | `agentId, title?` | `ResultDomain<AiConversation>` |
| `getConversation` | 获取会话信息 | `conversationId: string` | `ResultDomain<AiConversation>` |
| `updateConversation` | 更新会话 | `AiConversation` | `ResultDomain<AiConversation>` |
| `deleteConversation` | 删除会话 | `conversationId: string` | `ResultDomain<boolean>` |
| `listUserConversations` | 获取用户会话列表 | `agentId?: string` | `ResultDomain<AiConversation[]>` |
| `listMessages` | 获取会话消息列表 | `conversationId: string` | `ResultDomain<AiMessage[]>` |
| `getMessage` | 获取单条消息 | `messageId: string` | `ResultDomain<AiMessage>` |
| `regenerateAnswer` | 重新生成回答 | `messageId, StreamCallback?` | `ResultDomain<AiMessage>` |
| `generateSummary` | 异步生成会话摘要 | `conversationId: string` | `ResultDomain<boolean>` |
| `rateMessage` | 评价消息 | `messageId, rating, feedback?` | `ResultDomain<boolean>` |
### 5. 对话历史APIchatHistoryApi
| 方法 | 说明 | 参数 | 返回值 |
|------|------|------|--------|
| `pageUserConversations` | 分页查询用户会话 | `ConversationSearchParams` | `PageDomain<AiConversation>` |
| `searchConversations` | 搜索会话(全文) | `MessageSearchParams` | `PageDomain<AiConversation>` |
| `searchMessages` | 搜索消息内容 | `MessageSearchParams` | `PageDomain<AiMessage>` |
| `toggleFavorite` | 收藏/取消收藏 | `conversationId, isFavorite` | `ResultDomain<boolean>` |
| `togglePin` | 置顶/取消置顶 | `conversationId, isPinned` | `ResultDomain<boolean>` |
| `batchDeleteConversations` | 批量删除会话 | `conversationIds: string[]` | `ResultDomain<number>` |
| `getUserChatStatistics` | 获取用户对话统计 | `userId?: string` | `ResultDomain<UserChatStatistics>` |
| `getConversationStatistics` | 获取会话详细统计 | `conversationId: string` | `ResultDomain<ConversationStatistics>` |
| `exportConversationAsMarkdown` | 导出为Markdown | `conversationId: string` | `ResultDomain<string>` |
| `exportConversationAsJson` | 导出为JSON | `conversationId: string` | `ResultDomain<string>` |
| `batchExportConversations` | 批量导出会话 | `BatchExportParams` | `ResultDomain<string>` |
| `downloadExport` | 下载导出文件 | `conversationId, format` | `void` |
| `batchDownloadExport` | 批量下载导出 | `conversationIds, format` | `void` |
| `cleanExpiredConversations` | 清理过期会话 | `days: number` | `ResultDomain<number>` |
| `getRecentConversations` | 获取最近对话 | `limit?: number` | `ResultDomain<AiConversation[]>` |
| `getPopularConversations` | 获取热门对话 | `limit?: number` | `ResultDomain<AiConversation[]>` |
---
## 💡 使用示例
### 1. 创建智能体并进行流式对话
```typescript
import { aiAgentConfigApi, chatApi } from '@/apis/ai';
// 1. 创建智能体
const agentResult = await aiAgentConfigApi.createAgent({
name: '智能助手',
description: '帮助用户解答问题',
systemPrompt: '你是一个智能助手...',
modelName: 'gpt-3.5-turbo',
status: 1
});
const agentId = agentResult.data?.ID;
// 2. 流式对话
await chatApi.streamChat(
{
agentId: agentId!,
query: '你好,请介绍一下你自己',
stream: true
},
{
onMessage: (chunk) => {
console.log('接收到消息片段:', chunk);
},
onMessageEnd: (metadata) => {
console.log('消息结束,元数据:', metadata);
},
onComplete: () => {
console.log('对话完成');
},
onError: (error) => {
console.error('对话出错:', error);
}
}
);
```
### 2. 创建知识库并上传文件
```typescript
import { knowledgeApi, fileUploadApi } from '@/apis/ai';
// 1. 创建知识库
const knowledgeResult = await knowledgeApi.createKnowledge({
name: '产品文档知识库',
description: '包含所有产品相关文档',
indexingTechnique: 'high_quality',
embeddingModel: 'text-embedding-ada-002'
});
const knowledgeId = knowledgeResult.data?.ID;
// 2. 上传文件
const files = document.querySelector('input[type="file"]').files;
const uploadResult = await fileUploadApi.batchUploadFiles(
knowledgeId!,
Array.from(files)
);
console.log('上传成功:', uploadResult.data);
```
### 3. 搜索对话历史
```typescript
import { chatHistoryApi } from '@/apis/ai';
// 搜索包含关键词的会话
const searchResult = await chatHistoryApi.pageUserConversations({
keyword: '产品',
isFavorite: true,
startDate: '2024-01-01',
pageParam: {
pageNumber: 1,
pageSize: 20
}
});
console.log('搜索结果:', searchResult.dataList);
```
### 4. 导出对话记录
```typescript
import { chatHistoryApi } from '@/apis/ai';
// 导出为Markdown
const markdownResult = await chatHistoryApi.exportConversationAsMarkdown(
conversationId
);
// 创建下载链接
const blob = new Blob([markdownResult.data!], { type: 'text/markdown' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `conversation_${conversationId}.md`;
a.click();
// 或者直接使用下载方法
chatHistoryApi.downloadExport(conversationId, 'markdown');
```
---
## 📊 统计数据
| 类别 | 数量 | 说明 |
|------|------|------|
| **TypeScript接口** | 19个 | 完整的类型定义 |
| **API模块** | 5个 | 智能体、知识库、文件、对话、历史 |
| **API方法** | 62个 | 涵盖所有业务功能 |
| **文件总数** | 6个 | 1个类型文件 + 5个API文件 |
---
## ✅ 完成清单
- [x] TypeScript类型定义完整
- [x] 智能体配置API
- [x] 知识库管理API
- [x] 文件上传API
- [x] 对话功能API含流式SSE
- [x] 对话历史API
- [x] 搜索功能API
- [x] 统计功能API
- [x] 导出功能API
- [x] 权限控制API
- [x] 向后兼容处理
---
## 📝 备注
1. **SSE流式对话**使用EventSource实现支持实时消息推送
2. **文件上传**支持FormData multipart/form-data格式
3. **分页查询**统一使用PageParam和PageDomain
4. **权限控制**集成在知识库API中支持部门和角色级别
5. **导出功能**支持Markdown和JSON两种格式支持批量导出
6. **统计分析**:用户级和会话级双维度统计
7. **向后兼容**保留了conversationApi和messageApi别名
---
**前端API接口已全部完成可以直接在Vue组件中使用。**