Project Info
Inspiration
Over 100 million people wear sleep trackers, yet the data sits underutilized in app dashboards. We asked: what if disrupted sleep isn't just about being tired, but an early biomarker for serious health conditions? Sleep is one of the body's most sensitive indicators — changes in sleep architecture can precede clinical disease by months or years. We built SOMNI AI to transform wearable sleep data into evidence-based clinical intelligence, empowering people to detect health risks early and have informed conversations with their doctors.
What it does
SOMNI AI is a multi-agent clinical evidence synthesis platform that analyzes 30 days of sleep data from Apple Health, Fitbit, or Oura and generates two comprehensive reports: Statistical Analysis: Computes z-scores using standard error of the mean (SEM) to detect deviations from personal baseline Calculates Sleep Health Deviation Index (SHDI) — a weighted composite of fragmentation, deep sleep, REM, efficiency, and variability Identifies sleep phenotypes (fragmentation-dominant, deep sleep reduction, REM instability, efficiency instability) Patient Report: Written at 8th-grade reading level, empathetic and non-alarming, designed to be shared with family members. Includes "What This Does NOT Mean" section and clear next steps. Clinical Report: GRADE-style evidence for healthcare providers with structured tables, effect sizes, evidence strength ratings (strong/moderate/emerging), limitations, and screening recommendations.
How we built it
Multi-Agent Architecture: We built a sub-agent team system powered by Claude as the main orchestrator. Each sub-agent has its own context window and specializes in a specific task: Literature Search Agent: Queries PubMed using NCBI E-utilities Medical Reasoning Agent: GPT-4.5 with specialized prompts for ranking risk domains and generating structured reasoning traces Evidence Assessment Agent: Evaluates consistency across sources and provides refinement instructions Guidelines Agent: BrightData integration for CDC/AHA-style clinical guidelines and health disparity data Consensus Agent: Perplexity Sonar queries for scientific consensus and controversy Agents communicate like a real research team — when conflicts are detected, the assessment agent instructs the search agent to refine queries, and the system re-searches before finalizing reports. Technical Implementation: Frontend: Next.js 14 App Router, React, Tailwind CSS Backend: Serverless API routes on Vercel (single deployment, no separate backend) Statistical Engine: Pure TypeScript implementation of sleep analysis algorithms (30-day baseline, SEM-based z-scores, SHDI calculation, phenotype classification) APIs: Claude (orchestration), GPT-4.5 (reasoning), PubMed (literature), BrightData (guidelines), Perplexity Sonar (consensus) Safety: Prompt injection protection at every API boundary, context compaction for token efficiency Data Parsing: Support for Apple Health XML, Fitbit CSV, and Oura CSV formats
Challenges we ran into
1. Context Window Management Across Sub-Agents: With 30 days of sleep data, multiple research papers, and multi-turn agent conversations, we hit token limits quickly. We solved this with context compaction strategies that preserve critical information while summarizing less relevant details, and by giving each sub-agent its own focused context window. 2. Evidence Synthesis Without Over-Claiming: Medical information requires extraordinary precision. We had to build a feedback loop where the evidence assessment agent evaluates source quality and consistency, flagging conflicts before the system writes reports. This ensures we never make claims stronger than the evidence supports. 3. Balancing Technical Sophistication with Readability: The patient report needed to be accessible to someone with no medical background, while the clinical report needed to meet evidence-based medicine standards. We iterated extensively on tone, reading level, and structure to serve both audiences without compromising either. 4. Autonomous Agent Reliability: Getting Claude to consistently choose the right sub-agent at the right time required careful prompt engineering and tool design. We implemented explicit pipeline tracking so we could debug and optimize the decision-making flow.
Accomplishments we're proud of
Sub-Agent Team Architecture: We didn't just chain API calls — we built agents that genuinely collaborate, with separate context windows and inter-agent communication protocols. Evidence-Based Medicine Standards: Our clinical reports follow GRADE methodology with explicit evidence strength ratings, effect sizes, and limitations — this is the standard used by top medical journals. Human-Centered Design: The patient report opens with validation, not alarm. It's written to empower, not frighten. We tested it with non-technical readers to ensure accessibility. Production-Ready on Day One: Single Vercel deployment, TypeScript-only analysis engine, full PDF export, parser support for three major wearable platforms. This isn't a demo — it's deployable. Prompt Injection Protection: We hardened every API boundary to prevent malicious inputs from compromising the integrity of medical analysis.
What we learned
Agent orchestration is harder than it looks. Building a system where multiple AI agents communicate and refine each other's work required deep thinking about tool design, context management, and feedback loops. We learned that autonomous doesn't mean hands-off — it means building the right constraints. Medical applications demand a different standard. We couldn't treat this like a typical hackathon project. Every claim needed a citation. Every report needed disclaimers. Every edge case needed careful handling. We learned to think like clinical researchers, not just engineers. Sleep data is incredibly information-rich. Even "simple" metrics like awakenings or REM percentage can correlate with metabolic, cardiovascular, and neurological health. The challenge isn't finding signals — it's interpreting them responsibly.
What's next
for SOMNI AI 1. Longitudinal Tracking: Extend analysis beyond 30 days to detect long-term trends and seasonal patterns. Add alerts for significant trajectory changes. 2. Provider Integration: Build FHIR-compliant export so clinical reports can be sent directly to electronic health records with patient consent. 3. Expanded Biomarkers: Integrate heart rate variability, SpO2, and activity data for multi-modal health intelligence. 4. Clinical Validation Studies: Partner with sleep labs and primary care clinics to validate our deviation indices against clinical outcomes. 5. Disparity-Aware Recommendations: Use BrightData more extensively to ensure recommendations account for population-specific risk factors and access barriers. 6. Explainability Dashboard: Add visualizations showing exactly which sleep patterns triggered which research associations, making the "black box" transparent. SOMNI AI: Detecting tomorrow's health crisis in tonight's sleep.
SOMNI AI - Sleep Health Intelligence System
🏆 TreeHacks 2026 Project | Multi-Agent Clinical Evidence Synthesis
🎯 Overview
SOMNI AI transforms consumer wearable sleep data into actionable health intelligence through autonomous multi-agent scientific analysis. The system detects statistical deviations from personal sleep baselines and maps patterns to peer-reviewed longitudinal research associations.
Core Thesis: Sleep deviation is an early biomarker of systemic health drift. SOMNI AI detects trajectory shifts before clinical disease manifests.
Key Features
- 📊 Statistical Sleep Analysis - Z-scores, trend detection, variability indices
- 🤖 Multi-Agent Orchestration - Claude SDK → OpenAI o1 → PubMed → BrightData → Perplexity
- 📝 Dual Report Generation - Patient-friendly (8th grade) + Clinical (evidence-graded)
- 🔬 Scientific Rigor - GRADE methodology, effect sizes, confidence intervals
- 🚀 Production Architecture - Next.js 14 App Router, FastAPI, Edge streaming
🚀 Quick Start
Prerequisites
- Node.js 18+
- Python 3.11+
- API Keys (Anthropic, OpenAI, Perplexity, BrightData)
Installation
# Install Node.js dependencies
npm install
# Install Python dependencies
cd python
pip install -r requirements.txt
cd ..
# Set up environment variables
cp .env.example .env
# Edit .env with your API keys
Running the Application
# Terminal 1: Start Python backend
cd python
python api/main.py
# Terminal 2: Start Next.js frontend (in project root)
npm run dev
📁 Project Structure
somni-ai/
├── app/ # Next.js 14 App Router
│ ├── page.tsx # Landing page with upload
│ ├── analysis/[id]/page.tsx # Analysis results
│ └── api/ # API routes
├── lib/
│ ├── agents/ # Multi-agent orchestration
│ └── reports/ # Report generators
├── python/
│ ├── sleep_analysis/ # Statistical analysis engine
│ └── api/ # FastAPI backend
├── components/ui/ # shadcn/ui components
└── public/demo_data/ # Sample datasets
🏆 Prize Narratives & Demonstrations
Greylock — 5+ API Agent with Feedback Reasoning
Criterion: Best hack with an agent that reasons about feedback to dynamically complete complex tasks.
How we meet this:
- 5+ API sequence: Claude (orchestrator) → OpenAI o1 (medical reasoning) → PubMed (literature) → BrightData (guidelines) → Perplexity Sonar (consensus)
- Feedback loop:
assess_evidence_qualitytool evaluates consistency; returnsrefine_query,broaden_query, orproceed. When conflicts detected, Claude refines search and re-queries. - Visible proof: "Multi-API Pipeline" card on analysis page shows all services used. Terminal logs show
[Pipeline]sequence and[Feedback]refinements.
Demo points: "Our agent autonomously chooses which API to call and when. When evidence is inconsistent, it refines the query and re-searches before writing reports."
OpenAI — Most Creative Use of API
Criterion: Top three teams that use OpenAI API most creatively.
How we meet this:
- o1 as medical reasoning engine: Dedicated system prompt frames task as research associations and risk domain ranking (not diagnosis).
- Structured reasoning: Ask for step-by-step reasoning trace, then structured output (ranked domains, confidence, screening, reasoning).
reasoning_effort: 'high': Uses o1's extended reasoning for medical analysis.
Demo points: "We use o1 creatively as a clinical reasoning engine with a specialized system prompt. It stays strictly in research associations while providing explicit reasoning traces."
Anthropic Human Flourishing
Criterion: Patient report reads empathetically (test with family). Show how AI serves human potential.
How we meet this:
- Empathetic tone: Opening validates effort ("Taking an interest..."), normalizes variation ("Many people see temporary changes").
- Family-tested design: Report designed for reading with family members (see
docs/human-flourishing-note.md). - No alarm: 8th-grade reading level, hopeful framing, clear disclaimers.
Demo points: "We designed the patient report to be read with a parent or partner — supportive, clear, and without fear. AI should make life better by making health intelligence accessible."
Anthropic Best Agent (Claude SDK)
Criterion: Autonomous AI application that tackles real problems.
How we meet this:
- Autonomous tool use: Claude agent chooses when to call each of 5 tools based on evidence quality.
- Real problem: Turning messy wearable data into trustworthy, evidence-based health intelligence.
- No hand-coded sequence: Agent dynamically plans pipeline each run.
Demo points: "The orchestrator is a Claude agent with 5 tools. It autonomously decides the pipeline, reasons about evidence, and only then writes reports."
OpenEvidence — Clinical Info & Healthcare Track
Criterion (Clinical Info): Convert clinical data into product that improves understanding/decision-making/care delivery. Criterion (Healthcare): Most innovative healthcare product.
How we meet this:
- Clinical data sources: PubMed (literature), BrightData (guidelines), Perplexity (consensus).
- Dual products:
- Patient report: Improves understanding (empathetic, actionable, clear next steps)
- Clinical report: Supports decision-making (GRADE evidence, screening suggestions, differential diagnosis)
- Innovation: Multi-agent AI + wearable data + evidence synthesis, strictly non-diagnostic.
Demo points: "We convert existing clinical data into two reports: one for patient understanding, one for clinician decision-making. That's healthcare innovation with clear boundaries."
TreeHacks Most Impactful
Criterion: Potential to create significant positive change or address pressing societal issue.
How we meet this:
- Early warning system: Sleep deviation as biomarker of systemic health drift before clinical disease.
- Preventive focus: Detect trajectory shifts early so people and providers can act sooner.
- Equity angle: Consumer wearable analysis accessible where sleep labs are scarce.
Impact statement: "SOMNI AI turns wearable data into evidence-based insights so people can spot patterns before they become disease — reducing healthcare burden and supporting preventive, equitable access to understanding."
Demo points: "We're not diagnosing — we're surfacing research-backed patterns early. That's preventive, person-centered, and reduces pressure on the system."
Vercel — Best Use of Vercel
Criterion: Best leverages Vercel to build, deploy, and scale production-ready app.
How we meet this:
- Single deployment: TypeScript sleep analysis (no Python backend required) — everything on Vercel.
- Next.js 14 App Router: Server components, API routes, serverless functions.
- Production-ready: Full deployment with caching and edge capabilities.
Demo points: "The whole app runs on Vercel — frontend and APIs. We ported sleep analysis to TypeScript so there's no separate backend. One deploy, production-ready."
BrightData — Best AI-Powered Web Hack
Criterion: Use BrightData in an innovative way.
How we meet this:
- Innovative use: Pull public health guidelines and disparity data (CDC/AHA-style) into agent pipeline.
- Value-add: Grounds recommendations in current guidelines; surfaces population-level context (disparities).
- Real usage:
BRIGHTDATA_API_KEYset in production; "BrightData: real" shown in UI.
Demo points: "BrightData feeds our agent with guideline and disparity datasets so recommendations align with public health guidance."
Perplexity — Best Use of Sonar API
Criterion: Build something extraordinary with Sonar; innovative use, technical excellence, real-world value.
How we meet this:
- Consensus + controversy: Agent asks Sonar for both consensus AND controversy in literature.
- Real-world value: Calibrates strength of claims in reports based on where evidence agrees/disagrees.
- Evidence synthesis: Sonar citations integrated into research foundation.
Demo points: "We use Perplexity Sonar as our consensus engine: we ask for consensus and controversy so reports reflect where the evidence agrees and where it doesn't."
📚 Using Demo Data
Test the system with the included sample:
# Use the 30-day Fitbit sample
public/demo_data/fitbit_30days.csv
Upload this file through the web interface to see the full analysis pipeline.
⚠️ Important Disclaimers
SOMNI AI is NOT a diagnostic tool. It:
- Does NOT diagnose medical conditions
- Does NOT provide medical advice
- Uses consumer wearable estimates (not clinical PSG)
- Shows research associations, not causation
Always consult healthcare providers for medical decisions.
🧪 Testing
# Python tests
cd python
pytest tests/ -v
# Type checking
npm run type-check
# Build verification
npm run build
📧 Contact
Built for TreeHacks 2026
MIT License - See LICENSE file
Analysis
View
Metric
- 5
- 2
- 2
Figures cover GitHub contributors during the hackathon window. A co-authored commit counts in full for each author, so per-member totals add up to more than the whole-team figures.
Technology
- AnthropicIn code
- CSSIn code
- FastAPIIn code
- JavaScriptIn code
- Next.jsIn code
- OpenAIIn code
- PythonIn code
- ReactIn code
- Tailwind CSSIn code
- TypeScriptIn code
- Vercel AI SDKIn code
- VercelClaimed
11 of 12 appear in the indexed code. 1 claimed on Devpost could not be matched to code, which may simply mean the tool leaves no trace in the repository.
AI coding agents
- Claude CodeCommits
Detected from committed agent config files and commit authorship. Absence of a signal is not proof an agent was unused.
Codebase size
Source size
280 KB
Source files
54
Counts recognized source files only; vendored directories, binaries and lockfiles are excluded, so this is smaller than the repository on disk.
Repository
KartikeyaGoel/treehacks
69 files · 18.6 MB · @ 408c283
Structure
Interface
11 files · 16%Screens, components and styles rendered to the user.
API & routing
6 files · 9%Request entry points: routes, handlers and controllers.
Application logic
21 files · 30%Domain rules, services and shared utilities.
+2 more
Supporting
Layers are inferred from where files sit in the tree, not from reading the code. A project that names its directories unconventionally will read oddly here — open the file browser to check anything the diagram implies.
Languages
- TypeScript57%
- Markdown29%
- Python12%
- CSS1%
- JavaScript1%
- Shell0%
Share of indexed source by file size. Binary and vendored files are excluded.
Dependencies
package.json
npm · 42- @anthropic-ai/sdk
- @radix-ui/react-alert-dialog
- @radix-ui/react-dialog
- @radix-ui/react-dropdown-menu
- @radix-ui/react-label
- @radix-ui/react-progress
- @radix-ui/react-separator
- @radix-ui/react-slot
- @radix-ui/react-toast
- @react-pdf/renderer
- @vercel/kv
- ai
- class-variance-authority
- clsx
- fast-xml-parser
- lucide-react
- nanoid
- next
- +24 more
python/requirements.txt
pypi · 15- fastapi
- httpx
- lxml
- numpy
- pandas
- pydantic
- pydantic-settings
- pytest
- pytest-asyncio
- pytest-cov
- python-dotenv
- python-multipart
- scipy
- statsmodels
- uvicorn[standard]
Declared in the repository’s manifests at the indexed commit. A declared package is not proof it is used, and runtime dependencies are listed first.
This project’s features have not been analysed yet.
Export this project's context (description, README, evidence, key source files) to chat with an AI agent elsewhere.