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
499 lines
25 KiB
Markdown
499 lines
25 KiB
Markdown
# 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; }
|
||
}
|
||
```
|
||
|
||
|