AiDemo Component (AiDemo.tsx)
Relevant source files
The following files were used as context for generating this wiki page:The AiDemo component is a core feature of the AI for Thai EMS application, designed to provide a visual, real-time demonstration of how AI can analyze an emergency dispatch call. It simulates a conversation between a dispatcher and a caller, sending the transcript incrementally to a backend AI service for analysis. The results, including incident type, severity, location, and structured patient data, are then displayed on a dashboard.
This component is centrally featured in the main application view, serving as a practical showcase of the project's primary objective: to apply AI to improve the efficiency and accuracy of emergency medical services. It is rendered directly within the main App component.
Sources: components/AiDemo.tsx, App.tsx:65
Architecture and State Management
The component's logic is managed through several React state variables, which control the simulation's flow, store conversation data, and hold the AI analysis results.
Sources: components/AiDemo.tsx:38-44
State Variables
The following table describes the key state variables managed by the AiDemo component.
| State Variable | Type | Initial Value | Description |
|---|---|---|---|
simulationState | 'idle' | 'running' | 'finished' | 'idle' | Manages the current state of the simulation (not started, in progress, or completed). |
transcript | { speaker: string; text: string }[] | [] | An array storing the conversation lines of the simulated call as they are revealed. |
analysis | AiAnalysisResult | initialAnalysis | An object holding the structured data returned from the AI analysis service. |
isAnalyzing | boolean | false | A flag that indicates when an API call to the AI service is in progress. Used to show loading indicators. |
error | string | null | null | Stores any error message that occurs during the AI analysis API call. |
Sources: components/AiDemo.tsx:38-44, types.ts:12-21
Simulation Flow
The simulation is user-initiated and progresses through a predefined lifecycle, managed by the simulationState variable.
Sources: components/AiDemo.tsx:72-92, 98-107
Lifecycle States
The component operates in one of three states: idle, running, or finished. The user can start the simulation from the idle state or reset it at any time.
This diagram shows the state transitions of the simulation, triggered by user actions or component logic.
Sources: components/AiDemo.tsx:38, 79, 89, 98-107
Simulation Logic
- A user clicks the "Start Simulation" button, which calls the
handleStartfunction. handleStartresets all state variables to their initial values and setssimulationStateto'running'.- A
useEffecthook, dependent onsimulationState, activates when the state becomes'running'. - This effect sets up an interval (
setInterval) that adds one line from a hardcodedfullTranscriptarray to thetranscriptstate every 1.8 seconds. - After adding a line, if the speaker was the 'Caller', the
runAnalysisfunction is triggered with the current transcript. - When all lines from
fullTranscripthave been processed, thesimulationStateis set to'finished', and the interval is cleared. - The user can click "Reset" at any point to call
handleReset, which stops the simulation and clears all data, returning to theidlestate.
Sources: components/AiDemo.tsx:72-92, 98-107
AI Analysis Integration
The core functionality of the demo is its integration with the Gemini AI service to analyze the call transcript. This is handled by the runAnalysis function and the analyzeEmergencyCallWithGemini service.
Sources: components/AiDemo.tsx:46-62, services/geminiService.ts
Data Flow for Analysis
The following sequence diagram illustrates the process of sending a transcript for analysis and receiving the results.
This diagram shows the interaction between the UI component, the service layer, and the external Gemini API during an analysis cycle.
Sources: components/AiDemo.tsx:46-62, services/geminiService.ts:9-55
analyzeEmergencyCallWithGemini Service
This function, located in services/geminiService.ts, is responsible for communicating with the Google Gemini API.
- Input: A single string containing the conversation transcript.
- Process:
- It constructs a prompt instructing the AI to analyze the transcript.
- It defines a strict JSON
schemathat the AI's response must follow. This ensures a predictable, structured output. - It calls the
gemini-2.5-flashmodel with the prompt and schema, requesting a response inapplication/jsonformat. - It parses the JSON response text.
- Output: A
Promisethat resolves to anAiAnalysisResultobject. - Error Handling: If the API call fails or the response is not valid JSON, it throws an error, which is caught in the
AiDemocomponent and displayed to the user.
Sources: services/geminiService.ts:9-55
Data Structures
The component relies on a predefined data structure, AiAnalysisResult, to handle the data returned by the AI service.
Sources: types.ts:12-21
AiAnalysisResult Interface
This interface defines the shape of the structured data extracted from the emergency call.
This diagram shows the structure of the AiAnalysisResult object and its nested ExtractedData.
Sources: types.ts:12-21
The fields of the AiAnalysisResult are described below:
| Field | Type | Description |
|---|---|---|
incidentType | string | null | The category of the emergency (e.g., "Cardiac Emergency"). |
location | string | null | The full address of the incident. |
severity | 'Critical' | 'Urgent' | 'Non-Urgent' | null | The assessed severity level of the incident. |
recommendedAction | string | null | The suggested next step for the dispatcher (e.g., "Dispatch ALS Ambulance"). |
extractedData | object | An object containing specific details about the patient. |
extractedData.name | string | The patient's name. |
extractedData.age | string | The patient's age. |
extractedData.condition | string | A summary of the patient's reported condition. |
Sources: types.ts:12-21, services/geminiService.ts:12-26
User Interface (UI)
The UI of the AiDemo component is split into two main panels: a transcript view and an analysis dashboard.
Sources: components/AiDemo.tsx:117-183
Transcript Panel
- Purpose: Displays the simulated conversation in a chat-like interface.
- Implementation: It maps over the
transcriptstate array. Messages from the 'Dispatcher' are aligned to the left with a blue background, while messages from the 'Caller' are aligned to the right with a green background. A "Typing..." indicator is shown while waiting for the next message in the simulation. - File Reference:
components/AiDemo.tsx:129-148
AI Analysis Dashboard
- Purpose: Shows the real-time results from the AI analysis.
- Implementation:
- It displays the
severitywith a background color that changes based on the value (redfor 'Critical',yellowfor 'Urgent'). - It uses a reusable
AnalysisItemsub-component to display theincidentType,location, andrecommendedAction. Each item has a dedicated icon. - A
LoadingIndicatoris shown for each field whileisAnalyzingistrueand the field has no value yet. - Structured data (
name,age,condition) is displayed in a separate section at the bottom.
- It displays the
- Icons: The dashboard uses several SVG icons (e.g.,
BoltIcon,MapPinIcon) imported fromcomponents/Icons.tsxto visually distinguish different types of information. - File References:
components/AiDemo.tsx:151-183](), [components/Icons.tsx](https://github.com/ppakpoomm/AI-for-Thai-EMS/blob/HEAD/components/Icons.tsx)
Summary
The AiDemo.tsx component serves as a compelling proof-of-concept for the AI for Thai EMS project. It effectively simulates a real-world scenario and visualizes how AI can transform unstructured voice communication into structured, actionable intelligence for emergency dispatchers. By integrating a frontend simulation with a powerful backend AI model, it demonstrates a tangible path toward reducing errors, speeding up response times, and improving the overall quality of emergency medical services.
Sources: components/AiDemo.tsx, App.tsx:65