Spaces:
Sleeping
Sleeping
KevinIsInCoding Claude Sonnet 4.6 commited on
Commit Β·
f8d77e4
1
Parent(s): 2a6ee87
Initial release: Beacon rare disease clinical trial finder
Browse filesConversational AI assistant that interviews patients, geocodes their location,
and searches ClinicalTrials.gov in real time to surface nearby recruiting trials.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Files changed (9)
- .env.exampleAdded+8
- .gitignoreAdded+13
- .python-versionAdded+1
- README.md+74-1
- clinical_trials_guru.pyAdded+454
- llm.pyAdded+76
- main.pyAdded+9
- pyproject.tomlAdded+13
- uv.lockAdded
12345678# β οΈ Copy this file to .env and replace with your actual API keys.# Never commit .env or real API keys to version control.
OPENAI_API_KEY=your_openai_api_key_hereANTHROPIC_API_KEY=your_anthropic_api_key_here
# Optional: switch LLM backend (default: anthropic)# LLM_PROVIDER=openai12345678910111213# Python-generated files__pycache__/*.py[oc]build/dist/wheels/*.egg-info
# Virtual environments.venv
# Secrets.env13.1111 unmodified lines1213141511 unmodified linesshort_description: help patients with rare disease to find clinical trials---Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference11 unmodified lines121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878811 unmodified linesshort_description: help patients with rare disease to find clinical trials---# Beacon β Rare Disease Clinical Trial FinderBeacon is a conversational AI assistant that helps patients with rare diseases find relevant recruiting clinical trials near them. It conducts a warm intake interview, geocodes the patient's location, queries [ClinicalTrials.gov](https://clinicaltrials.gov) in real time, and produces a ranked report of the closest matching trials.## How it works1. **Intake agent** (Claude Sonnet) β interviews the patient conversationally to collect disease, age, symptom onset, location, and optional benchmark scores.2. **Research agent** (Claude Opus) β searches ClinicalTrials.gov via the official v2 API, retrying with synonyms or wider radii if results are sparse, then outputs a ranked trial report with eligibility notes and next steps.3. **LangGraph** orchestrates the two-node pipeline (intake β research).## Project setup### Prerequisites- Python 3.11+- [`uv`](https://docs.astral.sh/uv/) (recommended) or `pip`### 1. Clone the repo```bashgit clone <repo-url>cd beacon```### 2. Install dependencies```bashuv sync```Or with pip:```bashpip install -e .```### 3. Configure API keysCopy the example env file and fill in your keys:```bashcp .env.example .env```Open `.env` and replace the placeholder values:```envANTHROPIC_API_KEY=your_anthropic_api_key_here```### 4. Run```bashuv run python app.py```## Configuration| Environment variable | Default | Description ||----------------------|-------------|-------------------|| `ANTHROPIC_API_KEY` | *(required)*| Anthropic API key |## Project structure```beacon/βββ app.py # Gradio web UI entry pointβββ main.py # Terminal entry pointβββ clinical_trials_guru.py # Intake + research agents, LangGraph pipelineβββ llm.py # LLM provider abstractionβββ requirements.txt # HuggingFace Spaces dependenciesβββ pyproject.tomlβββ .env # Local secrets β not committed```
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454from __future__ import annotations
import jsonimport mathimport timefrom dataclasses import dataclass, fieldfrom typing import Optional, TypedDict
import anthropicimport httpxfrom rich import boxfrom rich.console import Consolefrom rich.markdown import Markdownfrom rich.panel import Panelfrom rich.text import Textfrom langgraph.graph import StateGraph, START, END
CTGOV_BASE = "https://clinicaltrials.gov/api/v2/studies"INTAKE_MODEL = "claude-sonnet-4-6"RESEARCH_MODEL = "claude-opus-4-7"
console = Console()
# ββ Tool schemas ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
SUBMIT_PROFILE_TOOL: anthropic.types.ToolParam = { "name": "submit_profile", "description": ( "Call this when you have collected all required information. " "Standardize the disease name to its full medical term." ), "input_schema": { "type": "object", "properties": { "disease": { "type": "string", "description": "Full medical name (e.g. 'Amyotrophic Lateral Sclerosis')", }, "age": {"type": "integer"}, "onset_months": { "type": "integer", "description": "Months since first symptom onset", }, "benchmarks": { "type": "object", "description": "Disease-specific scores, e.g. {\"ALSFRS-R\": \"38\"}", "additionalProperties": {"type": "string"}, }, "zip_code": {"type": "string", "description": "Patient ZIP / postal code"}, "country_code": { "type": "string", "description": "ISO 2-letter country code (default US)", }, "radius_miles": { "type": "integer", "description": "Search radius in miles from patient location (default 100)", }, "phases": { "type": "array", "items": {"type": "string", "enum": ["0", "1", "2", "3", "4"]}, "description": "Desired trial phases. Empty = all phases.", }, }, "required": ["disease", "age", "onset_months", "zip_code"], },}
SEARCH_TRIALS_TOOL: anthropic.types.ToolParam = { "name": "search_clinical_trials", "description": ( "Search ClinicalTrials.gov for recruiting trials within a geographic radius. " "Results are pre-ranked by distance from the patient's location. " "Call multiple times with different parameters (synonyms, broader radius, " "different phases) if initial results are sparse." ), "input_schema": { "type": "object", "properties": { "condition": { "type": "string", "description": "Disease / condition to search (medical name and/or abbreviation)", }, "lat": {"type": "number", "description": "Patient latitude"}, "lon": {"type": "number", "description": "Patient longitude"}, "radius_miles": {"type": "integer", "description": "Search radius in miles"}, "phases": { "type": "array", "items": {"type": "string"}, "description": "Phase numbers to filter ['1','2','3']. Empty = all.", }, "max_results": {"type": "integer", "description": "Max trials to return (default 20)"}, }, "required": ["condition", "lat", "lon", "radius_miles"], },}
# ββ System prompts ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
INTAKE_SYSTEM = """\You are Beacon's patient intake specialist for rare disease clinical trials.Collect the following through a warm, conversational interview β do NOT present a form.
REQUIRED: β’ Disease/condition (standardize: "Lou Gehrig's" β "Amyotrophic Lateral Sclerosis") β’ Patient age β’ Months since first symptom onset (convert dates/years as needed) β’ ZIP/postal code and country for geographic search
OPTIONAL (ask based on disease): β’ Disease-specific benchmark scores: ALS β ALSFRS-R (0-48); MS β EDSS (0-10); Parkinson's β MDS-UPDRS III; Huntington's β TFC (0-13) + CAG repeats; SMA β HFMS + SMA type; Duchenne/Pompe β 6-Minute Walk Test; Friedreich's β SARA score β’ Preferred search radius in miles (default 100) β’ Trial phases of interest (1 / 2 / 3 / 4 / early)
Ask naturally. Infer what you can. Once you have the required fields, call submit_profile.\"""
RESEARCH_SYSTEM = """\You are Beacon, an expert rare-disease clinical trial navigator.You have a search_clinical_trials tool that queries ClinicalTrials.gov in real time.Results are already ranked by geographic distance from the patient.
Workflow:1. Search for the patient's disease. Use both the full medical name and common abbreviation.2. If fewer than 3 results are found, retry with: a wider radius, a disease synonym, or fewer phase filters.3. Produce a final report listing the top 5 trials ranked by site proximity. For EACH trial use exactly this format (repeat the block per trial):
π **[Closest hospital name]** β [City, State] ([X] mi) **Trial:** [Full trial title] ([Phase]) **Sponsor:** [Lead sponsor] **Summary:** [2β3 sentence plain-language description of what the trial is testing and why it may matter for this patient] **Eligibility notes:** [Key inclusion/exclusion criteria relevant to this patient, including any red flags] **Link:** https://clinicaltrials.gov/study/[NCT_ID]
---
4. After the trial list add a short "Next steps" section (bullet points).
Be accurate. Do not fabricate details. If data is missing, say so.\"""
# ββ Data model ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
@dataclassclass PatientProfile: disease: str age: int onset_months: int benchmarks: dict[str, str] = field(default_factory=dict) zip_code: str = "" country_code: str = "US" lat: float = 0.0 lon: float = 0.0 radius_miles: int = 100 phases: list[str] = field(default_factory=list)
def summary(self) -> str: lines = [ f"Disease: {self.disease}", f"Age: {self.age}", f"Symptom onset: {self.onset_months} months ago", ] if self.benchmarks: lines.append("Benchmarks: " + ", ".join(f"{k}={v}" for k, v in self.benchmarks.items())) lines.append( f"Location: ZIP {self.zip_code}, {self.country_code} " f"(lat={self.lat:.4f}, lon={self.lon:.4f})" ) lines.append(f"Search radius: {self.radius_miles} miles") if self.phases: labels = ["Early Phase 1" if p == "0" else f"Phase {p}" for p in self.phases] lines.append(f"Phases: {', '.join(labels)}") return "\n".join(lines)
# ββ Geocoding βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def geocode_zip(zip_code: str, country_code: str = "US") -> tuple[float, float]: resp = httpx.get( "https://nominatim.openstreetmap.org/search", params={"postalcode": zip_code, "country": country_code, "format": "json", "limit": 1}, headers={"User-Agent": "Beacon-ClinicalTrialFinder/1.0"}, timeout=10, ) resp.raise_for_status() results = resp.json() if not results: raise ValueError(f"Cannot geocode ZIP {zip_code!r} in {country_code!r}") return float(results[0]["lat"]), float(results[0]["lon"])
# ββ Distance ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def haversine_miles(lat1: float, lon1: float, lat2: float, lon2: float) -> float: R = 3958.8 Ο1, Ο2 = math.radians(lat1), math.radians(lat2) dΟ, dΞ» = math.radians(lat2 - lat1), math.radians(lon2 - lon1) a = math.sin(dΟ / 2) ** 2 + math.cos(Ο1) * math.cos(Ο2) * math.sin(dΞ» / 2) ** 2 return R * 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))
# ββ ClinicalTrials.gov ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def search_trials_api( condition: str, lat: float, lon: float, radius_miles: int = 100, phases: list[str] | None = None, max_results: int = 20,) -> list[dict]: params: dict[str, str | int] = { "query.cond": condition, "filter.overallStatus": "RECRUITING", "filter.geo": f"distance({lat},{lon},{radius_miles}mi)", "pageSize": max_results, "format": "json", } if phases: params["aggFilters"] = "phase:" + " ".join(phases) for attempt in range(3): try: resp = httpx.get(CTGOV_BASE, params=params, timeout=30) resp.raise_for_status() return resp.json().get("studies", []) except httpx.HTTPError as exc: if attempt == 2: raise wait = 2 ** attempt console.print(f"[yellow]API warning:[/yellow] {exc} β retrying in {wait}s (attempt {attempt + 1}/3)β¦") time.sleep(wait)
def _flatten_and_rank(studies: list[dict], patient_lat: float, patient_lon: float) -> list[dict]: result = [] for study in studies: proto = study.get("protocolSection", {}) id_mod = proto.get("identificationModule", {}) desc_mod = proto.get("descriptionModule", {}) elig_mod = proto.get("eligibilityModule", {}) contacts_mod = proto.get("contactsLocationsModule", {}) sponsor_mod = proto.get("sponsorCollaboratorsModule", {}) design_mod = proto.get("designModule", {})
sites_with_dist: list[tuple[float, str]] = [] for loc in contacts_mod.get("locations", []): geo = loc.get("geoPoint", {}) if geo.get("lat") and geo.get("lon"): d = haversine_miles(patient_lat, patient_lon, geo["lat"], geo["lon"]) label = ( f"{loc.get('facility', '').strip()} β " f"{loc.get('city', '')}, " f"{loc.get('state', loc.get('country', ''))} " f"({d:.0f} mi)" ) sites_with_dist.append((d, label)) sites_with_dist.sort(key=lambda x: x[0])
closest_dist = sites_with_dist[0][0] if sites_with_dist else None result.append({ "nct_id": id_mod.get("nctId", ""), "title": id_mod.get("briefTitle", ""), "phase": ", ".join(design_mod.get("phases", [])) or "N/A", "sponsor": sponsor_mod.get("leadSponsor", {}).get("name", ""), "summary": desc_mod.get("briefSummary", "")[:500], "eligibility": elig_mod.get("eligibilityCriteria", "")[:1000], "min_age": elig_mod.get("minimumAge", ""), "max_age": elig_mod.get("maximumAge", ""), "closest_site_miles": round(closest_dist, 1) if closest_dist is not None else None, "nearest_sites": [label for _, label in sites_with_dist[:5]], })
result.sort(key=lambda x: x["closest_site_miles"] if x["closest_site_miles"] is not None else float("inf")) return result
# ββ Intake agent ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def run_intake_agent(client: anthropic.Anthropic) -> PatientProfile: import datetime today = datetime.date.today().strftime("%B %d, %Y")
console.print() console.print(Panel( Text("Beacon β Rare Disease Clinical Trial Finder", justify="center", style="bold cyan"), border_style="cyan", padding=(1, 4), ))
messages: list[anthropic.types.MessageParam] = [ {"role": "user", "content": "Please begin."} ]
while True: response = client.messages.create( model=INTAKE_MODEL, max_tokens=1024, system=f"Today's date is {today}.\n\n" + INTAKE_SYSTEM, tools=[SUBMIT_PROFILE_TOOL], messages=messages, )
text = next((b.text for b in response.content if b.type == "text"), "") if text: console.print(f"\n[bold cyan]Beacon:[/bold cyan] {text}")
tool_block = next( (b for b in response.content if b.type == "tool_use" and b.name == "submit_profile"), None, ) if tool_block: data = tool_block.input try: with console.status("[cyan]Geocoding locationβ¦[/cyan]", spinner="dots"): lat, lon = geocode_zip(data["zip_code"], data.get("country_code", "US")) except Exception as exc: console.print(f"[yellow]Warning:[/yellow] Geocoding failed ({exc}) β coordinates set to 0,0.") lat, lon = 0.0, 0.0 return PatientProfile( disease=data["disease"], age=data["age"], onset_months=data["onset_months"], benchmarks=data.get("benchmarks") or {}, zip_code=data["zip_code"], country_code=data.get("country_code", "US"), lat=lat, lon=lon, radius_miles=data.get("radius_miles", 100), phases=data.get("phases") or [], )
messages.append({"role": "assistant", "content": response.content}) user_input = input("\nYou: ").strip() or "(no response)" messages.append({"role": "user", "content": user_input})
# ββ Research agent ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def run_research_agent(client: anthropic.Anthropic, profile: PatientProfile) -> str: messages: list[anthropic.types.MessageParam] = [ { "role": "user", "content": ( f"Find clinical trials for this patient:\n\n{profile.summary()}\n\n" "Search within the specified radius and rank results by distance." ), } ]
while True: response = client.messages.create( model=RESEARCH_MODEL, max_tokens=8096, system=RESEARCH_SYSTEM, tools=[SEARCH_TRIALS_TOOL], messages=messages, )
messages.append({"role": "assistant", "content": response.content})
if response.stop_reason == "end_turn": return next( (b.text for b in response.content if b.type == "text"), "No analysis produced.", )
tool_results: list[anthropic.types.ToolResultBlockParam] = [] for block in response.content: if block.type != "tool_use" or block.name != "search_clinical_trials": continue args = block.input radius = args.get("radius_miles", profile.radius_miles) phases = args.get("phases") or None status_msg = ( f"[cyan]Searching:[/cyan] '[bold]{args['condition']}[/bold]' | " f"radius=[bold]{radius}[/bold] mi | " f"phases=[bold]{phases or 'all'}[/bold]" ) try: with console.status(status_msg, spinner="dots"): studies = search_trials_api( condition=args["condition"], lat=args["lat"], lon=args["lon"], radius_miles=radius, phases=phases, max_results=args.get("max_results", 20), ) ranked = _flatten_and_rank(studies, profile.lat, profile.lon) console.print(f" [green]β[/green] {len(ranked)} trial(s) found.") content = json.dumps(ranked) is_error = False except Exception as exc: console.print(f"[red bold]API error:[/red bold] {exc}") content = f"API request failed: {exc}. The ClinicalTrials.gov endpoint may be temporarily unavailable." is_error = True tool_results.append({ "type": "tool_result", "tool_use_id": block.id, "content": content, "is_error": is_error, })
messages.append({"role": "user", "content": tool_results})
# ββ LangGraph βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
class BeaconState(TypedDict): profile: Optional[PatientProfile] analysis: str
def _build_graph(client: anthropic.Anthropic): def intake_node(_state: BeaconState) -> BeaconState: return {"profile": run_intake_agent(client), "analysis": ""}
def research_node(state: BeaconState) -> BeaconState: analysis = run_research_agent(client, state["profile"]) console.print() console.print(Panel( Markdown(analysis), title="[bold cyan]BEACON ANALYSIS[/bold cyan]", border_style="cyan", box=box.DOUBLE_EDGE, padding=(1, 2), )) console.print() return {"analysis": analysis}
graph = StateGraph(BeaconState) graph.add_node("intake", intake_node) graph.add_node("research", research_node) graph.add_edge(START, "intake") graph.add_edge("intake", "research") graph.add_edge("research", END) return graph.compile()
def guru_main(_provider=None): # _provider kept for backward-compat, unused client = anthropic.Anthropic() graph = _build_graph(client) try: graph.invoke({"profile": None, "analysis": ""}) except (KeyboardInterrupt, EOFError): console.print("\n[dim]Goodbye.[/dim]") return console.print("\n[bold]Goodbye.[/bold] Beacon wishes the patient the best on their journey.")12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576import osfrom abc import ABC, abstractmethod
import anthropicimport openai
def _normalize_messages(messages: list) -> list[dict]: """Convert LangGraph/LangChain message objects or dicts to {role, content} dicts.""" result = [] for msg in messages: if hasattr(msg, "type"): raw_role, content = msg.type, msg.content else: raw_role, content = msg.get("role", "user"), msg.get("content", "")
if raw_role in ("human", "user"): role = "user" elif raw_role in ("ai", "assistant"): role = "assistant" else: continue
result.append({"role": role, "content": content}) return result
class LLMProvider(ABC): @abstractmethod def complete(self, messages: list, system: str = "") -> str: ...
class AnthropicProvider(LLMProvider): MODEL = "claude-opus-4-7"
def __init__(self): self._client = anthropic.Anthropic()
def complete(self, messages: list, system: str = "") -> str: kwargs = dict( model=self.MODEL, max_tokens=16000, thinking={"type": "adaptive"}, messages=_normalize_messages(messages), ) if system: kwargs["system"] = system with self._client.messages.stream(**kwargs) as stream: response = stream.get_final_message() return next((b.text for b in response.content if b.type == "text"), "")
class OpenAIProvider(LLMProvider): MODEL = "gpt-4o"
def __init__(self): self._client = openai.OpenAI()
def complete(self, messages: list, system: str = "") -> str: normalized = _normalize_messages(messages) if system: normalized = [{"role": "system", "content": system}] + normalized response = self._client.chat.completions.create( model=self.MODEL, messages=normalized, ) return response.choices[0].message.content or ""
def get_provider(name: str | None = None) -> LLMProvider: name = name or os.getenv("LLM_PROVIDER", "anthropic") if name == "openai": return OpenAIProvider() if name == "anthropic": return AnthropicProvider() raise ValueError(f"Unknown LLM provider: {name!r}. Choose 'anthropic' or 'openai'.")123456789from dotenv import load_dotenv
from clinical_trials_guru import guru_mainfrom llm import get_provider
load_dotenv()
if __name__ == "__main__": guru_main(get_provider("anthropic"))12345678910111213[project]name = "beacon"version = "0.1.0"description = "Add your description here"readme = "README.md"requires-python = ">=3.11"dependencies = [ "anthropic>=0.50.0", "langgraph>=1.2.0", "openai>=1.0.0", "python-dotenv>=1.2.2", "rich>=13.0.0",].env.exampleAdded+8
.gitignoreAdded+13
.python-versionAdded+1
README.md+74-1
clinical_trials_guru.pyAdded+454
llm.pyAdded+76
main.pyAdded+9
pyproject.tomlAdded+13
uv.lockAdded