Metadata-Version: 2.4
Name: aiva-agent
Version: 1.0.1
License-File: LICENSE
Summary: Clinical-genomics agent: ask natural-language questions over a local VCF and get literature-grounded answers.
License-Expression: LicenseRef-PolyForm-Noncommercial-1.0.0
Requires-Python: >=3.10
Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM
Project-URL: Homepage, https://github.com/MHSPL/aiva-agent
Project-URL: Issues, https://github.com/MHSPL/aiva-agent/issues
Project-URL: Repository, https://github.com/MHSPL/aiva-agent

# aiva-agent

A standalone clinical-genomics agent. Ask natural-language questions about a local pre-annotated VCF, gather variant annotations, search literature, find clinical trials, prioritize genes from HPO phenotypes, and run ACMG/AMP variant classification — using **any** OpenAI-compatible provider (OpenAI, Anthropic, xAI Grok, Together, Fireworks, OpenRouter, etc.).

```bash
export LLM_MODEL=gpt-6.1-sol
export LLM_BASE_URL=https://api.openai.com/v1
export LLM_API_KEY=sk-...
aiva_agent --vcf data/test.vcf.gz \
  --prompt "3yo female with developmental regression, hand stereotypies, and acquired microcephaly. Find candidate variants and propose the most likely diagnosis with supporting evidence."
```

## Contents

