Files
HaHafeng 2481b786d8 deploy: Complete 0126-27 deployment - database upgrade, services update, code recovery
Major Changes:
- Database: Install pg_bigm/pgvector plugins, create test database
- Python service: v1.0 -> v1.1, add pymupdf4llm/openpyxl/pypandoc
- Node.js backend: v1.3 -> v1.7, fix pino-pretty and ES Module imports
- Frontend: v1.2 -> v1.3, skip TypeScript check for deployment
- Code recovery: Restore empty files from local backup

Technical Fixes:
- Fix pino-pretty error in production (conditional loading)
- Fix ES Module import paths (add .js extensions)
- Fix OSSAdapter TypeScript errors
- Update Prisma Schema (63 models, 16 schemas)
- Update environment variables (DATABASE_URL, EXTRACTION_SERVICE_URL, OSS)
- Remove deprecated variables (REDIS_URL, DIFY_API_URL, DIFY_API_KEY)

Documentation:
- Create 0126 deployment folder with 8 documents
- Update database development standards v2.0
- Update SAE deployment status records

Deployment Status:
- PostgreSQL: ai_clinical_research_test with plugins
- Python: v1.1 @ 172.17.173.84:8000
- Backend: v1.7 @ 172.17.173.89:3001
- Frontend: v1.3 @ 172.17.173.90:80

Tested: All services running successfully on SAE
2026-01-27 08:13:27 +08:00

25 KiB
Raw Permalink Blame History

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

意图类型定义

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 │
  └──────────┘

执行策略

type ExecutionStrategy = 
  | 'guide_and_extract'        // 引导对话并提取数据
  | 'answer_question'          // 回答用户问题
  | 'update_context'           // 更新已有数据
  | 'trigger_tool'             // 触发工具调用
  | 'transition_stage'         // 执行阶段流转
  | 'request_clarification'    // 请求澄清
  | 'handle_chitchat';         // 处理闲聊

策略选择规则

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

工具注册格式

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

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规则类型

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记忆管理

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配置管理

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追踪日志

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可直接继承

// 基类
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; }
}