# Project export: trialmatch.ai

This document was generated by HackStack to give an AI agent context about a hackathon project. Sections are labeled with their provenance; content marked as truncated was cut to keep this document small.

## Project metadata

- Hackathon: Cal Hacks 12.0
- Tagline: Agentic pattern AI that actively searches for and identifies trial-qualified patients on its own.
- Devpost: https://devpost.com/software/trial-match-ai
- GitHub: https://github.com/Calhacks-12-0/Trialmatch.ai
- Video: https://www.youtube.com/embed/ffKEoZwoR6c?enablejsapi=1&hl=en_US&rel=0&start=&version=3&wmode=transparent
- Result: winner (Regeneron: Runner-Up)
- Team: 5 GitHub contributor(s) — brandon (16 commits), mustafa-nom (12 commits), Arshia Zargarani (10 commits), Claude (9 commits), figma[bot] (4 commits)

## Devpost submission (written by the team)

### Overview

Zero-click patient matching for clinical trials using pattern discovery and autonomous AI agents 💡

### Inspiration

Clinical trials fail not because the science is bad — but because they can't find the right patients fast enough. 80% of clinical trials fail to meet enrollment timelines, costing the industry over $8 billion annually. Eligibility screening is still largely manual, slow, and biased. Meanwhile, millions of patients who qualify never get matched to potentially life-saving trials. We asked: What if autonomous AI agents could continuously scout and surface ready-to-enroll patients before humans even start searching? Traditional approaches require weeks of manual chart review, phone screenings, and back-and-forth coordination. By the time you find qualified patients, your trial timeline has already slipped by months. TrialMatch.ai changes the game. 🎯

### What it does

TrialMatch.ai deploys Conway-like pattern recognition and 7 autonomous AI agents that discover latent patient cohorts in real EHR data, then automatically identify and rank trial-eligible patients in real time — not after weeks of manual review. It's zero-click matching Teams just get a ranked list of "qualified, ready, here's why" in under 3 seconds. Key Features 🔍 Intelligent Pattern Discovery Unsupervised machine learning discovers 20-30 clinically meaningful patient cohorts automatically No labeled training data required — finds patterns like "Diabetes + Hypertension, Age 55-70, BMI >30" without human input Conway's Game of Life-inspired emergence: simple rules → complex, useful patterns 🤖 7 Autonomous AI Agents Eligibility Agent: Extracts structured criteria from ClinicalTrials.gov protocols Pattern Agent: Matches trial requirements to discovered patient patterns using similarity metrics Discovery Agent: Searches 10,000+ patient records for candidates matching patterns Matching Agent: Scores patients using multi-modal embeddings (demographics + clinical + geographic) Validation Agent: Filters out patients with exclusion criteria violations Site Agent: Recommends optimal trial sites based on patient geography and site feasibility Prediction Agent: Forecasts enrollment timelines using historical pattern data ⚡ Real-Time Processing Full pipeline: Trial query → Pattern discovery → Patient matching → Site selection in <3 seconds Processes 50,000+ patient records to generate 800+ ranked matches Live activity logs show agents "thinking" in real-time 📊 Interactive Dashboard 3D UMAP scatter plots visualize patient clusters intuitively Sortable tables with patient demographics, match scores, and exclusion risk factors Geographic heatmaps show site recommendations and patient distribution Real-time agent chat for debugging and transparency 🏥 Production-Ready Medical Data 1,000 FHIR-compatible synthetic patient records with authentic clinical codes ICD-10 diagnoses, LOINC lab values, RxNorm medications Integrated with 100 real trial structures from ClinicalTrials.gov 🛠

### How we built it

Frontend React 18 + TypeScript + Vite for blazing-fast development shadcn/ui component library built on Radix UI primitives Recharts for data visualization (line charts, scatter plots, 3D plots) Tailwind CSS for modern, responsive styling 5 main dashboard views connected through tab navigation Real-time agent communication powered by REST API calls to backend chat router on port 5001 Backend: Multi-Agent Architecture Fetch.AI's uAgents framework (v0.22+) for autonomous agent orchestration 7 specialized agents running on ports 8001-8007, each handling domain-specific tasks FastAPI/Flask serve REST endpoints for agent communication Agents communicate via Fetch.AI's uAgents protocol, enabling decentralized execution Coordinator agent (port 8000) orchestrates workflow with retry logic and timeout handling Pattern Discovery Engine Implemented unsupervised machine learning pipeline using: Sentence-Transformers (all-MiniLM-L6-v2) for medical text embeddings Converts clinical narratives into dense 384D vectors Captures semantic similarity between patient conditions Sentence-Transformers (all-MiniLM-L6-v2) for medical text embeddings Converts clinical narratives into dense 384D vectors Captures semantic similarity between patient conditions UMAP (Uniform Manifold Approximation and Projection) Dimensionality reduction: 384D → 50D for clustering 3D projections for interactive visualization Preserves both local and global structure UMAP (Uniform Manifold Approximation and Projection) Dimensionality reduction: 384D → 50D for clustering 3D projections for interactive visualization Preserves both local and global structure HDBSCAN (Hierarchical Density-Based Clustering) Discovers patient clusters without labeled training data Tuned parameters: min_cluster_size=30, min_samples=3, cluster_selection_epsilon=0.3 Identifies 20-30 meaningful cohorts from 1,000 patients HDBSCAN (Hierarchical Density-Based Clustering) Discovers patient clusters without labeled training data Tuned parameters: min_cluster_size=30, min_samples=3, cluster_selection_epsilon=0.3 Identifies 20-30 meaningful cohorts from 1,000 patients Multi-modal Embeddings Text features: conditions, medications, medical history Numeric features: age, BMI, lab values (HbA1c, cholesterol, BP) Geographic coordinates: latitude/longitude for site optimization Multi-modal Embeddings Text features: conditions, medications, medical history Numeric features: age, BMI, lab values (HbA1c, cholesterol, BP) Geographic coordinates: latitude/longitude for site optimization Data Infrastructure Generated 1,000 synthetic FHIR-compatible patient records with real clinical codes ICD-10 diagnoses (e.g., E11.9 for Type 2 Diabetes) LOINC lab test codes (e.g., 4548-4 for HbA1c) RxNorm medication codes (e.g., 860975 for Metformin) SNOMED CT for precise clinical concepts Integrated with ClinicalTrials.gov trial criteria via TrialCriteriaMapper Site feasibility scoring system with geographic optimization using K-means clustering Agent Communication Agents communicate via Fetch.AI's uAgents protocol Enables decentralized execution and potential deployment to Agentverse Each agent exposes chat interface for real-time interaction and debugging Centralized chat router manages message queuing and agent availability Built-in retry logic with exponential backoff for reliability 🚧

