深度剖析构建可靠医疗分析 Agent 的实战经验,揭示 AI 系统追求可预测性而非真理的本质限制。
AI不追求真实,而是追求可预测性和取悦,这就是为什么它听起来像一面被编程为返回微笑的情感镜像 😀
消解我们的认知失调 🫠
强化信息泡泡,抑制我们的批判性思维 😳
因此,我敦促你:在AI掌控你之前先掌控它。
过去几个月我一直在探索AI对人类影响的色彩深渊,所以我想强调上面的这句话👆,这是我在AWS峰会和开发者大会上最近的演讲中一直倡导的观点,关于我对如何实现Agent事件驱动架构的看法。
AI智能体 + 微服务 = 💜
这会让你大吃一惊:如果你的医疗系统不仅仅处理数据,而是真正地对其进行推理,看起来像豪斯医生但没有所有那些💊😅,并且可以同时处理数千名患者,充分发挥其潜力,会怎样?
欢迎来到AI智能体事件驱动架构,我采纳了Sean Falconer的概念"AI智能体是有大脑的微服务",并将其应用于生死攸关的医疗分析,但我们需要退一步,作为产品工程师,我们需要以更加渐进式而非革命性的方式来实施我们的工作。在这一转变中,我们期望磨练新的技能,从日常跟踪到多个智能体之间决策模式的分析。我们不应仅关注可用性,而应通过探索意外操作的模拟以及我们的智能体如何对其做出反应来衡量目标的成功。最明显的思维转变是拥抱可控的不可预测性,也就是说,与确定性的服务调用不同,智能体在运行时做出决策,可以生成到达同一目标的不同路径。
服务发现变成智能体发现。
路由变成编排。
速率限制变成资源治理。
最终,这意味着什么?我们必须批判性地理解和指定成功是什么、看起来是什么样的,而不是分步描述如何实现它。
在传统模型中,路径是固定的:一个服务以预定的顺序调用另一个,就像脚本一样。在AI智能体方法中,AI模型根据上下文动态选择要使用的服务。微服务变成AI根据需要触发的工具。
在这里,MCP通过标准化AI智能体如何接收上下文信息、访问工具和处理事件而大放异彩。MCP在智能体与它们编排的微服务之间建立了一致的接口层。
传统医疗系统就像那种需要所有内容都写成三份的医生:
"处理这个实验室结果"
"保存那个患者记录"
"发送这个通知"
但是,如果你的系统能像一个医学住院医生一样思考,看到350mg/dL的葡萄糖读数并立即开始级联智能推理,会怎样:
"严重高血糖...让我检查一下这个患者的历史...啊,控制不力的糖尿病...这需要在24小时内进行紧急内分泌学干预。"
这正是当你将自主AI智能体与事件驱动微服务架构结合时发生的事情。
在我们的智能体-微服务系统的核心位置,坐着我们所谓的AI智能体协调器——用VoltAgent构建以获得最大灵活性,由Amazon Nova Micro驱动以进行医疗推理。
这是我们系统中的真实代码:
// 来自我们实际的智能体协调器实现
import { VoltAgent, Agent } from "@voltagent/core";
import { VercelAIProvider } from "@voltagent/vercel-ai";
import { BedrockRuntime } from "@aws-sdk/client-bedrock-runtime";
export class MedicalAgentCoordinator {
private agent: Agent;
private memory: DynamoDBMemoryStore;
private eventBridge: EventBridgeClient;
constructor() {
this.agent = new Agent({
name: "medical-analysis-coordinator",
instructions: `You are a medical analysis coordinator.
Analyze laboratory results and patient history to determine:
- Clinical urgency (0-24h, 1-7d, 30-90d)
- Required specialists (endocrinology, cardiology, nephrology)
- Risk factors and follow-up needs`,
llm: new VercelAIProvider(),
model: novaMicro("nova-micro-v1"),
});
}
}
当实验室结果被上传到我们的S3桶时,以下是发生的事情:
// S3触发事件级联
export const s3TriggerHandler = async (event: S3Event) => {
for (const record of event.Records) {
const { bucket, object } = record.s3;
// 提取实验室数据
const labData = await extractLabResults(bucket.name, object.key);
// 智能体使用完整上下文进行分析
const analysis = await this.agent.analyze({
labResults: labData,
patientHistory: await this.memory.getPatientContext(patientId),
clinicalProtocols: MEDICAL_GUIDELINES
});
// 根据分析发布智能事件
await this.publishMedicalEvents(analysis);
}
};
这里变得性感(以极客的方式)。每个智能体决策都会创建类型化事件,触发专门的响应:
interface MedicalAnalysisEvent {
eventType: 'medical.analysis.complete';
patientId: string;
findings: {
glucose: number;
priority: 'URGENT' | 'PRIORITY' | 'ROUTINE';
riskFactors: string[];
};
recommendations: {
specialty: 'endocrinology' | 'cardiology' | 'nephrology' | 'generalist';
timeframe: '0-24h' | '1-7d' | '30-90d';
};
}
// 智能体的持久内存系统
export class DynamoDBMemoryStore {
async updatePatientMemory(event: MedicalAnalysisEvent) {
const memoryUpdate = {
patientId: event.patientId,
lastAnalysis: event.findings,
riskTrend: this.calculateRiskTrend(event.findings),
urgentFlags: event.findings.priority === 'URGENT' ?
[...existing.urgentFlags, event.findings] : existing.urgentFlags
};
await this.dynamodb.putItem({
TableName: 'PatientMemory',
Item: memoryUpdate
});
// 为其他智能体发布内存更新事件
await this.eventBridge.publish('patient.memory.updated', memoryUpdate);
}
}
// 基于医疗紧迫性的自主预约调度
export const appointmentHandler = async (event: MedicalAnalysisEvent) => {
const appointmentData = {
patientId: event.patientId,
specialty: event.recommendations.specialty,
urgency: event.recommendations.timeframe,
reason: `${event.findings.riskFactors.join(', ')} - Priority: ${event.findings.priority}`,
medicalContext: event.findings
};
await this.eventBridge.publish('appointment.create.request', appointmentData);
};
精妙之处在哪里?每个微服务都是自主的。预约服务不需要理解医疗分析——它只是响应预约事件。内存系统不关心调度——它维护患者上下文并发布内存更新。
这是我们方法创新的地方。与其使用传统向量数据库来存储内存,我们构建了一个灵活的基于DynamoDB的内存系统,为我们的智能体提供真正的持久性:
// 我们的自定义内存实现
interface PatientMemoryContext {
patientId: string;
clinicalHistory: MedicalEvent[];
glucosePattern: {
trend: 'improving' | 'stable' | 'declining';
criticalEpisodes: number;
lastCritical: Date;
};
medications: CurrentMedication[];
riskFactors: ClinicalRiskFactor[];
preferences: PatientPreferences;
}
// 智能体使用完整上下文进行推理
const decision = await this.agent.analyze({
currentLab: newResults,
context: await this.memory.getFullContext(patientId),
protocols: CLINICAL_GUIDELINES
});
向量数据库非常适合相似性搜索,但医疗推理需要结构化的、关系型的上下文:
时间关系:"患者的葡萄糖在6个月内一直呈上升趋势"
临床协议:"鉴于糖尿病+高肌酐,需要肾脏病学咨询"
患者特定模式:"该患者的葡萄糖激增与药物依从性差相关"
我们的DynamoDB方法给我们提供:
结构化的医疗关系
用于关键医疗数据的ACID事务
用于复杂医疗推理的查询灵活性
大规模的成本效率
我们的智能体不会凭感觉做事——它们遵循基于证据的医疗协议:
const CLINICAL_PROTOCOLS = {
glucose: {
critical_high: {
threshold: 300,
urgency: '0-24h',
specialty: 'endocrinology',
actions: ['immediate_notification', 'urgent_appointment', 'medication_review']
},
critical_low: {
threshold: 50,
urgency: '0-24h',
specialty: 'emergency',
actions: ['immediate_notification', 'emergency_protocol']
}
},
creatinine: {
acute_elevation: {
threshold: 3.0,
urgency: '0-24h',
specialty: 'nephrology',
actions: ['kidney_function_assessment', 'medication_adjustment']
}
},
combined_risk: {
diabetes_kidney: {
conditions: ['high_glucose', 'elevated_creatinine'],
urgency: '0-24h',
specialty: 'endocrinology',
coordination: ['nephrology_consult']
}
}
};
VoltAgent 为我们带来了一些特别的东西——一个能够弥合简单 AI 工具与复杂企业需求之间差距的框架:
// VoltAgent's workflow engine for complex medical processes
import { createWorkflowChain, andThen, andAgent } from "@voltagent/core";
const medicalAnalysisWorkflow = createWorkflowChain({
id: "medical-analysis-workflow",
name: "Comprehensive Medical Analysis",
input: z.object({
labResults: z.object({
glucose: z.number(),
creatinine: z.number(),
hba1c: z.number()
}),
patientId: z.string()
})
})
.andThen({
name: "fetch-patient-context",
execute: async (data) => ({
...data,
patientHistory: await memory.getPatientContext(data.patientId)
})
})
.andAgent(
(data) => `Analyze these lab results: ${JSON.stringify(data.labResults)}
for patient with history: ${JSON.stringify(data.patientHistory)}`,
medicalAgent,
{ schema: MedicalAnalysisSchema }
)
.andThen({
name: "publish-medical-events",
execute: async (data) => {
await eventBridge.publishMedicalEvents(data.analysis);
return { success: true, eventsPublished: data.analysis.events.length };
}
});
为什么选择 VoltAgent,而不是其他框架?
模块化架构——可以按需添加语音、记忆或自定义工具
工作流编排——处理复杂的医疗流程,而不只是聊天
提供商灵活性——可在 OpenAI、Anthropic 或 Amazon 模型之间切换
企业级就绪——为生产环境而构建,而不只是用于原型
承诺:“AI 将自动化复杂的工作流!”
现实:“AI 会消耗你的云预算,通过测试同一个提示词的无数种变体,来决定究竟调用服务 A 还是服务 B。”
AI 智能体只有在所使用的接口足够优秀时,才能表现良好。定义不清晰的 API、不一致的行为或处理不当的错误,都会导致决策彻底失败。与人类开发者不同,AI 智能体不会“猜测”——它们只会根据自己理解到的内容采取行动。因此,清晰性、一致性和良好的可观测性至关重要。
AI 智能体会带来不确定性。由于操作是动态的、规划是概率性的,结果也可能有所不同。这就需要采用新的方式来测试、验证和审计工作流——不能只依赖单元测试,还要观察整体行为。
构建智能体式医疗系统并非总是阳光灿烂、自动决策一切顺利。以下是实际存在的挑战:
// Every decision must be auditable
interface MedicalDecisionAudit {
timestamp: Date;
agentVersion: string;
inputData: LabResults;
reasoning: string;
decision: MedicalRecommendation;
protocolsApplied: string[];
humanOversight: boolean;
}
医疗事件并不总是井然有序。实验室检查结果可能不会按照顺序到达,AI 智能体必须能够处理:
乱序事件:“两天前的实验室检查结果刚刚送达”
并发更新:多个 AI 智能体同时更新患者记忆
时间推理:理解医疗时间线
即使拥有持久化记忆,AI 智能体仍然存在上下文限制:
// Smart context management for medical reasoning
class MedicalContextManager {
async getRelevantContext(patientId: string, currentIssue: string) {
const fullHistory = await this.memory.getPatientHistory(patientId);
// Intelligent context selection based on medical relevance
return {
recentCritical: fullHistory.filter(event =>
event.priority === 'URGENT' &&
this.isRecentlyRelevant(event, currentIssue)
).slice(0, 10),
chronicConditions: fullHistory.filter(event =>
event.type === 'chronic_condition'
),
medicationHistory: this.getRelevantMedications(fullHistory, currentIssue)
};
}
}
我们的结构化记忆方案牺牲了一定的灵活性,以换取医疗准确性:
精确的医疗关系
关键数据的 ACID 合规性
复杂查询能力
大规模应用下的成本效益
灵活性不如向量搜索
需要结构化的医疗本体
需要手动演进模式
复杂的关系管理
让我们看一下测试套件中的一个真实场景:
// Test case: Critical hyperglycemia with kidney involvement
const testScenario = {
patientId: "patient-456",
labResults: {
glucose: 380, // Critical high
creatinine: 2.8, // Elevated but not critical
hba1c: 12.5 // Poor long-term control
},
patientHistory: {
conditions: ["type2_diabetes", "hypertension"],
medications: ["metformin", "lisinopril"],
lastVisit: "2024-08-15"
}
};
// Agent reasoning chain:
// 1. "Glucose 380 = URGENT (>300 threshold)"
// 2. "Creatinine 2.8 + diabetes = kidney concern"
// 3. "Combined risk = endocrinology + nephrology coordination"
// 4. "Generate events for urgent care"
const expectedEvents = [
{
type: 'appointment.urgent.endocrinology',
timeframe: '0-24h',
reason: 'Critical hyperglycemia with kidney involvement'
},
{
type: 'consultation.nephrology',
priority: 'high',
reason: 'Diabetic kidney disease progression'
},
{
type: 'medication.review.urgent',
focus: 'glucose_control_optimization'
}
];
这种架构并不只关乎单个 AI 智能体——它关乎医疗智能生态系统。我们可以在其中部署通过事件代理进行通信的 AI 智能体工作流。
// Multi-specialty agent coordination
const medicalSpecialistNetwork = {
endocrinology: new MedicalAgent({ specialty: 'diabetes_management' }),
cardiology: new MedicalAgent({ specialty: 'cardiovascular_risk' }),
nephrology: new MedicalAgent({ specialty: 'kidney_function' }),
emergency: new MedicalAgent({ specialty: 'critical_care' })
};
// Intelligent consultation routing
const coordinateSpecialists = async (medicalFindings) => {
const relevantSpecialists = determineSpecialists(medicalFindings);
const consultations = await Promise.all(
relevantSpecialists.map(specialist =>
specialist.consult(medicalFindings, patientContext)
)
);
return synthesizeRecommendations(consultations);
};
2024 年:“AI 将自动化一切!”
2025 年:“AI 与确定性系统协作时效果最好。”
2026 年:“价值在于智能编排,而不是完全自动化。”
部分评论可能只有已登录的访客才能看到。登录后查看所有评论。
如需采取进一步措施,你可以考虑屏蔽此人和/或举报滥用行为。