feat(aia): Implement Protocol Agent MVP with reusable Agent framework

Sprint 1-3 Completed (Backend + Frontend):

Backend (Sprint 1-2):
- Implement 5-layer Agent framework (Query->Planner->Executor->Tools->Reflection)
- Create agent_schema with 6 tables (agent_definitions, stages, prompts, sessions, traces, reflexion_rules)
- Create protocol_schema with 2 tables (protocol_contexts, protocol_generations)
- Implement Protocol Agent core services (Orchestrator, ContextService, PromptBuilder)
- Integrate LLM service adapter (DeepSeek/Qwen/GPT-5/Claude)
- 6 API endpoints with full authentication
- 10/10 API tests passed

Frontend (Sprint 3):
- Add Protocol Agent entry in AgentHub (indigo theme card)
- Implement ProtocolAgentPage with 3-column layout
- Collapsible sidebar (Gemini style, 48px <-> 280px)
- StatePanel with 5 stage cards (scientific_question, pico, study_design, sample_size, endpoints)
- ChatArea with sync button and action cards integration
- 100% prototype design restoration (608 lines CSS)
- Detailed endpoints structure: baseline, exposure, outcomes, confounders

Features:
- 5-stage dialogue flow for research protocol design
- Conversation-driven interaction with sync-to-protocol button
- Real-time context state management
- One-click protocol generation button (UI ready, backend pending)

Database:
- agent_schema: 6 tables for reusable Agent framework
- protocol_schema: 2 tables for Protocol Agent
- Seed data: 1 agent + 5 stages + 9 prompts + 4 reflexion rules

Code Stats:
- Backend: 13 files, 4338 lines
- Frontend: 14 files, 2071 lines
- Total: 27 files, 6409 lines

Status: MVP core functionality completed, pending frontend-backend integration testing

Next: Sprint 4 - One-click protocol generation + Word export
This commit is contained in:
2026-01-24 17:29:24 +08:00
parent 61cdc97eeb
commit 96290d2f76
345 changed files with 13945 additions and 47 deletions

View File

@@ -0,0 +1,183 @@
# Protocol Agent 开发计划总览
> 版本v1.0
> 创建日期2026-01-24
> 状态:待开发
---
## 一、项目背景
Protocol Agent研究方案制定助手是AIA模块的第13个智能体入口旨在通过多轮对话引导用户完成临床研究方案的核心要素制定。
### 1.1 核心价值
- **统一入口**整合样本量计算、PICO提取等7个工具的能力
- **长期记忆**ProtocolContext持久化存储研究方案要素
- **专业引导**:基于临床研究方法学的思维链引导
- **平台基础**为后续统计分析Agent、数据清洗Agent等提供可复用框架
### 1.2 设计哲学
```
Code as Skeleton, Data as Brain
代码是骨架(确定性流程),数据是大脑(灵活配置)
```
---
## 二、决策确认记录
| 决策项 | 选择 | 说明 |
|--------|------|------|
| **入口方式** | B - 第13个入口 | Protocol Agent作为独立入口12个现有智能体保留 |
| **状态流转** | **对话驱动** | 用户在对话中说"继续"或点击"同步"按钮,自然推进阶段 |
| **数据同步** | **内嵌同步按钮** | AI整理好数据后在回复中显示"同步到方案"按钮 |
| **Action Card** | B - 规则触发 | 基于阶段和条件规则触发非LLM决定 |
| **Reflexion** | B - Prompt-based | 使用Prompt模板进行质量检查P2优先级 |
| **MVP范围** | 渐进式演进 | Phase 1聚焦核心流程后续迭代增强 |
| **阶段数量** | **5个阶段** | 科学问题→PICO→研究设计→样本量→观察指标 |
| **完成功能** | **一键生成** | 5阶段完成后支持一键生成研究方案并下载Word |
---
## 三、文档索引
本开发计划包含以下文档:
| 序号 | 文档名称 | 内容说明 |
|------|----------|----------|
| 00 | 开发计划总览.md | 本文档,项目概述与决策记录 |
| 01 | 架构设计.md | 五层Agent架构、组件职责、执行流程 |
| 02 | 数据库设计.md | 完整Prisma Schema定义 |
| 03 | 代码结构设计.md | 目录结构、核心接口、类型定义 |
| 04 | 分阶段实施计划.md | Sprint划分、任务列表、里程碑 |
---
## 四、核心架构概览
### 4.1 核心交互模式:对话驱动
```
┌─────────────────────────────────────────────────────────────────────────┐
│ 对话驱动交互模式 │
├─────────────────────────────────────────────────────────────────────────┤
│ │
│ 【用户与AI对话】 │
│ ↓ │
│ 【AI收集信息整理数据】 │
│ ↓ │
│ 【AI回复中显示 "✅ 同步到方案" 按钮】 │
│ ↓ │
│ 【用户点击同步】→ 数据写入Context → State Panel更新 │
│ ↓ │
│ 【AI询问继续下一阶段吗】 │
│ ↓ │
│ 【用户说"继续"】→ AI识别意图 → 自动进入下一阶段 │
│ │
└─────────────────────────────────────────────────────────────────────────┘
```
### 4.2 五层架构
```
┌─────────────────────────────────────────────────────────┐
│ 1. Query Layer 意图识别、实体提取、上下文消歧 │
├─────────────────────────────────────────────────────────┤
│ 2. Planner Layer 状态机、策略选择、任务分解 │
├─────────────────────────────────────────────────────────┤
│ 3. Executor Layer LLM调用、工具调用、响应构建 │
├─────────────────────────────────────────────────────────┤
│ 4. Tools Layer 内部工具、外部工具、RAG、Deep Link │
├─────────────────────────────────────────────────────────┤
│ 5. Reflection Layer 质量检查、一致性校验、恢复处理 │
└─────────────────────────────────────────────────────────┘
```
### 4.3 三层职责划分
| 层次 | 职责 | 实现方式 |
|------|------|----------|
| **代码层** | 状态流转、数据存储、API调用、错误处理 | TypeScript代码 |
| **Prompt层** | 意图识别、对话生成、信息提取、质量检查 | Prompt模板 + LLM |
| **工具层** | Deep Link、外部API、知识库检索 | 工具注册 + 调用 |
---
## 五、阶段规划
### Phase 1MVP完整功能4周
**目标**完成Agent框架 + 5阶段对话 + 一键生成研究方案
- ✅ 通用Agent框架搭建
- ✅ 5个核心阶段科学问题→PICO→研究设计→样本量→观察指标
- ✅ 对话驱动 + 同步按钮交互模式
- ✅ ProtocolContext持久化
- ✅ State Panel前端展示
-**一键生成研究方案**
-**Word文档导出**
### Phase 2知识增强3周
**目标**:集成专家知识库,提升专业深度
- 🔲 EKB知识库建设
- 🔲 RAG检索集成
- 🔲 Function Calling工具调用
- 🔲 高级Reflexion质量检查
### Phase 3平台化2周
**目标**配置化、可观测性、多Agent支持
- 🔲 后台配置管理界面
- 🔲 Prompt在线调试
- 🔲 完整Trace分析
- 🔲 统计分析Agent接入准备
---
## 六、技术栈
| 类别 | 技术选型 | 说明 |
|------|----------|------|
| **后端框架** | Fastify v4 + TypeScript | 现有架构 |
| **数据库** | PostgreSQL 15 + Prisma 6 | 现有架构 |
| **LLM** | DeepSeek-V3 (主) / GPT-4 (备) | 通过LLM Gateway |
| **前端框架** | React 19 + Ant Design 6 | 现有架构 |
| **状态管理** | Zustand | 轻量级状态管理 |
---
## 七、风险与缓解
| 风险 | 影响 | 缓解措施 |
|------|------|----------|
| LLM幻觉 | 生成不准确的医学信息 | Reflexion检查 + 知识库约束 |
| 上下文丢失 | 长对话信息遗忘 | ProtocolContext持久化 + 摘要策略 |
| 提取不准确 | Context数据错误 | 置信度标记 + 用户确认 |
| Prompt调优耗时 | 延迟交付 | 预留充足调优时间 |
---
## 八、成功标准
### Phase 1 交付标准
1. **功能完整性**用户可完成5阶段研究方案要素制定
2. **数据准确性**Context提取准确率 > 85%
3. **用户体验**:单阶段平均对话轮数 < 5轮
4. **系统稳定性**API响应成功率 > 99%
---
## 九、相关文档
- [Protocol Agent PRD v1.0](../00-系统设计/Protocol_Agent_PRD_v1.0.md)
- [MVP简化指南](../00-系统设计/Protocol_Agent_Development_Simplification_Guide.md)
- [架构设计V3](../02-技术设计/Protocol_Agent_Architecture_Design_V3.md)
- [技术实现V3](../02-技术设计/Protocol_Agent_Technical_Implementation_V3.md)
- [后端配置设计](../02-技术设计/Protocol_Agent_Backend_Config_Design.md)

View File