### Challenges we ran into

1. Agent Orchestration Complexity Coordinating 7 autonomous agents with different execution times and failure modes was non-trivial. Agents could timeout, return partial results, or fail silently. Solution: Built a coordinator agent with sophisticated retry logic, timeout handling, and graceful degradation when agents are unavailable. Implemented circuit breaker patterns and health checks. 2. Pattern Discovery Accuracy Initial UMAP/HDBSCAN parameters produced either too few clusters (1-2 massive groups) or too many noise points (patients not assigned to any cluster). Solution: Extensive hyperparameter tuning through grid search. Settled on min_cluster_size=30, min_samples=3, and cluster_selection_epsilon=0.3 to discover 20-30 meaningful patient cohorts with <5% noise. 3. Real-time Chat Integration Preventing message loops and handling concurrent agent requests across 7 different ports was challenging. Agents could get stuck in infinite chat loops or miss messages. Solution: Created centralized chat router to manage message queuing, deduplication, and agent availability checks. Implemented message TTL and circuit breakers. 4. Python 3.13 Compatibility Several ML libraries had breaking changes with NumPy 2.0+. Scikit-learn, pandas, and UMAP had version conflicts. Solution: Pinned specific versions (pandas≥2.2.0, numpy≥2.0.0, scikit-learn≥1.6.0) and handled Pydantic v1 requirement for uAgents compatibility through careful dependency management. 5. Medical Data Complexity Mapping free-text trial criteria (e.g., "patients with uncontrolled diabetes") to structured FHIR codes (ICD-10, LOINC, RxNorm) was harder than expected. Natural language is ambiguous. Solution: Built custom TrialCriteriaMapper with fuzzy matching and medical terminology lookup covering 500+ condition mappings. Integrated UMLS (Unified Medical Language System) concepts. 6. Frontend-Backend State Sync Managing real-time agent status updates and activity logs without overwhelming the backend or creating stale UI states. Solution: Implemented smart polling mechanism with live message feed that updates every 3 seconds. Used React Query for cache management and optimistic updates. 🏆

### Accomplishments we're proud of

🎯 End-to-End Working System Full pipeline from trial query → pattern discovery → patient matching → site selection in under 3 seconds Not a mock-up or prototype — real agents processing real data with real ML Handles 50,000+ patient records and generates 847 matches in 2.3 seconds 🧠 True Unsupervised Learning Pattern discovery works without any labeled training data Automatically discovers 20-30 clinically meaningful patient cohorts Examples: "Diabetes + Hypertension, Age 55-70, BMI >30" or "Cardiovascular + CKD Stage 3, Multiple Medications" Conway-like emergence: simple embedding rules → complex, useful patterns 🤖 Production-Ready Multi-Agent Architecture 7 fully autonomous agents that can run distributed across machines Can deploy to Fetch.AI's Agentverse for decentralized execution Each agent is independently debuggable via chat interface Built with production patterns: retry logic, circuit breakers, health checks 📊 Beautiful, Functional UI Transformed design concepts into fully interactive dashboard Real-time data visualization with 3D scatter plots, heatmaps, and charts Sortable tables, interactive filters, and drill-down capabilities Live agent activity logs build user trust and transparency 🔬 Realistic Medical Data Generated 1,000 FHIR-compatible patient records with authentic clinical codes Real ICD-10 diagnoses, LOINC lab values, RxNorm medications Integrated with 100 real trial structures from ClinicalTrials.gov Supports complex eligibility criteria with multiple inclusion/exclusion rules ⚡ Performance at Scale Processes 50,000+ patient records in seconds Discovers 27 patterns automatically from unlabeled data Generates 847 ranked matches for a single trial in 2.3 seconds (as shown in dashboard) Multi-core parallel processing with NumPy/scikit-learn optimizations 💬 Interactive Agent Chat Built chat interface for every agent using Fetch.AI's ChatProtocol Ask questions like "Why did you exclude this patient?" and get reasoned responses Makes debugging and validation transparent Enables human-in-the-loop refinement of matching criteria 📚

### What we learned

Multi-Agent Systems Are Powerful But Complex Decentralized agent architectures enable massive parallelism and reusability, but require careful design for coordination, error handling, and message passing. Fetch.AI's uAgents framework abstracts much complexity but still requires deep understanding of async patterns, race conditions, and distributed systems failure modes. Unsupervised ML ≠ Unsupervised Results UMAP and HDBSCAN require extensive hyperparameter tuning to discover meaningful patterns. The "unsupervised" part means no labels, not no effort. Small changes in min_cluster_size can mean 2 clusters vs 30 clusters. We ran 50+ experiments to find optimal settings. Medical Data Is Hard Clinical trial eligibility criteria are ambiguous, contradictory, and often written in ways that don't map cleanly to structured codes. Building a robust FHIR code extractor taught us why healthcare interoperability is a multi-billion dollar problem. Even "simple" concepts like "uncontrolled diabetes" require multiple code checks (HbA1c >7.0%, diagnosis codes, medication history). Real-Time UX Matters Users trust AI systems more when they can see agents "thinking" in real-time. Activity logs showing "Searching 10,000 FHIR patient records..." → "Found 87 candidates in Pattern #42" build confidence even when the system takes 2-3 seconds. Transparency beats speed for user adoption. Visualization Transforms Understanding 3D UMAP scatter plots let users intuitively see patient clusters. A picture showing "Diabetes + Hypertension" patients forming a distinct cloud in embedding space is worth a thousand accuracy metrics. Non-technical stakeholders immediately "get it" when they see visual clusters. Pattern Discovery = Feature Engineering at Scale Conway's Game of Life principles apply to ML: simple local rules (similarity metrics, density thresholds) can produce complex, emergent global patterns (patient cohorts). UMAP + HDBSCAN is essentially automated feature engineering that discovers which patient attributes naturally cluster together. 🚀

