# Project export: AuthNeuro

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: UC Berkeley AI Hackathon 2026
- Tagline: AuthNeuro turns 3-week insurance delays into 30-second workflows. We generate precise medical letters with Claude Opus 4.7 and use Arize AX to verify every metric.
- Devpost: https://devpost.com/software/authneuro
- GitHub: https://github.com/arogya-gyawali/authneuro
- Demo: https://www.loom.com/share/b6af8d8bc50f417fbd0c7491d03bd074
- Team: 3 GitHub contributor(s) — arogya-gyawali (3 commits), Cursor (3 commits), Sanskrit Adhikari (1 commits)

## Devpost submission (written by the team)

### Inspiration

The inspiration for AuthNeuro was born from a realization of the disconnect between modern medical technology and administrative reality. Having personally experienced the frustration of an insurance denial for a medically necessary surgical procedure, I understand what it feels like to be trapped in administrative limbo. While my own case involved a relatively minor surgery, the denial still resulted in a month-long delay in care. That experience stayed with me. After developing my skills in software development and AI engineering, I wanted to solve this exact problem—the administrative "purgatory" patients face when insurers determine that treatment is not "medically necessary." AuthNeuro is our attempt to bridge that gap and accelerate access to care.

### What it does

AuthNeuro transforms neuroimaging data and physician documentation into payer-ready prior authorization packages. The platform: Parses FreeSurfer .stats neuroimaging files Extracts clinically relevant structural metrics Combines imaging findings with physician dictation and clinical notes Generates professional Letters of Medical Necessity (LMNs) Validates generated content against source imaging data Produces submission-ready PDF and email outputs The result is a streamlined workflow that reduces administrative burden while maintaining clinical integrity and traceability.

### How we built it

AuthNeuro was architected as a high-integrity, end-to-end clinical workflow. Clinical Reasoning Core We utilized Claude Opus 4.7 to perform the heavy synthesis work, transforming raw structural neuroimaging metrics and physician documentation into professional, persuasive Letters of Medical Necessity. Production Observability To ensure reliability and operational visibility, we instrumented the backend using Sentry for: Real-time error monitoring Performance tracking Latency analysis Production debugging Safety & Compliance The backbone of the project is the Arize AX observability stack, where we implemented a multi-layered LLM-as-a-Judge evaluation framework. Truth Layer A dedicated evaluator mathematically verifies that generated clinical metrics exactly match the source-of-truth neuroimaging files. Narrative Validation Layer A second evaluator reviews outputs for completeness, ensuring the generated letter captures all clinically relevant details and patient context.

### Challenges we ran into

Building AuthNeuro was not without significant hurdles. Major Project Pivot Midway through development, we were forced to abandon our original project direction entirely. This required rapid re-scoping, redesigning, and rebuilding under strict time constraints. Overcoming Hallucinations Clinical AI demands a much higher standard than traditional applications. We learned that AI-generated clinical documentation must be treated as a hypothesis rather than a source of truth. To address this, we built programmatic guardrails that continuously cross-reference generated content against authoritative neuroimaging data sources. This approach allowed us to create outputs that are both auditable and clinically trustworthy.

### Accomplishments we're proud of

We're incredibly proud of turning a complex vision into a functional, end-to-end prior authorization workflow. True Clinical Integrity The imaging data is honest. Every metric appearing in the final Letter of Medical Necessity is derived directly from parsed FreeSurfer .stats morphometry rather than manual user input. High Clinical Bar We implemented a mandatory KPI attestation step requiring physicians to verify extracted metrics before document generation. This was a deliberate design decision that prioritized patient safety over hackathon shortcuts. Infrastructure Complexity We successfully integrated an extensive healthcare AI stack, including: clabtoolkit Redis LangCache Sentry Claude Opus 4.7 Arize AX Deepgram AgentMail The resulting pipeline remains functional and resilient even when individual services experience configuration issues. Resilient Pivoting Perhaps most importantly, we're proud of our team's ability to completely change directions midway through development and still deliver a polished, production-quality solution.

### What we learned

Systems Engineering > Prompt Engineering Enterprise healthcare AI is fundamentally a systems engineering challenge. While model prompting is important, the real innovation lies in building reliable validation, monitoring, and auditing infrastructure around AI systems. The Necessity of Validation Clinical AI becomes safer when generated outputs are treated as hypotheses that must be verified against authoritative data sources. Programmatic guardrails and validation pipelines proved far more valuable than prompt optimization alone. The Power of Pivoting Being forced to abandon our initial idea taught us how to rapidly redefine scope, focus on core value, and still ship a high-quality product under pressure.