@@ -0,0 +1,498 @@
# Protocol Agent 架构设计
> 版本v1.0
> 创建日期2026-01-24
---
## 一、整体架构图
```
┌────────────────────────────────────────────────────────────────────────────┐
│ Protocol Agent 架构 │
├────────────────────────────────────────────────────────────────────────────┤
│ │
│ 用户输入 │
│ │ │
│ ▼ │
│ ┌────────────────────────────────────────────────────────────────────┐ │
│ │ 1. Query Layer (意图识别层) │ │
│ │ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │ │
│ │ │ Intent │ │ Entity │ │ Context │ │ │
│ │ │ Classifier │ │ Extractor │ │ Resolver │ │ │
│ │ │ (意图分类) │ │ (实体提取) │ │ (上下文消歧) │ │ │
│ │ └──────────────┘ └──────────────┘ └──────────────┘ │ │
│ └────────────────────────────────────────────────────────────────────┘ │
│ │ │
│ ▼ │
│ ┌────────────────────────────────────────────────────────────────────┐ │
│ │ 2. Planner Layer (规划层) │ │
│ │ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │ │
│ │ │ Stage │ │ Strategy │ │ Task │ │ │
│ │ │ Machine │ │ Selector │ │ Decomposer │ │ │
│ │ │ (状态机) │ │ (策略选择) │ │ (任务分解) │ │ │
│ │ └──────────────┘ └──────────────┘ └──────────────┘ │ │
│ └────────────────────────────────────────────────────────────────────┘ │
│ │ │
│ ▼ │
│ ┌────────────────────────────────────────────────────────────────────┐ │
│ │ 3. Executor Layer (执行层) │ │
│ │ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │ │
│ │ │ LLM │ │ Tool │ │ Response │ │ │
│ │ │ Invoker │ │ Invoker │ │ Builder │ │ │
│ │ │ (LLM调用) │ │ (工具调用) │ │ (响应构建) │ │ │
│ │ └──────────────┘ └──────────────┘ └──────────────┘ │ │
│ └────────────────────────────────────────────────────────────────────┘ │
│ │ │
│ ▼ │
│ ┌────────────────────────────────────────────────────────────────────┐ │
│ │ 4. Tools Layer (工具层) │ │
│ │ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │ │
│ │ │ Internal │ │ External │ │ Deep Link │ │ │
│ │ │ Tools │ │ Tools │ │ Generator │ │ │
│ │ └──────────────┘ └──────────────┘ └──────────────┘ │ │
│ │ ┌──────────────┐ ┌──────────────┐ │ │
│ │ │ RAG │ │ Knowledge │ ← Phase 2 │ │
│ │ │ Retriever │ │ Base │ │ │
│ │ └──────────────┘ └──────────────┘ │ │
│ └────────────────────────────────────────────────────────────────────┘ │
│ │ │
│ ▼ │
│ ┌────────────────────────────────────────────────────────────────────┐ │
│ │ 5. Reflection Layer (反思层) │ │
│ │ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │ │
│ │ │ Quality │ │ Consistency │ │ Recovery │ │ │
│ │ │ Checker │ │ Validator │ │ Handler │ │ │
│ │ │ (质量检查) │ │ (一致性校验) │ │ (恢复处理) │ │ │
│ │ └──────────────┘ └──────────────┘ └──────────────┘ │ │
│ └────────────────────────────────────────────────────────────────────┘ │
│ │
│ ═══════════════════════════════════════════════════════════════════════ │
│ │
│ ┌────────────────────────────────────────────────────────────────────┐ │
│ │ 横切关注点 (Cross-Cutting) │ │
│ │ ┌─────────┐ ┌─────────┐ ┌─────────┐ ┌─────────┐ ┌─────────┐ │ │
│ │ │ Memory │ │ Config │ │ Trace │ │ Prompt │ │ Event │ │ │
│ │ │ Manager │ │ Manager │ │ Logger │ │ Manager │ │ Bus │ │ │
│ │ └─────────┘ └─────────┘ └─────────┘ └─────────┘ └─────────┘ │ │
│ └────────────────────────────────────────────────────────────────────┘ │
│ │
└────────────────────────────────────────────────────────────────────────────┘
```
---
## 二、各层详细设计
### 2.1 Query Layer意图识别层
**职责**:理解用户输入,识别意图,提取实体
| 组件 | 功能 | 实现方式 | Phase |
|------|------|----------|-------|
| IntentClassifier | 识别用户意图类型 | Prompt + LLM | P1 |
| EntityExtractor | 从输入提取关键实体 | Prompt + LLM | P1 |
| ContextResolver | 结合历史消息消歧 | Prompt + LLM | P2 |
**意图类型定义**
```typescript
type IntentType =
| 'provide_info' // 提供信息(主流程)
| 'ask_question' // 询问问题
| 'request_change' // 请求修改已有数据
| 'confirm_complete' // 确认阶段完成
| 'navigate_stage' // 跳转阶段
| 'request_tool' // 请求使用工具
| 'chitchat' // 闲聊
| 'unclear'; // 不明确
```
**Query分析Prompt模板**
```
分析用户消息的意图。当前处于"{{currentStage}}"阶段。
用户消息: "{{userMessage}}"
已有上下文:
{{contextSummary}}
请判断:
1. 意图类型: [provide_info | ask_question | request_change | confirm_complete | navigate_stage | request_tool | chitchat | unclear]
2. 置信度: 0-1
3. 提取的实体: [{type, value, confidence}]
4. 是否需要澄清
以JSON格式返回。
```
### 2.2 Planner Layer规划层
**职责**:基于意图决定执行策略,管理状态流转
| 组件 | 功能 | 实现方式 | Phase |
|------|------|----------|-------|
| StageMachine | 管理阶段状态流转 | 代码 + 配置 | P1 |
| StrategySelector | 选择执行策略 | 规则 + 配置 | P1 |
| TaskDecomposer | 复杂任务分解 | LLM | P3 |
**状态机设计**
```
┌──────────────┐ 确认 ┌──────────────┐ 确认 ┌──────────────┐
│ 科学问题 │ ─────────→ │ PICO │ ─────────→ │ 研究设计 │
│ scientific_q │ │ pico │ │ study_design │
└──────────────┘ └──────────────┘ └──────────────┘
│ 确认
┌──────────────┐ 确认 ┌──────────────┐
│ 终点指标 │ ←───────── │ 样本量 │
│ endpoints │ │ sample_size │
└──────────────┘ └──────────────┘
│ 确认
┌──────────┐
│ 完成 │
│ complete │
└──────────┘
```
**执行策略**
```typescript
type ExecutionStrategy =
| 'guide_and_extract' // 引导对话并提取数据
| 'answer_question' // 回答用户问题
| 'update_context' // 更新已有数据
| 'trigger_tool' // 触发工具调用
| 'transition_stage' // 执行阶段流转
| 'request_clarification' // 请求澄清
| 'handle_chitchat'; // 处理闲聊
```
**策略选择规则**
```typescript
function selectStrategy(intent: IntentType, stage: string): ExecutionStrategy {
const rules = {
'provide_info': 'guide_and_extract',
'ask_question': 'answer_question',
'request_change': 'update_context',
'confirm_complete': 'transition_stage',
'request_tool': 'trigger_tool',
'chitchat': 'handle_chitchat',
'unclear': 'request_clarification'
};
return rules[intent];
}
```
### 2.3 Executor Layer执行层
**职责**执行具体任务调用LLM和工具
| 组件 | 功能 | 实现方式 | Phase |
|------|------|----------|-------|
| LLMInvoker | 调用LLM生成响应 | 代码 | P1 |
| ToolInvoker | 调用注册的工具 | 代码 | P1 |
| ResponseBuilder | 构建最终响应 | 代码 | P1 |
**LLM调用流程**
```
1. PromptBuilder.buildSystemPrompt() → 构建System Prompt
2. MemoryManager.getHistory() → 获取对话历史
3. LLMGateway.streamChat() → 流式调用LLM
4. ResponseParser.parse() → 解析响应
5. DataExtractor.extract() → 提取结构化数据
```
### 2.4 Tools Layer工具层
**职责**:提供各类工具能力
| 组件 | 功能 | 实现方式 | Phase |
|------|------|----------|-------|
| InternalTools | 内部计算工具 | 代码 | P1 |
| DeepLinkGenerator | 生成跳转链接 | 代码 | P1 |
| ExternalTools | 外部API工具 | 代码 | P2 |
| RAGRetriever | RAG知识检索 | RAG引擎 | P2 |
**工具注册格式**
```typescript
interface ToolDefinition {
toolId: string;
toolName: string;
description: string; // 给LLM看的描述
toolType: 'internal' | 'external' | 'deep_link' | 'rag';
// Function Calling 格式Phase 2
functionSchema?: {
name: string;
description: string;
parameters: JSONSchema;
};
// 执行配置
handler: (params: any) => Promise<any>;
}
```
**Deep Link Action Card**
```typescript
interface ActionCard {
cardId: string;
title: string;
description: string;
triggerType: 'stage_enter' | 'condition' | 'manual';
actionType: 'deep_link' | 'api_call' | 'modal';
// Deep Link配置
deepLinkConfig?: {
targetAgent: string; // 目标Agent ID
targetPath: string; // 目标路径
params: Record<string, string>; // 参数映射
onComplete: 'update_context' | 'notify' | 'none';
};
}
```
### 2.5 Reflection Layer反思层
**职责**:质量保障,一致性检查
| 组件 | 功能 | 实现方式 | Phase |
|------|------|----------|-------|
| QualityChecker | 检查输出质量 | Prompt + LLM | P1 |
| ConsistencyValidator | 检查数据一致性 | 规则 + LLM | P2 |
| RecoveryHandler | 错误恢复处理 | 代码 | P2 |
**Reflexion规则类型**
```typescript
type ReflexionRuleType =
| 'prompt_based' // Prompt驱动检查
| 'rule_based' // 规则驱动检查
| 'hybrid'; // 混合检查
interface ReflexionRule {
ruleId: string;
triggerStage: string; // 触发阶段
triggerTiming: 'on_extract' | 'on_complete' | 'on_transition';
ruleType: ReflexionRuleType;
// Prompt-based
promptTemplate?: string;
// Rule-based
ruleLogic?: {
field: string;
condition: string;
expectedValue: any;
};
severity: 'error' | 'warning' | 'info';
failureAction: 'block' | 'warn' | 'log';
}
```
**Reflexion Prompt模板示例**
```
检查研究方案的PICO要素是否完整和一致。
当前PICO数据:
{{picoData}}
科学问题:
{{scientificQuestion}}
请检查:
1. P/I/C/O四个要素是否都已定义
2. 各要素是否与科学问题一致
3. 是否存在逻辑矛盾
4. 是否符合临床研究规范
返回JSON格式:
{
"passed": boolean,
"issues": string[],
"suggestions": string[]
}
```
---
## 三、横切关注点
### 3.1 Memory Manager记忆管理
```typescript
interface MemoryManager {
// 短期记忆:对话历史
getConversationHistory(conversationId: string, limit?: number): Message[];
// 中期记忆:会话上下文
getSessionContext(sessionId: string): AgentSession;
// 长期记忆Protocol数据
getProtocolContext(conversationId: string): ProtocolContext;
// 记忆摘要(长对话优化)
summarizeHistory(messages: Message[]): string;
}
```
### 3.2 Config Manager配置管理
```typescript
interface ConfigManager {
// 加载Agent配置
getAgentConfig(agentId: string): AgentConfig;
// 加载阶段配置
getStageConfig(agentId: string, stageId: string): AgentStage;
// 加载工具配置
getToolConfig(toolId: string): AgentTool;
// 热更新支持Phase 3
reloadConfig(agentId: string): void;
}
```
### 3.3 Trace Logger追踪日志
```typescript
interface TraceLogger {
// 开始追踪
startTrace(conversationId: string): string; // 返回traceId
// 记录步骤
logStep(traceId: string, step: TraceStep): void;
// 结束追踪
endTrace(traceId: string, result: 'success' | 'error'): void;
// 查询追踪(调试用)
getTrace(traceId: string): AgentTrace[];
}
interface TraceStep {
stepType: 'query_analysis' | 'planning' | 'execution' | 'tool_call' | 'reflexion';
stepInput: any;
stepOutput: any;
durationMs: number;
llmTokens?: { prompt: number; completion: number };
}
```
---
## 四、完整执行流程
```
用户发送消息
┌─────────────────────────────────────────────────────────────────────┐
│ Step 1: 初始化 │
│ • 生成 traceId │
│ • 加载 AgentConfig, StageConfig │
│ • 加载 ProtocolContext │
│ • 获取对话历史 │
└─────────────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────────┐
│ Step 2: Query Analysis │
│ • IntentClassifier.classify(userMessage, context) │
│ • EntityExtractor.extract(userMessage) │
│ • ContextResolver.resolve(userMessage, history) │
│ → 输出: QueryAnalysisResult │
└─────────────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────────┐
│ Step 3: Planning │
│ • StageMachine.getCurrentState() │
│ • StrategySelector.select(intent, stage) │
│ • 确定需要调用的工具 │
│ → 输出: ExecutionPlan │
└─────────────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────────┐
│ Step 4: Execution │
│ • PromptBuilder.build(config, context, plan) │
│ • LLMInvoker.invoke(systemPrompt, history, userMessage) │
│ • 如需调用工具: ToolInvoker.invoke(toolId, params) │
│ • ResponseBuilder.build(llmOutput, toolResults) │
│ → 输出: ExecutionResult │
└─────────────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────────┐
│ Step 5: Data Extraction │
│ • 从LLM输出提取结构化数据 │
│ • 验证数据格式 │
│ • 计算置信度 │
│ → 输出: ExtractedData │
└─────────────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────────┐
│ Step 6: Reflection (可选) │
│ • QualityChecker.check(response) │
│ • ConsistencyValidator.validate(extractedData, context) │
│ • 如失败: RecoveryHandler.handle() │
│ → 输出: ReflexionResult │
└─────────────────────────────────────────────────────────────────────┘
┌─────────────────────────────────────────────────────────────────────┐
│ Step 7: Finalize │
│ • 更新 ProtocolContext │
│ • 保存 Message │
│ • 评估 Action Cards │
│ • 记录 Trace │
│ → 返回响应给用户 │
└─────────────────────────────────────────────────────────────────────┘
```
---
## 五、框架复用设计
该框架设计为可复用未来Agent可直接继承
```typescript
// 基类
abstract class BaseAgentOrchestrator<TContext> {
abstract getAgentId(): string;
abstract getContextSchema(): TContext;
async handleMessage(conversationId: string, message: string): Promise<Response> {
// 通用流程实现
}
}
// Protocol Agent
class ProtocolAgentOrchestrator extends BaseAgentOrchestrator<ProtocolContext> {
getAgentId() { return 'protocol_agent'; }
getContextSchema() { return ProtocolContextSchema; }
}
// 未来Statistics Agent
class StatisticsAgentOrchestrator extends BaseAgentOrchestrator<StatisticsContext> {
getAgentId() { return 'statistics_agent'; }
getContextSchema() { return StatisticsContextSchema; }
}
```

