One-Liner: An ambient memory assistant for individuals with dementia and mild cognitive impairment. A room camera passively observes environment facts without storing video, and a wearable device (M5StickC Plus2) enables natural spoken questions with calm audio answers while proactively delivering non-intrusive medication, appointment, and routine reminders.
- β¨ Key Features & Vision
- π Core Privacy Principle
- ποΈ System Architecture & Three Independent Loops
- π§ Multi-Agent Engine & Confidence System
- π₯οΈ Caregiver Web Setup & Control Dashboard
- β Wearable Hardware & Firmware (M5StickC Plus2)
- πΎ Data Schemas & Database Architecture
- π‘ Complete REST API Reference
- π Repository Structure
- π Installation & Quickstart Guide
- π§ͺ Testing & Verification
- π¬ Hackathon Demo Scenario Script
- π‘οΈ Safety, Ethics & Privacy Guidelines
- π License
Living with dementia or Mild Cognitive Impairment (MCI) creates daily frustration around misplaced items, missed medication, lost routines, and anxiety. Second Mind acts as an ambient cognitive safety net that preserves patient dignity and independence while reducing caregiver stress.
- Passive Camera Perception: Rooms are passively observed using OpenCV. Visual scenes are analyzed in memory by
gemma3:4bto track objects, locations, and medication events. - Wearable Natural Speech Interface: The patient uses a lightweight M5StickC Plus2 wrist/pendant device with a simple "Hold-to-Talk" button.
- Context-Aware Conversational Resolution: Automatically resolves pronouns ("them", "it") and time references ("this morning", "after lunch") across continuous turns.
- Deterministic Python Confidence Engine: Computes exact
HIGH,MEDIUM, orLOWconfidence in Python code based on observation freshness and timestamp validationβpreventing LLM hallucination. - Proactive Medication & Routine Reminders: Background loop evaluates scheduled events against passive observation logs to gently nudge the patient only when a dose or routine was actually missed.
- Emergency Instant-Triage: Recognizes distress phrases ("I need help", "call my daughter") instantly surfacing emergency contacts and logging safety events.
- Caregiver Control Center: Web-based dashboard for setup, real-time memory log inspection, schedule management, and system diagnostics.
ββββββββββββββββββ βββββββββββββββββββββββββββ ββββββββββββββββββββββββββ
β Webcam Stream β ββββΊ β In-Memory Frame Buffer β ββββΊ β OpenCV Frame Diffing β
ββββββββββββββββββ βββββββββββββββββββββββββββ βββββββββββββ¬βββββββββββββ
β (Frame Changed)
βΌ
ββββββββββββββββββ βββββββββββββββββββββββββββ ββββββββββββββββββββββββββ
β SQLite DB β ββββ β Structured Text Log β ββββ β Local Gemma 3 Vision β
β(second_mind.db)β β ("glasses on counter") β β (In-memory analysis) β
ββββββββββββββββββ βββββββββββββββββββββββββββ ββββββββββββββββββββββββββ
(Raw Frame Discarded)
No video or images are ever recorded or stored.
- Camera frames pass through an in-memory buffer analyzed by local OpenCV frame-diffing.
- Only modified frames trigger local vision extraction via
gemma3:4b. - Scene understanding converts visual frames into short, structured text facts (e.g., "reading glasses placed on kitchen counter, 09:15").
- Raw frames are immediately discarded from memory. Only text rows persist in the local
second_mind.dbSQLite database.
Second Mind runs entirely locally on laptop/edge hardware powered by gemma3:4b via Ollama.
ββββββββββββββββββββββββββ
β Room Camera (OpenCV) β
βββββββββββββ¬βββββββββββββ
β (Frame diff / poll)
βΌ
ββββββββββββββββββββββββββ
β Perception Agent β (Track B - Passive Loop)
βββββββββββββ¬βββββββββββββ
β (Write text observations)
βΌ
ββββββββββββββββββββββββββ ββββββββββββββββββββββββββ ββββββββββββββββββββββββββ
β Patient Profile Store β β Memory Store β β Schedule Store β
β (profile_setup.json) β β (second_mind.db) β β (schedule_setup.json) β
βββββββββββββ¬βββββββββββββ βββββββββββββ¬βββββββββββββ βββββββββββββ¬βββββββββββββ
β β β
βββββββββββββββββββββ β βββββββββββββββββββββ
βΌ βΌ βΌ
ββββββββββββββββββββββββββ
β Multi-Agent Engine β (Track A - Edge Runtime)
β - Orchestrator Agent β
β - Memory Agent β
β - Schedule Agent β
β - QA Agent β
β - Emergency Agent β
β - Reminder Agent β
βββββββββββββ¬βββββββββββββ
β
ββββββββββββββββββββββββββββ΄βββββββββββββββββββββββββββ
βΌ βΌ
βββββββββββββββββββββββββ βββββββββββββββββββββββββ
β Active Question Loop β β Proactive Care Loop β
β (Button Press -> Ask) β β (Idle Poll / Reminder)β
βββββββββββββ¬ββββββββββββ βββββββββββββ¬ββββββββββββ
β β
ββββββββββββββββββββββββββββ¬βββββββββββββββββββββββββββ
βΌ
ββββββββββββββββββββββββββ
β M5StickC Plus2 β (Track B - Wearable Device)
β - Speaker / Mic β
β - Hold-to-Talk Button β
ββββββββββββββββββββββββββ
| Loop Name | Frequency | Trigger | Flow |
|---|---|---|---|
| 1. Passive Observation Loop | Continuous (5β10s diff) | Room Motion / Camera | Webcam frame β Frame diff β gemma3:4b vision β MemoryStore (second_mind.db) |
| 2. Active Question Loop | On Demand | Wearable Button Press | M5Stick Mic β Wi-Fi audio β STT β Orchestrator β Specialized Agent β Confidence Engine β TTS β M5Stick Speaker |
| 3. Proactive Care Loop | Periodic (Every 5 min) | Background Timer Thread | ReminderAgent evaluates schedule vs memory log β Queues audio nudge β M5Stick idle polls /reminder/check β Plays audio β POST /reminder/ack |
Rather than relying on a single monolithic LLM prompt, Second Mind utilizes 7 specialized autonomous agents coordinated by a central Orchestrator.
ββββββββββββββββββββββββ
β Incoming Question β
ββββββββββββ¬ββββββββββββ
β
βΌ
ββββββββββββββββββββββββ
β Session Context β (Resolves pronouns & time references)
β Resolver β
ββββββββββββ¬ββββββββββββ
β
βΌ
ββββββββββββββββββββββββ
β Orchestrator Agent β (Classifies 6 intent categories)
ββββββββββββ¬ββββββββββββ
β
ββββββββββββββββ¬ββββββββββββββββββΌββββββββββββββββββ¬βββββββββββββββ
βΌ βΌ βΌ βΌ βΌ
ββββββββββββ βββββββββββββ βββββββββββββββ βββββββββββββ βββββββββββββ
β MEMORY β βMEDICATION β β SCHEDULE β β PROFILE β β EMERGENCY β
ββββββ¬ββββββ βββββββ¬ββββββ ββββββββ¬βββββββ βββββββ¬ββββββ βββββββ¬ββββββ
β β β β β
βΌ βΌ βΌ βΌ βΌ
ββββββββββββββββ ββββββββββββββββ βββββββββββββββ βββββββββββββ βββββββββββββ
β MemoryAgent β β MemoryAgent β βScheduleAgentβ β QAAgent β β Emergency β
β (Obs log) β β(Log+Profile) β β (Schedule) β β (Profile) β β Agent β
ββββββββ¬ββββββββ ββββββββ¬ββββββββ ββββββββ¬βββββββ βββββββ¬ββββββ βββββββ¬ββββββ
β β β β β
ββββββββββββββββββ΄βββββββββ¬ββββββββ΄βββββββββββββββ΄ββββββββββββββ
βΌ
ββββββββββββββββββββββββββββ
β Python Confidence β (Calculates HIGH / MEDIUM / LOW
β & Validation Engine β deterministically in code)
ββββββββββββββ¬ββββββββββββββ
βΌ
ββββββββββββββββββββββββββββ
β TTS Speech Synthesis β (Generates WAV audio response)
ββββββββββββββββββββββββββββ
PerceptionAgent: Monitors room webcam feed, runs frame-diffing, extracts structured object & medication events via local Gemma Vision, and writes rows toMemoryStore.OrchestratorAgent: Rewrites follow-up queries using rollingSessionStorecontext (resolving pronouns like "it" or "them"), then classifies intent into one of 6 categories:MEMORY,MEDICATION,SCHEDULE,PROFILE,EMERGENCY, orGENERAL.MemoryAgent: Resolves object location queries ("Where are my glasses?") and hybrid medication verification ("Did I take my morning pills?") by cross-referencingMemoryStoreobservations against caregiver profile schedule times.ScheduleAgent: Answers questions about appointments, routine daily steps, and custom caregiver reminders fromScheduleStore.QAAgent: Answers profile-based family/medical facts and general everyday conversational questions with calm, reassuring phrasing.EmergencyAgent: Fast-triages distress statements ("I need help", "call my son"), immediately surfaces emergency phone numbers, logs ahelp_requestevent, and provides calming voice output.ReminderAgent: Autonomous background timer thread that checks upcoming schedule events against observed memory logs to queue proactive spoken reminders.
To ensure safety in dementia care, LLMs are never allowed to invent confidence scores. Confidence is calculated deterministically in Python code:
- π’ HIGH: Exact match within expected time window (< 1 hour for objects; inside configured grace window for medication).
- π‘ MEDIUM: Match exists but observation is stale, or multiple candidate locations exist.
- π΄ LOW: No matching observation found in memory store.
Served locally at http://localhost:8000/dashboard (or http://localhost:8000/), the dashboard provides caregivers with complete administrative control.
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β SECOND MIND β Caregiver Setup & Ambient Intelligence Control Center [SYSTEM ONLINE] β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β [π€ Patient Profile] [π
Schedule & Routines] [ποΈ Live Memory Log] [β‘ System Health] β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β β
β βββββββββββββββββββββββββββββββββ ββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β Patient Metadata β β Medication Schedules β β
β β Name: Arthur Pendelton β β - Donepezil (5mg) @ 08:00 (Grace: 20 min) β β
β β Age: 76 β β - Memantine (10mg) @ 20:00 (Grace: 30 min) β β
β β Conditions: MCI, Hypertension β ββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β βββββββββββββββββββββββββββββββββ β
β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
β β Emergency Family Contacts β β
β β - Likhita (Daughter) - 555-0199 [Primary] β β
β ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
- Patient Profile: Edit patient name, age, medical conditions, medication dosing schedules, and family emergency contact numbers.
- Schedule & Routines: Manage upcoming appointments, structured daily routines (morning/evening steps), and custom caregiver reminders.
- Live Memory Log: Monitor real-time room observations captured by the perception loop with filtering by event type (
object_observation,medication_taken,help_request). - System Diagnostics: Real-time health status monitoring for Ollama connection, SQLite database, Whisper STT, pyttsx3 TTS, and active background threads.
The patient interface is built on the M5StickC Plus2 ESP32 wearable development board.
+------------------------+
| M5StickC Plus2 |
| |
| +----------------+ |
| | LCD Display | |
| | | |
| | [LISTENING] | |
| +----------------+ |
| |
| (o) Mic ( ) Speaker|
| |
| [ Button A: HOLD ] |
+-----------+------------+
|
βΌ (Wi-Fi HTTP)
+------------------------+
| FastAPI Backend |
+------------------------+
- MCU: ESP32-PICO-D4 (Wi-Fi & Bluetooth)
- Screen: 1.14 inch Color LCD (135x240)
- Microphone: SPM1423 PDM Microphone
- Speaker: Built-in I2S Buzzer / Speaker
- Battery: 200mAh Lithium Polymer
- Buttons: Button A (Main Hold-to-Talk front button), Button B (Side function button)
- Idle State: Screen displays "Hold Button A to Ask". Polling loop queries
GET /reminder/checkevery 25 seconds. - Button Down: Suspends polling, initiates microphone recording, screen displays π΄ "Listening...".
- Button Up: Stops recording, posts recorded WAV audio to
POST /ask, screen displays π‘ "Thinking...". - Response Received: Plays returned WAV answer over speaker, screen displays π’ "Speaking...".
- Reminder Triggered: On
GET /reminder/checkreturningpending: true, downloads audio URL, plays reminder, and issuesPOST /reminder/ack.
Stores structured room observations logged by the passive perception loop.
CREATE TABLE IF NOT EXISTS observations (
id TEXT PRIMARY KEY,
timestamp TEXT NOT NULL,
object TEXT NOT NULL,
location TEXT NOT NULL,
action TEXT NOT NULL,
event_type TEXT NOT NULL,
raw_description TEXT
);
CREATE INDEX idx_obs_event_type ON observations(event_type);
CREATE INDEX idx_obs_timestamp ON observations(timestamp);Observation Schema Example:
{
"id": "c62a84b1-9b1e-4c7b-a19f-0987654321fe",
"timestamp": "2026-07-30T09:15:00Z",
"object": "reading glasses",
"location": "kitchen counter",
"action": "placed",
"event_type": "object_observation",
"raw_description": "A pair of reading glasses was set down near the fruit bowl."
}profile_setup.json: Patient details, medical facts, medication schedule times, and emergency contacts.schedule_setup.json: Caregiver-defined appointments, daily routine sequences, and custom recurring reminders.
Liveness check verifying subsystem readiness.
{
"status": "healthy",
"ollama": "connected",
"database": "connected",
"whisper": "ready",
"tts": "ready",
"agents": 6,
"uptime_seconds": 128.4
}Primary endpoint for active questions (accepts multipart WAV audio file or JSON transcript body).
- Query Params:
return_json=true(optional, for debugging) - Request Body (JSON option):
{ "transcript": "Where are my reading glasses?", "device_id": "demo_device_01" } - Response Headers:
X-Transcript:Where are my reading glasses?X-Intent:MEMORYX-Confidence:highX-Reasoning:Matched single recent observation on kitchen counter.X-Answer-Text:Your reading glasses are on the kitchen counter.
Polled by wearable device every 20-30s while idle.
{
"pending": true,
"audio_url": "/audio/reminder_1722345600.wav",
"message": "It is time for your morning medication.",
"reminder_type": "medication"
}Acknowledges and clears currently pending reminder slot.
{
"status": "acknowledged",
"cleared": true
}Perception integration endpoint for Track B vision pipeline.
[
{
"object": "medication bottle",
"location": "small table next to bed",
"action": "picked up and opened",
"event_type": "medication_taken",
"raw_description": "Pill bottle opened."
}
]GET /api/profile|POST /api/profile: Retrieve or update patient profile data.GET /api/schedule|POST /api/schedule: Retrieve or update appointment and routine schedules.GET /api/observations: Fetch recent memory observations for dashboard UI.
SecondMind/
βββ backend/
β βββ main.py # FastAPI application entrypoint & routing
β βββ config.py # Pydantic environment configurations
β βββ constants.py # System enums (Intent, EventType, Confidence)
β βββ llm_service.py # Ollama client wrapper & low-level LLM calls
β βββ logger.py # Structured logging & request tracing
β βββ ollama_client.py # HTTP client communicating with Ollama API
β βββ perception.py # OpenCV webcam loop & Gemma Vision integration
β βββ prompt_manager.py # System prompt templates & few-shot examples
β βββ schemas.py # Pydantic response models & validation
β βββ stt.py # Speech-to-Text wrapper (faster-whisper)
β βββ tts.py # Text-to-Speech wrapper (pyttsx3)
β βββ agents/
β β βββ orchestrator.py # Session resolver & 6-category intent classifier
β β βββ memory_agent.py # Object location & medication hybrid check
β β βββ schedule_agent.py # Appointment, routine, & custom schedule queries
β β βββ qa_agent.py # Profile facts & general conversational QA
β β βββ emergency_agent.py # Emergency contact triage & help event logging
β β βββ reminder_agent.py # Background timer loop for proactive reminders
β βββ services/
β β βββ ask_service.py # Orchestrates STT -> Agent -> Confidence -> TTS
β β βββ health_service.py # Subsystem readiness diagnostics
β β βββ reminder_service.py # Lifecycle manager for background reminder thread
β βββ stores/
β β βββ memory_store.py # SQLite repository for room observations
β β βββ profile_store.py # Caregiver patient profile storage repository
β β βββ schedule_store.py # Caregiver appointment & routine schedule repository
β β βββ session_store.py # Thread-safe rolling conversation context store
β βββ tests/ # Automated pytest suite (10 test modules)
β βββ test_ask_endpoint.py
β βββ test_confidence.py
β βββ test_dashboard_api.py
β βββ test_demo_scenario.py
β βββ test_health.py
β βββ test_reminder_agent.py
β βββ test_reminder_endpoints.py
β βββ test_routing.py
β βββ test_session_context.py
β βββ test_stores.py
βββ firmware/
β βββ second_mind_stick/
β βββ second_mind_stick.ino # M5StickC Plus2 Arduino ESP32 firmware
βββ frontend/
β βββ index.html # Caregiver Setup Dashboard web app
β βββ style.css # Custom CSS styling (Neobrutalism design theme)
β βββ app.js # Dashboard logic & API synchronization
βββ audio_cache/ # Generated WAV audio cache directory
βββ second_mind.db # SQLite database file
βββ profile_setup.example.json # Template patient profile setup file
βββ profile_setup.json # Active caregiver patient profile setup
βββ schedule_setup.example.json # Template schedule setup file
βββ schedule_setup.json # Active caregiver schedule setup
βββ architecture.md # Technical design specification
βββ project.md # Project requirements & vision document
βββ README.md # Detailed documentation readme
- Python 3.11+ installed on host machine.
- Ollama installed and running locally (https://ollama.com).
- Pull the multimodal
gemma3:4bmodel:ollama pull gemma3:4b
Clone the repository and install required Python packages:
git clone https://github.com/YourRepo/SecondMind.git
cd SecondMind
# Create virtual environment
python -m venv venv
# Activate virtual environment (Windows)
.\venv\Scripts\activate
# Activate virtual environment (Linux/macOS)
source venv/bin/activate
# Install dependencies
pip install fastapi uvicorn pydantic pydantic-settings httpx pyttsx3 faster-whisper pytest opencv-pythonCopy default template files to create local configuration settings:
cp profile_setup.example.json profile_setup.json
cp schedule_setup.example.json schedule_setup.jsonStart the FastAPI application with Uvicorn server:
python -m uvicorn backend.main:app --host 0.0.0.0 --port 8000 --reload- Caregiver Dashboard: Open browser to
http://localhost:8000/dashboard - Swagger Interactive API Docs: Open browser to
http://localhost:8000/docs
- Open
firmware/second_mind_stick/second_mind_stick.inoin Arduino IDE. - Install
M5StickCPlus2library via Arduino Library Manager. - Update Wi-Fi SSID, Password, and your Laptop Server IP address in
second_mind_stick.ino:const char* ssid = "YOUR_WIFI_SSID"; const char* password = "YOUR_WIFI_PASSWORD"; const char* server_url = "http://192.168.1.100:8000";
- Select Board:
M5StickC-Plus2, Port, and click Upload.
Second Mind includes a comprehensive automated unit test suite covering stores, routing, confidence calculations, session resolution, reminder loops, and full demo scripts.
Run the test suite using pytest:
python -m pytest backend/tests/ -vFollow this step-by-step sequence for a complete live demonstration:
- Passive Observation Log: Camera logs
reading glassesplaced onkitchen counterat 09:15, andmedication bottlepicked up at 08:10. - Object Query: Patient asks "Where are my reading glasses?" β
MEMORYagent answers "Your reading glasses are on the kitchen counter." - Follow-up Query: Patient asks "Did I move them after lunch?" β Session resolver rewrites
"them"to"reading glasses"β answers contextually. - Schedule Query: Patient asks "Do I have any doctor appointments today?" β
SCHEDULEagent answers "Dr. Singh checkup tomorrow at 10:00 AM." - Profile Query: Patient asks "Who is Sarah?" β
PROFILEagent answers "Sarah is your daughter." - Medication Verification: Patient asks "Have I taken my morning medication?" β
MEDICATIONagent checks schedule againstsecond_mind.dbβ confirms dose taken at 08:00 AM. - Proactive Reminder: Background thread evaluates schedule against memory log β device idle polls
/reminder/checkβ plays audio reminder β issues/reminder/ack. - Emergency Trigger: Patient says "I need help, call my daughter!" β
EMERGENCYagent surfaces contact555-0199, logshelp_requestevent, and provides calming voice output.
- Privacy by Design: Zero cloud dependencies. Video frames remain strictly ephemeral in local system RAM.
- Caregiver Authority: Medical schedules and emergency contact numbers are controlled exclusively by designated caregivers through the secure local Web Dashboard.
- Dementia-Friendly Phrasing Guidelines: All system prompt templates enforce warm, simple, short, non-alarming, and non-judgmental spoken responses.
This project is licensed under the MIT License.