- [What it does](#what-it-does)
- [Prerequisites](#prerequisites)
- [Quickstart](#quickstart)
- [Web UI](#web-ui)
- [Examples](#examples)
- [Notebook usage](#notebook-usage)
- [Classify a single variant](#classify-a-single-variant-for-embedding--integrations)
- [Running on HPC](#running-on-hpc--older-glibc)
- [License](#license)

## What it does

The agent runs locally over a pre-annotated tabix-indexed VCF and can answer questions about your variants, retrieve supporting literature, surface clinical trials, prioritize candidate genes from phenotype terms, and run ACMG/AMP variant classification.

| Capability | What it does |
|---|---|
| Variant queries | Ask questions about your tabix-indexed `.vcf.gz` file. |
| Variant annotation | Annotate variants, for human and plant species. |
| Literature search | PubMed / PMC search with gene / disease / variant / chemical entity annotations, plus a per-variant lookup that returns the passages mentioning the variant. |
| Clinical trials | Search by condition, intervention, gene/variant, phase, recruiting status; full-detail retrieval by NCT ID. |
| Gene prioritization | Rank candidate genes for a list of HPO phenotype terms. Can use negative terms to exclude genes. |
| Web research | Web search and clean content extraction from any URL. |
| Variant classification | ACMG/AMP 2015 (germline) and AMP/ASCO/CAP 2017 (somatic) classification, returned as JSON. |
| BAM/CRAM access | Evidence from BAM/CRAM files (`--bam`): per-allele pileup with strand and indel counts, phase of two nearby variants, the reads in a window (CIGAR, mates, insert sizes) and window coverage. |
| Review and annotations | Flag variants per sample and save classifications to a local database the web UI's review panel reads. |
| File exploration | Look into any file in your working directory (CSV, TSV, Excel, JSON, parquet, plain text) and use whatever tools your environment has on PATH. Scope with `--workdir` or `AIVA_WORKDIR`; defaults to the current directory. |
| Task planning | Plans and tracks multi-step work within a single run: creates a todo list up front, marks items in progress, and completes them as it goes. State is per-run (not persisted across sessions). |
| Subagents | Runs subagents in parallel, one per independent unit of work (gene, sample, variant, question). Each subagent works from a self-contained goal and reports evidence, confidence, and caveats that the agent synthesizes. |

## Prerequisites

- **For `pip install`: Python 3.10+** with `pip ≥ 24`. The package is a compiled wheel; the agent itself doesn't run on Python. The Docker image needs no Python.
- **htslib tools** (`bgzip`, `tabix`) only needed for preparing VCFs (`brew install htslib` on macOS).
- **Linux: glibc ≥ 2.28** (Ubuntu ≥ 20.04, RHEL/Rocky ≥ 8, Debian ≥ 10) for the `vcf` tool. Older hosts can use the container image — see [Running on HPC](#running-on-hpc--older-glibc).
- **A `.env` file with your model settings.** Run `aiva_agent init` to create one with every setting explained in comments, then fill in your key. For all flags run `aiva_agent --help` (also `classify --help` and `aiva_agent_serve --help`); in Python or a notebook use `help(aiva_agent)`. `aiva_agent doctor` checks your setup.
- **Internet connectivity** — For HPC/cloud/remote environments/jobs, ensure outbound HTTPS to your LLM provider and to the public APIs the agent queries (NCBI E-utilities, ClinicalTrials.gov, DuckDuckGo, etc.). Behind a corporate proxy, set `HTTPS_PROXY` / `HTTP_PROXY` / `NO_PROXY` (honored automatically); for MITM proxies, add your org's root certificate to the system trust store. Only the local `vcf` tool runs without network.

## Quickstart

### 1. Install (pick one)

**pip** — fastest if you have Python 3.10+ on a modern Linux/macOS host:
```bash
pip install aiva-agent
```

**Docker** — works anywhere a container runs (Docker, Podman, Apptainer/Singularity). Useful when your host can't install Python or has older glibc (see [Running on HPC](#running-on-hpc--older-glibc)):
```bash
docker pull mhspl/aiva-agent:latest
```

**Python import** — call from a notebook or script (see [Notebook usage](#notebook-usage)):
```python
from aiva_agent import aiva_agent
```

### 2. Configure

Run `aiva_agent init` in your working directory. It creates a `.env` file with every setting explained in comments (it won't overwrite an existing `.env` unless you pass `--force`). Open it, set your model provider details, and uncomment the API key line:

```dotenv
LLM_MODEL=gpt-6.1-sol
LLM_BASE_URL=https://api.openai.com/v1
LLM_API_KEY=sk-...
```

The agent loads the file automatically on every run and works with any OpenAI-compatible endpoint. CLI flags and `export`ed variables take priority over it, so you can also use them for a one-off run.

**Web search works without a key**, at lower limits. For heavier use, add `WEB_API_KEY` to your `.env`: a [Firecrawl](https://www.firecrawl.dev) key (free tier ≈1,000 page fetches/month). `aiva_agent init` lists every optional key.

Questions about your VCF need `--vcf` (or `AIVA_VCF`); without one, that capability turns itself off.

**Security note:** prefer `.env` or `export LLM_API_KEY=...` over `--api-key sk-...` so the secret doesn't leak into shell history or `ps`.

Check the setup with `aiva_agent doctor`: it loads the VCF/BAM engine (installing its extension the first time) and says which keys are set, never their values.

### 3. Run

Prepare a tabix-indexed VCF (only once per file):
```bash
bgzip -k path/to/sample.vcf
tabix -p vcf path/to/sample.vcf.gz
```

A plain uncompressed `.vcf` also works, but region queries need the index, so the bgzip plus tabix form is recommended.

**Tip: prefer a pre-annotated VCF.** If you've already run your VCF through a variant-effect annotator (VEP, SnpEff, ANNOVAR, …), the agent can read those annotations directly from the file. Pre-annotation is recommended for variant prioritization and classification.

Then ask a question:
```bash
aiva_agent --vcf path/to/sample.vcf.gz \
  --prompt "List pathogenic variants"
```

Same invocation with Docker (bind-mount the VCF directory):
```bash
docker run --rm --env-file .env -v "$PWD/data:/work" \
  mhspl/aiva-agent:latest \
  --vcf /work/sample.vcf.gz --prompt "List pathogenic variants"
```

The same image also serves the browser UI — see [Web UI → With Docker](#web-ui).

## Web UI

A local browser chat for the same agent — useful when you want to drag-and-drop VCFs, browse multiple chats side-by-side, and read structured tabular results inline instead of as TSV in a terminal. Everything still runs on your machine; no data leaves the host.

### Install

The web UI is part of the base install (`pip install aiva-agent`); there is no separate extra any more.

### Run

Point the server at the directory that holds your VCFs / BAMs:

```bash
aiva_agent_serve --workdir ./data
```

Open `http://127.0.0.1:8765` in a browser. Then **+ New chat** → pick one or more VCF (and optional BAM) files from `--workdir`, give it a name, and ask questions.

Make sure to set `AIVA_WORKDIR` environment variable to the directory that holds your VCFs / BAMs.

**Remote VCFs (cloud buckets).** VCFs can live in object storage instead of `--workdir`. Two options:

- **Query in place** — in the **Attach** dialog, paste a remote URL (`gs://…`, `s3://…`, `https://…`) into the "remote VCF URL" field (or pass `--vcf gs://…` on the CLI). The `.tbi`/`.csi` index must sit next to the file in the bucket, and cloud credentials must be in the server's environment (`GCS_OAUTH_TOKEN` for GCS — refreshed hourly; the standard AWS chain for S3). No mount required.
- **Mount the bucket as `--workdir`** — FUSE-mount the bucket (gcsfuse / mount-s3 / s3fs) at a local path and pass it as `--workdir`; the picker then lists the bucket's files like any local folder. In this mode you **must** set `--state-dir` to local disk, since the `.aiva` DB can't live on the mount.

**With Docker.** The published image includes the server, available by overriding the entrypoint. Bind `0.0.0.0` so the container is reachable from the host, publish the port, and let your `.env` supply the model credentials:

```bash
docker run --rm --env-file .env -p 8765:8765 -v "$PWD/data:/work" \
  -e AIVA_HOST=0.0.0.0 \
  --entrypoint aiva_agent_serve \
  mhspl/aiva-agent:latest --workdir /work
```

Then open `http://127.0.0.1:8765`. The default entrypoint stays the CLI, so the same image runs either mode — see [Quickstart → Run](#3-run) for the CLI form.

The server answers only to `localhost`/`127.0.0.1` and its own `--host` address. To open it from another machine or through a proxy, add the name or address you browse to with `-e AIVA_ALLOWED_HOSTS=aiva.lab.example` (the UI has no login, so only do this on a trusted network).

### What's different from the CLI

- **Per-workdir history.** Conversation history lives at `<workdir>/.aiva/aiva.db`, so switching workdirs gives you a clean session namespace and you can keep one history per dataset.
- **Multi-session.** Each chat is its own session with its own VCF/BAM bindings — useful for keeping cases separate.

## Examples

For an end-to-end walkthrough in a notebook, see the example analysis on Colab:

[![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/drive/1G_4dG1XkBeulH3uJajseGDl3wUjyByJF?usp=sharing)

CLI one-liners:

```bash
# All tools are on by default — pass --disable vcf for prompts that don't need
# a local VCF, or set AIVA_DISABLE / AIVA_VCF in .env to make it permanent.

# Variant annotation
aiva_agent --disable vcf --model gpt-6.1-sol \
  --prompt "Annotate rs113488022. Report ClinVar significance and population AF."

# Literature search
aiva_agent --disable vcf --model gpt-6.1-sol \
  --prompt "Find 3 recent papers on TP53 R175H in lung cancer."

# Clinical trials
aiva_agent --disable vcf --model gpt-6.1-sol \
  --prompt "Find phase 2 recruiting BRAF V600E melanoma trials."

# HPO -> genes
aiva_agent --disable vcf --model gpt-6.1-sol \
  --prompt "Rank candidate genes for HP:0001250 + HP:0001263."

# Web search + scrape (handles PDFs; WEB_API_KEY raises the limits)
aiva_agent --disable vcf --model gpt-6.1-sol \
  --prompt "Find and scrape the latest NCCN melanoma guideline summary."

# ACMG/AMP classification — `classify` subcommand prints JSON (rs113488022 = BRAF V600E)
aiva_agent classify --type amp --assembly GRCh38 \
  --rsid rs113488022 --phenotype melanoma

# VCF query + literature (vcf tool turns on automatically once a path is provided)
aiva_agent --vcf data/test.vcf.gz --model gpt-6.1-sol \
  --prompt "Find any TP53 variants and pull supporting literature."
```

## Notebook usage

Set env vars in one cell, call `aiva_agent(...)` in the next; calls within the same kernel automatically share a session, so follow-up questions remember the prior turn.

```python
# cell 1
import os
os.environ["LLM_API_KEY"] = "sk-..."
os.environ["LLM_BASE_URL"] = "https://api.openai.com/v1"
os.environ["LLM_MODEL"] = "gpt-6.1-sol"
os.environ["AIVA_VCF"] = "data/sample.vcf.gz"

# cell 2
from aiva_agent import aiva_agent
print(aiva_agent("List 3 likely-pathogenic variants from vcf."))
print(aiva_agent("Of those, which is in a recessive disease gene?"))  # remembers
```

For every keyword argument, run `help(aiva_agent)` (or `?aiva_agent` in Jupyter). To start a fresh conversation mid-notebook, call `reset_session()`. To pin a specific ID (e.g. resume across kernel restarts), set `AIVA_SESSION_ID` in env or pass `session_id="my-case"` to `aiva_agent`. Per-call kwargs `vcf=`, `bam=`, `disable=`, `model=`, `base_url=`, `api_key=`, `workdir=`, `state_dir=` override the corresponding env vars; `stream=True` prints tool calls and the answer as they come.

## Classify a single variant (for embedding / integrations)

To run just ACMG/AMP classification on one variant — without the conversational agent — call `classify(...)`. It returns the classification as a `dict`, so other tools can consume it directly.

```python
import asyncio
from aiva_agent import classify

result = asyncio.run(classify(
    {"hgvs": "NM_004333.6:c.1799T>A"},   # required: or {"rsid": ...} or {"chrom","pos","ref","alt"}
    classification_type="acmg",          # required: "acmg" (germline, ACMG/AMP 2015) or "amp" (somatic, AMP/ASCO/CAP 2017)
    assembly="GRCh38",                   # required: "GRCh37" or "GRCh38"
    phenotype_terms="melanoma",          # optional: disease / phenotype context, e.g. "hereditary breast cancer"
    description="42yo, family history of breast cancer",   # optional: free-text sample/patient context
    additional_context="de novo, confirmed by trio sequencing; heterozygous",  # optional: verified clinical context (de novo status, zygosity, segregation, family history); criteria are applied strictly to what's stated here
    workdir="./data",                    # optional: scopes the classifier's shell access (default: current directory). It gets the same tools as the agent, including shell access for evidence gathering, so pass a path to sandbox it
    model="gpt-6.1-sol",                   # optional, falls back to LLM_MODEL
    base_url="https://api.openai.com/v1",  # optional, falls back to LLM_BASE_URL
    api_key="sk-...",                    # optional, falls back to LLM_API_KEY
))
print(result["classification"], result.get("criteria_met"))
```

The result is schema-validated through structured output, so it's always a well-formed `dict`: for `acmg` it contains `input_issue`, `classification`, `confidence`, `acmg_score`, `criteria_met`, `evidence_summary` (an entry per ACMG criterion), `classification_rationale`, and `sources`; for `amp` it contains `input_issue`, `classification`, `confidence`, `criteria_met`, `evidence_summary`, `therapeutic_summary`, `diagnostic_summary`, `prognostic_summary`, and `sources`. When the variant can't be verified as given (Ensembl rejects it, or no source has a record), `classification` is `"Not classified"` and `input_issue` says why; otherwise `input_issue` is empty. (Structured output requires a provider that supports it: OpenAI, Anthropic, and OpenAI-compatible endpoints with `json_schema` response format.)

The same is available from the command line via the `classify` subcommand, which prints the JSON result to stdout:

```bash
aiva_agent classify --type acmg --assembly GRCh38 \
  --hgvs "NM_004333.6:c.1799T>A" --phenotype melanoma
```

Specify the variant with `--hgvs`, `--rsid`, or all of `--chrom/--pos/--ref/--alt`. Optional flags mirror the Python kwargs: `--description`, `--context` (verified clinical context; maps to `additional_context`), `--workdir` (scopes the classifier's `bash` tool), and `--model/--base-url/--api-key` (fall back to the `LLM_*` env vars).

## Running on HPC / older glibc

If your host has glibc < 2.28 (typical on CentOS/RHEL 7-era HPC nodes), the wheel's compiled binaries won't load; use the container image instead. The image (`mhspl/aiva-agent:latest`) ships with the right binaries pre-baked. Apptainer/Singularity can pull it directly:

```bash
apptainer pull aiva-agent.sif docker://mhspl/aiva-agent:latest
apptainer exec --bind "$PWD:/work" aiva-agent.sif \
  aiva_agent --vcf /work/sample.vcf.gz --prompt "..."
```

Submit the job on a node that satisfies the [Outbound HTTPS](#prerequisites) prerequisite — the container doesn't change network requirements.

## License

aiva-agent is licensed under the **PolyForm Noncommercial License 1.0.0**.

- **Free for noncommercial use** — personal use, academic research, education, and use by charitable, public-research, public-health, and government institutions.
- **Commercial use requires a separate license.** Contact tarun@mamidi.ai for commercial licensing terms.