View File

@@ -0,0 +1,846 @@
# Protocol Agent 数据库设计
> 版本v1.0
> 创建日期2026-01-24
---
## 一、Schema规划
```
┌─────────────────────────────────────────────────────────────────────────┐
│ 数据库Schema架构 │
├─────────────────────────────────────────────────────────────────────────┤
│ │
│ agent_schema (通用Agent框架 - 可复用) │
│ ├── agent_configs Agent配置表 │
│ ├── agent_stages 阶段配置表 │
│ ├── agent_tools 工具注册表 │
│ ├── action_cards Action Card配置表 │
│ ├── reflexion_rules 反思规则表 │
│ ├── agent_sessions Agent会话表 │
│ └── agent_traces 追踪日志表 │
│ │
│ protocol_schema (研究方案Agent专用) │
│ ├── protocol_contexts 研究方案上下文表 │
│ ├── protocol_versions 版本历史表 │
│ └── protocol_exports 导出记录表 │
│ │
│ knowledge_schema (知识库 - Phase 2) │
│ ├── knowledge_docs 知识文档表 │
│ ├── knowledge_chunks 知识块表 │
│ └── knowledge_embeddings 向量嵌入表 │
│ │
│ aia_schema (已有 - 复用) │
│ ├── conversations 对话表 │
│ └── messages 消息表 │
│ │
│ capability_schema (已有 - 复用) │
│ └── prompt_templates Prompt模板表 │
│ │
└─────────────────────────────────────────────────────────────────────────┘
```
---
## 二、agent_schema - 通用Agent框架表
### 2.1 agent_configs (Agent配置表)
```prisma
/// Agent配置表 - 定义每个Agent的基础信息
model AgentConfig {
id String @id @default(uuid())
agentId String @unique @map("agent_id")
agentName String @map("agent_name")
agentDescription String? @map("agent_description")
baseSystemPrompt String @map("base_system_prompt") @db.Text
// 全局配置
toneOfVoice String? @map("tone_of_voice")
globalKnowledge String[] @map("global_knowledge")
memoryStrategy String @default("full") @map("memory_strategy")
maxHistoryTurns Int @default(20) @map("max_history_turns")
// LLM配置
defaultModel String @default("deepseek-v3") @map("default_model")
temperature Float @default(0.7)
maxTokens Int @default(4096) @map("max_tokens")
// 状态
isActive Boolean @default(true) @map("is_active")
version Int @default(1)
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
// 关联
stages AgentStage[] @relation("AgentConfigStages")
tools AgentTool[] @relation("AgentConfigTools")
reflexionRules ReflexionRule[] @relation("AgentConfigReflexion")
@@index([agentId, isActive])
@@map("agent_configs")
@@schema("agent_schema")
}
```
**字段说明**
| 字段 | 类型 | 说明 |
|------|------|------|
| agentId | string | Agent唯一标识`protocol_agent` |
| baseSystemPrompt | text | 基础系统Prompt |
| toneOfVoice | string | 语气风格,如"专业但亲和" |
| memoryStrategy | string | 记忆策略full/sliding_window/summary |
| maxHistoryTurns | int | 最大保留对话轮数 |
### 2.2 agent_stages (阶段配置表)
```prisma
/// 阶段配置表 - 定义Agent的各个阶段
model AgentStage {
id String @id @default(uuid())
agentConfigId String @map("agent_config_id")
stageId String @map("stage_id")
stageName String @map("stage_name")
stageOrder Int @map("stage_order")
// Prompt配置
instruction String @db.Text
extractionSchema Json @map("extraction_schema")
completionCriteria String? @map("completion_criteria") @db.Text
// 流转配置
nextStageId String? @map("next_stage_id")
transitionMode String @default("user_confirm") @map("transition_mode")
transitionCondition Json? @map("transition_condition")
// 工具配置
availableToolIds String[] @map("available_tool_ids")
isActive Boolean @default(true) @map("is_active")
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
agentConfig AgentConfig @relation("AgentConfigStages", fields: [agentConfigId], references: [id], onDelete: Cascade)
actionCards ActionCard[] @relation("StageActionCards")
@@unique([agentConfigId, stageId])
@@index([agentConfigId, stageOrder])
@@map("agent_stages")
@@schema("agent_schema")
}
```
**extractionSchema 示例** (PICO阶段)
```json
{
"type": "object",
"properties": {
"P": {
"type": "object",
"properties": {
"value": { "type": "string", "description": "研究人群" },
"details": { "type": "string" },
"confidence": { "type": "number" }
}
},
"I": { ... },
"C": { ... },
"O": { ... }
}
}
```
### 2.3 agent_tools (工具注册表)
```prisma
/// 工具注册表 - 定义Agent可用的工具
model AgentTool {
id String @id @default(uuid())
agentConfigId String? @map("agent_config_id")
toolId String @unique @map("tool_id")
toolName String @map("tool_name")
toolDescription String @map("tool_description") @db.Text
toolType String @map("tool_type")
// Function定义
functionSchema Json? @map("function_schema")
// 执行配置
handlerType String @map("handler_type")
handlerConfig Json @map("handler_config")
// 权限和限制
requiresAuth Boolean @default(false) @map("requires_auth")
rateLimit Int? @map("rate_limit")
timeout Int @default(30000)
isActive Boolean @default(true) @map("is_active")
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
agentConfig AgentConfig? @relation("AgentConfigTools", fields: [agentConfigId], references: [id], onDelete: Cascade)
@@index([agentConfigId, isActive])
@@index([toolType])
@@map("agent_tools")
@@schema("agent_schema")
}
```
**toolType 枚举值**
- `internal`: 内部计算工具
- `external`: 外部API工具
- `deep_link`: 深度链接跳转
- `rag`: RAG知识检索
### 2.4 action_cards (Action Card配置表)
```prisma
/// Action Card配置表
model ActionCard {
id String @id @default(uuid())
stageId String @map("stage_id")
cardId String @map("card_id")
title String
description String? @db.Text
iconType String? @map("icon_type")
// 触发配置
triggerType String @map("trigger_type")
triggerCondition Json? @map("trigger_condition")
// Action配置
actionType String @map("action_type")
actionPayload Json @map("action_payload")
// 回调配置
onCompleteAction String? @map("on_complete_action")
resultMapping Json? @map("result_mapping")
displayOrder Int @default(0) @map("display_order")
isActive Boolean @default(true) @map("is_active")
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
stage AgentStage @relation("StageActionCards", fields: [stageId], references: [id], onDelete: Cascade)
@@unique([stageId, cardId])
@@map("action_cards")
@@schema("agent_schema")
}
```
**actionPayload 示例** (Deep Link)
```json
{
"targetAgent": "sample_calculator",
"targetPath": "/aia/sample-calculator",
"params": {
"studyType": "{{studyDesign.type}}",
"primaryEndpoint": "{{endpoints.primary[0].name}}"
},
"openMode": "modal"
}
```
### 2.5 reflexion_rules (反思规则表)
```prisma
/// Reflexion规则表
model ReflexionRule {
id String @id @default(uuid())
agentConfigId String @map("agent_config_id")
ruleId String @map("rule_id")
ruleName String @map("rule_name")
ruleDescription String? @map("rule_description") @db.Text
// 触发配置
triggerStageId String? @map("trigger_stage_id")
triggerTiming String @map("trigger_timing")
// 规则内容
ruleType String @map("rule_type")
promptTemplate String? @map("prompt_template") @db.Text
ruleLogic Json? @map("rule_logic")
// 失败处理
severity String @default("warning")
failureAction String @map("failure_action")
isActive Boolean @default(true) @map("is_active")
priority Int @default(0)
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
agentConfig AgentConfig @relation("AgentConfigReflexion", fields: [agentConfigId], references: [id], onDelete: Cascade)
@@unique([agentConfigId, ruleId])
@@index([triggerStageId, triggerTiming])
@@map("reflexion_rules")
@@schema("agent_schema")
}
```
### 2.6 agent_sessions (Agent会话表)
```prisma
/// Agent会话表 - 扩展conversation的Agent状态
model AgentSession {
id String @id @default(uuid())
conversationId String @unique @map("conversation_id")
agentId String @map("agent_id")
userId String @map("user_id")
// 状态管理
currentStageId String @map("current_stage_id")
stageStatus String @default("in_progress") @map("stage_status")
// 元数据
sessionMetadata Json? @map("session_metadata")
// 生命周期
startedAt DateTime @default(now()) @map("started_at")
lastActiveAt DateTime @default(now()) @map("last_active_at")
completedAt DateTime? @map("completed_at")
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
@@index([agentId, userId])
@@index([currentStageId])
@@index([lastActiveAt])
@@map("agent_sessions")
@@schema("agent_schema")
}
```
### 2.7 agent_traces (追踪日志表)
```prisma
/// Agent追踪日志表 - 可观测性
model AgentTrace {
id String @id @default(uuid())
conversationId String @map("conversation_id")
messageId String? @map("message_id")
traceId String @map("trace_id")
// 步骤信息
stepType String @map("step_type")
stepOrder Int @map("step_order")
// 输入输出
stepInput Json? @map("step_input")
stepOutput Json? @map("step_output")
// LLM信息
llmModel String? @map("llm_model")
llmPromptTokens Int? @map("llm_prompt_tokens")
llmCompletionTokens Int? @map("llm_completion_tokens")
// 性能
durationMs Int? @map("duration_ms")
// 状态
status String @default("success")
errorMessage String? @map("error_message") @db.Text
createdAt DateTime @default(now()) @map("created_at")
@@index([conversationId, traceId])
@@index([traceId, stepOrder])
@@index([createdAt])
@@index([stepType, status])
@@map("agent_traces")
@@schema("agent_schema")
}
```
---
## 三、protocol_schema - 研究方案专用表
### 3.1 protocol_contexts (研究方案上下文表)
```prisma
/// Protocol上下文表 - 研究方案的结构化数据存储
model ProtocolContext {
id String @id @default(uuid())
sessionId String @unique @map("session_id")
conversationId String @unique @map("conversation_id")
userId String @map("user_id")
// ===== Phase 1 核心字段 =====
/// 阶段1科学问题
scientificQuestion Json? @map("scientific_question") @db.JsonB
/// 阶段2PICO
pico Json? @db.JsonB
/// 阶段3研究设计
studyDesign Json? @map("study_design") @db.JsonB
/// 阶段4样本量
sampleSize Json? @map("sample_size") @db.JsonB
/// 阶段5终点指标
endpoints Json? @db.JsonB
// ===== Phase 2 扩展字段 =====
/// 入选标准
inclusionCriteria Json? @map("inclusion_criteria") @db.JsonB
/// 排除标准
exclusionCriteria Json? @map("exclusion_criteria") @db.JsonB
/// 统计分析计划
statisticalPlan Json? @map("statistical_plan") @db.JsonB
// ===== Phase 3 扩展字段 =====
/// 伦理考量
ethicsConsiderations Json? @map("ethics_considerations") @db.JsonB
/// 研究时间线
timeline Json? @db.JsonB
/// 预算估算
budget Json? @db.JsonB
// ===== 元数据 =====
/// 总体进度 0-100
overallProgress Float @default(0) @map("overall_progress")
/// 已完成阶段
completedStages String[] @map("completed_stages")
/// 版本号
version Int @default(1)
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
versions ProtocolVersion[] @relation("ProtocolContextVersions")
@@index([userId])
@@index([conversationId])
@@map("protocol_contexts")
@@schema("protocol_schema")
}
```
**各字段JSON结构**
#### scientificQuestion
```json
{
"content": "探究新型降糖药X对2型糖尿病患者的降糖效果及安全性",
"clinicalBackground": "2型糖尿病患病率逐年上升...",
"researchGap": "目前缺乏针对中国人群的大规模临床研究",
"significance": "填补该领域空白,为临床用药提供依据",
"confidence": 0.95,
"sourceMessageIds": ["msg_123", "msg_125"],
"lastUpdated": "2026-01-24T10:30:00Z"
}
```
#### pico
```json
{
"P": {
"value": "2型糖尿病患者",
"details": "年龄18-70岁HbA1c 7.0-10.0%",
"confidence": 0.9
},
"I": {
"value": "新型降糖药X",
"details": "口服每日一次剂量10mg",
"confidence": 0.95
},
"C": {
"value": "二甲双胍",
"details": "口服每日两次剂量500mg",
"confidence": 0.88
},
"O": {
"value": "HbA1c变化",
"details": "治疗12周后HbA1c相对基线的变化值",
"confidence": 0.92
},
"sourceMessageIds": ["msg_130", "msg_132"],
"lastUpdated": "2026-01-24T11:00:00Z"
}
```
#### studyDesign
```json
{
"type": "RCT",
"phase": "III",
"blinding": "双盲",
"randomization": "中心随机",
"allocationRatio": "1:1",
"controlType": "阳性对照",
"multiCenter": true,
"centerCount": 20,
"duration": "12周治疗期 + 4周随访期",
"confidence": 0.9,
"sourceMessageIds": ["msg_140"],
"lastUpdated": "2026-01-24T11:30:00Z"
}
```
#### sampleSize
```json
{
"total": 500,
"perGroup": 250,
"groups": 2,
"calculationMethod": "优效性检验",
"assumptions": {
"alpha": 0.05,
"power": 0.8,
"effectSize": 0.5,
"dropoutRate": 0.15,
"standardDeviation": 1.2
},
"justification": "基于既往研究预期效应量0.5%...",
"toolUsed": "sample_calculator",
"confidence": 0.95,
"sourceMessageIds": ["msg_150"],
"lastUpdated": "2026-01-24T12:00:00Z"
}
```
#### endpoints
```json
{
"primary": [{
"name": "HbA1c变化值",
"definition": "治疗12周后HbA1c相对基线的变化",
"measurementMethod": "高效液相色谱法",
"timePoint": "第12周",
"analysisMethod": "ANCOVA"
}],
"secondary": [{
"name": "空腹血糖",
"definition": "...",
"measurementMethod": "...",
"timePoint": "第4、8、12周"
}],
"safety": [{
"name": "低血糖发生率",
"definition": "血糖<3.9mmol/L的事件"
}],
"exploratory": [],
"sourceMessageIds": ["msg_160", "msg_162"],
"lastUpdated": "2026-01-24T12:30:00Z"
}
```
### 3.2 protocol_versions (版本历史表)
```prisma
/// Protocol版本历史表 - 支持回溯
model ProtocolVersion {
id String @id @default(uuid())
contextId String @map("context_id")
version Int
changeType String @map("change_type")
changedFields String[] @map("changed_fields")
previousSnapshot Json @map("previous_snapshot") @db.JsonB
changeReason String? @map("change_reason")
changedBy String @map("changed_by")
createdAt DateTime @default(now()) @map("created_at")
context ProtocolContext @relation("ProtocolContextVersions", fields: [contextId], references: [id], onDelete: Cascade)
@@unique([contextId, version])
@@index([contextId, createdAt])
@@map("protocol_versions")
@@schema("protocol_schema")
}
```
### 3.3 protocol_generations (研究方案生成表)
```prisma
/// Protocol生成记录表 - 一键生成研究方案
model ProtocolGeneration {
id String @id @default(uuid())
contextId String @map("context_id")
userId String @map("user_id")
// 生成内容
generatedContent String @map("generated_content") @db.Text // 生成的研究方案全文
contentVersion Int @default(1) @map("content_version") // 版本号(重新生成时递增)
// 使用的Prompt和参数
promptUsed String @map("prompt_used") @db.Text
generationParams Json? @map("generation_params") @db.JsonB // 生成参数
// LLM调用信息
modelUsed String @map("model_used")
tokensUsed Int? @map("tokens_used")
durationMs Int? @map("duration_ms")
// 导出记录
wordFileKey String? @map("word_file_key") // Word文件OSS Key
pdfFileKey String? @map("pdf_file_key") // PDF文件OSS Key
lastExportedAt DateTime? @map("last_exported_at")
// 用户编辑(如有)
userEditedContent String? @map("user_edited_content") @db.Text
isEdited Boolean @default(false) @map("is_edited")
status String @default("completed") // generating, completed, failed
errorMessage String? @map("error_message")
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
@@index([contextId])
@@index([userId, createdAt])
@@map("protocol_generations")
@@schema("protocol_schema")
}
```
**字段说明**
| 字段 | 类型 | 说明 |
|------|------|------|
| generatedContent | text | LLM生成的完整研究方案 |
| contentVersion | int | 版本号,重新生成时递增 |
| promptUsed | text | 使用的Prompt便于复现和调试 |
| userEditedContent | text | 用户编辑后的内容(可选) |
| wordFileKey | string | 导出的Word文件在OSS中的Key |
### 3.4 protocol_exports (导出记录表)
```prisma
/// Protocol导出记录表
model ProtocolExport {
id String @id @default(uuid())
contextId String @map("context_id")
userId String @map("user_id")
exportType String @map("export_type")
exportVersion Int @map("export_version")
fileKey String? @map("file_key")
status String @default("pending")
errorMessage String? @map("error_message")
createdAt DateTime @default(now()) @map("created_at")
completedAt DateTime? @map("completed_at")
@@index([contextId])
@@index([userId, createdAt])
@@map("protocol_exports")
@@schema("protocol_schema")
}
```
---
## 四、knowledge_schema - 知识库表 (Phase 2)
### 4.1 knowledge_docs (知识文档表)
```prisma
/// 专家知识文档表
model KnowledgeDoc {
id String @id @default(uuid())
agentId String? @map("agent_id")
docType String @map("doc_type")
title String
description String? @db.Text
content String @db.Text
source String?
author String?
publishDate DateTime? @map("publish_date")
tags String[]
status String @default("active")
isPublic Boolean @default(true) @map("is_public")
createdAt DateTime @default(now()) @map("created_at")
updatedAt DateTime @updatedAt @map("updated_at")
chunks KnowledgeChunk[] @relation("DocChunks")
@@index([agentId, docType])
@@index([status, isPublic])
@@map("knowledge_docs")
@@schema("knowledge_schema")
}
```
### 4.2 knowledge_chunks (知识块表)
```prisma
/// 知识块表用于RAG检索
model KnowledgeChunk {
id String @id @default(uuid())
docId String @map("doc_id")
chunkIndex Int @map("chunk_index")
content String @db.Text
contentHash String @map("content_hash")
metadata Json? @db.JsonB
createdAt DateTime @default(now()) @map("created_at")
doc KnowledgeDoc @relation("DocChunks", fields: [docId], references: [id], onDelete: Cascade)
embedding KnowledgeEmbedding? @relation("ChunkEmbedding")
@@unique([docId, chunkIndex])
@@index([contentHash])
@@map("knowledge_chunks")
@@schema("knowledge_schema")
}
```
### 4.3 knowledge_embeddings (向量嵌入表)
```prisma
/// 向量嵌入表pgvector
model KnowledgeEmbedding {
id String @id @default(uuid())
chunkId String @unique @map("chunk_id")
embedding Unsupported("vector(1536)")
embeddingModel String @map("embedding_model")
createdAt DateTime @default(now()) @map("created_at")
chunk KnowledgeChunk @relation("ChunkEmbedding", fields: [chunkId], references: [id], onDelete: Cascade)
@@map("knowledge_embeddings")
@@schema("knowledge_schema")
}
```
---
## 五、数据库迁移计划
### 5.1 迁移步骤
```bash
# 1. 创建新Schema
CREATE SCHEMA IF NOT EXISTS agent_schema;
CREATE SCHEMA IF NOT EXISTS protocol_schema;
CREATE SCHEMA IF NOT EXISTS knowledge_schema;
# 2. 更新Prisma schema.prisma中的schemas配置
schemas = ["...", "agent_schema", "protocol_schema", "knowledge_schema"]
# 3. 生成迁移
npx prisma migrate dev --name add_agent_framework
# 4. 应用迁移
npx prisma migrate deploy
```
### 5.2 初始数据
```sql
-- 插入Protocol Agent配置
INSERT INTO agent_schema.agent_configs (
id, agent_id, agent_name, base_system_prompt,
memory_strategy, max_history_turns, default_model, is_active
) VALUES (
gen_random_uuid(),
'protocol_agent',
'研究方案制定助手',
'你是一位经验丰富的临床研究方法学专家,正在帮助研究者制定研究方案...',
'full',
20,
'deepseek-v3',
true
);
-- 插入阶段配置(示例:科学问题阶段)
INSERT INTO agent_schema.agent_stages (
id, agent_config_id, stage_id, stage_name, stage_order,
instruction, extraction_schema, next_stage_id, transition_mode
) VALUES (
gen_random_uuid(),
(SELECT id FROM agent_schema.agent_configs WHERE agent_id = 'protocol_agent'),
'scientific_question',
'科学问题澄清',
1,
'引导用户明确研究的核心科学问题...',
'{"type": "object", "properties": {...}}',
'pico',
'user_confirm'
);
```
---
## 六、ER关系图
```
agent_schema
┌───────────────────┐
│ AgentConfig │
│ (agent_configs) │
└────────┬──────────┘
┌────┴────┬─────────────┐
│ │ │
▼ ▼ ▼
┌─────────┐ ┌─────────┐ ┌─────────────┐
│AgentStage│ │AgentTool│ │ReflexionRule│
└────┬────┘ └─────────┘ └─────────────┘
┌─────────────┐
│ ActionCard │
└─────────────┘
┌─────────────┐ ┌─────────────┐
│AgentSession │ ───────→│ AgentTrace │
└─────────────┘ └─────────────┘
│ conversationId
aia_schema
┌─────────────┐ ┌─────────────┐
│Conversation │────────<│ Message │
└─────────────┘ └─────────────┘
protocol_schema
┌─────────────────┐ ┌─────────────────┐
│ProtocolContext │────<│ProtocolVersion │
└─────────────────┘ └─────────────────┘
```