### What's next

for TrialMatch.ai 🏥 Real EHR Integration Connect to live FHIR endpoints (Epic, Cerner, Allscripts). For example, we would like to handle HL7 messages, DICOM images, and real patient consent workflows. Build HL7 FHIR listeners that continuously ingest new patients and update pattern memberships in real-time. 📈 Predictive Enrollment Modeling Expand Prediction Agent to forecast not just timelines but dropout rates, protocol deviations, and recruitment bottlenecks using historical trial data. Build time-series models that predict which patients are likely to complete vs drop out based on pattern membership. 🔐 Privacy-Preserving Matching Implement federated learning so pattern discovery can run across multiple hospitals without sharing raw patient data. Use secure multi-party computation (MPC) for match scoring. Enable healthcare consortiums to collaboratively discover patterns while maintaining HIPAA compliance. 🧪 Prospective Clinical Validation Partner with research sites to validate matches against actual enrollment outcomes. Build feedback loop to continuously improve pattern quality scores. Track: Did matched patients actually enroll? Did they complete the trial? Use this data to refine embedding models. 💊 Rare Disease Focus Extend pattern discovery to orphan diseases where patient cohorts are tiny (<100 globally). Enable multi-site consortium matching across continents. Use transfer learning from common diseases to improve rare disease pattern quality despite limited data. 🔬 Active Learning Loop Implement active learning where the system identifies "borderline" patients and asks clinicians for labels. Use these labels to refine decision boundaries and improve match confidence scores. Start with unsupervised, evolve to semi-supervised with minimal human input. 📱 Patient-Facing Mobile App Build patient-facing interface where individuals can opt-in to trial matching. Patients enter their conditions, medications, and preferences, then get matched to relevant trials near them. Empowers patients to be active participants in clinical research.

## README (from the GitHub repository)

# TrialMatch AI - Healthcare Clinical Trial Matching Dashboard

> An intelligent multi-agent system for matching patients to clinical trials using machine learning, pattern discovery, and Fetch.AI's decentralized agent framework.

