Data Flow
Relevant source files
The following files were used as context for generating this wiki page:
This document outlines the data flow within the AI for Thai EMS application, focusing on how user input is processed by frontend components, sent to the Google Gemini AI service, and how the results are rendered back to the user. The application features two primary AI-driven functionalities: an Emergency Dispatch Simulation and an interactive AI Assistant Chatbot, each with a distinct data flow.
The core of the architecture involves React components capturing user interactions, a dedicated service layer for communicating with the Gemini API, and defined data structures for managing state and API responses. The Vite build tool is used to manage environment variables, such as the Gemini API key.
High-Level Architecture
The application's data flow is centered around two main UI components, AiDemo and Chatbot, which are integrated into the main App component. Both UI components utilize the geminiService to handle all interactions with the external Google Gemini API. Data types are standardized across the application via types.ts.
This diagram shows the high-level interaction between the main components.
Data Models
The application relies on specific data structures to manage state and handle API responses. The primary model for the emergency simulation is AiAnalysisResult.
Sources: types.ts
AiAnalysisResult Type
This interface defines the structure of the JSON object expected from the Gemini API after analyzing an emergency call transcript.
| Field | Type | Description |
|---|---|---|
incidentType | string | null | The type of incident (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 action (e.g., "Dispatch ALS Ambulance"). |
extractedData | object | A nested object containing structured patient data. |
extractedData.name | string | The patient's name. |
extractedData.age | string | The patient's age. |
extractedData.condition | string | A summary of the patient's condition. |
Sources: types.ts:12-21, services/geminiService.ts:10-25
Chat Message Type
The Chatbot component uses a Message type to structure the conversation history. The sender property is aligned with the Gemini API's role requirements (user or model).
type Message = {
id: number;
text: string;
sender: 'user' | 'model';
sources?: any[];
};
Sources: components/Chatbot.tsx:8-13
Emergency Dispatch Simulation Flow (AiDemo)
The AiDemo component simulates an emergency call and uses AI to analyze the conversation in real-time. The data flow is triggered automatically as the simulated conversation progresses.
- The user clicks "Start Simulation", setting the
simulationStateto'running'. - A
useEffecthook adds new lines to thetranscriptstate from a predefined script (fullTranscript) at set intervals. - When a message from the
'Caller'is added, therunAnalysisfunction is invoked. runAnalysiscallsanalyzeEmergencyCallWithGeminifrom thegeminiService, passing the current conversation transcript.- The service sends the transcript to the Gemini API, requesting a structured JSON response conforming to the
AiAnalysisResultschema. - Upon receiving the JSON response,
runAnalysisupdates theanalysisstate in theAiDemocomponent. - The UI re-renders to display the new analysis data, such as
severity,location, andincidentType.
Sources: components/AiDemo.tsx:55-70, 72-87, services/geminiService.ts:8-63
The following sequence diagram illustrates this process.
AI Assistant Chatbot Flow (Chatbot)
The Chatbot component provides two modes of input: text and audio. Both flows ultimately result in a call to the Gemini API via geminiService.
Text Input Flow
This is the primary interaction method where the user types a message and receives a streamed response.
- The user types a message in the
textareaand clicks the send button or presses Enter. - The
handleSendMessagefunction is called. It creates a newusermessage and adds it to themessagesstate. - The existing
messagesare mapped to ahistoryarray, formatted for the Gemini API. sendMessageToChatStreamis called with the history, new message, and current settings (e.g.,isThinkingMode).- The service initiates a streaming chat session with the Gemini API.
handleSendMessagecreates an emptymodelmessage in themessagesstate to hold the incoming response.- As response chunks arrive from the stream, the component appends the text to the
modelmessage, causing the UI to update in real-time.
Sources: components/Chatbot.tsx:71-106, services/geminiService.ts:89-112
This sequence diagram shows the text-based chat flow.
Audio Input & Transcription Flow
The chatbot can also accept audio input, which is first transcribed to text before being sent as a standard chat message.
- User clicks the microphone icon, triggering
startRecording. - The browser's
MediaRecorderAPI is used to capture audio from the user's microphone. - When the user clicks the stop icon,
stopRecordingis called, which stops the recorder. - The
onstopevent handler fires, creating an audioBlob. - A
live.connectsession is established with the Gemini API for real-time transcription. - The audio blob is converted to a Base64 string and sent to the live session.
- The
onmessagecallback receives transcription updates (inputTranscription.text) from the server. - The transcribed text is appended to the
inputstate of the component. - Once transcription is complete, the user can review the text and send it, initiating the standard Text Input Flow.
Sources: components/Chatbot.tsx:108-181
This flowchart illustrates the audio transcription process.
API Key Configuration
The application requires a Google Gemini API key to function. The key is managed as an environment variable and exposed to the application during the build process.
- The API key is expected to be in an environment variable named
GEMINI_API_KEY. - The
vite.config.tsfile usesloadEnvto read this variable. - It then uses Vite's
definefeature to replaceprocess.env.API_KEYin the source code with the actual key value at build time. - The
geminiService.tsfile then usesprocess.env.API_KEYto instantiate theGoogleGenAIclient.
Sources: vite.config.ts:6, 12, services/geminiService.ts:4, README.md:12