View File

@@ -0,0 +1,632 @@
# Protocol Agent 分阶段实施计划
> 版本v1.0
> 创建日期2026-01-24
---
## 一、总体规划
### 1.1 阶段划分
```
┌─────────────────────────────────────────────────────────────────────────────┐
│ Protocol Agent 开发路线图 │
├─────────────────────────────────────────────────────────────────────────────┤
│ │
│ Phase 1: MVP完整功能 (4周) │
│ ┌─────────────────────────────────────────────────────────────────────┐ │
│ │ │ │
│ │ Sprint 1 (W1) Sprint 2 (W2) Sprint 3 (W3) Sprint 4 (W4) │
│ │ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ │ │
│ │ │ 框架搭建 │ → │ 核心对话 │ → │ 前端UI │ → │ 一键生成 │ │ │
│ │ │ 数据库 │ │ 5阶段流程│ │ State │ │ Word导出 │ │ │
│ │ │ 类型定义 │ │ Prompt │ │ Panel │ │ Prompt │ │ │
│ │ │ │ │ Context │ │ 同步按钮│ │ 调优测试 │ │ │
│ │ └──────────┘ └──────────┘ └──────────┘ └──────────┘ │ │
│ │ │ │
│ │ 交付物完整MVP用户可通过对话完成5阶段一键生成研究方案并下载Word │ │
│ └─────────────────────────────────────────────────────────────────────┘ │
│ │ │
│ ▼ │
│ ───────────────────────────────────────────────────────────────────────── │
│ │
│ Phase 2: 知识增强 (3周) Phase 3: 平台化 (2周) │
│ ┌─────────────────────────┐ ┌─────────────────────────┐ │
│ │ □ EKB知识库建设 │ │ □ 后台配置管理 │ │
│ │ □ RAG检索集成 │ → │ □ Prompt在线调试 │ │
│ │ □ Function Calling │ │ □ 完整Trace分析 │ │
│ │ □ 高级Reflexion │ │ □ 多Agent支持 │ │
│ └─────────────────────────┘ └─────────────────────────┘ │
│ │
└─────────────────────────────────────────────────────────────────────────────┘
```
### 1.2 里程碑定义
| 里程碑 | 时间 | 交付物 | 验收标准 |
|--------|------|--------|----------|
| M1 | Week 2 | Agent框架 + 基础对话 | 能完成单阶段对话Context正确存储 |
| **M2** | **Week 4** | **MVP完整功能** | **5阶段对话 + 一键生成 + Word下载** |
| M3 | Week 7 | 知识增强版本 | RAG检索集成可用 |
| M4 | Week 9 | 平台化版本 | 后台配置管理可用 |
---
## 二、Phase 1 详细计划4周
### Sprint 1: 基础框架搭建Week 1
**目标**建立可复用的Agent框架骨架
#### 任务列表
| ID | 任务 | 优先级 | 预估 | 负责人 | 状态 |
|----|------|--------|------|--------|------|
| 1.1 | 创建agent_schema数据库迁移 | P0 | 4h | - | ⬜ |
| 1.2 | 创建protocol_schema数据库迁移 | P0 | 2h | - | ⬜ |
| 1.3 | 定义核心类型types/*.ts | P0 | 3h | - | ⬜ |
| 1.4 | 实现ConfigLoader | P0 | 2h | - | ⬜ |
| 1.5 | 实现BaseAgentOrchestrator抽象类 | P0 | 4h | - | ⬜ |
| 1.6 | 实现QueryAnalyzer | P0 | 3h | - | ⬜ |
| 1.7 | 实现Planner + StageManager | P0 | 3h | - | ⬜ |
| 1.8 | 实现TraceLogger | P1 | 2h | - | ⬜ |
| 1.9 | 创建Protocol Agent初始配置数据 | P0 | 2h | - | ⬜ |
**Sprint 1 产出**
- [ ] 数据库Schema创建完成
- [ ] 核心框架代码结构建立
- [ ] Agent配置可从数据库加载
#### 详细任务说明
**1.1 创建agent_schema数据库迁移**
```bash
# 执行步骤
1. 更新 schema.prisma添加 agent_schema 到 schemas 列表
2. 添加所有 agent_schema 表定义
3. 运行 npx prisma migrate dev --name add_agent_framework
4. 验证表创建成功
```
**1.5 实现BaseAgentOrchestrator抽象类**
```typescript
// 核心方法清单
- constructor(dependencies)
- abstract getAgentId(): string
- abstract getContextSchema(): TContext
- async handleMessage(conversationId, userMessage, messageId): Promise<AgentResponse>
- async handleStageComplete(conversationId): Promise<StageTransitionResult>
- protected getSession(conversationId): Promise<AgentSessionState>
- protected buildResponse(...): AgentResponse
```
---
### Sprint 2: Protocol Agent核心实现Week 2
**目标**实现Protocol Agent的完整对话流程
#### 任务列表
| ID | 任务 | 优先级 | 预估 | 负责人 | 状态 |
|----|------|--------|------|--------|------|
| 2.1 | 实现ProtocolOrchestrator | P0 | 4h | - | ⬜ |
| 2.2 | 实现ProtocolContextService | P0 | 3h | - | ⬜ |
| 2.3 | 实现PromptBuilder | P0 | 3h | - | ⬜ |
| 2.4 | 实现ExecutorLLM调用 | P0 | 4h | - | ⬜ |
| 2.5 | 实现ProtocolExtractor数据提取 | P0 | 4h | - | ⬜ |
| 2.6 | 实现MemoryManager | P1 | 2h | - | ⬜ |
| 2.7 | 编写5个阶段的Prompt配置 | P0 | 4h | - | ⬜ |
| 2.8 | 实现API路由 | P0 | 2h | - | ⬜ |
| 2.9 | 单元测试 | P1 | 3h | - | ⬜ |
**Sprint 2 产出**
- [ ] Protocol Agent后端完整实现
- [ ] 能通过API完成对话
- [ ] Context正确保存和更新
#### 核心交互模式:对话驱动 + 同步确认
```
【不需要显式的"确认完成"按钮】
用户通过两种方式推进阶段:
1. 同步按钮AI在对话中显示"同步到方案"按钮,用户点击后数据同步
2. 口头确认:用户说"继续"/"下一步"AI识别意图后自动进入下一阶段
示例流程:
┌─────────────────────────────────────────────────────┐
│ AI: 我已整理出您的科学问题: │
│ "阿司匹林预防老年高血压患者中风的疗效研究" │
│ │
│ ┌──────────────────┐ │
│ │ ✅ 同步到方案 │ ← 内嵌在AI回复中 │
│ └──────────────────┘ │
│ │
│ 确认后我们可以继续进行PICO梳理。 │
├─────────────────────────────────────────────────────┤
│ User: 好的,继续吧 │
├─────────────────────────────────────────────────────┤
│ AI: 好的让我们进入PICO梳理阶段... │
└─────────────────────────────────────────────────────┘
```
#### 详细Prompt配置
**科学问题阶段 Prompt**
```
你正在帮助研究者明确研究的核心科学问题。
引导要点:
1. 询问想解决什么临床问题
2. 了解目标人群是谁
3. 明确期望达成的目标
4. 探讨研究的临床意义
当前已知信息:
{{contextSummary}}
对话策略:
- 用温和专业的语气引导用户
- 当收集到足够信息后,整理出科学问题,并提供"同步到方案"选项
- 同步后询问用户是否继续进行PICO梳理
如果用户提供了信息,在回复末尾提取:
<extracted_data>
{
"content": "科学问题表述",
"clinicalBackground": "临床背景",
"researchGap": "研究空白",
"readyToSync": true // 是否可以同步
}
</extracted_data>
```
**PICO阶段 Prompt**
```
基于已确定的科学问题现在需要明确PICO四要素。
科学问题:{{scientificQuestion.content}}
请引导用户确定:
- P (Population): 研究人群的特征和入选标准
- I (Intervention): 干预措施的具体内容
- C (Comparison): 对照组的设置
- O (Outcome): 主要和次要结局指标
对话策略:
- 可以分多轮逐步收集各要素
- 当四要素都明确后,提供"同步到方案"选项
- 同步后,询问用户是否继续进行研究设计
提取格式:
<extracted_data>
{
"P": {"value": "", "details": ""},
"I": {"value": "", "details": ""},
"C": {"value": "", "details": ""},
"O": {"value": "", "details": ""},
"readyToSync": true
}
</extracted_data>
```
**观察指标阶段 Prompt**(新增):
```
基于PICO中的结局指标(O),现在需要详细设计观察指标。
已确定的PICO{{pico}}
研究设计:{{studyDesign}}
请引导用户明确:
1. 主要结局指标Primary Endpoint
- 指标名称、定义、测量方法、评价时点
2. 次要结局指标Secondary Endpoints
3. 安全性指标Safety Endpoints
4. 探索性指标Exploratory Endpoints可选
对话策略:
- 首先确认主要结局指标,这是最重要的
- 然后引导设置次要和安全性指标
- 当指标体系完整后,提供"同步到方案"选项
提取格式:
<extracted_data>
{
"primary": [{"name": "", "definition": "", "method": "", "timePoint": ""}],
"secondary": [...],
"safety": [...],
"readyToSync": true
}
</extracted_data>
```
---
### Sprint 3: 前端实现Week 3
**目标**完成State Panel、同步按钮和Action Card UI
#### 任务列表
| ID | 任务 | 优先级 | 预估 | 负责人 | 状态 |
|----|------|--------|------|--------|------|
| 3.1 | Protocol Agent入口页面 | P0 | 2h | - | ⬜ |
| 3.2 | 实现useProtocolAgent Hook | P0 | 3h | - | ⬜ |
| 3.3 | 实现protocolAgentStore | P1 | 2h | - | ⬜ |
| 3.4 | 实现StatePanel组件 | P0 | 4h | - | ⬜ |
| 3.5 | 实现StageProgress组件5阶段 | P0 | 2h | - | ⬜ |
| 3.6 | 实现ContextDisplay组件 | P0 | 3h | - | ⬜ |
| 3.7 | **实现SyncButton组件内嵌AI回复** | P0 | 3h | - | ⬜ |
| 3.8 | 实现ActionCard组件 | P0 | 2h | - | ⬜ |
| 3.9 | 与现有AIStreamChat集成 | P0 | 3h | - | ⬜ |
| 3.10 | 样式调整和响应式 | P1 | 2h | - | ⬜ |
**Sprint 3 产出**
- [ ] 完整的Protocol Agent界面
- [ ] State Panel实时显示5阶段Context
- [ ] **"同步到方案"按钮内嵌在AI回复中**
- [ ] Action Card交互
#### 核心组件SyncButton同步按钮
```typescript
// SyncButton - 内嵌在AI回复中的同步按钮
interface SyncButtonProps {
stageId: string; // 当前阶段
extractedData: any; // 要同步的数据
onSync: () => void; // 同步回调
synced: boolean; // 是否已同步
}
// 在AI回复中的展示效果
// ┌─────────────────────────────────────────────┐
// │ AI: 我已整理出您的科学问题: │
// │ "阿司匹林预防老年高血压患者中风研究" │
// │ │
// │ ┌──────────────────┐ │
// │ │ ✅ 同步到方案 │ ← SyncButton │
// │ └──────────────────┘ │
// │ │
// │ 同步后我们可以继续下一阶段。 │
// └─────────────────────────────────────────────┘
```
#### 页面布局设计
```
┌─────────────────────────────────────────────────────────────────┐
│ Header: 研究方案制定 Agent 当前阶段: Step 3: 研究设计 │
├───────────────────────────────────┬─────────────────────────────┤
│ │ │
│ Chat Area │ State Panel │
│ ┌─────────────────────────────┐ │ ┌───────────────────────┐│
│ │ │ │ │ 📋 方案状态 (Context) ││
│ │ AI: 您好!我是研究方案... │ │ │ ││
│ │ │ │ │ 01 科学问题 ✓ ││
│ │ User: 我想做一个糖尿病... │ │ │ 阿司匹林预防老年... ││
│ │ │ │ │ ││
│ │ AI: 好的,我已整理出... │ │ │ 02 PICO ✓ ││
│ │ ┌────────────────┐ │ │ │ P: ≥65岁高血压患者 ││
│ │ │ ✅ 同步到方案 │ │ │ │ I: 阿司匹林100mg/d ││
│ │ └────────────────┘ │ │ │ C: 安慰剂 ││
│ │ │ │ │ O: 脑卒中发生率 ││
│ │ User: 继续吧 │ │ │ ││
│ │ │ │ │ 03 研究设计 (当前) ││
│ │ AI: 好的,进入研究设计... │ │ │ RCT | 双盲 | 多中心 ││
│ │ │ │ │ ││
│ │ │ │ │ 04 样本量 ○ ││
│ │ │ │ │ 待计算... ││
│ │ │ │ │ ││
│ │ │ │ │ 05 观察指标 ○ ││
│ │ │ │ │ 待定义... ││
│ └─────────────────────────────┘ │ ├───────────────────────┤│
│ ┌─────────────────────────────┐ │ │ 进度: ████░░░░ 40% ││
│ │ [输入您的指令...] [发送]│ │ │ ││
│ └─────────────────────────────┘ │ │ [🚀 一键生成研究方案] ││
│ │ │ (5阶段完成后可用) ││
│ │ └───────────────────────┘│
│ │ │
└───────────────────────────────────┴─────────────────────────────┘
```
---
### Sprint 4: 一键生成 + 集成测试Week 4
**目标**实现一键生成研究方案、Prompt调优、端到端测试
#### 任务列表
| ID | 任务 | 优先级 | 预估 | 负责人 | 状态 |
|----|------|--------|------|--------|------|
| 4.1 | **设计研究方案生成Prompt** | P0 | 4h | - | ⬜ |
| 4.2 | **实现ProtocolGenerationService** | P0 | 3h | - | ⬜ |
| 4.3 | **实现生成API端点** | P0 | 2h | - | ⬜ |
| 4.4 | **实现Word文档导出docx库** | P0 | 4h | - | ⬜ |
| 4.5 | **前端:一键生成按钮与预览页** | P0 | 4h | - | ⬜ |
| 4.6 | 实现样本量计算器Action Card | P1 | 2h | - | ⬜ |
| 4.7 | Prompt调优5个阶段 | P0 | 6h | - | ⬜ |
| 4.8 | 端到端测试 | P0 | 4h | - | ⬜ |
| 4.9 | Bug修复和优化 | P0 | 4h | - | ⬜ |
| 4.10 | 文档更新 | P1 | 2h | - | ⬜ |
**Sprint 4 产出**
- [ ] **一键生成研究方案功能**
- [ ] **Word文档下载**
- [ ] 所有Prompt调优完成
- [ ] 端到端测试通过
- [ ] **MVP可交付**
#### 一键生成研究方案
**触发条件**5个阶段科学问题、PICO、研究设计、样本量、观察指标全部完成
**生成Prompt**
```markdown
你是一位资深的临床研究方法学专家,请基于以下核心要素生成一份完整、规范的临床研究方案。
## 核心要素
### 科学问题
{{scientificQuestion.content}}
### PICO要素
- **研究人群(P)**: {{pico.P.value}} - {{pico.P.details}}
- **干预措施(I)**: {{pico.I.value}} - {{pico.I.details}}
- **对照措施(C)**: {{pico.C.value}} - {{pico.C.details}}
- **结局指标(O)**: {{pico.O.value}} - {{pico.O.details}}
### 研究设计
- 研究类型: {{studyDesign.type}}
- 盲法: {{studyDesign.blinding}}
- 随机化: {{studyDesign.randomization}}
- 研究周期: {{studyDesign.duration}}
### 样本量
- 总样本量: {{sampleSize.total}}
- 每组: {{sampleSize.perGroup}}
- 计算依据: {{sampleSize.justification}}
### 观察指标
**主要结局指标**: {{endpoints.primary}}
**次要结局指标**: {{endpoints.secondary}}
**安全性指标**: {{endpoints.safety}}
---
请生成包含以下章节的完整研究方案:
1. 研究背景与立题依据
2. 研究目的
3. 研究方法(研究类型、设计、干预、对照)
4. 受试者选择(入选标准、排除标准)
5. 观察指标与评价标准
6. 统计分析计划
7. 质量控制
8. 伦理考虑
9. 研究进度安排
请使用专业规范的学术语言,确保内容完整、逻辑清晰。
```
**Word导出**
```typescript
// 使用 docx 库生成Word文档
import { Document, Paragraph, TextRun, HeadingLevel, Packer } from 'docx';
async function generateProtocolWord(content: string, metadata: any): Promise<Buffer> {
const doc = new Document({
sections: [{
children: [
// 封面
new Paragraph({
children: [new TextRun({ text: '临床研究方案', bold: true, size: 48 })],
heading: HeadingLevel.TITLE,
}),
// ... 正文Markdown转docx
]
}]
});
return await Packer.toBuffer(doc);
}
```
#### ReflexionP2优先级可延后
MVP阶段简化处理
- 在同步前由AI在对话中进行基础检查
- 完整的ReflexionEngine放到Phase 2实现
```
AI回复示例
"我已整理出您的PICO要素。在同步前让我确认一下
✓ P: 研究人群已明确
✓ I: 干预措施已定义
✓ C: 对照组已设置
✓ O: 结局指标已确定
[✅ 同步到方案]"
```
---
## 三、Phase 2 计划概要3周
### Sprint 5-6: 知识库建设Week 5-6
| ID | 任务 | 优先级 | 预估 |
|----|------|--------|------|
| 6.1 | 创建knowledge_schema数据库迁移 | P0 | 2h |
| 6.2 | 实现KnowledgeDocService | P0 | 4h |
| 6.3 | 实现KnowledgeChunkService | P0 | 3h |
| 6.4 | 集成现有RAG引擎 | P0 | 4h |
| 6.5 | 实现RAGTool | P0 | 3h |
| 6.6 | 准备临床研究方法学知识文档 | P0 | 8h |
| 6.7 | 知识文档分块和向量化 | P0 | 4h |
| 6.8 | RAG检索测试和调优 | P0 | 4h |
### Sprint 7: 高级功能Week 7
| ID | 任务 | 优先级 | 预估 |
|----|------|--------|------|
| 7.1 | 实现Function Calling支持 | P1 | 4h |
| 7.2 | 实现ToolRegistry完整功能 | P1 | 3h |
| 7.3 | 添加文献检索工具 | P2 | 4h |
| 7.4 | 实现高级Reflexion一致性校验 | P1 | 4h |
| 7.5 | 更多Action Card场景 | P1 | 4h |
| 7.6 | Phase 2集成测试 | P0 | 4h |
---
## 四、Phase 3 计划概要2周
### Sprint 8-9: 平台化Week 8-9
| ID | 任务 | 优先级 | 预估 |
|----|------|--------|------|
| 8.1 | Agent配置管理后台 | P1 | 8h |
| 8.2 | Prompt在线编辑和调试 | P1 | 6h |
| 8.3 | Trace分析可视化 | P2 | 6h |
| 8.4 | 配置热更新支持 | P2 | 4h |
| 8.5 | 多Agent路由支持 | P1 | 4h |
| 8.6 | 统计分析Agent接入准备 | P1 | 4h |
| 8.7 | 最终测试和文档 | P0 | 4h |
---
## 五、风险管理
### 5.1 已识别风险
| 风险 | 可能性 | 影响 | 缓解措施 | 负责人 |
|------|--------|------|----------|--------|
| LLM输出不稳定 | 高 | 中 | 多次测试调优Prompt | - |
| 数据提取准确率低 | 中 | 高 | 增加验证逻辑,用户确认 | - |
| 前端集成复杂度 | 中 | 中 | 复用现有组件 | - |
| Prompt调优耗时 | 高 | 中 | 预留充足时间 | - |
| 知识库内容准备 | 中 | 高 | 提前准备,分批导入 | - |
### 5.2 应急预案
**如果Phase 1延期**
1. 优先保证核心流程(对话+提取)
2. Reflexion可简化为基础规则检查
3. Action Card可延后到Phase 2
**如果数据提取准确率不达标**
1. 增加用户确认环节
2. 使用更强的模型GPT-4
3. 简化提取Schema
---
## 六、质量保证
### 6.1 测试策略
| 测试类型 | 覆盖范围 | 执行时机 |
|----------|----------|----------|
| 单元测试 | 核心Service、工具函数 | 每次提交 |
| 集成测试 | API端点、数据库操作 | 每个Sprint |
| E2E测试 | 完整用户流程 | 里程碑交付 |
| Prompt测试 | 各阶段Prompt效果 | 持续调优 |
### 6.2 验收标准
**Phase 1 验收标准**
- [ ] 用户可完成5阶段研究方案要素制定
- [ ] Context数据正确保存和展示
- [ ] 阶段流转逻辑正确
- [ ] Reflexion能阻止不完整的阶段提交
- [ ] Action Card正确触发和展示
- [ ] API响应时间 < 3s不含LLM
- [ ] 无P0级Bug
### 6.3 Code Review检查点
- [ ] 类型定义完整
- [ ] 错误处理完善
- [ ] 日志记录规范
- [ ] 代码风格一致
- [ ] 无硬编码配置
- [ ] 有必要的注释
---
## 七、资源需求
### 7.1 人力资源
| 角色 | 人数 | Phase 1 | Phase 2 | Phase 3 |
|------|------|---------|---------|---------|
| 后端开发 | 1 | 100% | 80% | 60% |
| 前端开发 | 1 | 60% | 40% | 40% |
| 产品/测试 | 1 | 30% | 30% | 40% |
### 7.2 技术资源
| 资源 | 用途 | 预估费用 |
|------|------|----------|
| DeepSeek API | LLM调用 | ¥500/月 |
| 开发服务器 | 测试环境 | 现有 |
| 数据库 | PostgreSQL | 现有 |
---
## 八、沟通计划
### 8.1 会议安排
| 会议 | 频率 | 参与者 | 目的 |
|------|------|--------|------|
| 每日站会 | 每日 | 开发团队 | 同步进度,解决阻塞 |
| Sprint评审 | 每周 | 全员 | 演示成果,收集反馈 |
| 技术讨论 | 按需 | 相关开发 | 解决技术难题 |
### 8.2 文档更新
| 文档 | 更新频率 | 负责人 |
|------|----------|--------|
| 开发计划 | 每Sprint | PM |
| 技术文档 | 实时 | 开发者 |
| API文档 | 代码变更时 | 后端 |
| 用户手册 | Phase完成时 | 产品 |
---
## 九、检查清单
### Phase 1 启动前检查
- [ ] 需求文档已确认
- [ ] 技术方案已评审
- [ ] 数据库设计已确认
- [ ] 开发环境已就绪
- [ ] 相关人员已到位
### 每Sprint完成检查
- [ ] 所有任务已完成或明确延期原因
- [ ] 代码已Code Review
- [ ] 测试已通过
- [ ] 文档已更新
- [ ] 下Sprint计划已明确
### Phase 1 交付检查
- [ ] 所有功能已实现
- [ ] 验收标准全部达成
- [ ] 无遗留P0/P1 Bug
- [ ] 文档完整
- [ ] 演示准备就绪

View File

@@ -0,0 +1,79 @@
# Protocol Agent 开发计划文档
> 创建日期2026-01-24
> 状态:待开发
---
## 📚 文档目录
| 序号 | 文档 | 说明 |
|:----:|------|------|
| 00 | [开发计划总览](./00-开发计划总览.md) | 项目背景、决策记录、核心架构概览 |
| 01 | [架构设计](./01-架构设计.md) | 五层Agent架构、各层详细设计、执行流程 |
| 02 | [数据库设计](./02-数据库设计.md) | 完整Prisma Schema、ER图、迁移计划 |
| 03 | [代码结构设计](./03-代码结构设计.md) | 目录结构、核心类型、API设计、前端组件 |
| 04 | [分阶段实施计划](./04-分阶段实施计划.md) | Sprint划分、任务列表、风险管理、验收标准 |
---
## 🎯 项目概述
Protocol Agent研究方案制定助手是AIA模块的第13个智能体入口通过多轮对话引导用户完成临床研究方案的核心要素制定。
### 核心架构
```
Query → Planner → Executor → Tools → Reflection
(意图识别) → (规划) → (执行) → (工具) → (反思)
```
### 开发周期
- **Phase 1**: MVP完整功能 (4周) - 包含一键生成研究方案
- **Phase 2**: 知识增强 (3周)
- **Phase 3**: 平台化 (2周)
**总周期9周**
---
## ✅ 已确认决策
| 决策项 | 选择 |
|--------|------|
| 入口方式 | B - Protocol Agent作为第13个入口 |
| 状态流转 | B - 用户按钮确认触发 |
| 数据提取 | C - 异步提取+LLM结构化 |
| Action Card | B - 规则触发 |
| Reflexion | B - Prompt-based |
---
## 📋 快速导航
### 需要了解业务需求?
→ 查看 [Protocol Agent PRD](../00-系统设计/Protocol_Agent_PRD_v1.0.md)
### 需要了解技术架构?
→ 查看 [01-架构设计](./01-架构设计.md)
### 需要了解数据库表结构?
→ 查看 [02-数据库设计](./02-数据库设计.md)
### 需要开始编码?
→ 查看 [03-代码结构设计](./03-代码结构设计.md)
### 需要了解任务安排?
→ 查看 [04-分阶段实施计划](./04-分阶段实施计划.md)
---
## 📎 相关文档
- [AIA模块当前状态](../00-模块当前状态与开发指南.md)
- [Protocol Agent PRD v1.0](../00-系统设计/Protocol_Agent_PRD_v1.0.md)
- [MVP简化指南](../00-系统设计/Protocol_Agent_Development_Simplification_Guide.md)
- [架构设计V3](../02-技术设计/Protocol_Agent_Architecture_Design_V3.md)
- [技术实现V3](../02-技术设计/Protocol_Agent_Technical_Implementation_V3.md)