### What's next

Version 1 proves the full workflow: .stats → metrics → clinical note → LMN → PDF/email submission The next phase is transforming the prototype into a deployable clinical product. What we didn't do (and why) EHR Integration & Auto-Fetch Imaging Hospital integrations require PHI handling, compliance reviews, and institutional access. Manual uploads were sufficient to validate the core concept. Real Payer APIs Insurance authorization APIs remain fragmented and difficult to onboard. For demonstration purposes, AgentMail simulates successful submission workflows. Authentication, Audit Trails & HIPAA Infrastructure This project was intentionally built as a single-user localhost application. Compliance and enterprise security belong in the productization phase, not a weekend hackathon. Appeals & Case Tracking We intentionally scoped the project to first-pass prior authorization generation rather than the full appeals lifecycle. Full Test Suite & CI/CD Given time constraints, we prioritized live API smoke testing over comprehensive automated testing infrastructure. How we move forward Pilot Ingestion Automated watched-folder workflows FHIR-based imaging retrieval by MRN Manual upload retained as a fallback option Trust Layer User authentication Comprehensive audit logging Attending physician sign-off prior to submission Clinical Visualization Provide physicians with interactive 3D visualizations of patient hippocampal, cortical, or vascular structures alongside extracted morphometric metrics. Real Clinical Workflow Expand from document generation to full authorization lifecycle management: Draft Submitted Under Review Approved Denied Appeals Case Tracking

## README (from the GitHub repository)

# AuthNeuro

**Prior authorization for epilepsy surgery — from FreeSurfer morphometry to a payer-ready Letter of Medical Necessity.**

AuthNeuro is a clinician-facing workflow that reads a patient's FreeSurfer `.stats` morphometry report, extracts quantitative neuroimaging measures (hippocampal volume loss, cortical thinning), combines them with a clinical indication, and drafts a Letter of Medical Necessity (LMN) for prior authorization. The finished letter is emailed to a payer review inbox via AgentMail and available as a PDF for the medical record.

---

## What it does

1. **Upload** a FreeSurfer morphometry report (e.g. `aseg.stats` from `recon-all`)
2. **Review** parsed structural measures with payer-threshold context
3. **Document** the clinical indication (type or dictate)
4. **Attest** to the imaging values that will appear in the letter
5. **Draft** the LMN — Claude synthesizes prose grounded in verified metrics
6. **Submit** — AgentMail dispatches the PDF to the configured payer outbox automatically

Raw MRI, DICOM, and unscanned NIfTI are **not** accepted on the main path. AuthNeuro expects post–`recon-all` text reports such as `aseg.stats`.

---

## Architecture

```mermaid
flowchart LR
  UI[Streamlit Surgeon Console] --> API[FastAPI backend]
  API --> CLAB[clabtoolkit metrics parse]
  API --> MEM[Agent Memory recall]
  API --> LC[LangCache semantic cache]
  API --> CLAUDE[Claude LMN synthesis]
  API --> REDIS[(Redis job state)]
  API --> PDF[ReportLab PDF]
  API --> MAIL[AgentMail outbox]
  API --> ARIZE[Arize AX tracing]
```

| Layer | Role |
|-------|------|
| **Streamlit** | Surgeon's Console — upload, intake, attestation, results |
| **FastAPI** | Metrics extraction, dictation, authorize pipeline, PDF delivery |
| **clabtoolkit** | Parse FreeSurfer `.stats` into structural KPIs |
| **Claude** | Draft LMN from clinical text + authoritative metrics |
| **Redis** | Exact-response cache and live job status polling |
| **LangCache** | Semantic cache for similar prior-auth letters |
| **Agent Memory** | Cross-case recall of payer-specific language (optional) |
| **AgentMail** | Programmable email outbox with PDF attachment |
| **Deepgram** | Clinical dictation transcription (optional) |
| **Arize / Sentry** | Observability and error tracking (optional) |

---

## Quick start

### Prerequisites

- **Python 3.11+** recommended
- **Redis** running locally (default `127.0.0.1:6379`)
- API keys for services you want live (minimum: `ANTHROPIC_API_KEY` for real letter synthesis)

### 1. Clone and install

```bash
git clone <repo-url>
cd authneuro

python -m venv .venv
source .venv/bin/activate   # Windows: .venv\Scripts\activate

pip install -r backend/requirements.txt
pip install -r frontend/requirements.txt
```

### 2. Configure environment

```bash
cp backend/.env.example backend/.env
```