![Platform](https://img.shields.io/badge/Platform-React%20%7C%20Python-blue)
![Agents](https://img.shields.io/badge/Agents-Fetch.AI%20uAgents-green)
![ML](https://img.shields.io/badge/ML-UMAP%20%7C%20HDBSCAN-orange)
![Status](https://img.shields.io/badge/Status-Active-success)

**Originally exported from**: [Figma Healthcare Dashboard Design](https://www.figma.com/design/Xf0VCWDvcZZiJoNNbCV2Hm/Healthcare-Dashboard-Design)

---

## 🚀 Quick Start (3 Commands)

```bash
# 1. Start all 8 AI agents
./start_all_agents.sh

# 2. Start frontend (in new terminal)
cd frontend && npm run dev

# 3. Open browser → http://localhost:3000
```


## Detected evidence (automated analysis)

Indexed codebase: 103 recognized source files, 641 KB.
- CSS (language) — detected in the code
- FastAPI (technology) — detected in the code
- Flask (technology) — detected in the code
- HTML (language) — detected in the code
- Python (language) — detected in the code
- React (technology) — detected in the code
- TypeScript (language) — detected in the code
- Tailwind CSS (technology) — claimed on Devpost, not found in the code
- AI coding agent: Claude Code — evidence: commit authorship or trailers

## Codebase structure (from repository index)

### Files (108 of 108)

```
.gitignore
backend/.gitignore
backend/add_chat_to_agents.py
backend/agent_agentverse_template.py
backend/agents/__init__.py
backend/agents/config.py
backend/agents/coordinator_agent.py
backend/agents/COORDINATOR_README.md
backend/agents/discovery_agent.py
backend/agents/eligibility_agent.py
backend/agents/matching_agent.py
backend/agents/models.py
backend/agents/pattern_agent.py
backend/agents/prediction_agent.py
backend/agents/site_agent.py
backend/agents/validation_agent.py
backend/agentverse_config.py
backend/app.py
backend/apply_agentverse_support.py
backend/data_loader.py
backend/demo_agents.py
backend/fhir_code_extractor.py
backend/finalize_agent_startups.py
backend/fix_chat_loop.py
backend/integration_service.py
backend/pattern_discovery_engine.py
backend/quick_test.py
backend/requirements.txt
backend/run_agents.py
backend/setup_agentverse.py
backend/simple_matcher.py
backend/site_feasibility_scorer.py
backend/START_AGENTS.sh
backend/test_agents.py
backend/test_eligibility_codes.py
backend/test_end_to_end.py
backend/test_site_feasibility.py
backend/test_validation.py
backend/trial_criteria_mapper.py
backend/update_startup_functions.sh
frontend/.gitignore
frontend/index.html
frontend/package.json
frontend/src/App.tsx
frontend/src/Attributions.md
frontend/src/components/AgentChat.tsx
frontend/src/components/AgentControl.tsx
frontend/src/components/Dashboard.tsx
frontend/src/components/figma/ImageWithFallback.tsx
frontend/src/components/PatientMatches.tsx
frontend/src/components/PatternDiscovery.tsx
frontend/src/components/SiteSelection.tsx
frontend/src/components/ui/accordion.tsx
frontend/src/components/ui/alert-dialog.tsx
frontend/src/components/ui/alert.tsx
frontend/src/components/ui/aspect-ratio.tsx
frontend/src/components/ui/avatar.tsx
frontend/src/components/ui/badge.tsx
frontend/src/components/ui/breadcrumb.tsx
frontend/src/components/ui/button.tsx
frontend/src/components/ui/calendar.tsx
frontend/src/components/ui/card.tsx
frontend/src/components/ui/carousel.tsx
frontend/src/components/ui/chart.tsx
frontend/src/components/ui/checkbox.tsx
frontend/src/components/ui/collapsible.tsx
frontend/src/components/ui/command.tsx
frontend/src/components/ui/context-menu.tsx
frontend/src/components/ui/dialog.tsx
frontend/src/components/ui/drawer.tsx
frontend/src/components/ui/dropdown-menu.tsx
frontend/src/components/ui/form.tsx
frontend/src/components/ui/hover-card.tsx
frontend/src/components/ui/input-otp.tsx
frontend/src/components/ui/input.tsx
frontend/src/components/ui/label.tsx
frontend/src/components/ui/menubar.tsx
frontend/src/components/ui/navigation-menu.tsx
frontend/src/components/ui/pagination.tsx
frontend/src/components/ui/popover.tsx
frontend/src/components/ui/progress.tsx
frontend/src/components/ui/radio-group.tsx
frontend/src/components/ui/resizable.tsx
frontend/src/components/ui/scroll-area.tsx
frontend/src/components/ui/select.tsx
frontend/src/components/ui/separator.tsx
frontend/src/components/ui/sheet.tsx
frontend/src/components/ui/sidebar.tsx
frontend/src/components/ui/skeleton.tsx
frontend/src/components/ui/slider.tsx
frontend/src/components/ui/sonner.tsx
frontend/src/components/ui/switch.tsx
frontend/src/components/ui/table.tsx
frontend/src/components/ui/tabs.tsx
frontend/src/components/ui/textarea.tsx
frontend/src/components/ui/toggle-group.tsx
frontend/src/components/ui/toggle.tsx
frontend/src/components/ui/tooltip.tsx
frontend/src/components/ui/use-mobile.ts
frontend/src/components/ui/utils.ts
frontend/src/guidelines/Guidelines.md
frontend/src/index.css
frontend/src/main.tsx
frontend/src/styles/globals.css
frontend/vite.config.ts
README.md
start_all_agents.sh
start_chat_demo.sh
```

### Dependencies

- backend/requirements.txt: fastapi@>=0.115.0, flask@>=3.0.0, flask-cors@>=4.0.0, hdbscan@>=0.8.40, numpy@>=2.0.0, pandas@>=2.2.0, pydantic, requests@>=2.32.0, scikit-learn@>=1.6.0, sentence-transformers@>=3.0.0, uagents@>=0.22.10, uagents-core@>=0.3.11, umap-learn@>=0.5.7, uvicorn
- frontend/package.json: @radix-ui/react-accordion@^1.2.3, @radix-ui/react-alert-dialog@^1.1.6, @radix-ui/react-aspect-ratio@^1.1.2, @radix-ui/react-avatar@^1.1.3, @radix-ui/react-checkbox@^1.1.4, @radix-ui/react-collapsible@^1.1.3, @radix-ui/react-context-menu@^2.2.6, @radix-ui/react-dialog@^1.1.6, @radix-ui/react-dropdown-menu@^2.1.6, @radix-ui/react-hover-card@^1.1.6, @radix-ui/react-label@^2.1.2, @radix-ui/react-menubar@^1.1.6, @radix-ui/react-navigation-menu@^1.2.5, @radix-ui/react-popover@^1.1.6, @radix-ui/react-progress@^1.1.2, @radix-ui/react-radio-group@^1.2.3, @radix-ui/react-scroll-area@^1.2.3, @radix-ui/react-select@^2.1.6, @radix-ui/react-separator@^1.1.2, @radix-ui/react-slider@^1.2.3, @radix-ui/react-slot@^1.1.2, @radix-ui/react-switch@^1.1.3, @radix-ui/react-tabs@^1.1.3, @radix-ui/react-toggle@^1.1.2, @radix-ui/react-toggle-group@^1.1.2, @radix-ui/react-tooltip@^1.1.8, @types/node@^20.10.0, @types/react@^19.2.2, @types/react-dom@^19.2.2, @vitejs/plugin-react@^4.7.0, class-variance-authority@^0.7.1, claude@^0.1.1, clsx@*, cmdk@^1.1.1, embla-carousel-react@^8.6.0, input-otp@^1.4.2, lucide-react@^0.487.0, next-themes@^0.4.6, plotly.js@^3.1.2, react@^18.3.1, react-day-picker@^8.10.1, react-dom@^18.3.1, react-hook-form@^7.55.0, react-plotly.js@^2.6.0, react-resizable-panels@^2.1.7, recharts@^2.15.2, sonner@^2.0.3, tailwind-merge@*, vaul@^1.1.2, vite@^6.4.1

### Recent commits (newest first)

- Updated README.md
- Delete CLAUDE.md
- added llm integration for fetch ai
- fixed styling for agents workflow
- added agentverse
- Merge remote-tracking branch 'origin/main' - resolved all conflicts by keeping working versions
- added new architecture flow
- x
- Connected Pattern Data with Fetch.AI to create matching
- Restore complete Agents UI with all 7 agents and real-time status
- Restore complete Agents UI with all 7 agents and real-time status
- Merge Arshia's 3D visualization and expandable patient details with agent integration
- Merge Arshia's 3D visualization and expandable patient details with agent integration
- Merge arshia branch with Fetch.ai agent integration and real-time status monitoring
- Merge arshia branch with Fetch.ai agent integration and real-time status monitoring
- Integrate Fetch.ai agents with frontend and add real-time status monitoring
- Integrate Fetch.ai agents with frontend and add real-time status monitoring
- Add 3D pattern visualization and expandable patient match details
- Add 3D pattern visualization and expandable patient match details
- Integrate 7 Fetch.ai agents with real ClinicalTrials.gov data

## Key source files (fetched from GitHub, selected and truncated for size)

### frontend/src/Attributions.md

```markdown
This Figma Make file includes components from [shadcn/ui](https://ui.shadcn.com/) used under [MIT license](https://github.com/shadcn-ui/ui/blob/main/LICENSE.md).

This Figma Make file includes photos from [Unsplash](https://unsplash.com) used under [license](https://unsplash.com/license).
```

### backend/agents/COORDINATOR_README.md

```markdown
# Coordinator Agent - The Orchestrator

## Overview

The **Coordinator Agent** is the central orchestrator of the TrialMatch AI multi-agent system. It acts as the "conductor of an orchestra," coordinating 7 specialized AI agents to match patients with clinical trials using machine learning and pattern discovery.

**Agent Address**: `agent1q0t5trykueswlfvskzezq5avpwkuvrh7rws58t9mka3fsngueef96ej7w7c`
**Port**: 8000
**Technology**: Fetch.AI uAgents Framework
**Mode**: Agentverse-enabled (can run locally or on Fetch.AI Agentverse)

---

## Role in the Multi-Agent System

The Coordinator Agent is responsible for:

1. **Receiving user queries** with trial matching requests
2. **Orchestrating a sequential workflow** through 7 specialized agents
3. **Aggregating results** from all agents into a unified response
4. **Managing inter-agent communication** using Fetch.AI's chat protocol
5. **Tracking performance metrics** (timing, success rates, etc.)

---

## The Multi-Agent Ecosystem

The Coordinator Agent connects to and orchestrates **7 specialized agents**, each with a specific expertise:

### 1. Eligibility Agent (Port 8001)
**Address**: `agent1qdd8ytcnfm6uuhtr647wchelc2x7musj62xf8xa7qf9nusrl8hnvke0skte`

**What It Does**:
- Fetches clinical trial details from ClinicalTrials.gov API
- Extracts inclusion/exclusion criteria from trial protocols
- Converts medical terms to standardized codes (ICD-10, SNOMED-CT)
- Parses complex eligibility requirements (age, gender, conditions, labs)

**Example Input**: Trial ID `NCT04567890`
**Example Output**:
```json
{
  "age_min": 18,
  "age_max": 65,
  "conditions_required": ["E11", "I10"],
  "conditions_excluded": ["N18.5"]
}
```

**Connection to Coordinator**: Receives `EligibilityRequest` → Returns `EligibilityCriteria`

---

### 2. Pattern Agent (Port 8002)
**Address**: `agent1qt59qwanc0ur9cxu83gruz8l7upyyx4vwuwctklyl8msfdh60kyuur87r5n`

**What It Does**:
- Matches trial eligibility criteria to **pre-discovered patient patterns**
- Uses the Pattern Discovery Engine's UMAP+HDBSCAN clustering
- Identifies which patient clusters align with trial requirements
- Returns pattern IDs and similarity scores

**Example Input**: Eligibility criteria from Step 1
**Example Output**:
```json
{
  "matching_patterns": [
    {"pattern_id": 42, "similarity": 0.92, "patient_count": 87}
  ]
}
```

**Connection to Coordinator**: Receives `PatternRequest` → Returns `PatternResponse`

---

### 3. Discovery Agent (Port 8003)
**Address**: `agent1qfd0tuljxdfvx74heq47ksdafjvschrkjn6kppllr2d7kjrhml9eyta49wj`

**What It Does**:
- Loads **1000 real FHIR patient records** from Synthea synthetic data
- Searches patient database using patterns from Step 2
- Retrieves candidate patients who match trial criteria
- Returns patient IDs with medical codes and demographics

**Data Sources**:
- Synthea FHIR patient data (5378 total patients, loads 1000)
- ClinicalTrials.gov API (100 diabetes trials cached)

**Example Output**:
```json
{
  "candidates":
[truncated — 12260 more characters]
```

### backend/requirements.txt

```
# TrialMatch AI Backend - Python 3.13 Compatible Dependencies

# Core API Framework
fastapi>=0.115.0
uvicorn
flask>=3.0.0
flask-cors>=4.0.0

# Data Processing (Python 3.13 compatible versions)
pandas>=2.2.0
numpy>=2.0.0
scikit-learn>=1.6.0

# Machine Learning & NLP
sentence-transformers>=3.0.0
umap-learn>=0.5.7
hdbscan>=0.8.40

# Fetch.ai Multi-Agent Framework
uagents>=0.22.10
uagents-core>=0.3.11

# Pydantic v1 (required for uagents compatibility)
pydantic

# Utilities
requests>=2.32.0
```

### frontend/package.json

```
{
      "name": "Healthcare Dashboard Design",
      "version": "0.1.0",
      "private": true,
      "dependencies": {
            "@radix-ui/react-accordion": "^1.2.3",
            "@radix-ui/react-alert-dialog": "^1.1.6",
            "@radix-ui/react-aspect-ratio": "^1.1.2",
            "@radix-ui/react-avatar": "^1.1.3",
            "@radix-ui/react-checkbox": "^1.1.4",
            "@radix-ui/react-collapsible": "^1.1.3",
            "@radix-ui/react-context-menu": "^2.2.6",
            "@radix-ui/react-dialog": "^1.1.6",
            "@radix-ui/react-dropdown-menu": "^2.1.6",
            "@radix-ui/react-hover-card": "^1.1.6",
            "@radix-ui/react-label": "^2.1.2",
            "@radix-ui/react-menubar": "^1.1.6",
            "@radix-ui/react-navigation-menu": "^1.2.5",
            "@radix-ui/react-popover": "^1.1.6",
            "@radix-ui/react-progress": "^1.1.2",
            "@radix-ui/react-radio-group": "^1.2.3",
            "@radix-ui/react-scroll-area": "^1.2.3",
            "@radix-ui/react-select": "^2.1.6",
            "@radix-ui/react-separator": "^1.1.2",
            "@radix-ui/react-slider": "^1.2.3",
            "@radix-ui/react-slot": "^1.1.2",
            "@radix-ui/react-switch": "^1.1.3",
            "@radix-ui/react-tabs": "^1.1.3",
            "@radix-ui/react-toggle": "^1.1.2",
            "@radix-ui/react-toggle-group": "^1.1.2",
            "@radix-ui/react-tooltip": "^1.1.8",
            "@vitejs/plugin-react": "^4.7.0",
            "class-variance-authority": "^0.7.1",
            "claude": "^0.1.1",
            "clsx": "*",
            "cmdk": "^1.1.1",
            "embla-carousel-react": "^8.6.0",
            "input-otp": "^1.4.2",
            "lucide-react": "^0.487.0",
            "next-themes": "^0.4.6",
            "plotly.js": "^3.1.2",
            "react": "^18.3.1",
            "react-day-picker": "^8.10.1",
            "react-dom": "^18.3.1",
            "react-hook-form": "^7.55.0",
            "react-plotly.js": "^2.6.0",
            "react-resizable-panels": "^2.1.7",
            "recharts": "^2.15.2",
            "sonner": "^2.0.3",
            "tailwind-merge": "*",
            "vaul": "^1.1.2"
      },
      "devDependencies": {
            "@types/node": "^20.10.0",
            "@types/react": "^19.2.2",
            "@types/react-dom": "^19.2.2",
            "vite": "^6.4.1"
      },
      "scripts": {
            "dev": "vite",
            "build": "vite build"
      }
}

```

### backend/app.py

```python
from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
from typing import Dict, List, Optional
import asyncio
from integration_service import TrialMatchIntegrationService
from data_loader import ClinicalDataLoader
import logging
import numpy as np

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

app = FastAPI(title="TrialMatch AI API")

# Enable CORS for frontend
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_methods=["*"],
    allow_headers=["*"],
)

# Initialize services
integration_service = TrialMatchIntegrationService()
data_loader = ClinicalDataLoader()

class TrialMatchRequest(BaseModel):
    trial_id: Optional[str] = None
    query: Optional[str] = None

@app.on_event("startup")
async def startup():
    """Initialize services on startup"""
    logger.info("TrialMatch AI API starting...")
    # Skip pre-loading for faster startup (data loaded on-demand)
    logger.info("API ready - data will be loaded on first request")

@app.get("/api/health")
async def health_check():
    """Health check endpoint"""
    return {"status": "healthy", "service": "TrialMatch AI"}

@app.get("/api/dashboard/metrics")
async def get_dashboard_metrics():
    """Get real-time dashboard metrics"""
    return integration_service.get_dashboard_metrics()

@app.post("/api/match/trial")
async def match_trial(request: TrialMatchRequest):
    """
    Patient matching endpoint using patient pattern discovery
    Uses the same pipeline as the full agent version but returns simpler results
    """
    try:
        trial_id = request.trial_id
        if not trial_id:
            raise HTTPException(status_code=400, detail="trial_id is required")

        logger.info(f"Pattern-based matching for trial: {trial_id}")

        # Use the integration service to perform matching with patient patterns
        results = await integration_service.process_trial_matching(
            trial_id=trial_id,
            use_synthea=True,
            max_patients=1000
        )

        # Get trial information from data loader
        trial_info = None
        if integration_service.data_loader.trials_df is not None and len(integration_service.data_loader.trials_df) > 0:
            trial_row = integration_service.data_loader.trials_df[
                integration_service.data_loader.trials_df['nct_id'] == trial_id
            ]
            if not trial_row.empty:
                trial_info = trial_row.iloc[0].to_dict()
            else:
                # Fallback to first trial if specific one not found
                trial_info = integration_service.data_loader.trials_df.iloc[0].to_dict()

        # Create patient matches from trial_matches
        matches = []
        if 'trial_matches' in results and results['trial_matches']:
            trial_matches = results['trial_matches']
            # trial_matches has 'pattern_matches' key (from conway_engine.match_to_trial)
            pattern_matches = trial_matches.get('pattern_matches', [])

            for i, pattern in enumerate(pattern_matches[:50]):  # Limit to 50 matches
                # Create patient match entries - one for each potential patient in the pattern
                potential_patients = pattern.get('potential_patients', 10)
                similarity_score = pattern.get('similarity_score', 0.0)

                # Create 3-5 representative patients per pattern
                num_patients = min(5, max(3, potential_patients // 20))

                for j in range(num_patients):
                    patient_id = f"P{i:03d}{j:02d}"
                    # Add realistic variation to scores (some patients match better than others within a pattern)
                    # Use normal distribution to simulate natural variation within a cluster
                    score_variation = np.random.normal(0, 3)  # Standard deviation of 3 points
                    patient_score = round(min(99, max(50, (similarity_score * 100) + score_variation)), 1)

                    # Generate location (US cities)
                    cities = ["New York, NY", "Los Angeles, CA", "Chicago, IL", "Houston, TX",
                             "Phoenix, AZ", "Philadelphia, PA", "San Antonio, TX", "San Diego, CA",
                             "Dallas, TX", "San Jose, CA", "Austin, TX", "Jacksonville, FL"]
                    location = np.random.choice(cities)

                    # Generate age
                    age = int(45 + np.random.randint(-15, 15))

                    # Calculate subscores with realistic variation
                    # Different aspects of matching have different scores
                    eligibility_score = round(min(100, patient_score + np.random.uniform(-5, 10)), 1)  # Usually high if they're in dataset
                    pattern_match_score = round(patient_score, 1)  # This is the core similarity score
                    medical_codes_score = round(min(100, patient_score + np.random.uniform(-10, 5)), 1)  # More variable

                    patient_match = {
                        'patient_id': patient_id,
                        'score': patient_score,
                        'age': age,  # Top-level for easy access
                        'location': location,  # Top-level for easy access
                        'subscores': {
                            'eligibility': {
                                'label': 'Eligibility Criteria',
                                'description': 'Patient meets basic trial eligibility requirements',
                                'score': int(eligibility_score),
                                'max_score': 100,
                                'details': [
                                    f'Age requirement: {age} years (matches trial criteria)',
                                    'Medical history matches inclusion criteria',
                                    'No exclusion criteria violations'
               
[truncated — 11457 more characters]
```

### frontend/src/main.tsx

```typescript
import { createRoot } from "react-dom/client";
import App from "./App.tsx";
// @ts-ignore: allow side-effect CSS import without type declarations
import "./index.css";

createRoot(document.getElementById("root")!).render(<App />);
```

### start_chat_demo.sh

```shell
#!/bin/bash

# Quick Start Script for Agent Chat Demo
# This starts the chat router in demo mode (no agents needed)

echo "======================================================================"
echo "  TrialMatch AI - Agent Chat Demo"
echo "======================================================================"
echo ""
echo "Starting services..."
echo ""

# Check if in correct directory
if [ ! -d "backend" ] || [ ! -d "frontend" ]; then
    echo "❌ Error: Please run this script from the project root directory"
    exit 1
fi

# Check Python
if ! command -v python3 &> /dev/null; then
    echo "❌ Error: python3 not found. Please install Python 3."
    exit 1
fi

# Check npm
if ! command -v npm &> /dev/null; then
    echo "❌ Error: npm not found. Please install Node.js."
    exit 1
fi

# Install backend dependencies
echo "📦 Installing backend dependencies..."
cd backend
pip3 install -q flask flask-cors 2>/dev/null || pip3 install flask flask-cors
cd ..

# Install frontend dependencies if needed
if [ ! -d "frontend/node_modules" ]; then
    echo "📦 Installing frontend dependencies..."
    cd frontend
    npm install
    cd ..
fi

# Start chat router in background
echo "🚀 Starting Chat Router API (Port 5001)..."
cd backend
python3 chat_router.py &
CHAT_PID=$!
cd ..

# Wait for chat router to start
sleep 3

# Start frontend dev server
echo "🚀 Starting Frontend Dev Server (Port 3000)..."
cd frontend
npm run dev &
FRONTEND_PID=$!
cd ..

echo ""
echo "======================================================================"
echo "✅ Services Started!"
echo "======================================================================"
echo ""
echo "  Chat Router:  http://localhost:5001"
echo "  Frontend:     http://localhost:3000"
echo ""
echo "======================================================================"
echo "📖 HOW TO USE:"
echo "======================================================================"
echo ""
echo "  1. Open http://localhost:3000 in your browser"
echo "  2. Click the 'Agent Control' tab (3rd tab)"
echo "  3. Click '💬 Chat' button on any agent hexagon"
echo "  4. Start chatting with the agent!"
echo ""
echo "  Example queries:"
echo "    - 'Find patients with Type 2 Diabetes'"
echo "    - 'Show me the top 10 matches'"
echo "    - 'What patterns have you discovered?'"
echo ""
echo "======================================================================"
echo "⚠️  DEMO MODE:"
echo "======================================================================"
echo ""
echo "  Currently running in DEMO mode with simulated responses."
echo "  To enable real agent communication:"
echo ""
echo "    1. Open 8 new terminals"
echo "    2. Run each agent: python3 backend/agents/<agent>_agent.py"
echo "    3. Chat will then use real agent responses"
echo ""
echo "======================================================================"
echo ""
echo "Press Ctrl+C to stop all services..."
echo ""

# Wait for user interrupt
trap "echo ''; echo 'Stopping services...'; kill $CHAT_PID $FRONTEND_PID 2>/dev/null; echo 'Done!'; exit 0" INT

# Keep script running
wait

```

### start_all_agents.sh

```shell
#!/bin/bash

###################################################################################
# TrialMatch AI - Start All Agents
#
# This script launches all 8 Fetch.AI agents for the TrialMatch AI system:
# - Coordinator (Port 8000) - Orchestrates the workflow
# - Eligibility (Port 8001) - Extracts trial criteria
# - Pattern (Port 8002) - Matches patient patterns
# - Discovery (Port 8003) - Searches patient database
# - Matching (Port 8004) - Scores patient-trial matches
# - Site (Port 8005) - Recommends trial sites
# - Prediction (Port 8006) - Forecasts enrollment timelines
# - Validation (Port 8007) - Validates exclusion criteria
#
# Usage:
#   ./start_all_agents.sh              # Start all agents in background
#   ./start_all_agents.sh foreground   # Start all agents in separate terminals
#   ./start_all_agents.sh stop         # Stop all agents
#
###################################################################################

set -e

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# Project paths
PROJECT_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
BACKEND_DIR="$PROJECT_ROOT/backend"
VENV_PYTHON="$PROJECT_ROOT/venv/bin/python"
PID_DIR="$PROJECT_ROOT/.agent_pids"

# Agent list
AGENTS=(
    "coordinator_agent:8000"
    "eligibility_agent:8001"
    "pattern_agent:8002"
    "discovery_agent:8003"
    "matching_agent:8004"
    "site_agent:8005"
    "prediction_agent:8006"
    "validation_agent:8007"
)

###################################################################################
# Functions
###################################################################################

print_header() {
    echo -e "${BLUE}========================================================================${NC}"
    echo -e "${BLUE}  TrialMatch AI - Multi-Agent System${NC}"
    echo -e "${BLUE}========================================================================${NC}"
}

check_requirements() {
    echo -e "${YELLOW}Checking requirements...${NC}"

    # Check if venv exists
    if [ ! -f "$VENV_PYTHON" ]; then
        echo -e "${RED}❌ Virtual environment not found at: $VENV_PYTHON${NC}"
        echo -e "${YELLOW}   Please create it with: python3 -m venv venv${NC}"
        echo -e "${YELLOW}   Then install requirements: venv/bin/pip install -r backend/requirements.txt${NC}"
        exit 1
    fi

    # Check if backend directory exists
    if [ ! -d "$BACKEND_DIR" ]; then
        echo -e "${RED}❌ Backend directory not found: $BACKEND_DIR${NC}"
        exit 1
    fi

    echo -e "${GREEN}✓ Requirements check passed${NC}"
}

create_pid_dir() {
    mkdir -p "$PID_DIR"
}

start_agent_background() {
    local agent_name=$1
    local port=$2
    local pid_file="$PID_DIR/${agent_name}.pid"

    echo -e "${YELLOW}Starting ${agent_name} on port ${port}...${NC}"

    # Start agent in background
    cd "$BACKEND_DIR"
    nohup "$VENV_PYTHON" -m "agents.${agent_name}" > "$PID_DIR/${agent_name}.log" 2>&1 &
    local pid=$!

    # Save PID
    echo $pid > "$pid_file"

    # Wait a moment and check if still running
    sleep 0.5
    if ps -p $pid > /dev/null 2>&1; then
        echo -e "${GREEN}✓ ${agent_name} started (PID: $pid)${NC}"
        return 0
    else
        echo -e "${RED}❌ ${agent_name} failed to start${NC}"
        return 1
    fi
}

start_agent_foreground() {
    local agent_name=$1
    local port=$2

    echo -e "${YELLOW}Starting ${agent_name} on port ${port} in new terminal...${NC}"

    # Detect OS and open appropriate terminal
    if [[ "$OSTYPE" == "darwin"* ]]; then
        # macOS
        osascript -e "tell application \"Terminal\" to do script \"cd '$BACKEND_DIR' && '$VENV_PYTHON' -m agents.${agent_name}\""
    elif [[ "$OSTYPE" == "linux-gnu"* ]]; then
        # Linux - try various terminal emulators
        if command -v gnome-terminal &> /dev/null; then
            gnome-terminal -- bash -c "cd '$BACKEND_DIR' && '$VENV_PYTHON' -m agents.${agent_name}; exec bash"
        elif command -v xterm &> /dev/null; then
            xterm -e "cd '$BACKEND_DIR' && '$VENV_PYTHON' -m agents.${agent_name}" &
        else
            echo -e "${YELLOW}⚠ No terminal emulator found. Starting in background instead.${NC}"
            start_agent_background "$agent_name" "$port"
        fi
    else
        echo -e "${YELLOW}⚠ Unknown OS. Starting in background instead.${NC}"
        start_agent_background "$agent_name" "$port"
    fi
}

stop_all_agents() {
    print_header
    echo -e "${YELLOW}Stopping all agents...${NC}"
    echo ""

    for agent_port in "${AGENTS[@]}"; do
        agent_name="${agent_port%%:*}"
        pid_file="$PID_DIR/${agent_name}.pid"

        if [ -f "$pid_file" ]; then
            pid=$(cat "$pid_file")
            if ps -p $pid > /dev/null 2>&1; then
                echo -e "${YELLOW}Stopping ${agent_name} (PID: $pid)...${NC}"
                kill $pid
                echo -e "${GREEN}✓ ${agent_name} stopped${NC}"
            else
                echo -e "${YELLOW}⚠ ${agent_name} was not running${NC}"
            fi
            rm "$pid_file"
        else
            echo -e "${YELLOW}⚠ No PID file for ${agent_name}${NC}"
        fi
    done

    echo ""
    echo -e "${GREEN}All agents stopped${NC}"
}

show_status() {
    print_header
    echo -e "${YELLOW}Agent Status:${NC}"
    echo ""

    printf "%-20s %-10s %-15s %-10s\n" "AGENT" "PORT" "STATUS" "PID"
    echo "------------------------------------------------------------------------"

    for agent_port in "${AGENTS[@]}"; do
        agent_name="${agent_port%%:*}"
        port="${agent_port##*:}"
        pid_file="$PID_DIR/${agent_name}.pid"

        if [ -f "$pid_file" ]; then
            pid=$(cat "$pid_file")
            if ps -p $pid > /dev/null 2>&1; then
                printf "%-20s %-10s ${GREEN}%-15s${NC} %-10s\n" "$agent_name" "$port" "RUNNING" "$pid"
            else
                printf "%-20s %-10s ${RED}%-15s${NC} %-10s\n" "$agent_nam
[truncated — 3347 more characters]
```

### frontend/index.html

```html

  <!DOCTYPE html>
  <html lang="en">
    <head>
      <meta charset="UTF-8" />
      <meta name="viewport" content="width=device-width, initial-scale=1.0" />
      <title>Healthcare Dashboard Design</title>
    </head>

    <body>
      <div id="root"></div>
      <script type="module" src="/src/main.tsx"></script>
    </body>
  </html>
  
```

### backend/update_startup_functions.sh

```shell
#!/bin/bash

# This script updates the startup functions for all agents to add Agentverse support

echo "Updating startup functions for all agents..."

# Array of agent names and their greeting messages
declare -A AGENTS
AGENTS[matching]="Ready to score patient candidates using Pattern Discovery similarity metrics!"
AGENTS[eligibility]="Ready to extract and parse trial eligibility criteria!"
AGENTS[pattern]="Ready to match pre-discovered patient patterns to trial criteria!"
AGENTS[prediction]="Ready to forecast enrollment timelines using pattern analysis!"
AGENTS[site]="Ready to recommend trial sites based on feasibility and patient geography!"
AGENTS[validation]="Ready to validate patient matches against exclusion criteria!"

echo "✓ Configuration ready"
echo ""
echo "Please manually update each agent's startup function using discovery_agent.py as a template."
echo ""
echo "Agent files to update:"
for agent in "${!AGENTS[@]}"; do
    echo "  - agents/${agent}_agent.py"
done

```

[91 more indexed source files omitted to keep this export small. The full file list is in the Codebase structure section above.]