Skip to main content
The /ws/analyze WebSocket endpoint provides real-time streaming of the analysis pipeline, allowing clients to receive incremental updates as each agent completes its work.

Endpoint

ws://localhost:8000/ws/analyze

Connection Flow

  1. Client connects to the WebSocket endpoint
  2. Client sends initial JSON payload with patient text
  3. Server streams progress updates as status events
  4. Server streams agent results as agent_result events
  5. Server sends final complete event with SOAP note and debate state
  6. Connection closes

Initial Request

After connecting, send a JSON payload:
text
string
required
Clinical text to analyze (patient presentation, symptoms, history)

Example

{
  "text": "45yo male presents with chest pain radiating to left arm, diaphoresis, BP 160/95, HR 110"
}

Event Types

The server sends different event types during the analysis:

Status Event

Progress updates during processing.
type
string
Always "status"
stage
string
Current pipeline stage: "parsing", "agents", "debate", "synthesis", "safety_panel"
detail
string
Human-readable description of current operation
{
  "type": "status",
  "stage": "parsing",
  "detail": "Parsing clinical input..."
}

Agent Result Event

Streamed when each agent completes.
type
string
Always "agent_result"
agent
string
Agent name: "clinical", "literature", "safety", "critic"
data
object
Agent-specific output (see Agent Outputs)
{
  "type": "agent_result",
  "agent": "clinical",
  "data": {
    "differentials": [...],
    "risk_scores": {...},
    "soap_draft": "...",
    "reasoning_trace": "...",
    "confidence": "high"
  }
}

Complete Event

Final result with synthesized SOAP note.
type
string
Always "complete"
soap
object
Final SOAP note (see SOAP Note model)
debate
object
Complete debate state with all agent outputs
med_error_panel
object
Medication safety analysis results
{
  "type": "complete",
  "soap": {
    "subjective": "...",
    "objective": "...",
    "assessment": "...",
    "plan": "...",
    "differentials": [...],
    "safety_flags": [...]
  },
  "debate": {...},
  "med_error_panel": {...}
}

Error Event

Sent if analysis fails.
type
string
Always "error"
message
string
Error description
{
  "type": "error",
  "message": "Analysis failed: Invalid input format"
}

Example Client (JavaScript)

const ws = new WebSocket('ws://localhost:8000/ws/analyze');

ws.onopen = () => {
  ws.send(JSON.stringify({
    text: '45yo male presents with chest pain...'
  }));
};

ws.onmessage = (event) => {
  const data = JSON.parse(event.data);
  
  switch (data.type) {
    case 'status':
      console.log(`[${data.stage}] ${data.detail}`);
      break;
      
    case 'agent_result':
      console.log(`Agent ${data.agent} completed:`, data.data);
      break;
      
    case 'complete':
      console.log('Analysis complete:', data.soap);
      ws.close();
      break;
      
    case 'error':
      console.error('Error:', data.message);
      ws.close();
      break;
  }
};

ws.onerror = (error) => {
  console.error('WebSocket error:', error);
};

ws.onclose = () => {
  console.log('Connection closed');
};

Example Client (Python)

import asyncio
import json
import websockets

async def analyze_stream():
    uri = "ws://localhost:8000/ws/analyze"
    
    async with websockets.connect(uri) as ws:
        # Send initial request
        await ws.send(json.dumps({
            "text": "45yo male presents with chest pain..."
        }))
        
        # Receive streaming updates
        async for message in ws:
            data = json.loads(message)
            
            if data["type"] == "status":
                print(f"[{data['stage']}] {data['detail']}")
                
            elif data["type"] == "agent_result":
                print(f"Agent {data['agent']} completed")
                
            elif data["type"] == "complete":
                print("Analysis complete:")
                print(json.dumps(data["soap"], indent=2))
                break
                
            elif data["type"] == "error":
                print(f"Error: {data['message']}")
                break

asyncio.run(analyze_stream())

Pipeline Stages

The WebSocket streams through these stages:
  1. parsing - Anonymizes and parses clinical input into structured PatientContext
  2. agents - Runs Clinical Agent (differential diagnosis, risk scores)
  3. agents - Runs Literature and Safety Agents in parallel
  4. debate - Critic Agent reviews all outputs
  5. synthesis - Generates final SOAP note from debate consensus
  6. safety_panel - Runs comprehensive medication error prevention checks

Error Handling

  • If text is missing, server sends error and closes connection
  • If analysis fails mid-stream, server sends error event
  • Client should handle WebSocketDisconnect gracefully
  • All errors are logged server-side for debugging
The WebSocket endpoint uses the same analysis pipeline as /api/analyze but provides incremental updates for better UX in interactive applications.

Build docs developers (and LLMs) love