Edit `backend/.env` and set at least:

| Variable | Required for | Notes |
|----------|----------------|-------|
| `ANTHROPIC_API_KEY` | Live LMN drafting | Without it, a placeholder letter is returned |
| `ANTHROPIC_MODEL` | Claude model | Default: `claude-opus-4-7` |
| `REDIS_HOST` / `REDIS_PORT` | Job state & cache | Local Redis for development |
| `DEEPGRAM_API_KEY` | Voice dictation | Optional |
| `AGENT_MAIL_API_KEY` / `AGENT_MAIL_INBOX_ID` | Auto email dispatch | Optional; PDF still downloadable |
| `LANGCACHE_*` | Semantic caching | Optional |
| `AGENT_MEMORY_*` | Payer memory recall | Optional |
| `ARIZE_*` / `SENTRY_DSN` | Telemetry | Optional |

Never commit `backend/.env`.

### 3. Start Redis

```bash
# macOS (Homebrew)
brew services start redis

# or Docker
docker run -d -p 6379:6379 redis:7
```

### 4. Run the backend

From the **repository root**:

```bash
uvicorn backend.main:app --reload --port 8001
```

- Health: [http://127.0.0.1:8001/health](http://127.0.0.1:8001/health)
- OpenAPI docs: [http://127.0.0.1:8001/docs](http://127.0.0.1:8001/docs)

### 5. Run the frontend

In a second terminal:

```bash
cd frontend
streamlit run app.py
```

Open the URL Streamlit prints (usually [http://localhost:8501](http://localhost:8501)).

Set `API_BASE_URL=http://127.0.0.1:8001` in `backend/.env` if the API is not on that host/port.

---

## Demo walkthrough

Sample morphometry files live in `sample_data/freesurfer_stats/`.

| File | Suggested MRN | Notes |
|------|---------------|-------|
| `MRN-10482_aseg.stats` | `MRN-10482` | Strong atrophy — good threshold demo |
| `sub-ctl-001_aseg.stats` | `sub-ctl-001` | Milder measures |
| `sub-epi-005_aseg.stats` | `sub-epi-005` | Epilepsy cohort naming |

**Suggested flow:**

1. Upload `MRN-10482_aseg.stats`
2. Enter MRN `MRN-10482`, pick a payer, leave target structure as **left hippocampus**
3. Enter a clinical indication (e.g. refractory left temporal lobe epilepsy, failed AED trials)
4. Check the attestation box confirming imaging values
5. Click **Draft Letter of Medical Necessity**
6. Review the letter, AgentMail status, and download the PDF for the chart
7. Use **New case** to start another patient (avoids duplicate outbox emails)

---

## API overview

| Method | Endpoint | Description |
|--------|----------|-------------|
| `GET` | `/health` | Service and Redis status |
| `POST` | `/api/v1/metrics/extract` | Parse `.stats` → structural KPIs |
| `POST` | `/api/v1/dictate` | Transcribe clinical audio (Deepgram) |
| `POST` | `/api/v1/authorize` | Full pipeline → LMN + telemetry |
| `GET` | `/api/v1/jobs/{case_id}/state` | Live job status for UI polling |
| `GET` | `/api/v1/cases/{case_id}/lmn.pdf` | Download generated PDF |
| `GET` | `/api/v1/observability` | Sponsor stack status snapshot |

Interactive request/response schemas are in Swagger at `/docs`.

---

## Project structure

```
authneuro/
├── backend/
│   ├── main.py              # FastAPI app & authorize pipeline
│   ├── requirements.txt
│   └── .env.example         # Environment template (copy to .env)
├── frontend/
│   ├── app.py               # Streamlit entry point
│   ├── pages/
│   │   └── surgeon_console.py
│   ├── assets/              # UI media (e.g. loading animation)
│   └── requirements.txt
└── sample_data/
    └── freesurfer_stats/    # Demo .stats files
```

---

## Design notes

- **Metrics are authoritative.** Values in the LMN come from the parsed `.stats` file, not free text in the clinical note. The UI requires explicit physician attestation before drafting.
- **One draft, one outbox send.** Regenerate was removed from the UI because each successful authorize dispatches email via AgentMail. Use **New case** for a fresh submission.
- **Cache behavior.** Identical cases may be served from Redis without re-calling Claude or re-sending email (`skipped_cached_response` in telemetry).
- **Target structures.** Supported regions: left/right hippocampus, left/right amygdala (from `aseg.stats` row names).

---

## Troubleshooting

| Symptom | Likely cause | Fix |
|---------|----------------|-----|
| Button does nothing after draft | Backend 422/502; error may have been transient | Refresh; check red banner; see backend logs |
| `Could not locate '…' in …stats` | Target structure not in file | Match structure to report (e.g. left hippocampus) |
| Placeholder letter text | Missing `ANTHROPIC_API_KEY` | Add key to `backend/.env`, restart API |
| `temperature is deprecated` | Old client params | Use current `backend/main.py` (no temperature on Opus 4.7) |
| Email not sent | AgentMail keys missing or cache hit | Configure `AGENT_MAIL_*` or start **New case** |
| `Redis disconnected` | Redis not running | Start Redis; check `REDIS_HOST` / `REDIS_PORT` |

---

## License

Add your license here if open-sourcing.


## Detected evidence (automated analysis)

Indexed codebase: 4 recognized source files, 192 KB.
- Anthropic (technology) — detected in the code
- FastAPI (technology) — detected in the code
- Python (language) — detected in the code
- Redis (technology) — detected in the code
- Streamlit (technology) — detected in the code
- AI coding agent: Cursor — evidence: commit authorship or trailers

## Codebase structure (from repository index)

### Files (19 of 19)

```
.gitignore
backend/.env.example
backend/main.py
backend/requirements.txt
frontend/.streamlit/config.toml
frontend/app.py
frontend/pages/surgeon_console.py
frontend/requirements.txt
README.md
sample_data/freesurfer_stats/MRN-10482_aseg.stats
sample_data/freesurfer_stats/MRN-22017_aseg.stats
sample_data/freesurfer_stats/sub-101_aseg.stats
sample_data/freesurfer_stats/sub-102_aseg.stats
sample_data/freesurfer_stats/sub-103_aseg.stats
sample_data/freesurfer_stats/sub-10482_aseg.stats
sample_data/freesurfer_stats/sub-ctl-001_aseg.stats
sample_data/freesurfer_stats/sub-ctl-002_aseg.stats
sample_data/freesurfer_stats/sub-epi-004_aseg.stats
sample_data/freesurfer_stats/sub-epi-005_aseg.stats
```

### Dependencies

- backend/requirements.txt: anthropic@>=0.40.0, arize-otel@>=0.7.0, clabtoolkit@>=0.4.0, fastapi@>=0.115.0, httpx@>=0.28.0, langcache@>=0.13.0, openinference-instrumentation-anthropic@>=0.1.0, openinference-semantic-conventions@>=0.1.30, pydantic@>=2.0.0, python-dotenv@>=1.0.0, python-multipart@>=0.0.9, redis@>=5.0.0, reportlab@>=4.2.0, sentry-sdk[fastapi]@>=2.0.0, uvicorn[standard]@>=0.32.0
- frontend/requirements.txt: plotly@==5.22.0, requests@==2.32.3, streamlit@==1.58.0

### Recent commits (newest first)

- Ship AuthNeuro v1: Surgeon Console, morphometry pipeline, and LMN outbox.
- Merge teammate Streamlit frontend; keep sponsor backend/main.py.
- Add sponsor-integrated FastAPI backend before frontend merge.
- Initial commit: AuthNeuro platform (backend + unified frontend)

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

### frontend/requirements.txt

```
streamlit==1.58.0
plotly==5.22.0
requests==2.32.3


```

### backend/requirements.txt

```
fastapi>=0.115.0
uvicorn[standard]>=0.32.0
redis>=5.0.0
anthropic>=0.40.0
httpx>=0.28.0
sentry-sdk[fastapi]>=2.0.0
arize-otel>=0.7.0
openinference-instrumentation-anthropic>=0.1.0
openinference-semantic-conventions>=0.1.30
clabtoolkit>=0.4.0
langcache>=0.13.0
pydantic>=2.0.0
python-dotenv>=1.0.0
python-multipart>=0.0.9
reportlab>=4.2.0

```

### frontend/app.py

```python
"""AuthNeuro — Streamlit entry point (Surgeon's Console)."""

import importlib.util
from pathlib import Path

import streamlit as st

st.set_page_config(
    page_title="AuthNeuro — Prior Authorization",
    page_icon="🧠",
    layout="wide",
    initial_sidebar_state="expanded",
)

_console_path = Path(__file__).parent / "pages" / "surgeon_console.py"
_spec = importlib.util.spec_from_file_location("surgeon_console", _console_path)
_module = importlib.util.module_from_spec(_spec)
assert _spec.loader is not None
_spec.loader.exec_module(_module)
_module.main()

```