feat(aia): Complete AIA V2.0 with universal streaming capabilities
Major Updates: - Add StreamingService with OpenAI Compatible format (backend/common/streaming) - Upgrade Chat component V2 with Ant Design X integration - Implement AIA module with 12 intelligent agents - Create AgentHub with 100% prototype V11 restoration - Create ChatWorkspace with streaming response support - Add ThinkingBlock for deep thinking display - Add useAIStream Hook for OpenAI Compatible stream handling Backend Common Capabilities (~400 lines): - OpenAIStreamAdapter: SSE adapter with OpenAI format - StreamingService: unified streaming service - Support content and reasoning_content dual streams - Deep thinking tag processing (<think>...</think>) Frontend Common Capabilities (~2000 lines): - AIStreamChat: modern streaming chat component - ThinkingBlock: collapsible deep thinking display - ConversationList: conversation management with grouping - useAIStream: OpenAI Compatible stream handler Hook - useConversations: conversation state management Hook - Modern design styles (Ultramodern theme) AIA Module Frontend (~1500 lines): - AgentHub: 12 agent cards with timeline design - ChatWorkspace: fullscreen immersive chat interface - AgentCard: theme-colored cards (blue/yellow/teal/purple) - 5 phases, 12 agents configuration - Responsive layout (desktop + mobile) AIA Module Backend (~900 lines): - agentService: 12 agents config with system prompts - conversationService: refactored with StreamingService - attachmentService: file upload skeleton (30k token limit) - 12 API endpoints with authentication - Full CRUD for conversations and messages Documentation: - AIA module status and development guide - Universal capabilities catalog (11 services) - Quick reference card for developers - System overview updates Testing: - Stream response verified (HTTP 200) - Authentication working correctly - Auto conversation creation working - Deep thinking display working - Message input and send working Status: Core features completed (85%), attachment and history loading pending
This commit is contained in:
769
docs/02-通用能力层/00-通用能力层清单.md
Normal file
769
docs/02-通用能力层/00-通用能力层清单.md
Normal file
@@ -0,0 +1,769 @@
|
||||
# 通用能力层清单
|
||||
|
||||
> **文档版本:** v2.0
|
||||
> **创建日期:** 2026-01-14
|
||||
> **最后更新:** 2026-01-14
|
||||
> **文档目的:** 列出所有通用能力模块,提供快速调用指南
|
||||
|
||||
---
|
||||
|
||||
## 📚 概述
|
||||
|
||||
通用能力层是平台的核心基础设施,提供可复用的技术能力,避免业务模块重复开发。
|
||||
|
||||
### 设计原则
|
||||
|
||||
1. **高复用性** - 一次开发,多处使用
|
||||
2. **标准化** - 统一接口,降低学习成本
|
||||
3. **解耦合** - 业务模块无需关心底层实现
|
||||
4. **云原生** - 支持多环境部署(本地/阿里云)
|
||||
|
||||
---
|
||||
|
||||
## 🎯 能力清单
|
||||
|
||||
### 后端通用能力
|
||||
|
||||
| 能力 | 路径 | 状态 | 说明 |
|
||||
|------|------|------|------|
|
||||
| **存储服务** | `common/storage/` | ✅ | 文件存储抽象层(本地/OSS) |
|
||||
| **日志服务** | `common/logging/` | ✅ | 结构化日志(Pino) |
|
||||
| **缓存服务** | `common/cache/` | ✅ | 缓存抽象层(内存/Redis/Postgres) |
|
||||
| **异步任务** | `common/jobs/` | ✅ | 队列服务(Memory/PgBoss) |
|
||||
| **LLM网关** | `common/llm/` | ✅ | 统一LLM适配器(5个模型) |
|
||||
| **流式响应** | `common/streaming/` | ✅ 🆕 | OpenAI Compatible流式输出 |
|
||||
| **RAG引擎** | `common/rag/` | ✅ | Dify集成(知识库检索) |
|
||||
| **文档处理** | `common/document/` | ✅ | 文档内容提取 |
|
||||
| **认证授权** | `common/auth/` | ✅ | JWT认证 + 权限控制 |
|
||||
| **Prompt管理** | `common/prompt/` | ✅ | 动态Prompt配置 |
|
||||
|
||||
### 前端通用能力
|
||||
|
||||
| 能力 | 路径 | 状态 | 说明 |
|
||||
|------|------|------|------|
|
||||
| **Chat组件** | `shared/components/Chat/` | ✅ 🆕 | AI对话通用组件(V2) |
|
||||
| **认证API** | `framework/auth/api.ts` | ✅ | Token管理 |
|
||||
| **API Client** | `common/api/axios.ts` | ✅ | 带认证的axios实例 |
|
||||
| **通用布局** | `shared/layouts/` | ✅ | 主布局、侧边栏 |
|
||||
|
||||
---
|
||||
|
||||
## 📦 详细文档
|
||||
|
||||
### 1. 流式响应服务(🆕 重点推荐)
|
||||
|
||||
**路径:** `backend/src/common/streaming/`
|
||||
|
||||
**功能:** 提供 OpenAI Compatible 格式的流式响应,支持深度思考
|
||||
|
||||
**使用方式:**
|
||||
|
||||
```typescript
|
||||
import { createStreamingService } from '../../../common/streaming';
|
||||
|
||||
// 在控制器中
|
||||
async function handler(request, reply) {
|
||||
const service = createStreamingService(reply, {
|
||||
model: 'deepseek-v3',
|
||||
temperature: 0.7,
|
||||
maxTokens: 4096,
|
||||
enableDeepThinking: true,
|
||||
userId: 'xxx',
|
||||
conversationId: 'xxx',
|
||||
});
|
||||
|
||||
const result = await service.streamGenerate(messages, {
|
||||
onContent: (delta) => console.log('内容:', delta),
|
||||
onThinking: (delta) => console.log('思考:', delta),
|
||||
onComplete: (content, thinking) => {
|
||||
// 保存到数据库
|
||||
},
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
**输出格式:**
|
||||
```
|
||||
data: {"id":"chatcmpl-xxx","choices":[{"delta":{"content":"你好"}}]}\n\n
|
||||
data: {"id":"chatcmpl-xxx","choices":[{"delta":{"reasoning_content":"让我想想"}}]}\n\n
|
||||
data: [DONE]\n\n
|
||||
```
|
||||
|
||||
**已使用模块:**
|
||||
- ✅ AIA - AI智能问答
|
||||
- 🔜 PKB - 个人知识库(待迁移)
|
||||
|
||||
---
|
||||
|
||||
### 2. Chat 通用组件(🆕 重点推荐)
|
||||
|
||||
**路径:** `frontend-v2/src/shared/components/Chat/`
|
||||
|
||||
**功能:** 现代感AI对话组件,支持流式响应、深度思考、会话管理
|
||||
|
||||
**核心组件:**
|
||||
|
||||
```typescript
|
||||
import {
|
||||
AIStreamChat, // 流式对话组件(推荐)
|
||||
ThinkingBlock, // 深度思考展示
|
||||
ConversationList, // 会话列表
|
||||
useAIStream, // 流式响应Hook
|
||||
useConversations, // 会话管理Hook
|
||||
} from '@/shared/components/Chat';
|
||||
```
|
||||
|
||||
**快速使用:**
|
||||
|
||||
```tsx
|
||||
<AIStreamChat
|
||||
apiEndpoint="/api/v1/xxx/chat/stream"
|
||||
conversationId={conversationId}
|
||||
agentId="xxx"
|
||||
enableDeepThinking={true}
|
||||
welcome={{
|
||||
title: '智能助手',
|
||||
description: '有什么可以帮您的?',
|
||||
}}
|
||||
/>
|
||||
```
|
||||
|
||||
**已使用模块:**
|
||||
- ✅ AIA - AI智能问答
|
||||
- ✅ DC Tool C - 科研数据编辑器
|
||||
- 🔜 PKB - 个人知识库(待迁移)
|
||||
|
||||
**详细文档:** [Chat组件README](../../frontend-v2/src/shared/components/Chat/README.md)
|
||||
|
||||
---
|
||||
|
||||
### 3. LLM 网关
|
||||
|
||||
**路径:** `backend/src/common/llm/`
|
||||
|
||||
**功能:** 统一LLM调用接口,支持5个主流模型
|
||||
|
||||
**支持模型:**
|
||||
- DeepSeek-V3(直连)
|
||||
- Qwen3-72B(阿里云)
|
||||
- Qwen-Long(1M上下文)
|
||||
- GPT-5-Pro(CloseAI代理)
|
||||
- Claude-4.5(CloseAI代理)
|
||||
|
||||
**使用方式:**
|
||||
|
||||
```typescript
|
||||
import { LLMFactory } from '../../../common/llm/adapters/LLMFactory';
|
||||
|
||||
// 获取适配器
|
||||
const llm = LLMFactory.getAdapter('deepseek-v3');
|
||||
|
||||
// 非流式调用
|
||||
const response = await llm.chat(messages, { temperature: 0.7 });
|
||||
|
||||
// 流式调用
|
||||
const stream = llm.chatStream(messages, { temperature: 0.7 });
|
||||
for await (const chunk of stream) {
|
||||
console.log(chunk.content);
|
||||
}
|
||||
```
|
||||
|
||||
**已使用模块:**
|
||||
- ✅ AIA - AI智能问答
|
||||
- ✅ PKB - 个人知识库
|
||||
- ✅ DC Tool B - 病历结构化
|
||||
- ✅ DC Tool C - 数据编辑器
|
||||
|
||||
---
|
||||
|
||||
### 4. 存储服务
|
||||
|
||||
**路径:** `backend/src/common/storage/`
|
||||
|
||||
**功能:** 文件存储抽象层,零代码切换本地/OSS
|
||||
|
||||
**使用方式:**
|
||||
|
||||
```typescript
|
||||
import { storage } from '../../../common/storage';
|
||||
|
||||
// 上传文件
|
||||
const url = await storage.upload('path/to/file.pdf', buffer, {
|
||||
contentType: 'application/pdf',
|
||||
});
|
||||
|
||||
// 下载文件
|
||||
const buffer = await storage.download('path/to/file.pdf');
|
||||
|
||||
// 删除文件
|
||||
await storage.delete('path/to/file.pdf');
|
||||
|
||||
// 获取签名URL(OSS)
|
||||
const signedUrl = await storage.getSignedUrl('path/to/file.pdf', 3600);
|
||||
```
|
||||
|
||||
**环境配置:**
|
||||
```env
|
||||
# 本地开发
|
||||
STORAGE_PROVIDER=local
|
||||
UPLOAD_DIR=./uploads
|
||||
|
||||
# 生产环境(阿里云OSS)
|
||||
STORAGE_PROVIDER=oss
|
||||
OSS_REGION=oss-cn-hangzhou
|
||||
OSS_BUCKET=your-bucket
|
||||
OSS_ACCESS_KEY_ID=xxx
|
||||
OSS_ACCESS_KEY_SECRET=xxx
|
||||
```
|
||||
|
||||
**已使用模块:**
|
||||
- ✅ PKB - 文档上传
|
||||
- ✅ DC Tool B - 病历文件
|
||||
- ✅ AIA - 附件上传(待完成)
|
||||
|
||||
---
|
||||
|
||||
### 5. 异步任务队列
|
||||
|
||||
**路径:** `backend/src/common/jobs/`
|
||||
|
||||
**功能:** Postgres-Only 异步任务处理,基于 PgBoss
|
||||
|
||||
**使用方式:**
|
||||
|
||||
```typescript
|
||||
import { JobFactory } from '../../../common/jobs';
|
||||
|
||||
// 获取队列实例
|
||||
const queue = JobFactory.getQueue();
|
||||
|
||||
// 创建任务
|
||||
const jobId = await queue.createJob('extraction-job', {
|
||||
taskId: 'xxx',
|
||||
fileUrl: 'xxx',
|
||||
options: {},
|
||||
});
|
||||
|
||||
// 注册 Worker
|
||||
queue.registerWorker('extraction-job', async (job) => {
|
||||
console.log('处理任务:', job.data);
|
||||
// 执行任务逻辑
|
||||
return { success: true };
|
||||
});
|
||||
|
||||
// 启动队列
|
||||
await queue.start();
|
||||
```
|
||||
|
||||
**已使用模块:**
|
||||
- ✅ DC Tool B - 病历批量提取
|
||||
- ✅ DC Tool C - 数据异步处理
|
||||
|
||||
**详细文档:** [Postgres-Only异步任务指南](./Postgres-Only异步任务处理指南.md)
|
||||
|
||||
---
|
||||
|
||||
### 6. 缓存服务
|
||||
|
||||
**路径:** `backend/src/common/cache/`
|
||||
|
||||
**功能:** 缓存抽象层(内存/Redis/Postgres)
|
||||
|
||||
**使用方式:**
|
||||
|
||||
```typescript
|
||||
import { cache } from '../../../common/cache';
|
||||
|
||||
// 设置缓存(TTL: 3600秒)
|
||||
await cache.set('key', { data: 'value' }, 3600);
|
||||
|
||||
// 获取缓存
|
||||
const value = await cache.get('key');
|
||||
|
||||
// 删除缓存
|
||||
await cache.delete('key');
|
||||
|
||||
// 批量删除(支持通配符)
|
||||
await cache.clear('prefix:*');
|
||||
```
|
||||
|
||||
**已使用模块:**
|
||||
- ✅ AIA - 智能体配置缓存
|
||||
- ✅ Prompt管理 - 模板缓存
|
||||
|
||||
---
|
||||
|
||||
### 7. 日志服务
|
||||
|
||||
**路径:** `backend/src/common/logging/`
|
||||
|
||||
**功能:** 结构化日志,支持多级别输出
|
||||
|
||||
**使用方式:**
|
||||
|
||||
```typescript
|
||||
import { logger } from '../../../common/logging';
|
||||
|
||||
// 不同级别
|
||||
logger.debug('调试信息', { detail: 'xxx' });
|
||||
logger.info('普通日志', { userId: 'xxx' });
|
||||
logger.warn('警告信息', { issue: 'xxx' });
|
||||
logger.error('错误信息', { error, stack: error.stack });
|
||||
|
||||
// 结构化字段
|
||||
logger.info('[ModuleName] 操作描述', {
|
||||
userId: 'xxx',
|
||||
conversationId: 'xxx',
|
||||
duration: 1234,
|
||||
});
|
||||
```
|
||||
|
||||
**日志格式:**
|
||||
```
|
||||
2026-01-14 18:44:27.500 [aiclinical-backend] info: [AIA:ConversationService] 消息发送完成
|
||||
{
|
||||
"conversationId": "xxx",
|
||||
"tokens": 1234,
|
||||
"hasThinking": true
|
||||
}
|
||||
```
|
||||
|
||||
**已使用模块:** 所有模块
|
||||
|
||||
---
|
||||
|
||||
### 8. RAG 引擎
|
||||
|
||||
**路径:** `backend/src/common/rag/`
|
||||
|
||||
**功能:** 知识库检索(基于Dify)
|
||||
|
||||
**使用方式:**
|
||||
|
||||
```typescript
|
||||
import { DifyClient } from '../../../common/rag/DifyClient';
|
||||
|
||||
const dify = new DifyClient(apiKey, baseURL);
|
||||
|
||||
// 检索知识库
|
||||
const results = await dify.retrievalSearch(query, {
|
||||
knowledgeBaseIds: ['kb1', 'kb2'],
|
||||
topK: 5,
|
||||
});
|
||||
|
||||
// 对话API(含RAG)
|
||||
const response = await dify.chatWithKnowledge(query, options);
|
||||
```
|
||||
|
||||
**已使用模块:**
|
||||
- ✅ PKB - 个人知识库
|
||||
|
||||
---
|
||||
|
||||
### 9. 文档处理引擎
|
||||
|
||||
**路径:** `backend/src/common/document/`
|
||||
|
||||
**功能:** 文档内容提取(PDF/Word/Excel/TXT)
|
||||
|
||||
**使用方式:**
|
||||
|
||||
```typescript
|
||||
import { ExtractionClient } from '../../../common/document/ExtractionClient';
|
||||
|
||||
const client = new ExtractionClient();
|
||||
|
||||
// 提取文本
|
||||
const text = await client.extractText(buffer, 'pdf');
|
||||
|
||||
// 提取结构化数据(Excel)
|
||||
const data = await client.extractStructured(buffer, 'xlsx');
|
||||
```
|
||||
|
||||
**已使用模块:**
|
||||
- ✅ PKB - 文档上传
|
||||
- ✅ DC Tool B - 病历文本提取
|
||||
- 🔜 AIA - 附件处理(待完成)
|
||||
|
||||
---
|
||||
|
||||
### 10. 认证授权
|
||||
|
||||
**路径:** `backend/src/common/auth/`
|
||||
|
||||
**功能:** JWT认证 + 基于角色的访问控制
|
||||
|
||||
**后端使用:**
|
||||
|
||||
```typescript
|
||||
import { authenticate, requirePermission } from '../../../common/auth/auth.middleware';
|
||||
|
||||
// 路由添加认证
|
||||
fastify.get('/api', { preHandler: [authenticate] }, handler);
|
||||
|
||||
// 要求特定权限
|
||||
fastify.post('/api', {
|
||||
preHandler: [authenticate, requirePermission('module:action')]
|
||||
}, handler);
|
||||
|
||||
// 控制器获取用户ID
|
||||
function getUserId(request: FastifyRequest): string {
|
||||
const userId = (request as any).user?.userId;
|
||||
if (!userId) throw new Error('User not authenticated');
|
||||
return userId;
|
||||
}
|
||||
```
|
||||
|
||||
**前端使用:**
|
||||
|
||||
```typescript
|
||||
import { getAccessToken } from '@/framework/auth/api';
|
||||
|
||||
// 方式1: 使用 apiClient(推荐)
|
||||
import apiClient from '@/common/api/axios';
|
||||
const response = await apiClient.get('/api/xxx');
|
||||
|
||||
// 方式2: 原生 fetch
|
||||
const response = await fetch('/api/xxx', {
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': `Bearer ${getAccessToken()}`,
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
**已使用模块:** 所有模块
|
||||
|
||||
**详细文档:** [模块认证规范](../04-开发规范/10-模块认证规范.md)
|
||||
|
||||
---
|
||||
|
||||
### 11. Prompt 管理系统
|
||||
|
||||
**路径:** `backend/src/common/prompt/`
|
||||
|
||||
**功能:** 动态Prompt配置、版本管理、A/B测试
|
||||
|
||||
**使用方式:**
|
||||
|
||||
```typescript
|
||||
import { PromptService } from '../../../common/prompt/prompt.service';
|
||||
|
||||
const promptService = new PromptService();
|
||||
|
||||
// 获取激活的Prompt
|
||||
const prompt = await promptService.getActivePrompt('template_code');
|
||||
|
||||
// 渲染Prompt(变量替换)
|
||||
const rendered = promptService.renderPrompt(template.content, {
|
||||
userName: '张三',
|
||||
context: '研究背景...',
|
||||
});
|
||||
```
|
||||
|
||||
**已使用模块:**
|
||||
- ✅ DC Tool C - 代码生成Prompt
|
||||
- 🔜 AIA - 智能体Prompt(待迁移)
|
||||
|
||||
---
|
||||
|
||||
## 🎨 前端 Chat 组件(V2)
|
||||
|
||||
### 概述
|
||||
|
||||
基于 **Ant Design X 2.1** 构建的现代感AI对话组件,支持流式响应、深度思考、会话管理。
|
||||
|
||||
### 核心组件
|
||||
|
||||
#### 1. AIStreamChat - 流式对话组件(推荐)
|
||||
|
||||
```tsx
|
||||
import { AIStreamChat } from '@/shared/components/Chat';
|
||||
|
||||
<AIStreamChat
|
||||
apiEndpoint="/api/v1/aia/conversations/xxx/messages/stream"
|
||||
conversationId="xxx"
|
||||
agentId="TOPIC_01"
|
||||
enableDeepThinking={true}
|
||||
welcome={{
|
||||
title: 'AI 助手',
|
||||
description: '有什么可以帮您的?',
|
||||
}}
|
||||
onMessageSent={(msg) => console.log('发送:', msg)}
|
||||
onMessageReceived={(msg) => console.log('接收:', msg)}
|
||||
/>
|
||||
```
|
||||
|
||||
**特性:**
|
||||
- ✅ 逐字流式显示(打字机效果)
|
||||
- ✅ 深度思考展示(可折叠)
|
||||
- ✅ 欢迎页配置
|
||||
- ✅ 快捷提示
|
||||
- ✅ 附件上传
|
||||
- ✅ 现代感设计
|
||||
|
||||
#### 2. ThinkingBlock - 深度思考组件
|
||||
|
||||
```tsx
|
||||
import { ThinkingBlock } from '@/shared/components/Chat';
|
||||
|
||||
<ThinkingBlock
|
||||
content={thinkingContent}
|
||||
isThinking={true}
|
||||
duration={2.5}
|
||||
defaultExpanded={true}
|
||||
/>
|
||||
```
|
||||
|
||||
#### 3. ConversationList - 会话列表
|
||||
|
||||
```tsx
|
||||
import { ConversationList } from '@/shared/components/Chat';
|
||||
|
||||
<ConversationList
|
||||
groups={groupedConversations}
|
||||
currentId={currentId}
|
||||
onSelect={setCurrent}
|
||||
onNew={createConversation}
|
||||
onDelete={deleteConversation}
|
||||
/>
|
||||
```
|
||||
|
||||
### Hooks
|
||||
|
||||
#### useAIStream - 流式响应处理
|
||||
|
||||
```tsx
|
||||
import { useAIStream } from '@/shared/components/Chat';
|
||||
|
||||
const {
|
||||
content, // 当前内容
|
||||
thinking, // 思考内容
|
||||
status, // 流式状态
|
||||
isStreaming, // 是否正在流式输出
|
||||
isThinking, // 是否正在思考
|
||||
error, // 错误信息
|
||||
sendMessage, // 发送消息
|
||||
abort, // 中断请求
|
||||
reset, // 重置状态
|
||||
} = useAIStream({
|
||||
apiEndpoint: '/api/v1/aia/chat/stream',
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
});
|
||||
```
|
||||
|
||||
#### useConversations - 会话管理
|
||||
|
||||
```tsx
|
||||
import { useConversations } from '@/shared/components/Chat';
|
||||
|
||||
const {
|
||||
conversations, // 会话列表
|
||||
groupedConversations, // 分组会话(今天/昨天/更早)
|
||||
current, // 当前会话
|
||||
setCurrent, // 设置当前会话
|
||||
addConversation, // 添加会话
|
||||
updateConversation, // 更新会话
|
||||
deleteConversation, // 删除会话
|
||||
} = useConversations();
|
||||
```
|
||||
|
||||
### 向后兼容
|
||||
|
||||
保留了 V1 版本的组件:
|
||||
- `ChatContainer` - 传统对话容器(非流式)
|
||||
- `MessageRenderer` - 消息渲染器
|
||||
- `CodeBlockRenderer` - 代码块渲染器(Tool C专用)
|
||||
|
||||
---
|
||||
|
||||
## 🔗 能力组合使用
|
||||
|
||||
### 场景1:AI对话模块(如AIA)
|
||||
|
||||
**前端:**
|
||||
```tsx
|
||||
import { AIStreamChat } from '@/shared/components/Chat';
|
||||
|
||||
<AIStreamChat
|
||||
apiEndpoint="/api/v1/aia/conversations/xxx/messages/stream"
|
||||
enableDeepThinking={true}
|
||||
/>
|
||||
```
|
||||
|
||||
**后端:**
|
||||
```typescript
|
||||
import { createStreamingService } from '../../../common/streaming';
|
||||
import { LLMFactory } from '../../../common/llm/adapters/LLMFactory';
|
||||
|
||||
async function sendMessageStream(userId, conversationId, request, reply) {
|
||||
const service = createStreamingService(reply);
|
||||
await service.streamGenerate(messages);
|
||||
}
|
||||
```
|
||||
|
||||
### 场景2:知识库问答(如PKB)
|
||||
|
||||
**前端:**
|
||||
```tsx
|
||||
<AIStreamChat
|
||||
apiEndpoint="/api/v1/pkb/chat/stream"
|
||||
enableAttachment={true} // 支持文档上传
|
||||
/>
|
||||
```
|
||||
|
||||
**后端:**
|
||||
```typescript
|
||||
import { DifyClient } from '../../../common/rag/DifyClient';
|
||||
import { createStreamingService } from '../../../common/streaming';
|
||||
|
||||
// RAG检索 + 流式输出
|
||||
const ragResults = await dify.retrievalSearch(query, options);
|
||||
const messages = buildMessagesWithRAG(query, ragResults);
|
||||
await service.streamGenerate(messages);
|
||||
```
|
||||
|
||||
### 场景3:代码生成工具(如Tool C)
|
||||
|
||||
**前端:**
|
||||
```tsx
|
||||
<ChatContainer
|
||||
conversationType="tool-c"
|
||||
customMessageRenderer={(msg) => (
|
||||
<MessageRenderer
|
||||
messageInfo={msg}
|
||||
onExecuteCode={handleExecute}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
```
|
||||
|
||||
**后端:**
|
||||
```typescript
|
||||
import { LLMFactory } from '../../../common/llm/adapters/LLMFactory';
|
||||
import { PromptService } from '../../../common/prompt/prompt.service';
|
||||
|
||||
// Prompt管理 + LLM调用
|
||||
const prompt = await promptService.getActivePrompt('code_gen');
|
||||
const llm = LLMFactory.getAdapter('deepseek-v3');
|
||||
const response = await llm.chat(messages);
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 📊 使用统计
|
||||
|
||||
### 能力使用矩阵
|
||||
|
||||
| 能力 | AIA | PKB | DC-B | DC-C | ASL | RVW |
|
||||
|------|-----|-----|------|------|-----|-----|
|
||||
| **StreamingService** | ✅ | 🔜 | ❌ | ❌ | ❌ | ❌ |
|
||||
| **Chat组件V2** | ✅ | 🔜 | ❌ | ✅ | ❌ | ❌ |
|
||||
| **LLM网关** | ✅ | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| **存储服务** | 🔜 | ✅ | ✅ | ✅ | ✅ | ✅ |
|
||||
| **异步任务** | ❌ | ❌ | ✅ | ✅ | ✅ | ✅ |
|
||||
| **RAG引擎** | 🔜 | ✅ | ❌ | ❌ | ❌ | ❌ |
|
||||
| **文档处理** | 🔜 | ✅ | ✅ | ❌ | ❌ | ❌ |
|
||||
| **认证授权** | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
|
||||
| **Prompt管理** | 🔜 | ❌ | ❌ | ✅ | ❌ | ❌ |
|
||||
|
||||
图例:✅ 已使用 | 🔜 计划使用 | ❌ 不需要
|
||||
|
||||
---
|
||||
|
||||
## 🚀 最佳实践
|
||||
|
||||
### 1. 优先使用通用能力
|
||||
|
||||
❌ **错误做法:**
|
||||
```typescript
|
||||
// 自己实现流式响应
|
||||
reply.raw.write(`data: ${JSON.stringify(chunk)}\n\n`);
|
||||
```
|
||||
|
||||
✅ **正确做法:**
|
||||
```typescript
|
||||
// 使用 StreamingService
|
||||
const service = createStreamingService(reply);
|
||||
await service.streamGenerate(messages);
|
||||
```
|
||||
|
||||
### 2. 标准化API格式
|
||||
|
||||
❌ **错误做法:**
|
||||
```typescript
|
||||
// 自定义SSE格式
|
||||
event: delta\ndata: {"content":"xxx"}\n\n
|
||||
```
|
||||
|
||||
✅ **正确做法:**
|
||||
```typescript
|
||||
// OpenAI Compatible格式
|
||||
data: {"choices":[{"delta":{"content":"xxx"}}]}\n\n
|
||||
```
|
||||
|
||||
### 3. 云原生设计
|
||||
|
||||
❌ **错误做法:**
|
||||
```typescript
|
||||
// 直接使用本地文件系统
|
||||
fs.writeFileSync('/tmp/file.txt', content);
|
||||
```
|
||||
|
||||
✅ **正确做法:**
|
||||
```typescript
|
||||
// 使用存储抽象层
|
||||
await storage.upload('path/file.txt', buffer);
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 📚 学习路径
|
||||
|
||||
### 新手入门
|
||||
|
||||
1. 阅读 [系统整体设计](../00-系统总体设计/00-系统当前状态与开发指南.md)
|
||||
2. 阅读 [云原生开发规范](../04-开发规范/08-云原生开发规范.md)
|
||||
3. 参考 AIA 或 DC Tool C 的实现
|
||||
|
||||
### 进阶学习
|
||||
|
||||
1. 深入 [Chat组件文档](../../frontend-v2/src/shared/components/Chat/README.md)
|
||||
2. 研究 [StreamingService 源码](../../backend/src/common/streaming/)
|
||||
3. 了解 [Postgres-Only架构](./Postgres-Only异步任务处理指南.md)
|
||||
|
||||
---
|
||||
|
||||
## 🔄 版本历史
|
||||
|
||||
### V2.0 (2026-01-14) 🎉
|
||||
|
||||
**通用能力层建设:**
|
||||
- 🆕 StreamingService - OpenAI Compatible流式响应
|
||||
- 🆕 Chat组件V2 - 现代感UI + 完整功能
|
||||
- 🆕 useAIStream Hook - 流式响应处理
|
||||
- 🆕 ThinkingBlock - 深度思考展示
|
||||
|
||||
**已应用模块:**
|
||||
- ✅ AIA - 首个使用者
|
||||
- 🔜 PKB - 计划迁移
|
||||
- 🔜 其他AI对话场景
|
||||
|
||||
### V1.0 (历史版本)
|
||||
|
||||
- 基础LLM网关
|
||||
- 简单Chat组件
|
||||
- 各模块独立实现
|
||||
|
||||
---
|
||||
|
||||
## 📞 获取帮助
|
||||
|
||||
- **通用能力层问题:** 查看本文档或各子模块README
|
||||
- **业务模块问题:** 查看对应模块的状态文档
|
||||
- **架构设计问题:** 查看系统总体设计文档
|
||||
|
||||
---
|
||||
|
||||
**维护说明:** 新增通用能力时,请及时更新本文档。
|
||||
|
||||
228
docs/02-通用能力层/快速引用卡片.md
Normal file
228
docs/02-通用能力层/快速引用卡片.md
Normal file
@@ -0,0 +1,228 @@
|
||||
# 通用能力层 - 快速引用卡片
|
||||
|
||||
> 一页纸速查表,快速找到需要的通用能力
|
||||
|
||||
---
|
||||
|
||||
## 🎯 我需要...
|
||||
|
||||
### 💬 AI 对话功能
|
||||
|
||||
**前端:**
|
||||
```tsx
|
||||
import { AIStreamChat } from '@/shared/components/Chat';
|
||||
<AIStreamChat apiEndpoint="/api/v1/xxx/chat/stream" enableDeepThinking={true} />
|
||||
```
|
||||
|
||||
**后端:**
|
||||
```typescript
|
||||
import { createStreamingService } from '../../../common/streaming';
|
||||
const service = createStreamingService(reply);
|
||||
await service.streamGenerate(messages);
|
||||
```
|
||||
|
||||
📚 [详细文档](./00-通用能力层清单.md#2-chat-通用组件)
|
||||
|
||||
---
|
||||
|
||||
### 🤖 调用 LLM
|
||||
|
||||
```typescript
|
||||
import { LLMFactory } from '../../../common/llm/adapters/LLMFactory';
|
||||
|
||||
const llm = LLMFactory.getAdapter('deepseek-v3');
|
||||
const response = await llm.chat(messages);
|
||||
|
||||
// 流式
|
||||
for await (const chunk of llm.chatStream(messages)) {
|
||||
console.log(chunk.content);
|
||||
}
|
||||
```
|
||||
|
||||
📚 [详细文档](./01-LLM大模型网关/)
|
||||
|
||||
---
|
||||
|
||||
### 📁 文件存储
|
||||
|
||||
```typescript
|
||||
import { storage } from '../../../common/storage';
|
||||
|
||||
// 上传
|
||||
const url = await storage.upload('path/file.pdf', buffer);
|
||||
|
||||
// 下载
|
||||
const buffer = await storage.download('path/file.pdf');
|
||||
```
|
||||
|
||||
📚 [详细文档](./00-通用能力层清单.md#4-存储服务)
|
||||
|
||||
---
|
||||
|
||||
### ⚡ 异步任务
|
||||
|
||||
```typescript
|
||||
import { JobFactory } from '../../../common/jobs';
|
||||
|
||||
const queue = JobFactory.getQueue();
|
||||
|
||||
// 创建任务
|
||||
await queue.createJob('job-name', { taskId: 'xxx' });
|
||||
|
||||
// 注册Worker
|
||||
queue.registerWorker('job-name', async (job) => {
|
||||
// 处理逻辑
|
||||
});
|
||||
```
|
||||
|
||||
📚 [详细文档](./Postgres-Only异步任务处理指南.md)
|
||||
|
||||
---
|
||||
|
||||
### 📄 文档处理
|
||||
|
||||
```typescript
|
||||
import { ExtractionClient } from '../../../common/document/ExtractionClient';
|
||||
|
||||
const client = new ExtractionClient();
|
||||
const text = await client.extractText(buffer, 'pdf');
|
||||
```
|
||||
|
||||
📚 [详细文档](./02-文档处理引擎/)
|
||||
|
||||
---
|
||||
|
||||
### 🔍 知识库检索(RAG)
|
||||
|
||||
```typescript
|
||||
import { DifyClient } from '../../../common/rag/DifyClient';
|
||||
|
||||
const dify = new DifyClient(apiKey, baseURL);
|
||||
const results = await dify.retrievalSearch(query, options);
|
||||
```
|
||||
|
||||
📚 [详细文档](./03-RAG引擎/)
|
||||
|
||||
---
|
||||
|
||||
### 💾 缓存服务
|
||||
|
||||
```typescript
|
||||
import { cache } from '../../../common/cache';
|
||||
|
||||
await cache.set('key', value, 3600); // TTL: 3600秒
|
||||
const value = await cache.get('key');
|
||||
await cache.delete('key');
|
||||
```
|
||||
|
||||
📚 [详细文档](./00-通用能力层清单.md#6-缓存服务)
|
||||
|
||||
---
|
||||
|
||||
### 📝 日志记录
|
||||
|
||||
```typescript
|
||||
import { logger } from '../../../common/logging';
|
||||
|
||||
logger.info('[Module] 操作描述', { userId: 'xxx', detail: 'xxx' });
|
||||
logger.error('[Module] 错误', { error, stack: error.stack });
|
||||
```
|
||||
|
||||
📚 [详细文档](./00-通用能力层清单.md#7-日志服务)
|
||||
|
||||
---
|
||||
|
||||
### 🔐 认证授权
|
||||
|
||||
**后端:**
|
||||
```typescript
|
||||
import { authenticate, getUserId } from '../../../common/auth';
|
||||
|
||||
// 路由
|
||||
fastify.get('/api', { preHandler: [authenticate] }, handler);
|
||||
|
||||
// 控制器
|
||||
const userId = getUserId(request);
|
||||
```
|
||||
|
||||
**前端:**
|
||||
```typescript
|
||||
import { getAccessToken } from '@/framework/auth/api';
|
||||
const token = getAccessToken();
|
||||
|
||||
// 或使用 apiClient(自动携带token)
|
||||
import apiClient from '@/common/api/axios';
|
||||
await apiClient.get('/api/xxx');
|
||||
```
|
||||
|
||||
📚 [详细文档](../04-开发规范/10-模块认证规范.md)
|
||||
|
||||
---
|
||||
|
||||
### 📋 Prompt 管理
|
||||
|
||||
```typescript
|
||||
import { PromptService } from '../../../common/prompt/prompt.service';
|
||||
|
||||
const promptService = new PromptService();
|
||||
const prompt = await promptService.getActivePrompt('template_code');
|
||||
const rendered = promptService.renderPrompt(template, variables);
|
||||
```
|
||||
|
||||
📚 [详细文档](./00-通用能力层清单.md#11-prompt-管理系统)
|
||||
|
||||
---
|
||||
|
||||
## 🏗️ 架构原则
|
||||
|
||||
### ✅ 正确做法
|
||||
|
||||
```typescript
|
||||
// 1. 使用通用能力,不要重复造轮子
|
||||
import { createStreamingService } from '../../../common/streaming';
|
||||
|
||||
// 2. 遵循云原生规范
|
||||
await storage.upload(); // 不要用 fs.writeFileSync()
|
||||
|
||||
// 3. 使用结构化日志
|
||||
logger.info('[Module] 操作', { detail }); // 不要用 console.log()
|
||||
|
||||
// 4. 统一认证
|
||||
fastify.get('/api', { preHandler: [authenticate] });
|
||||
|
||||
// 5. 标准化API格式
|
||||
// OpenAI Compatible, not 自定义格式
|
||||
```
|
||||
|
||||
### ❌ 错误做法
|
||||
|
||||
```typescript
|
||||
// 1. 自己实现已有的能力
|
||||
reply.raw.write('data: ...'); // ❌ 应该用 StreamingService
|
||||
|
||||
// 2. 直接操作本地文件
|
||||
fs.writeFileSync('/tmp/file'); // ❌ 应该用 storage
|
||||
|
||||
// 3. 使用 console.log
|
||||
console.log('debug'); // ❌ 应该用 logger
|
||||
|
||||
// 4. 硬编码用户ID
|
||||
const userId = 'test'; // ❌ 应该用 getUserId(request)
|
||||
|
||||
// 5. 自定义格式
|
||||
{ type: 'delta', content: 'xxx' } // ❌ 应该用 OpenAI Compatible
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 📚 完整文档
|
||||
|
||||
- [通用能力层清单(完整版)](./00-通用能力层清单.md)
|
||||
- [云原生开发规范](../04-开发规范/08-云原生开发规范.md)
|
||||
- [模块认证规范](../04-开发规范/10-模块认证规范.md)
|
||||
- [数据库开发规范](../04-开发规范/09-数据库开发规范.md)
|
||||
|
||||
---
|
||||
|
||||
**更新时间:** 2026-01-14
|
||||
|
||||
Reference in New Issue
Block a user