Project Info
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.
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.
Originally exported from: Figma Healthcare Dashboard Design
π Quick Start (3 Commands)
# 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
Analysis
View
Metric
- 16
- 12
- 10
- 9
- 4
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
- CSSIn code
- FastAPIIn code
- FlaskIn code
- HTMLIn code
- PythonIn code
- ReactIn code
- TypeScriptIn code
- Tailwind CSSClaimed
7 of 8 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
641 KB
Source files
103
Counts recognized source files only; vendored directories, binaries and lockfiles are excluded, so this is smaller than the repository on disk.
Repository
Calhacks-12-0/Trialmatch.ai
110 files Β· 963 KB Β· @ a7d79d3
Structure
Interface
57 files Β· 52%Screens, components and styles rendered to the user.
Application logic
41 files Β· 37%Domain rules, services and shared utilities.
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
- TypeScript46%
- Python44%
- CSS5%
- Markdown3%
- Shell2%
- HTML0%
Share of indexed source by file size. Binary and vendored files are excluded.
Dependencies
frontend/package.json
npm Β· 50- @radix-ui/react-accordion
- @radix-ui/react-alert-dialog
- @radix-ui/react-aspect-ratio
- @radix-ui/react-avatar
- @radix-ui/react-checkbox
- @radix-ui/react-collapsible
- @radix-ui/react-context-menu
- @radix-ui/react-dialog
- @radix-ui/react-dropdown-menu
- @radix-ui/react-hover-card
- @radix-ui/react-label
- @radix-ui/react-menubar
- @radix-ui/react-navigation-menu
- @radix-ui/react-popover
- @radix-ui/react-progress
- @radix-ui/react-radio-group
- @radix-ui/react-scroll-area
- @radix-ui/react-select
- +32 more
backend/requirements.txt
pypi Β· 14- fastapi
- flask
- flask-cors
- hdbscan
- numpy
- pandas
- pydantic
- requests
- scikit-learn
- sentence-transformers
- uagents
- uagents-core
- umap-learn
- uvicorn
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.
Feature verification
3D UMAP scatter plot visualizationVerified
3D UMAP scatter plots visualize patient clusters
Claimed on Devpostmedium confidencefrontend/src/App.tsx:798β PatternsView fetches embeddings_3d and cluster_labels from the backend and has an is3D toggle to render real 3D embeddings
7 autonomous Fetch.AI uAgents (Coordinator + 6 specialized)Verified
7 specialized agents (Eligibility, Pattern, Discovery, Matching, Validation, Site, Prediction) built with Fetch.AI uAgents on ports 8001-8007, coordinator on 8000
Claimed on Devposthigh confidencebackend/agents/config.py:14β Defines COORDINATOR_PORT=8000 and per-agent ports 8001-8007 matching the claimbackend/agents/eligibility_agent.py:48β uagents.Agent instance constructed, one of 7 separate agent files present in backend/agents/
Eligibility Agent extracts criteria from ClinicalTrials.govVerified
Eligibility Agent extracts structured criteria from ClinicalTrials.gov protocols
Claimed on Devpostmedium confidencebackend/agents/eligibility_agent.py:1β Agent file present handling eligibility extractionbackend/trial_criteria_mapper.py:1β TrialCriteriaMapper module referenced by README for mapping free-text criteria to structured codes
Enrollment timeline prediction (Prediction Agent)Verified
Forecasts enrollment timelines using historical pattern success rates
Claimed on Devposthigh confidencebackend/agents/prediction_agent.py:133β generate_forecast computes weekly enrollment rate, milestones, and risk factors from pattern success rates
Frontend: React 18 + TypeScript + Vite, shadcn/ui, Recharts, TailwindVerified
Frontend built with React 18, TypeScript, Vite, shadcn/ui (Radix), Recharts, Tailwind CSS
Claimed on readmehigh confidencefrontend/package.jsonβ Lists react, vite, tailwindcss, recharts and Radix-based shadcn/ui component setfrontend/src/components/ui/card.tsxβ shadcn/ui-style component library present under components/ui
Geographic heatmaps for site recommendationsVerified
Geographic heatmaps show site recommendations and patient distribution
Claimed on Devpostmedium confidencefrontend/src/App.tsx:1692β SitesView fetches real geographic data from /api/patients/geographic and renders clustered patient/site scatter
Sentence-Transformers medical text embeddings (all-MiniLM-L6-v2, 384D)Verified
Uses all-MiniLM-L6-v2 to embed clinical narratives into 384D vectors
Claimed on Devposthigh confidencebackend/pattern_discovery_engine.py:25β SentenceTransformer('all-MiniLM-L6-v2') instantiated as the text encoder
Site feasibility scoring / K-means geographic site optimizationVerified
Site feasibility scoring system with K-means clustering for optimal site recommendations
Claimed on Devposthigh confidencebackend/app.py:332β KMeans(n_clusters=n_sites) fit on patient coordinates to compute site clustersbackend/site_feasibility_scorer.py:1β Dedicated module for site feasibility scoring exists
Sortable patient match tables with demographics and scoresVerified
Sortable tables with patient demographics, match scores, and exclusion risk factors
Claimed on Devposthigh confidencefrontend/src/App.tsx:1521β MatchesView renders per-patient Match Score with expandable subscore breakdowns fed from backend trial results
Unsupervised pattern discovery (UMAP + HDBSCAN clustering)Verified
Discovers 20-30 patient cohorts using UMAP dimensionality reduction and HDBSCAN clustering, no labeled data
Claimed on Devposthigh confidencebackend/pattern_discovery_engine.py:27β umap.UMAP configured for 50D and 3D reduction, feeding sklearn HDBSCAN clusteringbackend/pattern_discovery_engine.py:31β HDBSCAN clustering instantiated with tunable parameters as claimed
Zero-click / autonomous patient-trial matching pipelineVerified
Full pipeline from trial query to ranked patient matches runs automatically via agents
Claimed on Devposthigh confidencebackend/agents/coordinator_agent.py:90β on_query handler orchestrates eligibility, pattern, discovery, matching, site, and prediction agent calls in sequencefrontend/src/App.tsx:72β App.tsx calls http://localhost:8080/api/match/trial to trigger the pipeline and renders results in MatchesView
Coordinator retry logic, timeout handling, circuit breakersCode-supported
Coordinator agent has sophisticated retry logic, timeout handling, circuit breaker patterns, and health checks
Claimed on Devpostlow confidencebackend/agents/coordinator_agent.py:44β Imports and uses QUERY_TIMEOUT for each downstream agent call, but no explicit retry-loop or circuit-breaker implementation was found in this file
FHIR-compatible synthetic patient records with ICD-10/LOINC/RxNorm codesCode-supported
1,000 (or 50,000+) FHIR-compatible synthetic patients with real ICD-10, LOINC, RxNorm, SNOMED codes
Claimed on Devpostmedium confidencebackend/fhir_code_extractor.py:1β Module extracts ICD-10/LOINC/RxNorm/SNOMED codes from FHIR bundlesbackend/data_loader.py:24β load_synthea_patients reads FHIR JSON from a backend/data/fhir directory that is gitignored and absent in this clone; falls back to generate_synthetic_patients if missing, so actual data files could not be verified
Multi-modal patient embeddings (text + numeric + geographic)Code-supported
Embeddings combine clinical text, numeric labs/demographics, and lat/long for site optimization
Claimed on Devpostmedium confidencebackend/pattern_discovery_engine.py:84β Dimensionality reduction pipeline references combined feature vectorsbackend/app.py:306β K-means over patient coordinates used for site clustering, consistent with a geographic component, but full fusion of all three modalities into one embedding wasn't traced end-to-end
Unused legacy dashboard component files (Figma export)Code-supported
Implied by '5 main dashboard views connected through tab navigation' description of the frontend architecture
Claimed on readmehigh confidencefrontend/src/components/PatientMatches.tsx:121β Standalone component with hardcoded mock patient/matchScore data and no props, not imported anywhere in App.tsx which instead defines its own live-data MatchesViewfrontend/src/components/SiteSelection.tsx:54β Hardcoded heatmapRegions/sites mock data, unused; App.tsx's real SitesView fetches live geographic data instead
Validation Agent filters exclusion-criteria violationsCode-supported
Validation Agent filters out patients violating trial exclusion criteria
Claimed on Devpostmedium confidencebackend/agents/validation_agent.py:1β Dedicated validation agent file exists in the multi-agent pipeline
Chat router backend on port 5001Claimed only
Real-time agent communication powered by REST API calls to a backend chat router on port 5001
Claimed on readmehigh confidenceReal-time agent activity logs / live agent chatClaimed only
Live activity logs show agents 'thinking' in real time, plus real-time agent chat for debugging
Claimed on Devpostmedium confidence
An AI agent derived these features from the projectβs Devpost page and readme, then searched the code for each one. Verified features are backed by cited code; claimed-only features had no supporting code, which is not by itself proof a feature is missing.
Export this project's context (description, README, evidence, key source files) to chat with an AI agent elsewhere.