人工智慧並不致力於追求真理,而是追求可預測性和愉悅性,這就是為什麼它聽起來像一面被編程為回報微笑的情感鏡子😀
消除我們的認知失調🫠
強化資訊泡沫並抑制我們的批判性思維😳
在此,我敦促你們:在人工智慧控制你之前,先掌握它。
過去幾個月我一直在探索人工智慧對人類影響的深淵,所以我想強調上面的引言👆,我在最近的演講中一直在倡導如何在AWS 峰會和開發者大會上實現代理事件驅動架構的觀點。
有件事會讓你大吃一驚:如果你的醫療系統不僅僅處理資料,而且實際上對其進行推理,看起來像豪斯醫生,但沒有所有那些💊😅,並且可以充分發揮其潛力同時處理數千名患者,那會怎樣?
歡迎來到代理事件驅動架構,在這裡我採用了Sean Falconer的概念“AI 代理是具有大腦的微服務” ,並將其應用於生命攸關的領域:醫學分析,然而我們需要退一步,作為產品工程師,我們需要以一種漸進而非革命性的方式在這裡實施我們的努力。
在這轉變過程中,我們期望磨練新的技能,從日常追蹤到分析多個智能體之間的決策模式。我們不應僅關注可用性,而應透過探索意外行為的模擬以及智能體如何應對這些行為來衡量目標的成功程度。
最明顯的思維轉變是接受可控的不可預測性,也就是說,與確定性的服務呼叫不同,代理在執行時所做的決策可以產生到達同一目的地的不同路徑。
服務發現變為代理發現。
路由變成了編排。
速率限製成為資源治理。
最終,這意味著什麼?
我們必須批判地理解和明確成功是什麼,以及它是什麼樣子,而不是一步一步地描述如何成功。
在傳統模型中,路徑是固定的:一個服務按照預先定義的順序呼叫另一個服務,就像腳本一樣。
在代理程式方法中,AI 模型會根據情境動態選擇要使用的服務。
微服務成為AI按需觸發的工具。
在這裡, MCP透過標準化 AI 代理程式接收上下文資訊、存取工具和處理事件的方式而大放異彩。
MCP 在代理程式和它們協調的微服務之間建立一致的介面層。
傳統醫療系統就像醫生,需要把所有事情都記錄下來,一式三份:
“處理此實驗室結果”
“保存該病人的記錄”
“發送此通知”
但是,如果您的系統能夠像住院醫生一樣思考,當醫生看到血糖讀數為350mg/dL
時,會立即啟動一系列智慧推理:
“嚴重高血糖……讓我檢查一下這個病人的病史……啊,糖尿病控制不好……需要在24小時內緊急進行內分泌幹預。”
這正是將自主 AI 代理與事件驅動的微服務架構結合時所發生的情況。
我們的代理微服務系統的核心是我們所謂的代理協調器- 使用VoltAgent建置以實現最大的靈活性,並由 Amazon Nova Micro 提供支援以進行醫學推理。
這是我們系統中的真實程式碼:
// From our actual agent-coordinator implementation
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 triggers the event cascade
export const s3TriggerHandler = async (event: S3Event) => {
for (const record of event.Records) {
const { bucket, object } = record.s3;
// Extract lab data
const labData = await extractLabResults(bucket.name, object.key);
// Agent analyzes with full context
const analysis = await this.agent.analyze({
labResults: labData,
patientHistory: await this.memory.getPatientContext(patientId),
clinicalProtocols: MEDICAL_GUIDELINES
});
// Publish intelligent events based on analysis
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';
};
}
// The agent's persistent memory system
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
});
// Publish memory update event for other agents
await this.eventBridge.publish('patient.memory.updated', memoryUpdate);
}
}
// Autonomous appointment scheduling based on medical urgency
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 的靈活內存系統,為我們的代理提供了真正的持久性:
// Our custom memory implementation
interface PatientMemoryContext {
patientId: string;
clinicalHistory: MedicalEvent[];
glucosePattern: {
trend: 'improving' | 'stable' | 'declining';
criticalEpisodes: number;
lastCritical: Date;
};
medications: CurrentMedication[];
riskFactors: ClinicalRiskFactor[];
preferences: PatientPreferences;
}
// The agent reasons with full context
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 模型之間切換
企業級-專為生產而打造,而不僅僅是原型
承諾:“人工智慧將使複雜的工作流程自動化!”
現實:「人工智慧將消耗你的雲端預算,測試無數種變化
相同的提示來決定是否呼叫服務 A 或 B。 」
只有使用良好的接口,代理才能表現良好。定義不明確的 API、不一致的行為或處理不當的錯誤都會導致決策失敗。與人類開發人員不同,代理人不會「猜測」——它們只會根據自己理解的內容採取行動。因此,清晰、一致和良好的可觀察性至關重要。
代理會帶來不確定性。由於行動是動態的,規劃是機率性的,結果也可能有差異。這需要新的方法來測試、驗證和審核工作流程——不僅僅是單元測試,還要關注整體行為。
建立代理醫療系統並非總是一帆風順,也不全然是自主決策。真正的挑戰在於:
// Every decision must be auditable
interface MedicalDecisionAudit {
timestamp: Date;
agentVersion: string;
inputData: LabResults;
reasoning: string;
decision: MedicalRecommendation;
protocolsApplied: string[];
humanOversight: boolean;
}
醫療事件並非總是有秩序的。實驗室結果可能出現順序混亂的情況,因此代理必須處理以下問題:
無序事件:“兩天前的實驗室剛到達”
並發更新:多個代理同時更新患者記憶
時間推理:理解醫療時間表
即使具有持久內存,代理也存在上下文限制:
// 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'
}
];
這種架構不僅涉及一個代理,它還涉及醫療智慧生態系統,我們可以在其中放置可以透過事件代理進行通訊的代理工作流程
// 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年:“人工智慧將使一切自動化!”
2025 年:“當人工智慧與確定性系統協作時,其效果最佳。”
2026 年:“價值在於智慧編排,而不是完全自動化。”
原文出處:https://dev.to/aws-builders/building-an-agentic-medical-analysis-system-that-actually-thinks-3dg1