# Genomic Intelligence API > A typed REST API and MCP server for six DNA sequence analysis tasks (promoter, splice, enhancer, chromatin, expression, annotation) powered by transformer language models. Bearer auth, typed {data, meta} envelopes, sync + async dispatch. This file contains all documentation content in a single document following the llmstxt.org standard. ## Agent integration guide The Genomic Intelligence API runs six DNA sequence analysis tasks built on transformer language models. Each task is a single HTTP endpoint — `POST /v1/tasks//predict` — and one composite workflow chains two of them. The same tasks are also reachable over [MCP](mcp.md). This page orients you to the REST API and points to the canonical guides and reference. For the step-by-step walkthrough, jump to the [REST API guide](rest-api.md). Base URL: `https://api.genomicintelligence.ai` ### Overview Every endpoint shares one contract: - **Six tasks**, one published operation each: `POST /v1/tasks/{promoter,splice,enhancer,chromatin,annotation,expression}/predict`, plus the composite `POST /v1/workflows/find-genes-and-predict-expression`. - **Per-task request bodies.** Each task has its own request schema, its own minimum `sequence` length, and its own **closed** `options` object — there is no shared `PredictRequest`. The URLs are unchanged; a typed client generated from an older document is not. - **Bearer authentication** on every `/v1/*` route. Public routes (no key): `/health`, `/docs`, `/redoc`, `/v1/openapi.json`, and `GET /v1/tasks/{task}/models` (the model list). - **One success envelope**: `{data, meta}` on every 2xx and 202. `data` carries task-specific fields; `meta` is uniform across tasks. `GET /v1/tasks/{task}/models` is the exception — a flat `{task, default_model, models}` object. - **One error envelope**: `{error: {code, message, request_id, details?}}`. `code` is a closed 21-value enum; treat an unlisted value as a generic failure rather than a parse error. - **Synchronous by default, asynchronous on request.** `Prefer: respond-async` is a declared header parameter on all six predict operations and the composite: the call returns `202` with `{data: {job_id, status, links}, meta}`, and you poll `GET /v1/tasks/jobs/{job_id}` until it reaches a terminal state. Async is JSON-only. #### Length bounds per task Minimums are per task, published as `minLength` on that task's request schema and enforced before any model loads; the maximum is 500,000 bp everywhere. Lengths are measured **after whitespace is stripped**. | Task | `sequence` | Model window (`context_window_bp`) | |---|---:|---:| | `promoter` | 300–500,000 bp | 2,000 (default) · 300 on the `*-300bp` models | | `splice` | 100–500,000 bp | 15,000 | | `enhancer` | 50–500,000 bp | 249 | | `chromatin` | 200–500,000 bp | 1,000 | | `annotation` | 1,000–500,000 bp | — | | `expression` | 9,198–500,000 bp, TSS ≥ 4,599 bp from each end | — (see `recommended_flank_bp`) | | `find-genes-and-predict-expression` | 1,000–500,000 bp | — | Being above the floor is **not** the same as being in regime: a sequence shorter than the selected model's `context_window_bp` (from `GET /v1/tasks/{task}/models`) is accepted and scored against a window padded out to that size, with nothing in the response flagging it. Longer than the context window is fine — the scanner steps a window at a time. Out-of-range lengths are `422 validation_failed`, **not** `413`; `413` means either the 16 MiB body cap (`payload_too_large`) or a synchronous-delivery cap (`sync_too_large`) — the composite's 50,000 bp or annotation's 200,000 bp, the only two in the contract. Annotation's applies to a **JSON** response only: `?format=bed` and `?format=gff3` are uncapped and stay synchronous, since async is JSON-only and a text format with `Prefer: respond-async` is a `400`. The live OpenAPI document at `https://api.genomicintelligence.ai/v1/openapi.json` is the machine-readable source of truth. It carries a `oneOf` discriminator on `data.task`, so generated typed clients (Python pydantic, TypeScript zod) narrow the success payload correctly. `error.details` is an **undiscriminated** `anyOf` — narrow it on `error.code`, not by shape. A rendered view is at `https://api.genomicintelligence.ai/redoc`. ### Authentication All `/v1/*` routes require an API key: ```http Authorization: Bearer gi_... ``` Verify connectivity before integrating: ```bash curl -sS https://api.genomicintelligence.ai/health # {"status":"healthy","version":"YYYY.MM.DD.iter (commit)"} curl -sS -H "Authorization: Bearer $GI_API_KEY" \ https://api.genomicintelligence.ai/v1/tasks/promoter/models # 200 with {task, default_model, models: [...]} ``` Model-listing endpoints return a flat object, not the `{data, meta}` envelope used by predict endpoints. Per-key rate caps, the `RateLimit-*` headers, and the concurrency limiter are documented in [Limits](reference/limits.md). ### Get started The [REST API guide](rest-api.md) has the full walkthrough: the contract, the downloadable integration kit (a drop-in single-file `gi_client.py` depending only on `requests`), simple sync and async examples in Python, and self-contained recipes — promoters across a gene list, async annotation polling, rate-limit-aware retry, typed error handling. #### Using with an AI coding agent If you are integrating from inside an AI coding agent, point it at this page and the [llms.txt](https://docs.genomicintelligence.ai/llms.txt) index so it works from the same contract. To have an agent inherit these rules across sessions, save this guide into your repo as `AGENTS.md` (or `CLAUDE.md`) — the raw Markdown is served at [docs.genomicintelligence.ai/AGENTS.md](https://docs.genomicintelligence.ai/AGENTS.md). If your agent runs in an MCP client such as Claude Desktop, Cursor, or Claude Code, the [MCP server](mcp.md) reaches the same six tasks with typed tools. If your agent loads [Agent Skills](https://agentskills.io), download [genomic-intelligence.zip](https://docs.genomicintelligence.ai/skill/genomic-intelligence.zip) and unzip it into the agent's skills directory. It carries a short `SKILL.md` (when to use MCP or REST, key setup, and the input mistakes the API accepts without an error) and the same `gi_client.py` and recipes as the integration kit. It holds no API key and no limits of its own; it points back to this guide for those. ### The six tasks Each task accepts a DNA `sequence` (and a `sequence_name` label) and returns task-specific fields under `data`. See the [Tasks](tasks.md) page for biology, task-specific options, and output fields; per-task length caps are in [Limits](reference/limits.md). | Task | Endpoint | Output | |---|---|---| | [`promoter`](tasks.md#promoter) | `POST /v1/tasks/promoter/predict` | Promoter-region probabilities (binary classification). | | [`splice`](tasks.md#splice) | `POST /v1/tasks/splice/predict` | Per-token acceptor and donor splice-site predictions. | | [`enhancer`](tasks.md#enhancer) | `POST /v1/tasks/enhancer/predict` | Developmental and housekeeping enhancer-activity scores (regression). | | [`chromatin`](tasks.md#chromatin) | `POST /v1/tasks/chromatin/predict` | Multi-label chromatin features grouped into tracks. | | [`annotation`](tasks.md#annotation) | `POST /v1/tasks/annotation/predict` | Gene-finding transcript intervals (TSS/PolyA detection). | | [`expression`](tasks.md#expression) | `POST /v1/tasks/expression/predict` | Predicted gene expression in log(TPM+1), from sequence plus an experimental description. | | [composite](tasks.md#find-genes-and-predict-expression) | `POST /v1/workflows/find-genes-and-predict-expression` | Genes found in a region, each with a predicted expression — annotation and expression chained server-side. | #### `options` is typed and closed per task Unknown keys are rejected with `422 validation_failed` (`type: "extra_forbidden"`, `loc: ["body","options",""]`), never ignored. A model is selected with the **top-level `model` field**, not `options.model`. | Task | `options` | |---|---| | `promoter` | `threshold` (0–1, default 0.5) | | `splice` | `threshold` (0–1, default 0.5 — see the response-size cap under [Error handling](#error-handling)), `site_types` (subset of `["donor","acceptor"]`, default both) | | `enhancer` | *no fields* | | `chromatin` | `threshold` (0–1, default 0.5) | | `annotation` | `shift_coordinates`, `reverse_complement` (default `true`) | | `expression` | `description` — **required**, as is `options` itself | | composite | `description` (required at runtime), `annotation_model`, `expression_model`, `shift_coordinates`; `options` itself is required | **`expression` is the task with the most extra rules.** The rule is the same for every expression model: its `sequence` must be **at least 9,198 bp** (up to 500,000) with the TSS **at least 4,599 bp from each end** (shorter is a hard `422` — no padding, no truncation), and any submission that is not exactly 9,198 bp must also carry **`tss_index`**: the 0-based TSS offset into the **whitespace-stripped** sequence, bounded by `4599 <= tss_index <= len(sequence) - 4599`. There is no `tes_index`. Longer TSS-centred sequence is better, and the model list says how much; never hard-code a window, flank or model id. Read `GET /v1/tasks/expression/models` (public): use the model your user named, else `default_model`, and pass it as `model` on every call of a run; take `F` = the largest `bio_spec.recommended_flank_bp` among the listed models (one fetch serves any of them), never below 4,599 and with `2F` within `request_max_bp`; put the TSS at offset `F` of the gene-sense sequence and send `tss_index = F`. With `tss` the 0-based genomic TSS position, fetch `[tss − F, tss + F)` on the plus strand, or `(tss − F, tss + F]` and reverse-complement it on the minus strand; reverse-complementing the plus-strand interval leaves the TSS at `F − 1`, a legal index for the wrong window. The server cuts what the model reads around `tss_index` and echoes it at `meta.task_specific_counts.scored_window` (its width depends on the model) — check that it sits around your TSS, because a wrong-but-in-range index returns a confident `200` for the wrong region. A window dominated by `N` or low-complexity repeats can be refused with `422` (roughly 2 kb of real sequence upstream and 2.6 kb downstream for `g0-expression`; 3.3 kb and 2.6 kb for `g0-expression-8192`). The `tss_index` checks report at `loc: ["body"]`, never `body.tss_index`, so match on `error.code`. Details: [Tasks](tasks.md#expression) and [Limits](reference/limits.md#expression-sequence-length-and-tss_index). **The composite** takes plus-strand genomic input, finds the genes itself and windows each TSS, so it needs no `tss_index` and its floor is 1,000 bp. It scores each gene with the API's default expression model (or the one named in `options.expression_model`), using as much flank around each TSS as the submitted region holds, so longer regions give better predictions. Above 50,000 bp it refuses synchronous delivery with `413 sync_too_large` — resend with `Prefer: respond-async`. (`POST /v1/tasks/annotation/predict` has the same behaviour above 200,000 bp; no other endpoint is capped.) `meta.task_specific_counts` is `{genes_found, genes_predicted, genes_skipped}` (they sum), with per-gene causes in `data.expression_predictions[].skip_reason`. ### Model selection Each task has a default model and may offer alternatives. List them with `GET /v1/tasks/{task}/models` (public, no key needed; an unknown task is `404 not_found`); the response is a flat object with `default_model` and a `models` array, each carrying a `bio_spec` with `request_max_bp` (the enforced ceiling), `context_window_bp`, `trained_window_bp` and, for expression, `recommended_flank_bp`. Use `request_max_bp` as the cap. Older responses may also carry `max_seq_length_bp`; it is ambiguous — the request cap for every model except `g0-expression`, where it is instead the 9,198 bp trained window — so do not read it, and do not depend on it being present. If you do not name a model the task uses `default_model`; to pick one, pass its id in the **top-level `model` field** of the request body — `options.model` is a `422`. Beyond the default human models, `promoter` offers species-specific variants (Drosophila, yeast, Arabidopsis) and DNABERT k-mer variants exist for `promoter`, `enhancer`, and `chromatin`; `expression` offers more than one model, and `default_model` names the current default. The model-list endpoint is authoritative for what each task currently serves. ### Error handling Every error uses the envelope `{error: {code, message, request_id, details?}}`. Switch on `error.code`, not on `error.message` — the code is the authoritative discriminator; the message is for human-readable logs and can change without notice. Map every code to one of three actions: 1. **Retryable transient** (`too_many_requests`, `rate_limited`, `model_loading`, `service_unavailable`, `timeout`, `insufficient_memory`): honor `Retry-After`; if absent, back off exponentially, capped at 30 s. 2. **Permanent client error** (other `4xx`): surface `error.message`; do not retry. `422` messages are deterministic and safe to echo. 3. **Server error** (`5xx` other than `503`): capture `request_id`, retry once at most, then escalate. Read `error.details` defensively and **never branch on `loc`**: `validation_failed` details are *usually* the declared object (`{errors: [...]}`, each entry the FastAPI `{loc, msg, type}` shape), but the `loc` values themselves are not a stable contract — expression's `tss_index` checks report at `loc: ["body"]` rather than `body.tss_index`. One `validation_failed` has a different shape entirely: splice's response-size cap sends `{task, record_count, maximum_records, sequence_length, threshold}` with no `errors` key. Switch on `code`, and read `details.get("errors", [])`. **The splice response-size cap is not in OpenAPI.** `POST /v1/tasks/splice/predict` returns `422 validation_failed` if the response would carry more than **20,000 sites** — reachable only by setting `options.threshold` very low on a long sequence, where the site count tracks length rather than biology. The remedy is a higher threshold, never a shorter sequence. If you are lowering the threshold to capture everything, use `1e-3` rather than `0`: equivalent within 4.6e-4, ~4x faster (serialisation, not inference, is the bottleneck), and under the cap. Details: [Limits](reference/limits.md#response-size-the-splice-site-cap). `504 gateway_timeout` is the one response with no envelope (it comes from the edge proxy) — treat it as a signal to switch to async. The full code catalog, typed `details` shapes, and handling notes are in [Errors](reference/errors.md). ### Next steps - [REST API guide](rest-api.md): the REST walkthrough, the downloadable `gi_client.py`, and runnable recipes. - [Errors](reference/errors.md): the `error.code` catalog and handling strategy. - [Limits](reference/limits.md): per-task caps, rate quotas, and async job TTL. - [Support](resources/support.md): contact, bug reports, and production access. - [MCP server](mcp.md): the six tasks over Model Context Protocol. - [Agent Skill](https://docs.genomicintelligence.ai/skill/genomic-intelligence.zip): this guide's routing rules plus the client, packaged for agents that load skills. - [API reference (ReDoc)](https://api.genomicintelligence.ai/redoc): the full rendered OpenAPI. - [OpenAPI schema](https://api.genomicintelligence.ai/v1/openapi.json): the live machine-readable contract. --- ## Overview Genomic Intelligence runs transformer language models over DNA sequences for six tasks: promoter, splice site, enhancer, chromatin, expression, and annotation. The same models are exposed two ways: a typed REST API and an MCP server. :::tip[Full API reference] **[ReDoc](https://api.genomicintelligence.ai/redoc) is the full API reference, generated from the live OpenAPI schema.** It documents every endpoint, field, and response. The pages here are guides and orientation — they don't restate the schema. ::: ### Two ways to integrate #### Integrate directly Call the REST API from any language. Authenticate with an API key, post a sequence to `/v1/tasks//predict`, and get back typed results. Use this when you are wiring the API into an application or pipeline. [REST API →](rest-api.md) #### Use it in an AI chat Ask questions over DNA in **Claude, ChatGPT, or your own agent** and let it call the six tasks as tools. Start with **no key and no install** via the hosted GI connector, then move to a local server for real work. [Use GI in an AI chat →](mcp.md) ### The contract Both paths share one contract: - **Six tasks**, one endpoint each: `POST /v1/tasks//predict` for `promoter`, `splice`, `enhancer`, `chromatin`, `expression`, `annotation` — plus two workflows: [find-genes-and-predict-expression](tasks.md#find-genes-and-predict-expression) and [genomic-variant-interpretation](tasks.md#genomic-variant-interpretation), which takes a VCF rather than a sequence. - **Bearer auth** on every `/v1/*` route. Public (no key): `/health`, `/docs`, `/redoc`, `/v1/openapi.json`, and **capability discovery** — `GET /v1/tasks/{task}/models`, so you can read each model's window geometry and `request_max_bp` before you have a key. Discovery is rate-limited per source IP. - **One success envelope** — `{data, meta}` on every 2xx and 202. `data` is task-specific; `meta` is uniform. - **One error envelope** — `{error: {code, message, request_id, details?}}`. Switch on `error.code`, never the message. - **Sync by default, async on request** — add `Prefer: respond-async` to submit a job, then poll `GET /v1/tasks/jobs/{job_id}`. - **Per-task bounds** — each task sets its own minimum sequence length (promoter 300 bp … expression 9,198 bp, with longer input recommended) and its own closed `options`; the maximum is 500,000 bp everywhere. See [Limits](reference/limits.md#input-length-per-task). No key yet? Email [contact@genomicintelligence.ai](mailto:contact@genomicintelligence.ai). ### The tasks | Task | What it does | |---|---| | [Promoter](tasks.md#promoter) | Classify whether a sequence contains a promoter region. | | [Splice](tasks.md#splice) | Annotate donor and acceptor splice sites across long sequences. | | [Enhancer](tasks.md#enhancer) | Score developmental and housekeeping enhancer activity. | | [Chromatin](tasks.md#chromatin) | Predict chromatin features (DNase, CTCF, histone marks, …) as grouped tracks. | | [Expression](tasks.md#expression) | Predict gene expression from sequence + an experimental description, in log(TPM+1). | | [Annotation](tasks.md#annotation) | Find genes by detecting TSS and PolyA signals, emitting transcript intervals. | | [Find genes + expression](tasks.md#find-genes-and-predict-expression) | Composite: find the genes in a region and predict each one's expression in one call. | ### Integrating from a coding agent Point a coding agent at the [`llms.txt`](https://docs.genomicintelligence.ai/llms.txt) index so it works from the same contract, or drop the single-file agent guide into your repo as `AGENTS.md` (or `CLAUDE.md`) — the raw Markdown is served at [`/AGENTS.md`](https://docs.genomicintelligence.ai/AGENTS.md). For MCP clients, the [MCP server](mcp.md) reaches the same six tasks as typed tools. ### Live URLs - API base: [https://api.genomicintelligence.ai](https://api.genomicintelligence.ai) - API reference (ReDoc): [https://api.genomicintelligence.ai/redoc](https://api.genomicintelligence.ai/redoc) - Interactive API explorer (Swagger UI): [https://api.genomicintelligence.ai/docs](https://api.genomicintelligence.ai/docs) - OpenAPI schema: [https://api.genomicintelligence.ai/v1/openapi.json](https://api.genomicintelligence.ai/v1/openapi.json) --- For research and development use, not clinical or diagnostic decisions. Prefer to explore in a browser? Try the [web app](https://app.genomicintelligence.ai). Questions: [contact@genomicintelligence.ai](mailto:contact@genomicintelligence.ai). --- ## Python client The client is one dependency-light file you drop into your project — no SDK to install, no build step. Read it here, or download the whole kit: **[Download the integration kit](https://docs.genomicintelligence.ai/integration-kit.tar.gz)** (`.tar.gz`) — every file below plus the docs, bundled. ### client/gi_client.py Single-file client. Depends only on `requests`. Wraps sync predict, async submit + poll, the composite annotation→expression workflow, job lifecycle, and model listing; returns the unified `{data, meta}` envelope and raises a typed `GIError` on any non-2xx. [Download raw](https://docs.genomicintelligence.ai/client/gi_client.py) ```python title="client/gi_client.py" """Tiny client for the Genomic Intelligence API. Wraps `requests` with bearer auth, the unified `{data, meta}` / `{error}` envelope, and a polling helper for async jobs. Drop this file into your project and `from gi_client import Client`. Endpoints covered: - the six per-task predictors, each its own published operation: ``POST /v1/tasks/{promoter,splice,enhancer,chromatin,annotation, expression}/predict`` - the composite ``POST /v1/workflows/find-genes-and-predict-expression`` - the async job endpoints ``GET /v1/tasks/jobs[/{job_id}]`` - model discovery ``GET /v1/tasks/{task}/models`` Plus one input helper, ``Client.fetch_expression_window(symbol)``: a TSS-centred, gene-sense expression input fetched from the public Ensembl REST API, sized from the model list. Contract reference: https://api.genomicintelligence.ai/redoc """ from __future__ import annotations import time from typing import Any, Dict, Mapping, Optional, Tuple import requests #: Minimum ``sequence`` length per task, in bp, measured AFTER whitespace is #: stripped. This is a MIRROR for local pre-flight only — the authority is the #: ``minLength`` published on each task's request schema in the live OpenAPI #: document (``GET /v1/openapi.json``, public and unauthenticated), generated #: from the service's ``api/core/limits.py``. #: #: The two can no longer disagree quietly. ``scripts/check_contract.py`` reads #: this table straight out of this file and asserts it against #: ``scripts/contract.json``, a pin of the live document; it runs on every PR #: and **blocks the deploy**. ``scripts/sync_contract.py --check`` re-verifies #: the pin against the live API daily. If you need to change a number here, #: re-pin first and reconcile this table to the contract — never the reverse. TASK_MIN_BP: Dict[str, int] = { "promoter": 300, "splice": 100, "enhancer": 50, "chromatin": 200, "annotation": 1_000, "expression": 9_198, "find-genes-and-predict-expression": 1_000, } #: Maximum ``sequence`` length, in bp, for every task (same mirror caveat). #: Also published per model as ``bio_spec.request_max_bp``. MAX_BP = 500_000 #: Above this, the composite workflow refuses synchronous delivery with #: ``413 sync_too_large`` — resend the same body with ``Prefer: respond-async``. FIND_GENES_SYNC_LIMIT_BP = 50_000 #: The expression floor per side: the TSS must sit at least this far from each #: end. Derived from the pinned ``TASK_MIN_BP["expression"]`` (2 x 4,599) so #: there is one number to keep in step with the contract, not two. It is a #: floor, never the flank to fetch: :meth:`Client.fetch_expression_window` #: takes the flank from the model list. EXPRESSION_MIN_FLANK_BP = TASK_MIN_BP["expression"] // 2 #: Public Ensembl REST base (no key). Override per call with ``ensembl_url=``. ENSEMBL_URL = "https://rest.ensembl.org" class GIError(RuntimeError): """Raised on any non-2xx response from the API. Attributes mirror the unified error envelope so callers can switch on ``code`` rather than HTTP status alone: {"error": {"code": "...", "message": "...", "request_id": "...", "details": ...}} ``details`` is carried through verbatim and never parsed. Its shape is keyed on the sibling ``code`` and has varied across releases — for ``validation_failed`` you may see either a bare ``[{loc, msg, type}, ...]`` array or ``{"errors": [...]}`` — and splice's response-size cap emits a ``validation_failed`` with neither (``{task, record_count, maximum_records, sequence_length, threshold}``). Branch on ``code`` and treat ``details`` as display-only, and you are correct against all of them. """ def __init__( self, status: int, body: Dict[str, Any], headers: Optional[Mapping[str, str]] = None, ): err = (body or {}).get("error", {}) if isinstance(body, dict) else {} self.status = status self.code = err.get("code", "http_error") self.message = err.get("message", "") # The X-Request-Id header is set on every response, including any # error whose body omits error.request_id. Fall back to it — support # tickets always need a correlation id. self.request_id = err.get("request_id") or (headers or {}).get("X-Request-Id") self.details = err.get("details") rid = self.request_id or "unset" super().__init__(f"[{status} {self.code}] {self.message} (request_id={rid})") class EnsemblError(RuntimeError): """Ensembl could not be reached, or did not resolve the gene or region.""" class ExpressionWindowError(ValueError): """The gene cannot be windowed for expression. Raised when the canonical TSS is so close to a chromosome end that even the 4,599 bp-per-side floor does not fit, or when Ensembl resolves no canonical transcript (the gene body can sit tens of kb from the TSS, so falling back to it would score the wrong window at full confidence). """ # ------------------------------------------------- expression window helpers # # Ported from a tested implementation; see the tests in # kit/client/tests/test_expression_window.py. All genomic coordinates below # are Ensembl's: 1-based, inclusive. def expression_flank_bp(listing: Mapping[str, Any]) -> Tuple[int, Optional[str]]: """How much to fetch on each side of the TSS, and which model asked for it. ``listing`` is the body of :meth:`Client.list_models` for ``expression``. F is the largest ``bio_spec.recommended_flank_bp`` among the listed models, so one fetch serves whichever model scores it (the server ignores flank beyond what a model reads). It is never below the 4,599 bp floor and is capped so 2F fits every listed model's ``request_max_bp`` (or :data:`MAX_BP` where a model publishes none). Returns ``(F, model_id)``; ``model_id`` is None when no model recommends more than the floor. """ models = [m for m in (listing.get("models") or []) if isinstance(m, dict)] caps = [] for m in models: cap = (m.get("bio_spec") or {}).get("request_max_bp") caps.append(cap if isinstance(cap, int) and not isinstance(cap, bool) else MAX_BP) ceiling = (min(caps) if caps else MAX_BP) // 2 best, source = EXPRESSION_MIN_FLANK_BP, None for m in models: f = (m.get("bio_spec") or {}).get("recommended_flank_bp") if not isinstance(f, int) or isinstance(f, bool): continue f = min(f, ceiling) if f > best or (f == best and source is None): best, source = f, m.get("id") return best, source def expression_window_bounds(tss: int, strand: int, flank: int) -> Tuple[int, int]: """1-based inclusive genomic bounds of the 2F window around a 1-based TSS. The TSS must land at offset F of the sequence *as submitted*. Ensembl reverse-complements the region for ``strand=-1``, so that sequence reads from ``end`` down to ``start`` and the TSS sits at ``end - tss``; giving the extra base to the high side on the minus strand puts both strands at F. In 0-based terms: plus ``[tss-F, tss+F)``, minus ``(tss-F, tss+F]`` then reverse-complemented. A one-base error here is invisible downstream: the length and the index are still legal, and the API scores a window shifted by one with full confidence. """ if strand == -1: return tss - flank + 1, tss + flank return tss - flank, tss + flank - 1 def _largest_fitting_flank(tss: int, strand: int, flank: int, chrom_len: Optional[int]) -> int: """The largest symmetric flank <= ``flank`` whose window stays on the chromosome.""" # Plus: start = tss - F >= 1, end = tss + F - 1 <= len. # Minus: start = tss - F + 1 >= 1, end = tss + F <= len. room_low = tss - 1 if strand == 1 else tss f = min(flank, room_low) if chrom_len is not None: room_high = chrom_len - tss + 1 if strand == 1 else chrom_len - tss f = min(f, room_high) return f def _ensembl_get(base: str, path: str, *, accept: str = "application/json", params: Optional[Dict[str, Any]] = None, timeout: float = 30.0) -> requests.Response: # A bare requests.get, never the API session: the GI key must not go to Ensembl. try: return requests.get( f"{base.rstrip('/')}{path}", headers={"Accept": accept, "User-Agent": "gi-client"}, params=params, timeout=timeout, ) except requests.RequestException as exc: raise EnsemblError(f"could not reach Ensembl at {base} ({type(exc).__name__}: {exc})") from exc def lookup_symbol(symbol: str, species: str = "human", ensembl_url: str = ENSEMBL_URL, timeout: float = 30.0) -> Dict[str, Any]: """Resolve a gene symbol with its canonical transcript (Ensembl ``expand=1``). Returns ``{ensembl_id, gene, seq_region, strand, tss}`` with ``tss`` the 1-based canonical-transcript start on the plus strand, end on the minus strand. The gene body is never used as a fallback: its ends can sit tens of kb from the real TSS (HBB's gene end is 2,324 bp from it, ACTB's 33,301 bp). """ r = _ensembl_get(ensembl_url, f"/lookup/symbol/{species}/{symbol}", params={"expand": 1}, timeout=timeout) if r.status_code == 404: raise EnsemblError(f"gene symbol {symbol!r} not found in {species}") if not r.ok: raise EnsemblError( f"Ensembl lookup failed ({r.status_code}) for {symbol!r} in species {species!r}" ) try: d = r.json() except ValueError as exc: raise EnsemblError(f"Ensembl lookup for {symbol!r} returned non-JSON") from exc strand = -1 if int(d.get("strand", 1)) < 0 else 1 canonical = next( (t for t in d.get("Transcript") or [] if t.get("is_canonical") == 1), None ) if canonical is None: raise ExpressionWindowError( f"{symbol} ({d.get('id')}): Ensembl resolved no canonical transcript, so " "the TSS is unknown; supply the window and tss_index yourself" ) tss = int(canonical["start"]) if strand == 1 else int(canonical["end"]) return { "ensembl_id": d["id"], "gene": d.get("display_name", symbol), "seq_region": str(d["seq_region_name"]), "strand": strand, "tss": tss, } def chromosome_length(seq_region: str, species: str = "human", ensembl_url: str = ENSEMBL_URL, timeout: float = 30.0) -> Optional[int]: """Length of a seq region from Ensembl ``/info/assembly``; None if unknown.""" r = _ensembl_get(ensembl_url, f"/info/assembly/{species}/{seq_region}", timeout=timeout) if not r.ok: return None try: length = r.json().get("length") except ValueError: return None return length if isinstance(length, int) and not isinstance(length, bool) else None def fetch_region(seq_region: str, start: int, end: int, strand: int = 1, species: str = "human", ensembl_url: str = ENSEMBL_URL, timeout: float = 30.0) -> str: """Sequence of a 1-based inclusive region; ``strand=-1`` comes back reverse-complemented.""" region = f"{seq_region}:{start}..{end}:{strand}" r = _ensembl_get(ensembl_url, f"/sequence/region/{species}/{region}", accept="text/x-fasta", timeout=timeout) if not r.ok: raise EnsemblError(f"Ensembl sequence fetch failed ({r.status_code}) for {region}") return "".join( ln.strip() for ln in r.text.splitlines() if ln.strip() and not ln.startswith(">") ).upper() class Client: """Thin synchronous client. >>> c = Client(api_key="gi_…") >>> r = c.predict("promoter", sequence="ACGT" * 500, sequence_name="demo") >>> r["meta"]["inference_time_ms"] """ def __init__( self, api_key: str, base_url: str = "https://api.genomicintelligence.ai", timeout: float = 120.0, client_app: Optional[str] = None, ) -> None: """``client_app`` (optional) names the tool or group calling, sent as ``X-GI-Client-App`` on every request. It changes nothing about auth, routing or the response; it lets us tell callers sharing one key apart. Omitted, the header is not sent.""" self.base_url = base_url.rstrip("/") self.timeout = timeout self._session = requests.Session() self._session.headers.update( { "Authorization": f"Bearer {api_key}", "Content-Type": "application/json", "Accept": "application/json", } ) if client_app is not None: self._session.headers["X-GI-Client-App"] = client_app # ------------------------------------------------------------------ helpers def _check(self, resp: requests.Response) -> Dict[str, Any]: try: body = resp.json() except ValueError: # A response arrived but is not JSON — usually an edge proxy. Use # http_error: error.code is a closed enum published in the schema, # so a synthesized value outside it is one no caller can match on. # Client-origin errors carry no request_id (the server never saw # this one), which is how you tell them apart from server errors. body = {"error": {"code": "http_error", "message": resp.text[:200]}} if not resp.ok: raise GIError(resp.status_code, body, resp.headers) return body # ----------------------------------------------------------------- requests def health(self) -> Dict[str, Any]: r = self._session.get(f"{self.base_url}/health", timeout=self.timeout) return self._check(r) def list_models(self, task: str) -> Dict[str, Any]: """``GET /v1/tasks/{task}/models`` — public; the key is sent but not needed. Returns a FLAT ``{task, default_model, models: [...]}`` object, not the ``{data, meta}`` envelope. Each model carries ``bio_spec`` with ``request_max_bp`` (the enforced ceiling), ``context_window_bp`` (the model's own window — compare your sequence length against it to know whether the model saw real sequence or padding; null for annotation and expression) and ``trained_window_bp`` (fixed receptive field where the model has one; null for sliding-window models). Expression models also carry ``recommended_flank_bp``. Never hard-code a window, flank or model id: use the model your user named, else ``default_model``, and pass it as ``model`` on every call of a run; take F = the largest ``recommended_flank_bp`` among the listed models (one fetch serves any of them), never below 4,599 and with 2F within ``request_max_bp``. Put the TSS at offset F of the gene-sense sequence and send ``tss_index = F``. With ``tss`` the 0-based genomic TSS position, fetch ``[tss - F, tss + F)`` on the plus strand, or ``(tss - F, tss + F]`` reverse-complemented on the minus strand. :meth:`fetch_expression_window` does all of this for a gene symbol. ``request_max_bp`` is the only cap; the window fields describe what the model reads, not what the route accepts. An unknown ``task`` is ``404 not_found``. """ r = self._session.get( f"{self.base_url}/v1/tasks/{task}/models", timeout=self.timeout ) return self._check(r) def fetch_expression_window( self, symbol: str, species: str = "human", listing: Optional[Mapping[str, Any]] = None, ensembl_url: str = ENSEMBL_URL, ) -> Dict[str, Any]: """Fetch a TSS-centred, gene-sense expression input for a gene symbol. Applies the rule in :meth:`list_models` end to end, so you need not: * F comes from ``list_models("expression")`` (or ``listing``, if you already hold it) via :func:`expression_flank_bp`: the largest ``recommended_flank_bp``, at least 4,599, 2F within ``request_max_bp``. * The TSS is the Ensembl canonical transcript's (its start on the plus strand, its end on the minus strand), never the gene body. * Minus-strand genes come back reverse-complemented, so the sequence is always gene-sense and the TSS base sits at offset F. * Near a chromosome end F shrinks to the largest symmetric flank that fits (``meta["flank_shortened"]``); below the 4,599 bp floor this raises :class:`ExpressionWindowError`. Returns ``{"sequence", "tss_index", "meta"}``. Send ``sequence`` and ``tss_index`` unchanged to :meth:`predict`, with ``model`` set to the model your user named or ``meta["default_model"]``:: w = client.fetch_expression_window("HBB") client.predict("expression", w["sequence"], "HBB", model=w["meta"]["default_model"], tss_index=w["tss_index"], options={"description": "..."}) ``meta`` carries ``gene``, ``ensembl_id``, ``region`` (``chrom:start-end``, 1-based inclusive), ``strand``, ``tss`` (1-based), ``flank_bp``, ``flank_requested_bp``, ``flank_shortened``, ``flank_model`` (the model whose ``recommended_flank_bp`` set F; None if none asked for more than the floor), ``default_model`` and ``species``. Ensembl's public REST API is called directly (no key; your API key is never sent there), with the client's ``timeout`` per request. Raises :class:`EnsemblError` if Ensembl is unreachable or does not know the gene, and :class:`GIError` or a ``requests`` exception if the model list cannot be read. """ if listing is None: listing = self.list_models("expression") requested, flank_model = expression_flank_bp(listing) locus = lookup_symbol(symbol, species, ensembl_url, self.timeout) tss, strand = locus["tss"], locus["strand"] chrom_len = chromosome_length(locus["seq_region"], species, ensembl_url, self.timeout) flank = _largest_fitting_flank(tss, strand, requested, chrom_len) if flank < EXPRESSION_MIN_FLANK_BP: raise ExpressionWindowError( f"{symbol}: the canonical TSS ({locus['seq_region']}:{tss:,}) is " f"{max(flank, 0):,} bp from a chromosome end, under the " f"{EXPRESSION_MIN_FLANK_BP:,} bp per side every expression model " f"needs ({TASK_MIN_BP['expression']:,} bp total), so it cannot be scored" ) start, end = expression_window_bounds(tss, strand, flank) seq = fetch_region(locus["seq_region"], start, end, strand, species, ensembl_url, self.timeout) if len(seq) != 2 * flank: raise EnsemblError( f"expected {2 * flank} bp for {locus['seq_region']}:{start}-{end}, " f"Ensembl returned {len(seq)}" ) return { "sequence": seq, "tss_index": flank, "meta": { "gene": locus["gene"], "ensembl_id": locus["ensembl_id"], "region": f"{locus['seq_region']}:{start}-{end}", "strand": strand, "tss": tss, "flank_bp": flank, "flank_requested_bp": requested, "flank_shortened": flank < requested, "flank_model": flank_model, "default_model": listing.get("default_model"), "species": species, }, } @staticmethod def _body( sequence: str, sequence_name: str, model: Optional[str], options: Optional[Dict[str, Any]], tss_index: Optional[int] = None, ) -> Dict[str, Any]: body: Dict[str, Any] = {"sequence": sequence, "sequence_name": sequence_name} if model is not None: body["model"] = model if options is not None: body["options"] = options if tss_index is not None: body["tss_index"] = tss_index return body def predict( self, task: str, sequence: str, sequence_name: str = "sequence", model: Optional[str] = None, options: Optional[Dict[str, Any]] = None, tss_index: Optional[int] = None, ) -> Dict[str, Any]: """Synchronous prediction. Returns the full ``{data, meta}`` body. ``task`` is one of ``promoter``, ``splice``, ``enhancer``, ``chromatin``, ``annotation``, ``expression`` — each a separately published operation at the same URL this method builds. An unrecognised task is ``404 not_found``, not a validation error. ``model`` is a TOP-LEVEL field, not ``options["model"]``: every task's ``options`` object is closed (``additionalProperties: false``), so an unknown key — ``model`` included — is rejected with ``422 validation_failed`` at ``loc ["body","options",""]``. The accepted option keys differ per task; see the request schema in ReDoc (``PromoterOptions``, ``SpliceOptions``, …). ``expression`` additionally *requires* ``options["description"]``. ``sequence`` must be within this task's bounds (see :data:`TASK_MIN_BP` / :data:`MAX_BP`, measured after whitespace is stripped); outside them is ``422 validation_failed``, never ``413``. A sequence above the floor but shorter than the selected model's ``bio_spec.context_window_bp`` (from :meth:`list_models`) is still accepted and scored — against a window padded out to that size. ``tss_index`` applies to the ``expression`` task only: the 0-based offset of the TSS into the whitespace-stripped ``sequence``. Every expression model takes at least 9,198 bp with the TSS at least 4,599 bp from each end, i.e. ``4599 <= tss_index <= len(sequence) - 4599``; ``tss_index`` is required unless ``sequence`` is exactly 9,198 bp. 9,198 bp is a floor, not a target: longer TSS-centred sequence is better, and the model list says how much (the rule and strand handling are in :meth:`list_models`; :meth:`fetch_expression_window` builds the input from a gene symbol). There is no ``tes_index``. The client does not validate any of this — the API returns ``422 validation_failed`` (the ``tss_index`` checks at ``loc ["body"]``, so switch on ``error.code``). A window dominated by ``N`` or low-complexity repeats can also be refused with ``422``: each model needs roughly 2-3.3 kb of real sequence upstream of the TSS and 2.6 kb downstream. """ body = self._body(sequence, sequence_name, model, options, tss_index) r = self._session.post( f"{self.base_url}/v1/tasks/{task}/predict", json=body, timeout=self.timeout, ) return self._check(r) def submit_async( self, task: str, sequence: str, sequence_name: str = "sequence", model: Optional[str] = None, options: Optional[Dict[str, Any]] = None, tss_index: Optional[int] = None, ) -> str: """Submit a task in async mode. Returns the ``job_id``. ``Prefer: respond-async`` is a declared header parameter on all six predict operations and on the composite workflow. Async delivery is JSON-only: combining it with a text ``?format=`` is a ``400``. ``tss_index`` is the ``expression``-only TSS offset; see :meth:`predict`. """ body = self._body(sequence, sequence_name, model, options, tss_index) r = self._session.post( f"{self.base_url}/v1/tasks/{task}/predict", headers={"Prefer": "respond-async"}, json=body, timeout=self.timeout, ) body = self._check(r) # 202 envelope is {data: {job_id, status, links}, meta: {...}} — # uniform with the {data, meta} shape every other successful # response on the inference URL produces. return body["data"]["job_id"] # --------------------------------------------------- composite workflow def find_genes_and_predict_expression( self, sequence: str, description: str, sequence_name: str = "sequence", options: Optional[Dict[str, Any]] = None, async_: bool = False, ) -> Dict[str, Any]: """``POST /v1/workflows/find-genes-and-predict-expression``. Runs annotation over the region, cuts a window around each found gene's TSS, and scores expression for each — one round trip. Each gene is scored with the API's default expression model (or the one named in ``options["expression_model"]``), using as much flank around each TSS as the submitted region holds, so longer regions give better predictions. ``sequence`` is 1,000–500,000 bp (the annotation stage's floor). ``description`` is the experimental context applied to every gene; it is required (missing or empty is ``422 validation_failed``) and is passed as ``options["description"]``. Extra ``options`` may add ``annotation_model``, ``expression_model`` and ``shift_coordinates``; the object is closed, so any other key is a ``422``. Above :data:`FIND_GENES_SYNC_LIMIT_BP` (50,000 bp) synchronous delivery is refused with ``413 sync_too_large`` carrying ``details = {sequence_length, threshold}`` — resend the identical body with ``async_=True``. Returns the ``{data, meta}`` body; with ``async_=True`` that body is the ``202`` acceptance ``{data: {job_id, status, links}, meta}``, so poll :meth:`wait_for_job` on ``body["data"]["job_id"]``. ``meta.task_specific_counts`` is ``{genes_found, genes_predicted, genes_skipped}`` with ``genes_predicted + genes_skipped == genes_found``; per-gene causes are in ``data.expression_predictions[].skip_reason``. """ opts: Dict[str, Any] = dict(options or {}) opts["description"] = description body = self._body(sequence, sequence_name, None, opts) headers = {"Prefer": "respond-async"} if async_ else None r = self._session.post( f"{self.base_url}/v1/workflows/find-genes-and-predict-expression", headers=headers, json=body, timeout=self.timeout, ) return self._check(r) def get_job(self, job_id: str) -> requests.Response: """Single poll. The caller inspects ``status_code`` to discriminate.""" return self._session.get( f"{self.base_url}/v1/tasks/jobs/{job_id}", timeout=self.timeout ) def wait_for_job( self, job_id: str, poll_interval: float = 2.0, max_wait: float = 30 * 60, on_progress=None, ) -> Dict[str, Any]: """Poll until terminal. Returns ``{data, meta}`` on success, raises ``GIError``.""" deadline = time.monotonic() + max_wait while True: r = self.get_job(job_id) if r.status_code == 200: return r.json() if r.status_code == 202: if on_progress is not None: try: # 202 poll body is also {data: {progress: {...}}, meta}. on_progress((r.json().get("data") or {}).get("progress") or {}) except Exception: pass if time.monotonic() > deadline: raise TimeoutError(f"job {job_id} did not finish within {max_wait}s") time.sleep(poll_interval) continue # Terminal error try: body = r.json() except ValueError: # http_error for the same reason as _check above: the code must # come from the published enum. body = {"error": {"code": "http_error", "message": r.text[:200]}} raise GIError(r.status_code, body, r.headers) def list_jobs(self, limit: int = 50) -> Dict[str, Any]: r = self._session.get( f"{self.base_url}/v1/tasks/jobs", params={"limit": limit}, timeout=self.timeout, ) return self._check(r) ``` ### client/quickstart.py Runs every task end to end against the bundled real sequences. The fastest way to confirm your key works before you write any code. [Download raw](https://docs.genomicintelligence.ai/client/quickstart.py) ```python title="client/quickstart.py" """Genomic Intelligence API — partner quickstart. Hits every public task endpoint with a real, biologically meaningful sequence drawn from the bundled ``sequences/`` directory. The promoter, splice, enhancer and chromatin files are the same fixtures the service uses for its golden numeric-regression tests; the expression sample is not (it is generated with ``Client.fetch_expression_window``, so its flank is the largest ``recommended_flank_bp`` among the listed models). Each FASTA header records its provenance. Sync calls are sized so each task completes in a few seconds on a warm GPU; ``annotation`` is the one outlier and is intentionally exercised both sync and async. ``expression`` is the exception to the bundled inputs: it fetches HBB's TSS window from Ensembl, sized from the live model list, and falls back to the bundled fixture only when either is unreachable. pip install -r requirements.txt export GI_API_KEY=gi_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx export GI_BASE_URL=https://api.genomicintelligence.ai # optional export GI_CLIENT_APP=my-tool # optional, sent as X-GI-Client-App python quickstart.py """ from __future__ import annotations import os import pathlib import sys import requests from gi_client import ( Client, EnsemblError, ExpressionWindowError, GIError, expression_flank_bp, ) SEQ_DIR = pathlib.Path(__file__).parent / "sequences" def load_fasta(filename: str) -> tuple[str, str]: """Return (sequence_name, sequence) from a single-record FASTA file.""" text = (SEQ_DIR / filename).read_text() lines = text.splitlines() header = lines[0].lstrip(">").strip() sequence = "".join(line.strip() for line in lines[1:] if line.strip()) return header, sequence.upper() #: The bundled expression sample: HBB gene-sense, TSS-centred, with its #: ``tss_index`` in the header. Used only when a live window cannot be built. EXPRESSION_SAMPLE = "expression_hbb_k562.fa" def load_expression_sample(filename: str = EXPRESSION_SAMPLE) -> tuple[str, str, int]: """Return (sequence_name, sequence, tss_index) for a TSS-centred sample. ``tss_index`` is read from the header's ``tss_index=`` field, never assumed, so a regenerated sample cannot silently disagree with the index sent with it. ``sequence_name`` is the header's first four fields (species, gene, window, region), which stays inside the API's 128-char cap. """ header, sequence = load_fasta(filename) fields = header.split("|") hits = [f.split("=", 1)[1] for f in fields if f.startswith("tss_index=")] if len(hits) != 1: raise ValueError(f"{filename}: header carries no single tss_index= field: {header}") return "|".join(fields[:4]), sequence, int(hits[0]) def _section(title: str) -> None: print(f"\n=== {title} ===") def _summary(label: str, body: dict) -> None: meta = body.get("meta", {}) counts = meta.get("task_specific_counts", {}) print( f"{label:<22} model={meta.get('model'):<32} " f"{meta.get('inference_time_ms', '?')} ms counts={counts}" ) def main() -> int: api_key = os.environ.get("GI_API_KEY") if not api_key: print("ERROR: set GI_API_KEY (your gi_… bearer key)", file=sys.stderr) return 2 base_url = os.environ.get("GI_BASE_URL", "https://api.genomicintelligence.ai") # Optional attribution: unset, no X-GI-Client-App header is sent. client = Client(api_key=api_key, base_url=base_url, client_app=os.environ.get("GI_CLIENT_APP") or None) _section("Health") print(client.health()) # These four are real biological inputs from the service's golden # fixtures — see client/sequences/. Each FASTA carries # provenance in its header (gene symbol, coordinates, assembly). tp53_name, tp53_seq = load_fasta("promoter_tp53.fa") # human, ~26 kb, gene-sense (TP53 is - strand) hbb_name, hbb_seq = load_fasta("splice_hbb.fa") # human, ~4 kb eve_name, eve_seq = load_fasta("enhancer_eve.fa") # drosophila, ~10 kb, eve developmental enhancer (+ strand) chr19_name, chr19_seq = load_fasta("chromatin_active_promoter_chr19.fa") # human, ~40 kb _section("Sync inference (real biological sequences)") try: _summary("promoter (TP53)", client.predict("promoter", tp53_seq, tp53_name)) _summary("splice (HBB)", client.predict("splice", hbb_seq, hbb_name)) # Enhancer model is Drosophila-trained — use a fly enhancer. _summary("enhancer (eve)", client.predict("enhancer", eve_seq, eve_name)) _summary("chromatin (chr19)", client.predict("chromatin", chr19_seq, chr19_name)) except GIError as exc: print(f"sync task failed: {exc}", file=sys.stderr) return 1 except requests.RequestException as exc: # Transport-level: DNS, TLS, connection refused, read timeout. # Routine for a hosted service and not a request problem. print(f"sync task failed: network error: {type(exc).__name__}: {exc}", file=sys.stderr) return 1 _section("Expression (HBB in K562, TSS-centred)") # Expression reads the sequence around a gene's TSS. fetch_expression_window # sizes the window from the live model list (F = the largest # bio_spec.recommended_flank_bp, so one fetch serves every listed model), # takes the TSS from the Ensembl canonical transcript, reverse-complements # minus-strand genes such as HBB, and returns 2F bp gene-sense with the TSS # base at offset F and tss_index = F. Nothing here hard-codes a window, a # flank or a model id. Pass the model explicitly (the one your user named, # else default_model) so every call of a run uses the same one. # # If Ensembl or the model list is unreachable, the quickstart falls back to # the bundled sample: the same HBB window, generated with # fetch_expression_window, with its tss_index in the FASTA header. If the # model list answers but Ensembl does not, and the sample holds less than # 2F for the live F, it says so rather than scoring a short window # quietly. The number printed is the model's prediction for this exact # description: the description is model input, and rewording it changes # the score (see options.description on the Tasks page). model = None listing = None try: listing = client.list_models("expression") model = listing.get("default_model") window = client.fetch_expression_window("HBB", listing=listing) hbb_tss_seq, tss_index = window["sequence"], window["tss_index"] wmeta = window["meta"] hbb_tss_name = f"{wmeta['gene']}|{wmeta['region']}|strand={wmeta['strand']}" print( f"fetched {wmeta['gene']} ({wmeta['ensembl_id']}) {wmeta['region']} " f"strand {wmeta['strand']:+d}: {len(hbb_tss_seq):,} bp, " f"tss_index={tss_index} (flank from {wmeta['flank_model']})" ) except (EnsemblError, ExpressionWindowError, GIError, requests.RequestException) as exc: hbb_tss_name, hbb_tss_seq, tss_index = load_expression_sample() print( f"note: could not build a live window ({type(exc).__name__}: {exc}); " f"using the bundled sample instead ({len(hbb_tss_seq):,} bp, " f"tss_index={tss_index})" ) if listing is not None: live_flank, flank_model = expression_flank_bp(listing) if len(hbb_tss_seq) < 2 * live_flank: print( f"note: the bundled sample is shorter than the model list " f"recommends: {len(hbb_tss_seq):,} bp against " f"{2 * live_flank:,} bp (2 x {live_flank:,} for {flank_model}); " f"{model} will score less flank than it was trained on" ) # tss_index is the 0-based offset into the whitespace-stripped sequence; an # index counted over line-wrapped FASTA characters is off by the newline # count and can silently score the wrong region, so check the # scored_window echoed back below. try: body = client.predict( "expression", sequence=hbb_tss_seq, sequence_name=hbb_tss_name, model=model, tss_index=tss_index, options={ "description": ( "assay term name is polyA plus RNA-seq. " "biosample summary is Homo sapiens K562." ), }, ) pred = body.get("data", {}).get("prediction", {}) counts = body.get("meta", {}).get("task_specific_counts", {}) print( f"expression: {pred.get('expression_log_tpm')} log(TPM+1) " f"({pred.get('expression_tpm')} TPM)" ) # Windowing provenance: confirm the server scored the window you meant. print( f" tss_index={counts.get('tss_index')} " f"scored_window={counts.get('scored_window')}" ) except GIError as exc: print(f"expression failed: {exc}", file=sys.stderr) except requests.RequestException as exc: print(f"expression failed: network error: {type(exc).__name__}: {exc}", file=sys.stderr) _section("Async job — annotation on TP53 (~26 kb)") # Annotation is the slowest atomic task and the one where async # actually matters. TP53 is well-annotated; expect at least one # transcript in the response. try: job_id = client.submit_async( "annotation", sequence=tp53_seq, sequence_name=tp53_name, ) print(f"submitted job_id={job_id}") def progress(p): pct = p.get("current_percent") msg = p.get("message", "") print(f" {pct:>3}% {msg}") body = client.wait_for_job(job_id, poll_interval=2.0, on_progress=progress) meta = body.get("meta", {}) counts = meta.get("task_specific_counts", {}) transcripts = body.get("data", {}).get("transcripts", []) or [] print( f"done — counts={counts} " f"transcripts={len(transcripts)} " f"total_time_ms={meta.get('inference_time_ms')}" ) except GIError as exc: print(f"annotation failed: {exc}", file=sys.stderr) return 1 except requests.RequestException as exc: print(f"annotation failed: network error: {type(exc).__name__}: {exc}", file=sys.stderr) return 1 except TimeoutError as exc: # wait_for_job gives up rather than polling forever. print(f"annotation timed out: {exc}", file=sys.stderr) return 1 _section("Recent jobs") print(client.list_jobs(limit=5)) return 0 if __name__ == "__main__": raise SystemExit(main()) ``` ### client/requirements.txt The client's only runtime dependency. [Download raw](https://docs.genomicintelligence.ai/client/requirements.txt) ```text title="client/requirements.txt" requests>=2.31 ``` ### Example sequences Real sequences the quickstart and recipes run against — download or curl them directly: - [`sequences/promoter_tp53.fa`](https://docs.genomicintelligence.ai/client/sequences/promoter_tp53.fa) - [`sequences/splice_hbb.fa`](https://docs.genomicintelligence.ai/client/sequences/splice_hbb.fa) - [`sequences/enhancer_eve.fa`](https://docs.genomicintelligence.ai/client/sequences/enhancer_eve.fa) - [`sequences/chromatin_active_promoter_chr19.fa`](https://docs.genomicintelligence.ai/client/sequences/chromatin_active_promoter_chr19.fa) - [`sequences/expression_hbb_k562.fa`](https://docs.genomicintelligence.ai/client/sequences/expression_hbb_k562.fa) --- ## Recipes Each recipe is a single runnable script that solves one real integration problem end to end. Read them here, or download the whole kit: **[Download the integration kit](https://docs.genomicintelligence.ai/integration-kit.tar.gz)** (`.tar.gz`) — every file below plus the docs, bundled. ### recipes/01_health_probe.py The minimum check before any other work: API reachable, key valid, per-task model lists loadable. Exits 0 on green. [Download raw](https://docs.genomicintelligence.ai/recipes/01_health_probe.py) ```python title="recipes/01_health_probe.py" """Recipe 01 — health probe. The minimum check before any other work: is the API reachable, is your key valid, are the per-task model lists loadable. Exits 0 on green, 1 on any failure. GI_API_KEY=gi_… python3 01_health_probe.py """ from __future__ import annotations import os import sys import requests BASE_URL = os.environ.get("GI_BASE_URL", "https://api.genomicintelligence.ai") API_KEY = os.environ.get("GI_API_KEY") def fail(msg: str) -> None: print(f"FAIL: {msg}", file=sys.stderr) sys.exit(1) def main() -> int: if not API_KEY: fail("set GI_API_KEY") # 1. Public liveness — no auth required. r = requests.get(f"{BASE_URL}/health", timeout=10) if not r.ok: fail(f"/health returned {r.status_code}: {r.text[:200]}") health = r.json() print(f"health : {health.get('status')} {health.get('version')}") # 2. Authenticated round-trip — proves the bearer key is registered. r = requests.get( f"{BASE_URL}/v1/tasks/promoter/models", headers={"Authorization": f"Bearer {API_KEY}"}, timeout=10, ) if r.status_code == 401: fail("401 unauthorized — key missing, malformed, or unrecognised. " f"Check Authorization header. Body: {r.text[:200]}") if not r.ok: body = r.json() if r.headers.get("content-type", "").startswith("application/json") else {} err = body.get("error") or {} fail(f"{r.status_code} {err.get('code', 'unknown')} request_id={err.get('request_id')}") # Note: model-listing endpoints (`/v1/tasks/{task}/models`, # `/v1/tasks/{task}/models/{id}/status`) return flat objects, NOT the # `{data, meta}` envelope used by predict endpoints. Live OpenAPI at # /v1/openapi.json is the source of truth for shapes per route. body = r.json() models = body.get("models", []) print(f"models : {len(models)} registered for task=promoter " f"(default={body.get('default_model')})") # 3. Read RateLimit headers — confirms your tier and your headroom. print(f"ratelimit: limit={r.headers.get('RateLimit-Limit')} " f"remaining={r.headers.get('RateLimit-Remaining')} " f"reset={r.headers.get('RateLimit-Reset')}s " f"policy={r.headers.get('RateLimit-Policy')}") print("ok") return 0 if __name__ == "__main__": raise SystemExit(main()) ``` ### recipes/02_promoters_for_gene_list.py Realistic batch shape: fetch each gene from Ensembl (public, no auth) and run promoter prediction, one BED-style row per detected region. [Download raw](https://docs.genomicintelligence.ai/recipes/02_promoters_for_gene_list.py) ```python title="recipes/02_promoters_for_gene_list.py" """Recipe 02 — promoter prediction across a list of human gene symbols. Realistic batch shape: you have N gene symbols, you want promoters for each. We fetch the genomic sequence for each gene from Ensembl REST (public, no auth) and run `POST /v1/tasks/promoter/predict` against each. Output is one BED-style row per detected promoter region. Demonstrates: - sequence acquisition from a public bioinformatics source (Ensembl) - serial pacing against a per-key concurrency cap - extraction of the typed `data.regions` field per the contract GI_API_KEY=gi_… python3 02_promoters_for_gene_list.py TP53 MYC GAPDH """ from __future__ import annotations import os import sys import time from typing import Iterable import requests BASE_URL = os.environ.get("GI_BASE_URL", "https://api.genomicintelligence.ai") API_KEY = os.environ.get("GI_API_KEY") ENSEMBL = "https://rest.ensembl.org" # Default genes to demo if the user gives no args. Sized for sub-2s per call. DEFAULT_GENES = ["TP53", "MYC", "GAPDH"] def fetch_gene_sequence(symbol: str, species: str = "human") -> tuple[str, str]: """Resolve `symbol` to an Ensembl ID and fetch its genomic sequence. Returns (display_name, sequence). Raises on any HTTP failure. Fetches on the gene's native strand so that minus-strand genes (e.g. TP53) are returned in 5'→3' coding orientation — the orientation the promoter model was trained on. """ # Lookup Ensembl ID + strand r = requests.get( f"{ENSEMBL}/lookup/symbol/{species}/{symbol}", headers={"Accept": "application/json"}, timeout=15, ) r.raise_for_status() info = r.json() chrom, start, end = info["seq_region_name"], info["start"], info["end"] strand = info.get("strand", 1) # Fetch genomic sequence on the gene's strand region = f"{chrom}:{start}..{end}:{strand}" r = requests.get( f"{ENSEMBL}/sequence/region/{species}/{region}", headers={"Accept": "text/plain"}, timeout=30, ) r.raise_for_status() return f"{symbol}|chr{chrom}:{start}-{end}|strand:{strand}", r.text.strip().upper() def predict_promoter(sequence: str, sequence_name: str) -> tuple[dict, dict]: """One sync call to /v1/tasks/promoter/predict. Returns ``(body, headers)`` — the parsed ``{data, meta}`` body plus the response headers, so the caller can pace off the ``RateLimit-*`` spine. """ r = requests.post( f"{BASE_URL}/v1/tasks/promoter/predict", headers={ "Authorization": f"Bearer {API_KEY}", "Content-Type": "application/json", }, json={"sequence": sequence, "sequence_name": sequence_name, "options": {"threshold": 0.5}}, timeout=120, ) if not r.ok: body = r.json() if r.headers.get("content-type", "").startswith("application/json") else {} err = body.get("error") or {} raise RuntimeError( f"{r.status_code} {err.get('code', 'unknown')}: " f"{err.get('message', r.text[:200])} (request_id={err.get('request_id')})" ) return r.json(), r.headers def pace(headers) -> float: """Return how many seconds to sleep before the next call to stay at ~80% of capacity. Reads IETF RateLimit-* headers. If headroom is low, slow down; if plenty, no wait. Conservative pacing — beats reactive 429 retries. """ try: remaining = int(headers.get("RateLimit-Remaining", "999")) limit = int(headers.get("RateLimit-Limit", "10")) reset = float(headers.get("RateLimit-Reset", "0")) except (TypeError, ValueError): return 0.0 threshold = max(1, int(limit * 0.2)) # aim to stay above 20% headroom if remaining <= threshold and reset > 0: # Spread remaining work across the reset window return reset / max(1, remaining) return 0.0 def run(symbols: Iterable[str]) -> int: if not API_KEY: print("ERROR: set GI_API_KEY", file=sys.stderr) return 2 print("# track start end name score") last_headers = {} for symbol in symbols: wait = pace(last_headers) if wait > 0: print(f"# pacing: sleep {wait:.2f}s", file=sys.stderr) time.sleep(wait) try: display, sequence = fetch_gene_sequence(symbol) except requests.HTTPError as exc: print(f"# {symbol}: ensembl lookup failed — {exc}", file=sys.stderr) continue try: body, last_headers = predict_promoter(sequence, display) except RuntimeError as exc: print(f"# {symbol}: predict failed — {exc}", file=sys.stderr) continue # `last_headers` now carries this call's RateLimit-* state, so the # pace() at the top of the next iteration slows down before we run low. regions = body.get("data", {}).get("regions") or [] for r in regions: print(f"{symbol}\t{r['start']}\t{r['end']}\t{r.get('name', '.')}\t{r['score']:.4f}") if not regions: print(f"# {symbol}: 0 regions above threshold", file=sys.stderr) return 0 if __name__ == "__main__": args = sys.argv[1:] or DEFAULT_GENES raise SystemExit(run(args)) ``` ### recipes/03_async_annotation_polling.py Async dispatch with progress polling for large inputs — HTTP status discriminates progress (`202`) from terminal (`200`/`4xx`/`5xx`). [Download raw](https://docs.genomicintelligence.ai/recipes/03_async_annotation_polling.py) ```python title="recipes/03_async_annotation_polling.py" """Recipe 03 — async annotation with progress polling. Annotation is the slowest atomic task. For inputs above ~30 kbp, opt into async to avoid the 300 s upstream proxy timeout. The polling shape is uniform: HTTP status discriminates progress (`202`) vs terminal (`200` success, `4xx`/`5xx` failure). Body is always `{data, meta}` while running and on success; only terminal failure switches to the error envelope. Demonstrates: - `Prefer: respond-async` opt-in - 202-progress polling shape - exponential backoff on the poll interval (don't hammer) - terminal-state discrimination GI_API_KEY=gi_… python3 03_async_annotation_polling.py path/to/sequence.fa """ from __future__ import annotations import os import sys import time import requests BASE_URL = os.environ.get("GI_BASE_URL", "https://api.genomicintelligence.ai") API_KEY = os.environ.get("GI_API_KEY") HEADERS = {"Authorization": f"Bearer {API_KEY}", "Content-Type": "application/json"} def load_fasta(path: str) -> tuple[str, str]: text = open(path).read().splitlines() name = text[0].lstrip(">").strip() sequence = "".join(line.strip() for line in text[1:] if line.strip()).upper() return name, sequence def submit_async(sequence: str, sequence_name: str) -> str: """POST with `Prefer: respond-async`; return the job_id. Annotation accepts 1,000–500,000 bp (whitespace-stripped); shorter is `422 validation_failed`. `options` is closed — annotation accepts only `shift_coordinates` and `reverse_complement`, and a model is chosen with the TOP-LEVEL `model` field, never inside `options`. """ r = requests.post( f"{BASE_URL}/v1/tasks/annotation/predict", headers={**HEADERS, "Prefer": "respond-async"}, json={"sequence": sequence, "sequence_name": sequence_name}, timeout=30, ) r.raise_for_status() return r.json()["data"]["job_id"] def poll_until_terminal(job_id: str, max_wait_s: float = 30 * 60) -> dict: """Poll `/v1/tasks/jobs/{id}` until 200 or terminal 4xx/5xx. Returns the final body. Raises on terminal failure or timeout. """ deadline = time.monotonic() + max_wait_s interval = 2.0 # seconds; doubled up to a cap on each 202 while True: r = requests.get( f"{BASE_URL}/v1/tasks/jobs/{job_id}", headers={"Authorization": f"Bearer {API_KEY}"}, timeout=30, ) if r.status_code == 200: return r.json() # done — {data, meta} if r.status_code == 202: # In flight. Body is also {data, meta}; data.progress carries # current_percent / message / elapsed_seconds. body = r.json() progress = (body.get("data") or {}).get("progress") or {} pct = progress.get("current_percent") msg = progress.get("message", "") print(f" [{pct:>3}%] {msg}", file=sys.stderr) if time.monotonic() > deadline: raise TimeoutError(f"job {job_id} did not terminate within {max_wait_s}s") time.sleep(interval) interval = min(interval * 1.5, 15.0) # back off, cap at 15s continue # Terminal failure — unified error envelope. body = r.json() if r.headers.get("content-type", "").startswith("application/json") else {} err = body.get("error") or {} raise RuntimeError( f"job {job_id} terminal: {r.status_code} {err.get('code', 'unknown')} " f"{err.get('message', '')} (request_id={err.get('request_id')})" ) def main() -> int: if not API_KEY: print("ERROR: set GI_API_KEY", file=sys.stderr); return 2 if len(sys.argv) < 2: print("usage: 03_async_annotation_polling.py ", file=sys.stderr); return 2 name, sequence = load_fasta(sys.argv[1]) print(f"submitting {len(sequence):,} bp as async annotation job…", file=sys.stderr) job_id = submit_async(sequence, name) print(f"job_id={job_id}", file=sys.stderr) body = poll_until_terminal(job_id) transcripts = body.get("data", {}).get("transcripts") or [] meta = body.get("meta", {}) print(f"done — transcripts={len(transcripts)} " f"inference_ms={meta.get('inference_time_ms')} " f"counts={meta.get('task_specific_counts')}") for t in transcripts: print(f" {t.get('name', '.')}\t{t.get('start')}\t{t.get('end')}\t" f"{t.get('strand')}\t{t.get('score'):.4f}") return 0 if __name__ == "__main__": raise SystemExit(main()) ``` ### recipes/04_ratelimit_aware_retry.py A `call()` wrapper that paces itself off the IETF `RateLimit-*` headers, honours `Retry-After` on 429, and backs off on 5xx. [Download raw](https://docs.genomicintelligence.ai/recipes/04_ratelimit_aware_retry.py) ```python title="recipes/04_ratelimit_aware_retry.py" """Recipe 04 — rate-limit-aware request wrapper. A `call()` helper that: - reads IETF `RateLimit-*` headers from every response and paces the next call to stay at ~80% of capacity - on `429`, honours `Retry-After`; on `5xx`, exponential backoff capped at 30 s - never retries permanent 4xx errors (catalogue: https://docs.genomicintelligence.ai/reference/errors.md) - returns the parsed `{data, meta}` body on success or raises a typed exception on permanent failure Use this as a drop-in for `requests.post(...)` when you need pacing without managing it by hand. GI_API_KEY=gi_… python3 04_ratelimit_aware_retry.py """ from __future__ import annotations import os import time from dataclasses import dataclass, field from typing import Any, Optional import requests BASE_URL = os.environ.get("GI_BASE_URL", "https://api.genomicintelligence.ai") API_KEY = os.environ.get("GI_API_KEY") @dataclass class GIError(Exception): status: int code: str message: str request_id: Optional[str] = None details: Any = None def __str__(self) -> str: return f"[{self.status} {self.code}] {self.message} (request_id={self.request_id})" @dataclass class RateLimitState: """Sticky pacing state between calls. Threadsafe? No — per-worker.""" limit: int = 0 remaining: int = 0 reset_seconds: float = 0.0 last_response_at: float = field(default_factory=time.monotonic) PERMANENT_4XX = { "bad_request", "unauthorized", "forbidden", "not_found", "model_not_found", "validation_failed", "task_not_supported_by_model", "payload_too_large", "sync_too_large", "unsupported_format", "conflict", "job_expired", } RETRYABLE = { "too_many_requests", # 429: rate or concurrency cap "rate_limited", # 429: same treatment "model_loading", # 503: warmup race "service_unavailable", # 503: startup/shutdown "timeout", # inference deadline — resubmit async "insufficient_memory", # GPU pressure — retry, or shorten the sequence } def _wait_before_next(state: RateLimitState) -> float: """Pacing: stay above 20% headroom of the token bucket.""" if state.limit <= 0: return 0.0 threshold = max(1, int(state.limit * 0.2)) if state.remaining > threshold: return 0.0 elapsed = time.monotonic() - state.last_response_at remaining_window = max(0.0, state.reset_seconds - elapsed) if remaining_window <= 0 or state.remaining <= 0: return 0.0 return remaining_window / max(1, state.remaining) def _read_headers(state: RateLimitState, headers) -> None: try: state.limit = int(headers.get("RateLimit-Limit", state.limit)) state.remaining = int(headers.get("RateLimit-Remaining", state.remaining)) state.reset_seconds = float(headers.get("RateLimit-Reset", state.reset_seconds)) except (TypeError, ValueError): pass state.last_response_at = time.monotonic() def call( method: str, path: str, *, json_body: Optional[dict] = None, headers: Optional[dict] = None, state: RateLimitState, max_attempts: int = 5, ) -> dict: """Issue one logical request with retries on retryable errors.""" url = f"{BASE_URL}{path}" base_headers = {"Authorization": f"Bearer {API_KEY}", "Content-Type": "application/json"} if headers: base_headers.update(headers) backoff = 1.0 for attempt in range(1, max_attempts + 1): wait = _wait_before_next(state) if wait > 0: time.sleep(wait) r = requests.request(method, url, json=json_body, headers=base_headers, timeout=120) _read_headers(state, r.headers) if r.ok: return r.json() body = r.json() if r.headers.get("content-type", "").startswith("application/json") else {} err = (body or {}).get("error") or {} code = err.get("code", "unknown") if code in PERMANENT_4XX: # Don't retry; surface to caller. raise GIError(r.status_code, code, err.get("message", ""), err.get("request_id"), err.get("details")) if code in RETRYABLE and attempt < max_attempts: retry_after = r.headers.get("Retry-After") sleep = float(retry_after) if retry_after else min(backoff, 30.0) time.sleep(sleep) backoff *= 2 continue # 5xx server bug — one retry then give up. if r.status_code >= 500 and attempt < max_attempts: time.sleep(min(backoff, 30.0)) backoff *= 2 continue raise GIError(r.status_code, code, err.get("message", ""), err.get("request_id"), err.get("details")) raise GIError(0, "exhausted", f"max_attempts={max_attempts} reached", None, None) def demo() -> int: if not API_KEY: print("ERROR: set GI_API_KEY"); return 2 state = RateLimitState() # A burst of small calls — the wrapper paces automatically. for i in range(15): try: body = call( "POST", "/v1/tasks/promoter/predict", json_body={"sequence": "ACGT" * 500, "sequence_name": f"demo-{i}", "options": {"threshold": 0.5}}, state=state, ) ms = body.get("meta", {}).get("inference_time_ms") print(f"call {i:>2}: {ms} ms (limit={state.limit} remaining={state.remaining})") except GIError as exc: print(f"call {i:>2}: FAILED — {exc}") return 0 if __name__ == "__main__": raise SystemExit(demo()) ``` ### recipes/05_typed_error_handling.py Switch on `error.code`, never on `error.message`. Maps every error code to retryable / permanent / server-bug plus the action to take. [Download raw](https://docs.genomicintelligence.ai/recipes/05_typed_error_handling.py) ```python title="recipes/05_typed_error_handling.py" """Recipe 05 — typed error handling. Switch on `error.code`, never on `error.message`. Every code from https://docs.genomicintelligence.ai/reference/errors.md is mapped here to one of four buckets — retryable, permanent, server-bug, or proxy-timeout (the enveloped-less 504 special case) — plus the action your code should take. Use this as the template for your own error handler. Copy `handle()` into your codebase, register it as your one place to translate API errors to your domain's exception types. GI_API_KEY=gi_… python3 05_typed_error_handling.py """ from __future__ import annotations import os import sys from dataclasses import dataclass from typing import Any, Optional import requests BASE_URL = os.environ.get("GI_BASE_URL", "https://api.genomicintelligence.ai") API_KEY = os.environ.get("GI_API_KEY") @dataclass class APIError(Exception): status: int code: str message: str request_id: Optional[str] details: Any bucket: str # "retryable" | "permanent" | "server_bug" | "proxy_timeout" action: str # human-readable action hint for the caller def per_field(details: Any) -> list: """Normalise `error.details` for a `validation_failed` into a list. The service usually emits `{"errors": [...]}`, matching the `ValidationFailedDetails` schema; older releases emitted the bare FastAPI array, and splice's response-size cap emits a different object entirely (`{task, record_count, maximum_records, sequence_length, threshold}`, no `errors` key). This helper accepts either list shape and treats anything else — including that one — as "no structured detail"; read `error.message` there. """ if isinstance(details, list): return details if isinstance(details, dict): errors = details.get("errors") return errors if isinstance(errors, list) else [] return [] def handle(response: requests.Response) -> dict: """Convert an API response into either a parsed body or a raised APIError. Single source of truth for every code in the catalogue. If we ever add a new error code, the `unknown_code` branch surfaces it cleanly. """ if response.ok: return response.json() # 504 from the edge proxy is the one response on the contract that # is NOT the unified error envelope. Treat as a special case. if response.status_code == 504: raise APIError( status=504, code="gateway_timeout", message="Upstream proxy read timeout (300 s).", request_id=None, details=None, bucket="proxy_timeout", action="Retry the same request with header `Prefer: respond-async`.", ) body = response.json() if response.headers.get("content-type", "").startswith("application/json") else {} err = (body or {}).get("error") or {} code = err.get("code", "unknown_code") msg = err.get("message", "") request_id = err.get("request_id") details = err.get("details") # Retryable transient — the API or upstream is asking you to back off. if code == "too_many_requests": raise APIError(response.status_code, code, msg, request_id, details, bucket="retryable", action="Honour Retry-After. Both rate-bucket and concurrency 429s use this code.") if code == "rate_limited": raise APIError(response.status_code, code, msg, request_id, details, bucket="retryable", action="Same treatment as too_many_requests — honour Retry-After.") if code == "model_loading": raise APIError(response.status_code, code, msg, request_id, details, bucket="retryable", action="Wait ~30 s and retry. The model is warming up.") if code == "service_unavailable": raise APIError(response.status_code, code, msg, request_id, details, bucket="retryable", action="Backoff and retry. Server is starting up or shutting down.") # Permanent client errors — surface to the caller, don't retry. if code == "bad_request": raise APIError(response.status_code, code, msg, request_id, details, bucket="permanent", action="Fix the HTTP-level precondition and re-issue.") if code == "unauthorized": raise APIError(response.status_code, code, msg, request_id, details, bucket="permanent", action="Check Authorization header. WWW-Authenticate splits invalid_request vs invalid_token.") if code == "forbidden": raise APIError(response.status_code, code, msg, request_id, details, bucket="permanent", action="Key is registered but disabled. Contact the API operator.") if code == "not_found": raise APIError(response.status_code, code, msg, request_id, details, bucket="permanent", action="Unknown route, unknown job, or cross-tenant access (returned as 404 not 403).") if code == "model_not_found": # details.available_models is the typed list of alternatives. raise APIError(response.status_code, code, msg, request_id, details, bucket="permanent", action=f"Pick a model from details.available_models: {details}.") if code == "validation_failed": # `details` is usually per-field validation output. Read it # DEFENSIVELY: the service wraps the FastAPI errors in an object # ({"errors": [...]}), matching the schema; the bare array # ([{loc, msg, type}, ...]) is the legacy shape this helper still # tolerates. Splice's response-size cap is a validation_failed with # neither shape — {task, record_count, maximum_records, # sequence_length, threshold} — and neither is expression's refusal of # a window with too little real (non-N) sequence around the TSS, # whose details are {invalid_characters: [], invalid_positions: [], # valid_characters: [...]} with empty lists. So never index # details["errors"], and never infer the cause from details. # Never make control flow depend on its shape — or on `loc`. Sequence # bound violations report at ["body","sequence"], an unknown options # key at ["body","options",""], but expression's tss_index checks # come from a whole-model validator and report at ["body"] — there is # no ["body","tss_index"] to match on. Switch on `code` only. raise APIError(response.status_code, code, msg, request_id, per_field(details), bucket="permanent", action="Surface message verbatim — it's deterministic. Never branch on details[].loc.") if code == "task_not_supported_by_model": raise APIError(response.status_code, code, msg, request_id, details, bucket="permanent", action="Pick a different model — see details.supported_tasks.") if code == "payload_too_large": # 413 #1: the 16 MiB raw-body cap, enforced before parsing. NOT the # sequence-length cap — an over-500,000 bp sequence is a 422. raise APIError(response.status_code, code, msg, request_id, details, bucket="permanent", action="Body exceeded 16 MiB. Split the request or use sequence references if available.") if code == "sync_too_large": # 413 #2: an operation refusing synchronous JSON delivery above its # published cap — the composite find-genes-and-predict-expression # workflow above 50,000 bp, or annotation above 200,000 bp. details # carries {sequence_length, threshold}. Resend the identical body async. # (BED/GFF3 annotation responses are uncapped and never land here.) raise APIError(response.status_code, code, msg, request_id, details, bucket="permanent", action="Resend the same body with `Prefer: respond-async`.") if code == "unsupported_format": # 415. Per-task format sets differ (promoter json|bed|bedgraph, # splice json|bed|gff3, enhancer json|bedgraph, chromatin json|bed, # annotation json|bed|gff3, expression json only) and there is no # silent fallback to JSON. The message names the supported values. raise APIError(response.status_code, code, msg, request_id, details, bucket="permanent", action="The Accept / ?format= value is not in this task's allowed set.") if code == "conflict": raise APIError(response.status_code, code, msg, request_id, details, bucket="permanent", action="Reserved (e.g. busy-model unload conflict). Retry once after delay.") if code == "job_expired": raise APIError(response.status_code, code, msg, request_id, details, bucket="permanent", action="Async result evicted (24 h TTL or process restart). Resubmit the original POST.") # Server-side capacity / timing — retry once, then shrink the request. if code == "timeout": raise APIError(response.status_code, code, msg, request_id, details, bucket="retryable", action="Inference exceeded the server deadline. Resubmit with `Prefer: respond-async`.") if code == "insufficient_memory": raise APIError(response.status_code, code, msg, request_id, details, bucket="retryable", action="GPU memory exhausted. Retry after a delay, or submit a shorter sequence.") # Server bug — capture and escalate. if code == "internal_error": raise APIError(response.status_code, code, msg, request_id, details, bucket="server_bug", action=f"Email contact@genomicintelligence.ai with request_id={request_id}.") if code in ("http_error", "unknown"): raise APIError(response.status_code, code, msg, request_id, details, bucket="server_bug", action="Generic failure the service could not classify. Capture request_id.") # Unknown code — the enum is closed today (21 values) but a new code can # ship before your client is regenerated, so treat an unlisted value as a # generic failure rather than a parse error. Log loudly. raise APIError(response.status_code, code, msg, request_id, details, bucket="server_bug", action=f"Unknown error.code={code!r}. Treat as server bug; capture and escalate.") def demo() -> int: if not API_KEY: print("ERROR: set GI_API_KEY"); return 2 # Trigger 422 validation_failed. "ZZZZ" is both out-of-alphabet and below # promoter's 300 bp floor (each task publishes its own minLength: splice # 100, enhancer 50, chromatin 200, annotation 1000, expression 9198 with the TSS at least 4599 from each end). # Either way the code is validation_failed — which is exactly why you # switch on `code` and not on the shape of `details`. print("# trigger validation_failed (422)") r = requests.post( f"{BASE_URL}/v1/tasks/promoter/predict", headers={"Authorization": f"Bearer {API_KEY}", "Content-Type": "application/json"}, json={"sequence": "ZZZZ", "sequence_name": "bad-input"}, timeout=30, ) try: handle(r) except APIError as exc: print(f" caught: {exc.code} bucket={exc.bucket}") print(f" action: {exc.action}") print(f" message: {exc.message}") # Trigger 401 unauthorized with a clearly-bad key. print("\n# trigger unauthorized (401)") r = requests.get( f"{BASE_URL}/v1/tasks/promoter/models", headers={"Authorization": "Bearer gi_definitely_not_a_real_key"}, timeout=10, ) try: handle(r) except APIError as exc: print(f" caught: {exc.code} bucket={exc.bucket}") print(f" action: {exc.action}") print(f" www-authenticate: {r.headers.get('WWW-Authenticate')}") return 0 if __name__ == "__main__": raise SystemExit(demo()) ``` --- ## Use GI in an AI chat ## Use Genomic Intelligence inside Claude, ChatGPT, or your AI agent Ask natural-language questions over DNA sequences. Genomic Intelligence can fetch genomic regions, run the **promoter, splice, enhancer, chromatin, expression, and annotation** models, and return structured biological predictions — all from an AI assistant. You type *"fetch TP53 and scan it for promoters"*; the model calls the right tools and shows you ranked hits with coordinates and scores. Under the hood this rides the [Model Context Protocol](https://modelcontextprotocol.io) (MCP): a thin translator that turns each task into a tool your AI host can call, forwarding to the same REST API documented in the [REST API guide](rest-api.md). ### Choose how you want to try it Both options below connect your AI chat to the **same Genomic Intelligence MCP server** — the same six models, the same tools. They differ only in where that server runs and whether you bring a key: - **Option A — a hosted server we run for you.** You paste one URL into an AI chat that supports custom connectors. Nothing to install, no key, no account with us. This is the fastest way to see a real biology result. - **Option B — a local server you run on your own machine.** You install a small program and give it your own API key. This unlocks your full rate limits, keeps private sequences on your machine, and records your job history. | Path | Best for | Setup | |---|---|---| | **[A. Hosted MCP server (no setup)](#option-a--hosted-mcp-server-no-setup)** | Seeing a biology result in your existing Claude or ChatGPT, right now | Paste one URL. No key, no install. | | **[B. Local MCP server (your own key)](#option-b--local-mcp-server-your-own-key)** | Scientists and developers doing real work — higher caps, private sequences, all tools | `uvx gi-mcp` + a `gi_...` key | | **[C. REST API](rest-api.md)** | Production integrations and pipelines | Auth + HTTP | Start with Option A to see what GI can do, then move to Option B for sustained work. You don't need to know any MCP terminology — pick a path and paste a prompt. ### Option A — Hosted MCP server (no setup) **Best for:** first-time users who want to understand what GI can do before installing anything or getting a key. This path is for **web AI chats that support custom MCP connectors** (ChatGPT, Claude, and others below). We run a Genomic Intelligence MCP server at **`https://mcp.genomicintelligence.ai/mcp`**. Any AI chat that can add a custom (remote) MCP server by URL can reach it. Because our hosted server carries a shared **demo key**, it answers **anonymously** — you add the URL, leave authentication blank, and start asking questions. No install, no account, no API key. :::note[What the demo mode is for] The shared demo key has shared rate limits and is for evaluation, not production. Job history is disabled in demo mode, and you're sharing quota with other evaluators. For real work — your own caps, private sequences, the full tool surface — use [Option B](#option-b--local-mcp-server-your-own-key). ::: #### Which apps can connect To use Option A, your AI chat needs to support **custom (remote) MCP connectors** — a setting that lets you add an MCP server by URL. Whether it's available, and on which plan, varies by platform. The apps below are confirmed to support it. In every case the server URL is `https://mcp.genomicintelligence.ai/mcp` and authentication is left empty. | App | Plan required | Where to add a connector | |---|---|---| | **ChatGPT** (web and desktop) | Plus, Pro, Team, Enterprise, or Edu (not the free tier) | Settings → Apps & Connectors → Developer mode | | **Claude** (claude.ai web and Claude Desktop) | Pro, Max, Team, or Enterprise | Settings → Connectors → Add custom connector | | **Mistral Le Chat** | All plans (including free) | Settings → Connectors → Add custom connector | | **Perplexity** | Pro, Max, or Enterprise | Settings → Connectors → Add custom connector | Two detailed walkthroughs follow — ChatGPT and Claude, the two most common paths — then a general note for everything else. #### Set it up in ChatGPT Custom connectors in ChatGPT live behind **Developer mode**, available on paid plans (Plus, Pro, Team, Enterprise, and Edu — not the free tier). There's no dedicated Genomic Intelligence GPT yet; instead you add our hosted server as a custom connector. 1. Open **Settings → Apps & Connectors → Advanced settings** and turn on **Developer mode**. 2. Back in **Settings → Apps & Connectors**, choose **Create** (also shown as "Add custom connector"). 3. Fill in: - **Name:** `Genomic Intelligence` - **MCP server URL:** `https://mcp.genomicintelligence.ai/mcp` - **Authentication:** **No authentication** 4. Acknowledge ChatGPT's custom-connector risk notice and save. 5. Start a new chat. Open the tools/apps menu (**Tools → Use apps**) and toggle **Genomic Intelligence** on. 6. Paste a prompt from [Your first prompts](#your-first-prompts). :::note On individual Plus and Pro plans, ChatGPT may limit custom connectors to read-only tools; Team, Enterprise, and Edu workspaces get the full surface. GI's tools return data rather than change anything, so the core fetch-and-predict flow works. ::: #### Set it up in Claude (web or Desktop) Custom connectors are available on Claude's paid plans (Pro, Max, Team, and Enterprise). The same steps work on claude.ai in a browser and in the Claude Desktop app. 1. Open **Settings → Connectors** (on the web, the direct link is [claude.ai/settings/connectors](https://claude.ai/settings/connectors)). 2. Click **Add custom connector** (the **+** button). 3. Fill in: - **Name:** `Genomic Intelligence` - **Remote MCP server URL:** `https://mcp.genomicintelligence.ai/mcp` - Leave the **Advanced settings** (OAuth) fields empty. - Optional, to use your own key instead of the demo key: under **Request headers**, add `x-api-key` with your `gi_...` key as the value (see [Option B](#option-b--local-mcp-server-your-own-key) for how to get one). 4. Click **Add**. 5. Start a new chat. Click the **+** button near the message box, choose **Connectors**, and toggle **Genomic Intelligence** on. 6. Paste a prompt from [Your first prompts](#your-first-prompts). Claude reaches your connector from Anthropic's cloud, so a public URL like ours works without any extra network setup. #### Other apps and your own agent Any client that speaks **Streamable-HTTP MCP** can point at the same URL — developer tools like Cursor, Windsurf, Zed, and VS Code, and any custom agent you build. Add `https://mcp.genomicintelligence.ai/mcp` as a remote (HTTP) MCP server and leave authentication empty to use the demo key. To use your own key instead, send it as an `Authorization: Bearer gi_...` header (or `X-GI-Key: gi_...`, or `x-api-key: gi_...`) — see [Option B](#option-b--local-mcp-server-your-own-key) for how to get a key. ### Your first prompts Paste these into a freshly-connected client, in order — simplest first (no inference), then a real fetch-and-predict workflow. **1 — Warm up (lists models, no inference):** > What Genomic Intelligence models are available for expression prediction? **2 — A real workflow (fetch, then predict):** > Fetch a 100 kb window around human TP53 from Ensembl and scan it for promoter regions. Show me the strongest hits. **What "working" looks like:** the assistant calls the **genomic-intelligence** tools, fetches the sequence from Ensembl, runs promoter prediction, and returns ranked promoter-like regions with coordinates and scores — not a text guess. If you see tool calls and coordinate/score output, the connection is live. **No external fetch needed?** The server ships one curated demo sequence per task, so you can run a full prediction without touching Ensembl: > Load the bundled human demo sequence and run promoter prediction on it. Explain the strongest hits. #### One prompt per task Once connected, these exercise every task plus the composite workflow: | # | Task | Prompt | |---|------|--------| | 0 | warm-up | "What Genomic Intelligence models are available for the expression task?" | | 1 | promoter | "Fetch a 100 kb window around human TP53 from Ensembl and scan it for promoter regions. Show me the strongest hits." | | 2 | expression | "Predict HBB expression in K562 cells and report the score in log(TPM+1)." | | 3 | splice | "Fetch the human HBB gene sequence and predict its splice sites." | | 4 | enhancer | "Fetch the Drosophila ftz gene and predict enhancer activity." | | 5 | annotation | "Find the genes in chr8:127,680,000-127,800,000." | | 6 | composite | "Find the genes in chr8:127,680,000-127,800,000 and predict each one's expression in K562." | The enhancer model is trained on *Drosophila*, so example 4 uses a fly gene (`ftz`); the other tasks are human. ### Option B — Local MCP server (your own key) Here you run the Genomic Intelligence MCP server **on your own machine** and give it your own API key, instead of using our shared hosted one. It's the same six models and the same tools — only the location and the key change. **Who this is for:** scientists, bioinformaticians, and developers doing real work rather than a first look. If you've tried the [hosted server](#option-a--hosted-mcp-server-no-setup) and want to go further, this is the next step. **Why run it locally.** The hosted demo is deliberately limited; a local server with your own key removes those limits: - **Your own rate caps.** You no longer share the demo key's small quota with every other evaluator — you get the throughput your key is provisioned for (see [Limits](reference/limits.md)). - **Private sequences stay local.** The server reads local FASTA files straight from your disk and forwards only what a prediction needs to the API under your key — nothing routes through our shared demo principal. - **Your job history.** Async jobs are scoped to your key, so you can list and poll them (job history is turned off in demo mode). - **The full tool surface**, including tools that are disabled for shared demo users. The local server is a thin protocol translator: it owns no inference and stores no key on any server, forwarding each request to the API under **your** key. #### Which apps can run a local server Option A was for web chats. Option B is for hosts that can **launch a local program** as an MCP server — desktop apps, coding CLIs, and IDEs: | App | How you add a local server | |---|---| | **Claude Desktop** | Edit `claude_desktop_config.json` (or Settings → Developer → Edit Config) | | **Claude Code** (CLI) | `claude mcp add … -- uvx gi-mcp` | | **OpenAI Codex CLI** | `codex mcp add …`, or a `[mcp_servers.*]` block in `~/.codex/config.toml` | | **Cursor** | Settings → MCP, or edit `~/.cursor/mcp.json` | | **Windsurf / Zed / other MCP hosts** | Point the host at the local command `uvx gi-mcp` | Detailed walkthroughs for Claude Desktop, Claude Code, and Codex follow; the pattern for any other host is the same command with `GI_API_KEY` set. #### Step 1 — Get a key Email **contact@genomicintelligence.ai** for a `gi_...` key; your caps come with it (see [Limits](reference/limits.md)). The same key works for the REST API and the MCP server. #### Step 2 — Install `uv` Every setup below runs the server with [`uv`](https://docs.astral.sh/uv/); its `uvx` command fetches and runs `gi-mcp` with no manual install. Install `uv` once: ```bash curl -LsSf https://astral.sh/uv/install.sh | sh ``` #### Step 3 — Add GI to your client In every client the shape is identical: run the command `uvx gi-mcp` with `GI_API_KEY` set in its environment. Pick your client below. ##### Claude Desktop 1. Open your config file. The quickest route is **Settings → Developer → Edit Config**, which opens `claude_desktop_config.json` (macOS: `~/Library/Application Support/Claude/`, Windows: `%APPDATA%\Claude\`). 2. Add the `genomic-intelligence` server (merge into `mcpServers` if the file already has other servers): ```json { "mcpServers": { "genomic-intelligence": { "command": "uvx", "args": ["gi-mcp"], "env": { "GI_API_KEY": "gi_..." } } } } ``` 3. **Fully quit and reopen** Claude Desktop — closing the window is not enough; the app must restart to pick up the config. 4. Open a new chat and click the tools (**plug/hammer**) icon — you should see **genomic-intelligence** listed. Ask *"List the available promoter models"* to confirm it responds. ##### Claude Code (CLI) 1. Add the server in one command: ```bash claude mcp add genomic-intelligence --env GI_API_KEY=gi_... -- uvx gi-mcp ``` Everything after `--` is the command Claude Code launches. By default this is **local scope** (this project only). Add `--scope user` to make GI available in every project on your machine: ```bash claude mcp add --scope user genomic-intelligence --env GI_API_KEY=gi_... -- uvx gi-mcp ``` 2. Verify from the shell with `claude mcp list`, or inside a session run the `/mcp` slash command to see **genomic-intelligence** and its status. 3. Ask a prompt from [Your first prompts](#your-first-prompts). ##### OpenAI Codex CLI Either add it with the CLI: ```bash codex mcp add genomic-intelligence --env GI_API_KEY=gi_... -- uvx gi-mcp ``` …or add a block to `~/.codex/config.toml` by hand (note the key goes in a nested `.env` table): ```toml [mcp_servers.genomic-intelligence] command = "uvx" args = ["gi-mcp"] [mcp_servers.genomic-intelligence.env] GI_API_KEY = "gi_..." ``` Confirm it registered with `codex mcp list`, then start Codex and ask a prompt from [Your first prompts](#your-first-prompts). ##### Any other MCP host Cursor, Windsurf, Zed, or your own agent: add the same JSON block to the host's MCP config, or point any MCP-capable client at the stdio command `uvx gi-mcp` with `GI_API_KEY` set in its environment. Pin a release for reproducibility with `uvx gi-mcp@`; pick up new releases with `uvx --refresh gi-mcp`. #### Step 4 — Verify Whichever client you used, it should now list the **genomic-intelligence** server. Ask *"List the available promoter models"* — it runs the catalog tool and returns the registry — then work through [the first prompts](#your-first-prompts). Calls now count against **your** key's caps, not the shared demo's. ### How it works **The handle pattern.** Genomic sequences are large (expression needs at least 9,198 bp and is best fed as much flank on each side of the TSS as the model list recommends; every task accepts up to 500,000 bp). Round-tripping those through the LLM twice would blow the context window, so acquisition and prediction are split: 1. An **acquisition** tool fetches/loads a sequence, stores it server-side, and returns a short **handle** (`seq_ab12cd34`) plus light metadata, never the bases. 2. A **prediction** tool takes that handle; the server resolves the bases internally. Small sequences can still be passed inline. Either way, the bases stay out of the model's context. **What's exposed.** The tools group into **acquisition** (fetch from Ensembl, by coordinates, by local file, inline, or bundled demos), **prediction** (the six tasks, sync or async-with-progress), a composite **annotation-to-expression workflow**, plus read-only **resources** (model catalog, task docs, your recent jobs) and **slash-command prompts** (`gi-promoter-screen`, `gi-expression-screen`). For the exact, current surface, ask your client *"what tools do you have?"* once connected — MCP self-describes, so the list matches your running version. ### The underlying API The MCP server is a convenience layer over the REST contract. To integrate directly, or to understand error codes, limits, and response shapes: - [REST API guide](rest-api.md): auth, then sync, then async, with curl and Python. - [Errors](reference/errors.md): every `error.code`. - [Limits](reference/limits.md): per-task caps, rate quotas, async TTL. - [Agent Skill](https://docs.genomicintelligence.ai/skill/genomic-intelligence.zip): for agents that load skills. It tells the agent to use these MCP tools when they are connected and the bundled Python client otherwise. ### Contact **contact@genomicintelligence.ai**: key issuance, raised caps, bug reports, anything else. --- ## Errors :::tip[Authoritative source] The per-`code` list and the typed `error.details` shapes are in the published OpenAPI schema — browse them in **[ReDoc](https://api.genomicintelligence.ai/redoc)** or fetch [`/v1/openapi.json`](https://api.genomicintelligence.ai/v1/openapi.json). This page covers the envelope, the discriminate-on-`code` rule, the handling strategy, and a few codes whose behavior the schema can't fully express. ::: Every non-2xx response uses the unified envelope: ```json { "error": { "code": "", "message": "", "request_id": "", "details": "" } } ``` `error.code` is the **authoritative discriminator**. Never parse `error.message`. The same `request_id` appears on the `X-Request-Id` response header and on every server log line for the request — quote it in support tickets. :::note[Read `request_id` from the header if the body omits it] The `X-Request-Id` **header** is set on every response, including any error whose body omits `error.request_id`. Read `error.request_id or X-Request-Id` so you always have a correlation id to quote. The bundled client does this for you. ::: ### The code list `code` is a closed enum in the schema — see the `ErrorBody.code` definition in [ReDoc](https://api.genomicintelligence.ai/redoc) or [`/v1/openapi.json`](https://api.genomicintelligence.ai/v1/openapi.json) for the current set. A new code can ship before your client is regenerated — so **treat an unlisted value as a generic failure, not a parse error**. (The schema says so explicitly; a generated client that rejects unknown enum members will break on the next release, not on a bug.) ### Reading `error.details` `details` is an `anyOf` over `ValidationFailedDetails` | `TaskNotSupportedByModelDetails` | `ModelNotFoundDetails` | `SyncTooLargeDetails` | `GenericDetails` | `null`, keyed on the sibling `code`. Switch on `code` first, then read `details`; codes without a typed shape carry only the human-readable `message` and should be treated as opaque. :::warning[Read `details` defensively — and never branch on `loc`] One trap, still live — plus one shape note: 1. **Shape.** For `validation_failed`, `details` is *usually* `{"errors": [...]}`, matching the schema; each entry has the standard FastAPI `{loc, msg, type}` shape. Older releases emitted the bare per-field array, so defensive clients that accept either stay correct. **Two `validation_failed`s break that shape**: the splice response-size cap sends `{task, record_count, maximum_records, sequence_length, threshold}`, and the expression refusal for too little real sequence sends `{invalid_characters: [], invalid_positions: [], valid_characters: [...]}` with empty lists; neither has an `errors` key (see below). Read `details.get("errors", [])` rather than indexing it. 2. **`loc`.** Some checks report where you'd expect — a sequence bound at `["body","sequence"]`, an unknown option key at `["body","options",""]` — but expression's `tss_index` checks come from a whole-model validator and report at **`["body"]`**. There is no `["body","tss_index"]` to match on, and matching on it will silently never fire. Match on `error.code`; use `message` for display only. ::: ### Notable codes Most codes are self-explanatory from the OpenAPI schema. A few have behavior worth noting: - **`504` (no envelope):** a sync request past the upstream read timeout is terminated by the edge proxy with the proxy's body, not the unified `{error: {...}}` envelope (see [Limits](./limits.md)). Retry with `Prefer: respond-async`. - **`404 not_found` on an unknown task:** an unrecognised `{task}` segment — on either `POST /v1/tasks/{task}/predict` or `GET /v1/tasks/{task}/models` — is a `404`, not a `422`. Only the six published tasks exist. - **`404 not_found` on cross-account access:** accessing another caller's job returns `404`, not `403`, to prevent id enumeration. - **The two `413`s are different failures.** `payload_too_large` is the **16 MiB raw-body cap**, enforced before parsing — split the request. `sync_too_large` is an operation refusing **synchronous JSON** delivery above its published cap, with `details = {sequence_length, threshold}` — resubmit the identical body with `Prefer: respond-async`. Two operations have such a cap: the composite `find-genes-and-predict-expression` workflow above 50,000 bp and `POST /v1/tasks/annotation/predict` above 200,000 bp. The other five predict endpoints never emit it, and neither does an annotation request for `?format=bed` or `?format=gff3`, which stays synchronous at any accepted length. See [Limits](./limits.md). - **A too-long `sequence` is *not* a `413`.** Above 500,000 bp — or below the task's floor — is `422 validation_failed` at `loc` `["body","sequence"]`, with the bound and your submitted length in the message. - **`415 unsupported_format`:** an unsupported `?format=` (or `Accept`) value is rejected outright, never silently downgraded to JSON; the message names the supported set. Formats differ per task — promoter `json|bed|bedgraph`, splice `json|bed|gff3`, enhancer `json|bedgraph`, chromatin `json|bed`, annotation `json|bed|gff3`, expression JSON only. Text formats are synchronous-only: pairing one with `Prefer: respond-async` is a `400`. - **`422 validation_failed` on a closed `options`:** every task's `options` object rejects unknown keys (`type: "extra_forbidden"`, `loc` `["body","options",""]`). Notably `model` belongs at the **top level** of the body, not inside `options`. See [Tasks](../tasks.md#options). - **`422 validation_failed` on the splice response-size cap:** `POST /v1/tasks/splice/predict` refuses a request whose response would carry more than **20,000 sites** — reachable only by setting `options.threshold` very low (notably `0`) on a long sequence, where the site count tracks sequence length rather than biology. `details` is `{task, record_count, maximum_records, sequence_length, threshold}` — **not** the `{errors: [...]}` array every other `validation_failed` carries, and not something the OpenAPI schema declares (error responses are typed generically, so this page is the only place it is written down). The remedy is a higher `options.threshold`, never a shorter sequence; use `1e-3` rather than `0` if you want everything. See [Limits](./limits.md#response-size-the-splice-site-cap). - **`422 validation_failed` on `expression`:** five checks are specific to `POST /v1/tasks/expression/predict`, the same for both expression models — sequence below 9,198 bp, sequence above 500,000 bp, `tss_index` missing on a sequence that is not exactly 9,198 bp, `tss_index` outside `[4599, len(sequence) - 4599]` (the TSS must be at least 4,599 bp from each end), and too little real sequence on one side of the TSS. The last one fires on windows dominated by `N` or low-complexity repeats: as a rule of thumb `g0-expression` needs roughly 2 kb of real (non-`N`) sequence upstream of the TSS and 2.6 kb downstream, `g0-expression-8192` roughly 3.3 kb upstream and 2.6 kb downstream; the `message` says which side fell short. The fix is real sequence in place of the `N` or repeat run; for `g0-expression-8192`, more real flank also helps. There is no flag, header, or query parameter that relaxes any of them, and the `tss_index` pair reports at `loc` `["body"]` (see the warning above). See [Limits](./limits.md#expression-sequence-length-and-tss_index). - **`429 too_many_requests`:** comes from three paths — the per-key concurrency cap, the per-key rate cap, or the edge per-IP cap. All emit `Retry-After`; the application paths also emit `RateLimit-*` headers. On the edge path, `error.request_id` is an edge-assigned identifier (32 hex chars) rather than a UUID, but still correlates with the edge access log. See [Limits](./limits.md). ### Handling errors Three buckets: 1. **Retryable transient** (`too_many_requests`, `rate_limited`, `model_loading`, `service_unavailable`, `timeout`, `insufficient_memory`): honor `Retry-After`; if absent, exponential backoff capped at ~30 s. For `timeout` and `insufficient_memory`, resubmit async or with a shorter sequence rather than hammering the same request. 2. **Permanent** (other `4xx`): surface `error.message` to the user; do not retry. `422 validation_failed` messages are usually deterministic and safe to echo verbatim. 3. **Server bug** (`5xx` other than `503` and `504`): capture `request_id` and [contact us](../resources/support.md). One retry is fine; tight loops are not. `504` is the exception to bucket 3: it carries no envelope and means the sync request outran the proxy window, so retry it with `Prefer: respond-async` rather than treating it as a server bug (see the note above). --- Back to the workflow: [REST API guide](../rest-api.md) · [Tasks](../tasks.md). --- ## Limits This page is the single owner of the API's numeric caps and rate quotas. For per-endpoint request/response schemas and the `error.code` list, see [ReDoc](https://api.genomicintelligence.ai/redoc); for how to handle each error, see [Errors](./errors.md). ### Input length per task Each task carries its **own** minimum, published as `minLength` on that task's request schema and enforced at request validation — before any model is loaded. The maximum is **500,000 bp** everywhere. Bounds are `minLength`/`maxLength` on each task's request schema in [`/v1/openapi.json`](https://api.genomicintelligence.ai/v1/openapi.json); per-model context windows (`context_window_bp`) are served by [`GET /v1/tasks/{task}/models`](../tasks.md#model-selection). A task's floor is the strictest its models need — it is **not** per-model, and every listed model stays selectable. Sequences must contain only `A/C/G/T/N` (case-insensitive); oversized, undersized, or out-of-alphabet inputs are rejected with `422 validation_failed` before any GPU work. Request body cap: **16 MiB**. All lengths are counted **after ASCII whitespace is stripped**, so a line-wrapped FASTA sequence body can be pasted verbatim (a `>` header line cannot — it fails the alphabet check). That cuts both ways, and it is the one place the published schema and the server disagree in a way worth knowing: `minLength`/`maxLength` are checked by a *generated client* against the raw string you hand it, and by the *server* against the stripped one. 9,000 bases wrapped over 200 lines is 9,200 raw characters — it satisfies expression's published 9,198 minimum as a string and is still rejected once stripped. **Count bases, not characters.** Since contract revision 5 the alphabet is machine-readable too: every `sequence` field publishes `pattern` as `^\s*(?:[ACGNTacgnt]\s*)+$`, so a generated client enforces it without you retyping the rule. It admits lowercase and inline whitespace deliberately — that is what the server accepts, and a stricter pattern would make your client refuse sequence the API scores. #### The floor is admission control, not regime :::warning[Above the floor is not the same as in regime] A sequence at or above the task floor but **shorter than the selected model's `context_window_bp`** is accepted and scored — against a window **padded out** to the context window. Nothing in the response flags this. Enhancer is the sharpest case: the bound is 50 bp, but `g0-deepstarr` scores 249 bp windows, so a 60 bp submission is ~75% padding. Compare your length against `context_window_bp` — served per model by [`GET /v1/tasks/{task}/models`](../tasks.md#model-selection) as part of `bio_spec` — to know whether the model saw real sequence or padding. Longer-than-context input is never a problem: the scanner steps one prediction window at a time and pads only the final partial window. ::: `bio_spec` also carries **`request_max_bp`** (the enforced ceiling — 500,000 for every model, `g0-expression` included) and **`trained_window_bp`** (a fixed receptive field where one exists: 9,198 for `g0-expression`; null for `g0-expression-8192` and for sliding-window models). Expression models also carry **`recommended_flank_bp`**, how much sequence to send on each side of the TSS (see [below](#expression-sequence-length-and-tss_index)). Use `request_max_bp` as the cap. Older responses may also carry `max_seq_length_bp`; it is ambiguous — the request cap for every model *except* `g0-expression`, where it is instead the trained window — so do not read it, and do not depend on it being present. #### Which status you get | Situation | Response | |---|---| | `sequence` below the task floor or above 500,000 bp | `422 validation_failed` (**not** `413`), `loc` `["body","sequence"]` | | Unknown key inside `options` | `422 validation_failed`, `loc` `["body","options",""]`, `type` `extra_forbidden` | | Raw request body above 16 MiB | `413 payload_too_large`, refused before parsing | | Composite submitted synchronously above 50,000 bp, or annotation above 200,000 bp | `413 sync_too_large` (see [Hard sync cap](#hard-sync-cap)) | | Expression: `tss_index` missing on a sequence that is not exactly 9,198 bp, or the TSS closer than 4,599 bp to either end | `422 validation_failed`, `loc` `["body"]` (see [Expression](#expression-sequence-length-and-tss_index)) | | Expression: too little real (non-`N`, non-repeat) sequence on one side of the TSS | `422 validation_failed` (see [Windows with too little real sequence](#windows-with-too-little-real-sequence)) | | Splice response would carry more than 20,000 sites | `422 validation_failed` (see [Response size](#response-size-the-splice-site-cap)) | | Unknown `{task}` segment | `404 not_found` | | Unsupported `?format=` value | `415 unsupported_format` — never a silent fallback to JSON | #### Expression: sequence length and `tss_index` Every expression model takes the same request body and the same length rule: - Submit **at least 9,198 bp**, with the TSS **at least 4,599 bp from each end** of the whitespace-stripped sequence. The maximum is 500,000 bp. - **`tss_index` is required unless the sequence is exactly 9,198 bp**, where it defaults to `4599`, the only legal value at that length. - There is no `tes_index`. The body is closed, so sending one is a `422`. 9,198 bp is a **floor, not a target**. Longer TSS-centred sequence is better: the server cuts what the model reads out of whatever you submit, around `tss_index`, so extra flank costs one string slice and no async threshold applies. How much to fetch is published per model as **`bio_spec.recommended_flank_bp`** by [`GET /v1/tasks/expression/models`](../tasks.md#model-selection) (public, no key). Never hard-code a window, a flank or a model id; the list changes as models are added: 1. **Model.** Use the one your user named; otherwise the listing's `default_model`. Resolve it once per run and pass it as `model` on every call, so a ref/alt pair or a screen never straddles a change of default. 2. **Flank.** `F` = the largest `recommended_flank_bp` among the listed models, so one fetch serves any of them (flank beyond what a model reads is ignored). Never below 4,599, and capped so `2F` is within `request_max_bp`. 3. **Fetch** gene-sense with the TSS at offset `F` (table below), and send `tss_index = F`. Near a chromosome end, use the largest symmetric `F` that fits, down to 4,599, and say the flank was shortened. Mind the strand when you turn that into genomic coordinates. With `tss` the **0-based** genomic position of the TSS base (subtract 1 from a 1-based coordinate such as a GTF's or Ensembl's), fetch: | Gene strand | Genomic interval to fetch (0-based) | Then | |---|---|---| | `+` | `[tss − F, tss + F)` | send as is | | `−` | `(tss − F, tss + F]`, i.e. `[tss − F + 1, tss + F + 1)` | reverse-complement it | The minus-strand interval is shifted by one base, not mirrored: reverse-complementing `[tss − F, tss + F)` puts the TSS at offset `F − 1`, which is still a legal `tss_index` and so scores the wrong window without an error. How much of the submission a model reads differs by model: for some the server cuts a fixed window around the TSS and the model reads part of it, others read as much flank on each side as they can take. A floor-sized submission is accepted by every model, but a model that would read more then scores less than it was trained on and its number drifts. `meta.task_specific_counts.scored_window` reports what the server cut (the span read, for a model whose `trained_window_bp` is null) and `data.model` which model read it; log both rather than asserting a width. Client-side gates written as `len(seq) != 9198` are wrong: the check is `len(seq) >= 9198` on the whitespace-stripped string, plus the TSS position rule below. There is no flag, header, or query parameter that pads or truncates a short submission. | Submitted `sequence` | `tss_index` | |---|---| | exactly 9,198 bp | optional, defaults to `4599` | | 9,199–500,000 bp | **required** | `tss_index` is the **0-based offset of the transcription start site into the whitespace-stripped sequence**, not a file character offset and not a genomic coordinate. Compute it after removing newlines, or a line-wrapped FASTA will be off by its newline count. It must satisfy `4599 <= tss_index <= len(sequence) - 4599`; violations are rejected with `422`, never clamped or padded. :::warning The legal `tss_index` range is wide, so an index that is merely **wrong** (computed against un-stripped FASTA characters, or against a locus start rather than the submitted slice) does not error: it returns a confident `200` for the wrong window. Assert on the echoed `meta.task_specific_counts.scored_window`, the half-open `[start, end]` of your submitted sequence the server cut for the model, to confirm the server read the region you meant. ::: ##### Windows with too little real sequence A submission that passes the length rule can still be refused with `422 validation_failed` when the sequence around the TSS is dominated by `N` or by low-complexity repeats: each model needs a minimum amount of real sequence on each side of the TSS. As a rule of thumb, at typical genomic density: | Model | Real (non-`N`) sequence upstream of the TSS | Downstream of the TSS | |---|---|---| | `g0-expression` | roughly 2 kb | roughly 2.6 kb | | `g0-expression-8192` | roughly 3.3 kb | roughly 2.6 kb | These are not exact bp cutoffs: repeat-rich sequence needs more, and the point moves from gene to gene by a few hundred bp. The `message` says which side fell short. Ordinary reference-genome TSS windows clear it with room to spare; the usual cause is an N-masked or assembly-gap region. The fix is real sequence in place of the `N` or repeat run; for `g0-expression-8192`, more real flank also helps. (`g0-expression` is always cut the same 9,198 bp around the TSS and reads its central part, so extra flank cannot fix it.) The endpoint does **not** discover the TSS for you and does **not** reverse-complement: submit the gene's coding (sense) strand. If you have raw genomic input where the TSS isn't known, use the composite [find-genes-and-predict-expression](../tasks.md#find-genes-and-predict-expression) workflow instead. It finds the genes and cuts a window around each TSS itself, so it takes no `tss_index` and its floor is annotation's 1,000 bp rather than 9,198. It scores each gene with the API's default expression model (or the one named in `options.expression_model`), using as much flank around each TSS as the submitted region holds, so longer regions give better predictions. ### Response size: the splice site cap Input bounds admit a request; one cap bounds what a request may **emit**. `POST /v1/tasks/splice/predict` refuses any request whose response would carry more than **20,000 splice sites**, with `422 validation_failed`: ```json { "error": { "code": "validation_failed", "message": "splice prediction exceeded the 20000 record response cap at threshold 0.0 on a 60000 bp sequence. Raise options.threshold and retry — a threshold at or below 0 marks nearly every token as a site regardless of the biology.", "request_id": "a375d0cf-4ffd-4317-b3c5-fcbf4292c98e", "details": { "task": "splice", "record_count": 20002, "maximum_records": 20000, "sequence_length": 60000, "threshold": 0.0 } } } ``` `details` carries `record_count`, `maximum_records`, `sequence_length` and `threshold`, so you can compute the retry without parsing the message. Note this is the one `validation_failed` whose `details` is **not** the `{errors: [...]}` array — see [Errors](./errors.md#reading-errordetails). This is the only response-size cap in the API, and splice is the only task with one. It exists because splice is token-level: at a low `options.threshold` the site count tracks **sequence length rather than biology**, and every site is serialised three times (in `sites`, in `tracks`, and in the BED/GFF3 strings under `formats`). At `threshold: 0` a 500,000 bp input would emit roughly 176,000 sites and ~64 MB. Three things worth knowing about how it fires: - **Only a low threshold reaches it.** At the `0.5` default a 500,000 bp input returns a few hundred sites — the cap sits ~66x above any plausible real result. Normal traffic never sees it. - **It is not admission control.** The check runs while sites accumulate during inference, not before the model loads, so it costs a few seconds rather than failing instantly. - **The request is rejected, not truncated.** A silently short site list would read as a complete one. The fix is always a higher `options.threshold`, never a shorter sequence. #### Don't use `threshold: 0` — use `1e-3` If you are lowering the threshold to "get everything", set it to **`1e-3`**, not `0`. `0` marks nearly every token a site regardless of the biology, and it is what the cap exists to reject. `1e-3` is not a compromise. In our SGE splice benchmark, scoring at `1e-3` instead of `0` moved no score by more than **4.6e-4** — entirely inside the noise band you would discard anyway — and ran about **4x faster**, because the bottleneck is serialising the response, not GPU inference. On a 60,000 bp input, `threshold: 0` is a `422` while `1e-3` and `0.5` both return in ~2 s. ### Latency Rough sync latency at the recommended input size, on a warm model. | Task | Sync latency at recommended size | When to go async | |---|---|---| | Promoter / enhancer / chromatin | 0.3–10 s | inputs above 100,000 bp | | Splice | 0.3–10 s | inputs above 250,000 bp | | Annotation | 1–60 s | inputs above 30,000 bp | | Expression (see [below](#expression-sequence-length-and-tss_index)) | 0.5–3 s | n/a — sync is always safe | #### Cold start If a task's model isn't already loaded into GPU memory, the first request pays a model-load cost. The response carries `meta.cold_start: true` and `meta.model_load_time_ms`. Cold start adds 5–15 s for the smaller models and 30–90 s for `expression` and `annotation`. Subsequent calls are warm. ### Sync delivery: timeout and guidance Sync delivery (the default, no `Prefer` header) is best-effort within the upstream HTTP read timeout of 300 seconds. A request that takes longer than that is terminated by the edge proxy and surfaces to your client as a connection reset or `504 gateway_timeout`. The body in this case is the proxy's, not the unified `{error: {...}}` envelope; this is the only place where that happens. Pick async whenever you expect a request to push past ~60 s. #### Hard sync cap Two operations enforce a hard sync cap, and both return [`413 sync_too_large`](./errors.md#notable-codes) to a synchronous request above their threshold: | Operation | Sync cap | |---|---:| | `POST /v1/workflows/find-genes-and-predict-expression` (the composite) | 50,000 bp | | `POST /v1/tasks/annotation/predict` | 200,000 bp | Resend the identical body with `Prefer: respond-async` (as the MCP server's `find_genes_and_predict_expression` and `find_genes` tools always do) to lift the cap. The other five predict endpoints — promoter, splice, enhancer, chromatin, expression — have no sync cap at all: each accepts sync up to its per-task max (see "Input length per task" above), and none of them emits `sync_too_large`. **The cap governs JSON delivery.** Async jobs return JSON, so a request that asks for `?format=bed` or `?format=gff3` is not capped: annotation still serves those synchronously above 200,000 bp, which means a large text-format request can run long enough to hit the 300 s proxy timeout described above. Size those calls yourself. Both thresholds are published structurally, not just here in prose: each is `x-sync-limit-bp` on its own operation in [`/v1/openapi.json`](https://api.genomicintelligence.ai/v1/openapi.json), so a client can read them instead of hardcoding them — and the absence of that extension on the other five predict operations is the contract saying they are uncapped. #### Recommended async opt-in (client-side guidance, not enforced) Use `Prefer: respond-async` when your input exceeds the threshold below. These are calibrated against typical inference times. Sync still works under them, but bursty traffic plus GPU contention can push individual requests past the 300 s proxy window without warning. | Task | Recommended async above | |---|---:| | Promoter | 100,000 bp | | Splice | 250,000 bp | | Enhancer | 100,000 bp | | Chromatin | 100,000 bp | | Annotation | 30,000 bp — advisory; above **200,000 bp** it becomes **enforced**, sync JSON delivery is `413 sync_too_large` | | Expression | n/a — sync is always safe regardless of submission size (see [above](#expression-sequence-length-and-tss_index)) | | Find genes + predict expression | 50,000 bp — and this one is **enforced**, not advisory: above it, sync delivery is `413 sync_too_large` | If sync is critical for your workload and these guidelines push more traffic to async than you'd like, contact us; we can profile your distribution and tune the proxy timeout for your account. ### Per-key quotas Two limiters run per key — concurrent in-flight requests and requests per minute — plus a fixed cap at the edge. Caps are issued **per key**; your account owner tells you the values for yours. You can also read your current limit off the `RateLimit-Limit` response header (your rpm ÷ 6) on any authenticated response — see below. | Setting | Enforced? | |---|---| | Concurrent in-flight requests | Yes. Exceeding the cap returns `429 too_many_requests` with `Retry-After: 1`. | | Per-minute request rate | Yes. Token bucket; capacity = `rate / 6` (10-second burst). An empty bucket returns `429 too_many_requests` with `Retry-After` set to approximately the seconds until the next token. | | Edge per-IP cap | 10 r/s burst 20 on `api.*`. Yes, at the edge; returns `429 too_many_requests` with the unified `{error: {...}}` envelope (see [errors](./errors.md)). | The `÷ 6` burst divisor above is also published structurally as `x-rate-limit-burst-divisor` at the root of [`/v1/openapi.json`](https://api.genomicintelligence.ai/v1/openapi.json) — read it from there rather than hardcoding `6`. #### `RateLimit-*` headers (every authenticated response) The application emits the IETF [httpapi-ratelimit-headers](https://datatracker.ietf.org/doc/draft-ietf-httpapi-ratelimit-headers/) draft set on every authenticated `2xx` and on every `429` from this service, so you can pace from header state without inferring rate from `429`s: | Header | Meaning | |---|---| | `RateLimit-Limit` | Token-bucket capacity (= `rate_per_minute / 6`). | | `RateLimit-Remaining` | Tokens left after this request, integer. | | `RateLimit-Reset` | Seconds until the bucket refills to full. | | `RateLimit-Policy` | `;w=60`. The `w=60` is the draft's window syntax, not a statement that `capacity` is your per-minute allowance — see below. | | `Retry-After` | On `429` only, seconds until at least one token is available. | #### Pacing guidance - `RateLimit-Limit` is a **burst capacity, not your per-minute budget**. It is your tier's `rate_per_minute` divided by 6 (a 10-second burst), so a 300 rpm key advertises `RateLimit-Limit: 50`. Sizing a minute's work from the header alone leaves you pacing 6x slower than your tier allows. Pace sustained work against your issued rpm; use `RateLimit-Remaining` to avoid emptying the bucket in a burst. - Pace at ~80% of `RateLimit-Limit` for burst headroom, and serialize a small worker pool against your concurrency cap rather than firing N parallel requests at it. - The token bucket and concurrency semaphore are independent: a 429 can come from either. Both carry the same `RateLimit-*` spine, but only the rate-bucket 429 has a `Retry-After` calibrated against refill time; the concurrency 429 uses `Retry-After: 1`. ### Async result store Async job results are retained for **24 h** from last activity, then expire. A fetch after the TTL (or after a service restart) returns `410 job_expired`, so retrieve results promptly and re-submit if a job has expired. --- ### Genomic variant interpretation This workflow takes a VCF rather than a sequence, so the bp caps above do not apply to it. Its own bounds: | Bound | Value | |---|---| | Input VCF | 2 GiB maximum, and it must not be empty | | Input | One VCF object, named directly; the key must end `.vcf`, `.vcf.gz` or `.vcf.bgz` | | `options.window` | 1–100,000 bp, default 5,000 | | `options.tissues` | 1–16 entries, default `["heart", "liver", "brain"]` | | `options.genes` | Up to 1,000 HGNC symbols or Ensembl gene ids; omit to score every nearby gene | | `client_ref` | 128 characters | | Delivery | Asynchronous only — `Prefer: respond-async` is required | | Result retention | 24 hours, then `410`. The annotated file in your bucket is not on that clock | Uncompressed, `bgzip`-compressed and plain `gzip`-compressed VCFs are all accepted. Full contract: [Tasks](../tasks.md#genomic-variant-interpretation). Back to the workflow: [REST API guide](../rest-api.md) · [Tasks](../tasks.md). --- ## Support and production access ### Contact Email [contact@genomicintelligence.ai](mailto:contact@genomicintelligence.ai) for API keys, integration questions, bug reports, and access changes. Include your `client_id` so we can trace your traffic. When filing a bug, attach the correlators from the failing call so we can find it in the logs: - `error.request_id` from the response body — also on the `X-Request-Id` response header. See [Errors](../reference/errors.md) for where it appears. - `X-Job-Id`, set on every successful POST, when the issue is with a specific prediction or async job. ### Running at scale The default API tier (see [Limits](../reference/limits.md)) covers development and steady production traffic. For high-volume or latency-sensitive integrations, contact us at [contact@genomicintelligence.ai](mailto:contact@genomicintelligence.ai). We provision production-shaped deployments with higher concurrency and dedicated throughput, sized to your workload. ### Server-side task chaining The **find-genes-and-predict-expression** workflow chains the annotation and expression tasks server-side, so a single call finds genes in a region and predicts their expression without round-tripping intermediate results back to your client. It is a published endpoint — `POST /v1/workflows/find-genes-and-predict-expression`, on the same key as every other route, nothing to enable. Contract and options: [Tasks](../tasks.md#find-genes-and-predict-expression); the 50,000 bp synchronous cap is in [Limits](../reference/limits.md#hard-sync-cap). Other kinds of chaining (a task pipeline we don't ship, or a variant of this one) are worth an [email](mailto:contact@genomicintelligence.ai) — tell us the shape of the call you'd like to make. --- ## REST API Call the REST API from any language: post a sequence to `POST /v1/tasks//predict` with an API key, get back typed JSON. This page walks the contract, then the [integration kit](#3-get-the-kit) — a single-file Python client and runnable recipes that let you reproduce every call in a few minutes. Base URL: `https://api.genomicintelligence.ai` ### 1. The contract Every endpoint shares one shape: - **Six tasks**, one operation each: `POST /v1/tasks/promoter/predict`, `/splice/predict`, `/enhancer/predict`, `/chromatin/predict`, `/annotation/predict`, `/expression/predict` — plus two workflows, `POST /v1/workflows/find-genes-and-predict-expression` and `POST /v1/workflows/genomic-variant-interpretation`. - **API key** on every `/v1/*` route, sent as `Authorization: Bearer gi_…`. Public (no key): `/health`, `/docs`, `/redoc`, `/v1/openapi.json`, and `GET /v1/tasks/{task}/models` — capability discovery needs no key, so you can size a request against a model's `bio_spec` before onboarding. It is metered per source IP rather than per partner, so a burst of discovery calls can `429`. - **One success envelope** — `{data, meta}` on every predict and workflow 2xx, including the `202`. `data` is task-specific; `meta` is uniform across tasks. The read-only endpoints are deliberately bare: `GET /v1/tasks/{task}/models` returns `{task, default_model, models}` and `GET /v1/tasks/jobs` returns `{jobs, count}`. `meta` describes the computation that produced a result — `model`, `cold_start`, timings, `job_id` — so an endpoint that runs no inference has nothing to put there. - **One error envelope** — `{error: {code, message, request_id, details?}}`. Switch on `error.code`, never the message. - **Tell us what is calling** — optional. `X-GI-Client-App: ` (and `X-GI-Client-App-Version`) is recorded against the request and changes nothing about auth, routing or the response. It is worth setting if your key is shared across a team, a course or an event: without it every caller on one key is one caller to us, and we cannot tell your traffic from anyone else's when you ask about your own usage. Up to 64 characters (32 for the version); control characters are stripped. - **Sync by default, async on request** — `Prefer: respond-async` is a declared header parameter on all six predict operations and the composite: the call returns `202` with a `job_id`, and you poll `GET /v1/tasks/jobs/{job_id}`. - **Per-task bodies.** Each task has its own request schema, its own minimum `sequence` length, and its own **closed** `options` object — there is no shared `PredictRequest` any more. The URLs are unchanged, so client *code* needs no new URL construction, but a typed SDK generated from the old document must be regenerated. See [Tasks](tasks.md#options) and [Limits](reference/limits.md#input-length-per-task). The live [OpenAPI schema](https://api.genomicintelligence.ai/v1/openapi.json) (browse it in [ReDoc](https://api.genomicintelligence.ai/redoc)) is the machine-readable source of truth for every field. **Pin the contract revision.** The document carries a top-level `x-contract-revision` — a monotonic integer that changes whenever anything partner-visible in it changes, and only then. Record the value you built against and compare it on a schedule; you get a one-integer answer to "has the contract moved?" without diffing the document. A version bump alone never moves it. :::note The six-operation document, the typed `options`, the per-task minimums, and the published composite are rolling out to `api.genomicintelligence.ai` now. If a schema you fetched still reports a single templated `POST /v1/tasks/{task}/predict`, you have the previous version — the request URLs and response bodies are identical either way. ::: ### 2. Get a key Email [contact@genomicintelligence.ai](mailto:contact@genomicintelligence.ai) for a `gi_…` API key. The same key works for the REST API and the [MCP server](mcp.md). Verify it in one call: ```bash curl -sS https://api.genomicintelligence.ai/health # {"status":"healthy","version":"YYYY.MM.DD.iter (commit)"} ``` ### 3. Get the kit Browse the code in your browser — the [Python client](/integration-kit/client) and [recipes](/integration-kit/recipes) render with syntax highlighting — or **[download the integration kit](https://docs.genomicintelligence.ai/integration-kit.tar.gz)** (`.tar.gz`) to run it locally. Fetch it inline: ```bash curl -L https://docs.genomicintelligence.ai/integration-kit.tar.gz | tar -xz cd integration-kit/ ``` Inside: | Path | What it is | |---|---| | `client/gi_client.py` | Single-file client. Depends only on `requests`. Drop it into your project. | | `client/quickstart.py` | Runs every task end to end on real bundled sequences. | | `client/sequences/` | Real FASTA fixtures, one per task. | | `recipes/` | Five self-contained integration patterns (see [Recipes](#6-recipes)). | ### 4. Run the quickstart This hits every task with a real biological sequence and prints the result — the fastest way to see the API work: ```bash cd integration-kit/client pip install -r requirements.txt export GI_API_KEY=gi_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx python quickstart.py ``` ### 5. Call a task Drop `gi_client.py` into your project and call a task. Every prediction returns the full `{data, meta}` body: ```python import os from gi_client import Client client = Client(api_key=os.environ["GI_API_KEY"]) body = client.predict("promoter", sequence="ACGT" * 500, sequence_name="demo") print(body["meta"]["model"], body["meta"]["inference_time_ms"], "ms") print(body["data"]["regions"]) ``` Two things to get right on any task: - **Mind the per-task minimum.** Promoter needs ≥ 300 bp, splice 100, enhancer 50, chromatin 200, annotation 1,000, expression 9,198 — measured after whitespace is stripped, and enforced before any model loads. Under it (or over 500,000 bp) is `422 validation_failed`, not `413`. Being *above* the floor is not the same as being in regime: if your sequence is shorter than the chosen model's `context_window_bp`, it is scored against a padded window. For expression, `context_window_bp` is null; compare against `2 × recommended_flank_bp` instead. [Limits](reference/limits.md#the-floor-is-admission-control-not-regime) has the table. - **`options` is closed.** Each task accepts a fixed set of keys — an unknown one is `422 validation_failed` with `loc` `["body","options",""]`. In particular, choose a model with the top-level `model=` argument, never `options={"model": …}`. The per-task keys are in [Tasks](tasks.md#options). The `expression` task requires an experimental-context description and a TSS position. Every expression model takes at least 9,198 bp with the TSS at least 4,599 bp from each end. Longer TSS-centred sequence is better, and the model list says how much: build a gene-sense sequence with the TSS at that offset, and pass `tss_index`, the **0-based offset of the TSS into the whitespace-stripped sequence**. Do not hard-code a model id or a flank; read both from the list, so a new default or a longer-window model needs no change on your side. With the Python client, one call builds that input from a gene symbol. It reads the model list, takes the TSS from the Ensembl canonical transcript, reverse-complements minus-strand genes, and returns `2F` bp gene-sense with the TSS at offset `F`: ```python w = client.fetch_expression_window("HBB") # Ensembl REST, no key; HBB is minus strand body = client.predict( "expression", sequence=w["sequence"], # 2 * F bp, F from the model list sequence_name="HBB", model=w["meta"]["default_model"], # or the model your user picked tss_index=w["tss_index"], # F, or less near a chromosome end options={"description": "polyA plus RNA-seq; Homo sapiens K562"}, ) ``` `w["meta"]` records the gene, Ensembl id, region, strand, the flank and the model whose `recommended_flank_bp` set it. Near a chromosome end the flank shrinks to the largest that fits (`flank_shortened`); a TSS closer than 4,599 bp to an end raises `ExpressionWindowError`. To build the input yourself, mind the strand when you fetch: ```python listing = client.list_models("expression") model = listing["default_model"] # or the model your user picked; resolve once per run # One fetch that serves every listed model: the largest recommended flank (the # server ignores flank beyond what a model reads), never below the 4,599 bp # per-side floor, and with 2F within the request cap. flank = max([4599] + [m["bio_spec"].get("recommended_flank_bp") or 0 for m in listing["models"]]) flank = min(flank, min(m["bio_spec"]["request_max_bp"] for m in listing["models"]) // 2) # tss = 0-based genomic position of the TSS base. fetch() and revcomp() are your own. if strand == "+": locus = fetch(chrom, tss - flank, tss + flank) # [tss - F, tss + F) else: locus = revcomp(fetch(chrom, tss - flank + 1, tss + flank + 1)) # (tss - F, tss + F], then reverse-complemented # Either way the TSS now sits at offset `flank` of the gene-sense sequence. body = client.predict( "expression", sequence=locus, # 2 * flank bp; at least 9,198, up to 500,000 sequence_name="HBB", model=model, # explicit, so a run never straddles a default change tss_index=flank, # required unless len(sequence) == 9198 options={"description": "polyA plus RNA-seq; Homo sapiens K562"}, ) print(body["data"]["model"], body["data"]["prediction"]["expression_log_tpm"], "log(TPM+1)") # Confirm the server read the region you meant; its width depends on the model. print(body["meta"]["task_specific_counts"]["scored_window"]) ``` The same body works with any listed model: pass another id as `model` and the server cuts what that model reads around `tss_index`. Near a chromosome end, use the largest symmetric flank that fits, down to 4,599 bp. A submission of exactly 9,198 bp centred on the TSS needs no `tss_index` (it defaults to `4599`), but it is the floor, not a target: a model that reads more flank than that scores less than it was trained on. Sequences shorter than 9,198 bp, or with the TSS closer than 4,599 bp to either end, are rejected with `422 validation_failed`; there is no padding or truncation fallback. A window dominated by `N` or low-complexity repeats can also be refused, because each model needs a minimum of real sequence on each side of the TSS. A `tss_index` computed against line-wrapped FASTA *characters* rather than the stripped nucleotide string will be off by its newline count, which can silently score the wrong region; always check the echoed `scored_window`. Full rules: [Limits](reference/limits.md#expression-sequence-length-and-tss_index). Per-task inputs, options, and outputs are on the [Tasks](tasks.md) page. #### Asynchronous jobs For long inputs, submit asynchronously and poll. The client handles both steps — submit returns a `job_id`, and `wait_for_job` polls until the job is done: ```python job_id = client.submit_async( "annotation", sequence=long_sequence, sequence_name="chr8:1-120000", ) result = client.wait_for_job(job_id, on_progress=print) print(len(result["data"].get("transcripts", [])), "transcripts") ``` `Prefer: respond-async` is a declared header parameter on all six predict operations and on both workflows — **required** on [genomic-variant-interpretation](tasks.md#genomic-variant-interpretation), which has no synchronous mode, and required for an [annotation](tasks.md#annotation) JSON response above 200,000 bp; optional everywhere else. The `202` body is the same `{data, meta}` envelope as a sync `200`, with `data = {job_id, status: "accepted", links}`; the id is also on the `Content-Location` and `X-Job-Id` response headers. Polling `GET /v1/tasks/jobs/{job_id}` returns `202` with `data = {job_id, status, progress}` while the job runs, then `200` with the result. Async is JSON-only — pairing it with a text `?format=` is a `400`. Use async above the per-task size thresholds in [Limits](reference/limits.md); below them, sync is simplest. #### Find genes, then predict their expression `POST /v1/workflows/find-genes-and-predict-expression` chains annotation and expression server-side: it finds the genes in a region, cuts a window around each TSS, and scores each gene with the API's default expression model (or the one named in `options.expression_model`), using as much flank around each TSS as the submitted region holds, so longer regions give better predictions, so you never compute a `tss_index`. ```python body = client.find_genes_and_predict_expression( sequence=region, # 1,000–500,000 bp, plus strand sequence_name="chr8:127,680,000-127,800,000", description="polyA plus RNA-seq; Homo sapiens K562", async_=True, # required above 50,000 bp ) result = client.wait_for_job(body["data"]["job_id"]) print(result["meta"]["task_specific_counts"]) # {genes_found, genes_predicted, genes_skipped} for gene in result["data"]["expression_predictions"]: print(gene.get("skip_reason") or gene["expression"]) # log(TPM+1); expression_tpm is linear ``` Submitted synchronously above 50,000 bp it returns `413 sync_too_large` with `details = {sequence_length, threshold}`; resend the identical body with `async_=True`. `POST /v1/tasks/annotation/predict` behaves the same way above 200,000 bp, but only for a **JSON** response: `?format=bed` and `?format=gff3` have no cap and stay synchronous at any accepted length, because async delivery is JSON-only and pairing `Prefer: respond-async` with a text format is a `400`. Those two operations are the contract's only sync caps. Full contract: [Tasks](tasks.md#find-genes-and-predict-expression). #### Interpret the variants in a VCF `POST /v1/workflows/genomic-variant-interpretation` is the one operation that takes no DNA `sequence`. Point it at a VCF in your own object storage; it scores the variants near a transcription start site and writes an annotated copy beside it, named after the input and the job — read the exact name from `data.output.uri`. The JSON is a receipt — where the file is and how the run went — so you never parse a VCF to drive the workflow. ```http POST /v1/workflows/genomic-variant-interpretation Authorization: Bearer gi_... Prefer: respond-async ``` ```json { "input": { "type": "s3_object", "uri": "s3://your-bucket/cases/CASE-00123/sample.vcf.gz" }, "client_ref": "CASE-00123", "options": { "genome_build": "GRCh37" } } ``` `Prefer: respond-async` is **required** here — a case runs for hours, so there is no synchronous mode and a request without the header is `400`. Poll `GET /v1/tasks/jobs/{job_id}` as above. Resubmitting the same case returns the job you already have rather than starting a second run. Full contract, including the annotation format and why `meta.model` may be absent: [Tasks](tasks.md#genomic-variant-interpretation). #### Error handling Every non-2xx raises `GIError`, carrying the envelope's fields. Switch on `code`, not HTTP status: ```python from gi_client import Client, GIError try: client.predict("promoter", sequence="ACGT" * 500, sequence_name="demo") except GIError as exc: print(exc.code, exc.message, exc.request_id) ``` Every `error.code` and how to handle it is in [Errors](reference/errors.md). ### 6. Recipes Self-contained scripts that each show one pattern. [Read them all in the browser](/integration-kit/recipes), or link straight to the raw source: | Intent | Recipe | |---|---| | Verify connectivity and key | [`01_health_probe.py`](https://docs.genomicintelligence.ai/recipes/01_health_probe.py) | | Promoters across a gene list | [`02_promoters_for_gene_list.py`](https://docs.genomicintelligence.ai/recipes/02_promoters_for_gene_list.py) | | Async annotation with polling | [`03_async_annotation_polling.py`](https://docs.genomicintelligence.ai/recipes/03_async_annotation_polling.py) | | Rate-limit-aware retry | [`04_ratelimit_aware_retry.py`](https://docs.genomicintelligence.ai/recipes/04_ratelimit_aware_retry.py) | | Typed error handling | [`05_typed_error_handling.py`](https://docs.genomicintelligence.ai/recipes/05_typed_error_handling.py) | ### Client reference `gi_client.py` exposes: - `Client(api_key, base_url=…, timeout=…)` — session configured with your key. - `predict(task, sequence, sequence_name, model=None, options=None, tss_index=None)` — synchronous; returns `{data, meta}`. `model` is top-level, not an `options` key. - `submit_async(...)` — same arguments, submitted with `Prefer: respond-async`; returns a `job_id`. - `find_genes_and_predict_expression(sequence, description, sequence_name=…, options=None, async_=False)` — the composite workflow. - `wait_for_job(job_id, poll_interval=2.0, on_progress=None)` — poll until terminal. - `fetch_expression_window(symbol, species="human")` — a TSS-centred, gene-sense expression input from a gene symbol, fetched from Ensembl and sized from `list_models("expression")`; returns `{sequence, tss_index, meta}`. - `list_models(task)`, `list_jobs(limit=…)`, `health()` — supporting calls. `list_models` returns the flat `{task, default_model, models}` object, each model carrying `bio_spec.request_max_bp` / `context_window_bp` / `trained_window_bp` (and, for expression, `recommended_flank_bp`). - `TASK_MIN_BP`, `MAX_BP`, `FIND_GENES_SYNC_LIMIT_BP` — local mirrors of the published bounds, for pre-flight checks. The authority is the served schema, not these constants. - `GIError` — raised on any non-2xx, carrying `code`, `message`, `request_id`, `details`. - `EnsemblError`, `ExpressionWindowError` — from `fetch_expression_window`: Ensembl unreachable or the gene unknown; the TSS too close to a chromosome end, or no canonical transcript. ### Output formats Predictions return JSON in the `{data, meta}` envelope by default. Tasks that also emit text tracks (BED, bedGraph, GFF3) expose them via the `Accept` header or a `?format=` query parameter; the [Tasks](tasks.md) page lists the formats each one supports. An unsupported value is `415 unsupported_format` — never a silent fallback to JSON — and text formats are synchronous-only, so combining one with `Prefer: respond-async` is a `400`. #### GFF3 `source` (column 2) In every GFF3 this API **generates**, column 2 is the id of the model that produced the feature — the same value as `data.model` — so a saved track records its own provenance: ``` chr1 g0-splice-bigbird splice_donor 68 73 0.9949 . . ID=SD_1 ``` :::note Changed in contract revision 4 Splice GFF3 previously emitted the literal `gpu_service` here. Saved files produced before revision 4 carry the old value; nothing else about the line changed. If you parse column 2, read it as the model id. ::: The one exception is annotation's `g0-annotation`, whose upstream pipeline emits its own canonical GFF3. That document is passed through **verbatim**, so its column 2 reads `GENATATOR-PIPELINE` — a four-stage pipeline rather than a single model, which a single model id would misdescribe. ### Next steps - [Tasks](tasks.md): per-task input sizes, options, outputs, and strand-sensitivity. - [Errors](reference/errors.md): every `error.code` and how to handle it. - [Limits](reference/limits.md): per-task length caps, rate quotas, async TTL. - [MCP server](mcp.md): the same six tasks as agent tools. - [OpenAPI schema](https://api.genomicintelligence.ai/v1/openapi.json) · [ReDoc](https://api.genomicintelligence.ai/redoc): the full machine-readable contract. --- ## Tasks Six tasks, each its **own published operation** — `POST /v1/tasks/promoter/predict`, `/v1/tasks/splice/predict`, `/v1/tasks/enhancer/predict`, `/v1/tasks/chromatin/predict`, `/v1/tasks/annotation/predict`, `/v1/tasks/expression/predict` — plus two [workflows](#find-genes-and-predict-expression) that compose them. The URLs are exactly the strings you already POST to; what changed is that each now has its own request schema, its own `minLength`, and its own closed `options` object, instead of one shared `PredictRequest`. (Regenerate typed clients built against the old shared model.) The same six tasks are also tools over [MCP](mcp.md). Each accepts a DNA `sequence` (and a `sequence_name` label) and returns task-specific fields under `data`; `meta` is uniform across tasks. Request and response schemas — with copyable examples — are in [ReDoc](https://api.genomicintelligence.ai/redoc); per-task length caps and latency are in [Limits](reference/limits.md). | Task | Input (bp) | Model window | Strand-sensitive | Output | |---|---|---|---|---| | [Promoter](#promoter) | 300–500,000 | 2,000 (300 on the `*-300bp` models) | Yes (coding strand) | Promoter-region probabilities | | [Splice](#splice) | 100–500,000 | 15,000 | Yes (transcript orientation) | Donor / acceptor sites | | [Enhancer](#enhancer) | 50–500,000 | 249 | Yes (dev/hk channels) | `dev` + `hk` activity scores | | [Chromatin](#chromatin) | 200–500,000 | 1,000 | No | 919 features in 8 track groups | | [Expression](#expression) | 9,198–500,000 (+ `tss_index`) | — (`recommended_flank_bp` per model) | Yes (coding strand) | Expression in log(TPM+1) | | [Annotation](#annotation) | 1,000–500,000 | — | Plus-strand input | Transcripts with type + exon/intron/CDS structure (GFF3) | | [Find genes + expression](#find-genes-and-predict-expression) | 1,000–500,000 | — | Plus-strand input | Genes found, each with a predicted expression | | [Variant interpretation](#genomic-variant-interpretation) | A VCF, not a sequence | — | Coordinates, not strand | An annotated copy of your VCF, written back to your bucket | Where a task is marked strand-sensitive, submit DNA 5'→3' on the gene's coding (sense) strand; for annotation, submit the plus-strand region. `GET /v1/tasks/{task}/models` returns `{task, default_model, models}`; each model's `is_default` marks the default. The model-list endpoint is authoritative for what each task currently serves. The "input" column is the **accepted** range, enforced before any model loads. The "model window" is the model's own `context_window_bp`: a sequence above the floor but below that window is still scored — against a window padded out to it. Expression models publish no `context_window_bp`; for them, compare against `2 × recommended_flank_bp`. See [the floor is admission control, not regime](reference/limits.md#the-floor-is-admission-control-not-regime). ### Model selection Each task has a `default_model` and may offer alternatives. List them with `GET /v1/tasks/{task}/models` (a flat `{task, default_model, models}` object, not the `{data, meta}` envelope; it is public, no key needed, and an unknown task is `404 not_found`). To pick one, pass its id in the **top-level `model` field of the request body** — *not* `options.model`: every task's `options` object is closed, so an unrecognised key there is `422 validation_failed` with `loc` `["body","options","model"]`. Each model's `bio_spec` carries `request_max_bp` (the enforced ceiling), `context_window_bp` (its own window), `trained_window_bp` (a fixed receptive field where it has one) and, for expression, `recommended_flank_bp` (how much sequence to send on each side of the TSS) — see [Limits](reference/limits.md#the-floor-is-admission-control-not-regime). Beyond the default human models, `promoter` offers species-specific variants (Drosophila, yeast, Arabidopsis), and DNABERT k-mer variants exist for `promoter`, `enhancer`, and `chromatin`; `expression` offers more than one model, with longer-window models added over time; `default_model` names the current default. The model-list endpoint is authoritative for what each task currently serves; the same roster and default are also published statically as `x-models` on each predict operation in [`/v1/openapi.json`](https://api.genomicintelligence.ai/v1/openapi.json), for tooling that wants it without a live call. ### Options `options` is typed and **closed** per task: unknown keys are rejected with `422 validation_failed` (`type: extra_forbidden`) rather than ignored. The complete set: | Task | `options` keys | Required | |---|---|---| | Promoter | `threshold` (0–1, default 0.5) | — | | Splice | `threshold` (0–1, default 0.5), `site_types` (subset of `["donor","acceptor"]`, default both) | — | | Enhancer | *none — the object accepts no fields* | — | | Chromatin | `threshold` (0–1, default 0.5) | — | | Annotation | `shift_coordinates` (string, e.g. `"UCSC"`), `reverse_complement` (bool, default `true`) | — | | Expression | `description` (string) | **`description`**, and `options` itself | | Find genes + expression | `description`, `annotation_model`, `expression_model`, `shift_coordinates` | `options` itself; `description` enforced at runtime | ### The tasks, one card each Each task below has its own notes, an example call from the [kit client](https://docs.genomicintelligence.ai/integration-kit/client) and from an [MCP](mcp.md) host, then **Applications** and **Usage tips**. On the rendered page ([docs.genomicintelligence.ai/tasks](https://docs.genomicintelligence.ai/tasks)) each card also carries Input, Options and Output panels, generated at build time from the pinned [`/v1/openapi.json`](https://api.genomicintelligence.ai/v1/openapi.json) so they cannot drift from it; **Source** on a panel opens that operation in ReDoc. The prose does not restate those schemas; outside the panels, read them in [ReDoc](https://api.genomicintelligence.ai/redoc) or in `/v1/openapi.json` itself. ### Promoter Binary classification that detects promoter regions. The default `g0-promoter-2000bp` is a G0 BERT-Large encoder trained on human promoters from EPDnew. Inputs above 2,000 bp are scanned in windows automatically. - `sequence`: floor set by the smallest `context_window_bp` among the promoter models (bounds in the table above); below `g0-promoter-2000bp`'s own 2,000 bp window the input is padded out to it. - `options.threshold` (0–1, default 0.5): probability cutoff for calling a window a promoter. The only key `PromoterOptions` accepts. - Strand-sensitive — submit the coding (sense) strand. Output: per-window promoter probabilities. Also `BED` and `bedGraph` — `?format=json|bed|bedgraph` (see [output formats](rest-api.md#output-formats)). #### API reference **Python client** ```python import os from gi_client import Client # the kit's single-file client client = Client(api_key=os.environ["GI_API_KEY"]) # sent as Authorization: Bearer gi_... r = client.predict("promoter", sequence=seq, options={"threshold": 0.5}) regions = r["data"]["regions"] ``` **MCP** Ask the [MCP server](mcp.md): *"Fetch a 100 kb window around human TP53 and scan it for promoter regions."* #### Applications Use it to locate transcription start regions in unannotated sequence, or to score designed constructs for promoter strength inside an optimisation loop. The per-window detail in `data.window_details` makes it usable as a fitness signal rather than only a binary call. #### Usage tips - **The floor is 300 bp** — the `minLength` on this operation's request schema. It is a property of the endpoint, so choosing a different `model` does not lower it. - **Input shorter than the model's window is padded, not rejected.** A 300 bp submission is scored against `g0-promoter-2000bp`'s 2,000 bp window; compare your length with `bio_spec.context_window_bp` from `GET /v1/tasks/promoter/models` before reading much into a marginal call. - **Submit the coding (sense) strand.** The task is strand-sensitive. ### Splice Token-level classification labeling each position as a splice acceptor (3' site), donor (5' site), or neither. The default `g0-splice-bigbird` is a G0 BigBird encoder trained on human splice sites from SpliceAI. Long inputs are scanned in a 15,000 bp sliding window; predictions are most reliable in the central region of each window. - `sequence`: the floor (bounds in the table above) is well below the model's 15,000 bp window, so short submissions are scored against heavy padding — treat 15,000 bp as the in-regime size. - `options.threshold` (0–1, default 0.5): score cutoff for emitting a site. A response carrying more than **20,000 sites** is refused with `422 validation_failed` — only a very low threshold on a long sequence gets there. If you want everything, use `1e-3`, not `0`: it is numerically equivalent (no score moved by more than 4.6e-4 in our benchmark), ~4x faster, and stays under the cap. See [Limits](reference/limits.md#response-size-the-splice-site-cap). - `options.site_types`: subset of `["donor", "acceptor"]` (default both). With `threshold`, the only two keys `SpliceOptions` accepts. - Strand-specific — submit the transcript's orientation. The wrong strand does not fail loudly, and it does not return near-zero scores either: it returns sites at different positions, often still at high confidence. On our BRCA1 fixture the reverse complement scored 0.9101 and 0.9946 where gene-sense scored 0.9998 and 0.9999; on SMN1 it returned 1 site instead of 17. Neither the site count nor the scores give you a usable check, and there is no `strand` flag in the contract, so track orientation on your side. - **`start`/`end` bound the scored token, not the junction.** The model reads your sequence as BPE tokens and scores whole tokens, so a site's span is that token's character range — typically 4–8 bp, and varying from site to site because token lengths do. A donor or acceptor junction is a single base. `token_index` names the token the span came from. Do not treat the span as the feature's extent, and be careful intersecting it with a base-resolution reference annotation: at that scale it will be quietly wrong. We publish no derived base position — deriving one from a token score would be a modelling claim we cannot currently defend, and invented precision in a file you keep is worse than an honest span. Stated in the contract since revision 5. Output: detected acceptor and donor sites with scores. Also `BED` and `GFF3` — `?format=json|bed|gff3` (see [output formats](rest-api.md#output-formats)). The GFF3 `source` column carries the model id (`g0-splice-bigbird`); it read `gpu_service` before contract revision 4. **Columns 4–5 of that GFF3 are the token spans described above**, so a saved track has token resolution, not base resolution. #### API reference **Python client** ```python # client = Client(api_key=os.environ["GI_API_KEY"]), as in Promoter r = client.predict("splice", sequence=seq, options={"threshold": 1e-3, "site_types": ["donor", "acceptor"]}) sites = r["data"]["sites"] # start/end bound a token, not the junction base ``` **MCP** Ask the [MCP server](mcp.md): *"Fetch the human HBB gene sequence and predict its splice sites."* #### Applications Use it to locate exon boundaries in unannotated transcripts, to check whether a designed edit creates or destroys a splice site, or to screen variants for splice disruption by scoring the reference and the edited sequence side by side. #### Usage tips - **Submit the transcript's orientation.** The wrong strand does not fail loudly: it returns sites at different positions, often at high confidence, and no score or count identifies a mis-oriented submission afterwards. Reverse-complement minus-strand genes before you call. - **A site's `start`/`end` is a token span, not the junction base** — typically 4–8 bp. Locate a boundary to within the span; do not reduce it to one base or intersect it with base-resolution annotation as though it were one. - **The floor is 100 bp, the window 15,000 bp.** Treat 15,000 bp as the in-regime size. - **Do not send `threshold: 0`.** A response over 20,000 sites is refused with `422 validation_failed`; `1e-3` returns effectively everything and stays under the cap. ### Enhancer Regression predicting two scores per window: developmental (`dev`) and housekeeping (`hk`). The default `g0-deepstarr` is a G0 BERT-Base encoder trained on Drosophila enhancers from DeepSTARR. The sequence is split into consecutive, non-overlapping 249 bp windows, each scored independently. - `sequence`: the floor (bounds in the table above) is admission control — the shortest input `g0-deepstarr` will admit — not a useful size: the model scores 249 bp windows, so anything shorter is accepted and scored against a padded window. Submit ≥ 249 bp to stay in regime. - `options`: **`EnhancerOptions` accepts no fields.** Send `{}` or omit it; any key is a `422`. There is no threshold on this task — it is regression, not classification. The model is Drosophila-trained and strand-sensitive for the dev/hk channels — use a fly sequence on the gene's coding (sense) strand. Output: per-window `dev` and `hk` scores, embedding bedGraph renderings of each track. `bedGraph` is also available directly — `?format=json|bedgraph` (see [output formats](rest-api.md#output-formats)). #### API reference **Python client** ```python # client = Client(api_key=os.environ["GI_API_KEY"]), as in Promoter r = client.predict("enhancer", sequence=fly_seq) # no options: EnhancerOptions accepts none windows = r["data"]["windows"] ``` **MCP** Ask the [MCP server](mcp.md): *"Fetch the Drosophila ftz gene and predict enhancer activity."* #### Applications Use it to rank candidate enhancers, or as a dual-objective fitness function when designing regulatory elements that favour one programme (developmental or housekeeping) over the other. #### Usage tips - **The floor is 50 bp**, the lowest of the six, but the model scores 249 bp windows. Submit at least 249 bp to stay in regime. - **The developmental/housekeeping split is a *Drosophila* STARR-seq definition** (DeepSTARR). Read the two scores as relative activity within a comparison, not as calibrated cross-species values. - **Send no options.** `EnhancerOptions` accepts no fields: send `{}` or omit it; any key is a `422`. ### Chromatin Multi-label classification predicting 919 mammalian chromatin features (DeepSEA-style), grouped into eight categories (DNase, CTCF, Pol2, c-Myc, H3K27ac, H3K27me3, H3K4me1, Other). The default `g0-deepsea` is a G0 BERT-Base encoder trained on ENCODE data. The sequence is tiled into 1,000 bp windows stepping every 200 bp. - `sequence`: the model's window is 1,000 bp (floor in the table above), so submit at least that to avoid padding. - `options.threshold` (0–1, default 0.5): only features scoring above this are returned. The only key `ChromatinOptions` accepts. Output: per-feature probabilities (above the threshold), grouped by category. Also `BED` — `?format=json|bed` (see [output formats](rest-api.md#output-formats)). #### API reference **Python client** ```python # client = Client(api_key=os.environ["GI_API_KEY"]), as in Promoter r = client.predict("chromatin", sequence=seq, options={"threshold": 0.5}) windows = r["data"]["windows"] print(r["meta"]["task_specific_counts"]["total_annotations"]) ``` **MCP** Ask the [MCP server](mcp.md): *"Fetch the human HBB promoter region and predict its chromatin features."* #### Applications Use it to ask whether a sequence looks accessible, bound, or marked, and to compare designed variants against a natural reference across many assays at once. #### Usage tips - **The floor is 200 bp; the window is 1,000 bp.** Submit at least 1,000 bp to avoid padding. - **Lowering `threshold` grows the response.** Only features scoring above it are returned, and each window is scored on all 919. - **A count is not a cell type.** `meta.task_specific_counts.total_annotations` sums calls across every window and every feature; a high count is not evidence about any one cellular context. Read the individual features for that. ### Expression Predicts gene expression from a DNA sequence plus an experimental-context description, on a log(TPM+1) scale. Each model's training data is published as `bio_spec.training_data` in the [model list](#model-selection) (today, for both: human and mouse RNA-seq from ENCODE bulk, GTEx via recount3, and cellxgene single-cell pseudobulk). The models differ in how much flank around the TSS they read; the [model list](#model-selection) names the default, and the top-level `model` field selects another. Expression has its own operation and request schema — `POST /v1/tasks/expression/predict`, `ExpressionPredictRequest` — as every task now does. It remains the only one that takes a `tss_index` and the only one whose `options` has a required field. The body accepts exactly five fields — `sequence` (required), `options` (required), `tss_index`, `sequence_name`, `model` — and is closed: any other top-level key returns `422 validation_failed`. - **`sequence`** (required): **at least 9,198 bp, up to 500,000 bp**, gene-sense strand, with the TSS at least 4,599 bp from each end. Longer TSS-centred sequence is better, and the model list says how much: put the TSS at offset `F` of the gene-sense sequence, `F` the largest `bio_spec.recommended_flank_bp` in [`GET /v1/tasks/expression/models`](#model-selection) (never below 4,599, `2F` within `request_max_bp`), and send `tss_index = F`. In 0-based genomic coordinates that is `[tss − F, tss + F)` on the plus strand, and `(tss − F, tss + F]` reverse-complemented on the minus strand; see [Limits](reference/limits.md#expression-sequence-length-and-tss_index). Shorter input is a hard `422`, never padded or truncated. Lengths are counted after whitespace is stripped, so a line-wrapped FASTA body pastes verbatim (the `>` header line does not). - **`tss_index`** (integer, 0-based): offset of the TSS **into the whitespace-stripped `sequence`**. Required unless `sequence` is exactly 9,198 bp, where it defaults to `4599`. Must satisfy `4599 <= tss_index <= len(sequence) - 4599`. The server cuts what the model reads around it; how much depends on the model. It does **not** discover the TSS for you and does **not** reverse-complement. There is no `tes_index`. See [Limits](reference/limits.md#expression-sequence-length-and-tss_index) for the full rules, the silent-wrong-window gotcha, and the `422` for windows with too little real (non-`N`) sequence. - **`model`** (optional, top-level): any id from the model list; omitted, the listing's `default_model`. Pass it explicitly when comparing calls, so they never straddle a change of default. - **`options.description`** (required): free-text experimental context (cell type, assay, conditions). `options` is a closed object — `description` is its only accepted key, and it must be non-empty. Omitting it returns `422 validation_failed`. This string is **model input, not a label.** It conditions the prediction, and the exact wording changes the number: on one fixture, same sequence and same model (`g0-expression`, measured in August 2026, when it was the default), `"K562"` scored 1.38 and `"K562 cells"` scored 0.70 log(TPM+1) — roughly a 2x spread in TPM from phrasing alone. There is no enum and no canonical vocabulary. Pick one form and keep it fixed: when you compare predictions across sequences, runs, or releases, a changed `description` invalidates the comparison as surely as a changed sequence. Output: `data.prediction` = `{expression, expression_log_tpm, expression_tpm, unit}` — `expression`/`expression_log_tpm` are log(TPM+1); `expression_tpm` is the back-transformed linear value. JSON only (no text-track formats; `?format=` anything but json is `415 unsupported_format`). Windowing provenance is echoed back: `meta.task_specific_counts` carries `tss_index` and `scored_window` (`data.input` echoes `tss_index` only) — `scored_window` is the half-open `[start, end]` of your submitted sequence that the server cut for the model. For a model whose `bio_spec.trained_window_bp` is null it is the span actually read, and its width, `scored_window[1] - scored_window[0]`, shows how much of your flank was used; `g0-expression` always gets the same 9,198 bp slice and reads its central part. The width depends on the model; log it, do not assert it. The length you **submitted** (whitespace-stripped) is `meta.sequence_length`. (`data.input.sequence_length` was removed at contract revision 13.) #### API reference **Python client** ```python # client = Client(api_key=os.environ["GI_API_KEY"]), as in Promoter listing = client.list_models("expression") model = listing["default_model"] # resolve once per run, pass on every call # F = the largest recommended flank, never below 4,599, with 2F within the cap flank = max([4599] + [m["bio_spec"].get("recommended_flank_bp") or 0 for m in listing["models"]]) flank = min(flank, min(m["bio_spec"]["request_max_bp"] for m in listing["models"]) // 2) r = client.predict( "expression", sequence=locus, # 2F bp, gene-sense strand, TSS at offset F model=model, tss_index=flank, # 0-based, into the whitespace-stripped sequence options={"description": "K562 cells"}, ) print(r["data"]["prediction"]["expression"]) # log(TPM+1) print(r["meta"]["task_specific_counts"]["scored_window"]) # log it; width depends on the model ``` **MCP** Ask the [MCP server](mcp.md): *"Predict HBB expression in K562 cells."* #### Applications Use it to estimate the transcriptional output of a locus or a designed promoter under a stated cellular context, and as the objective in an expression-maximising or expression-matching design loop. #### Usage tips - **9,198 bp is a floor, not a target.** Submit at least 9,198 bp with the TSS at least 4,599 bp from each end, and more where you can. Follow `default_model` (or the model your user named) and never hard-code a window, flank or model id: take `F` as the largest `bio_spec.recommended_flank_bp` in the [model list](#model-selection) and send `2F` bp with the TSS at offset `F` and `tss_index = F`. On the minus strand fetch `(tss − F, tss + F]` (0-based) and reverse-complement it; reverse-complementing `[tss − F, tss + F)` leaves the TSS one base off. Under-length input is rejected, never padded, and so is a window dominated by `N` or repeats. - **`description` is conditioning text, not a label.** It is fed to the model, so rewording it changes the prediction. Hold it fixed across runs you intend to compare. - **An in-range but wrong `tss_index` still scores** — a different window, with a confident `200`. Read the applied window back from `meta.task_specific_counts.scored_window` rather than assuming the request's. - **The sequence is never reverse-complemented.** Submit minus-strand genes in transcript orientation. ### Annotation Gene finding over long DNA: detects transcripts and returns their intervals. The `g0-annotation` model (multispecies) predicts transcript **boundaries**, transcript **type** (mRNA / lnc_RNA), and full internal **exon/intron/CDS structure**, and emits a browser-ready `GFF3` track. Submit the **plus-strand** genomic region; the model finds transcripts on both strands. This is the longest-running task, and the only predict operation with a hard sync cap: above **200,000 bp** a synchronous JSON request is refused with `413 sync_too_large`, `details` = `{sequence_length, threshold}` — resend the identical body with `Prefer: respond-async`. Below that, sync works at any accepted length, but prefer async above ~30,000 bp (see [Asynchronous jobs](rest-api.md#asynchronous-jobs)). The cap is on JSON delivery only: `?format=bed` and `?format=gff3` are served synchronously at any accepted length, so size those calls against the 300 s proxy timeout yourself. - `sequence`: the highest floor of the five non-expression tasks (bounds in the table above); the gene finder cannot work below its own window. - `model` (optional, top-level): `g0-annotation` — the only annotation model, selected by default. - `options.shift_coordinates: "UCSC"`: rebase output coordinates from a UCSC-style `sequence_name` (e.g. `chr8:127,680,000-127,800,000`). Note that the header goes in `sequence_name` (≤ 128 chars), not in the `sequence` — a `>` line inside the sequence fails the alphabet check. - `options.reverse_complement` (bool, default `true`): average each locus with its reverse complement, improving minus-strand recall. Set `false` for a faster single-pass run. `AnnotationOptions` accepts those two keys and nothing else. Output: transcript intervals, each carrying its own strand (`+`/`-`) plus `tss_position` and `polya_position`. Each transcript additionally carries `transcript_type`, `transcript_type_score`, and 0-based half-open `exons`/`introns`/`cds` arrays, and `data.formats.gff3` holds a full `GFF3` track (also via `Accept: text/x-gff3`). `BED` is also available — `?format=json|bed|gff3`. See [output formats](rest-api.md#output-formats). #### API reference **Python client** ```python # client = Client(api_key=os.environ["GI_API_KEY"]), as in Promoter # Prefer: respond-async, then poll GET /v1/tasks/jobs/{job_id} job_id = client.submit_async("annotation", sequence=region, options={"shift_coordinates": "UCSC"}, sequence_name="chr8:127,680,000-127,800,000") result = client.wait_for_job(job_id) transcripts = result["data"]["transcripts"] ``` **MCP** Ask the [MCP server](mcp.md): *"Find the genes in chr8:127,680,000-127,800,000."* #### Applications Use it to annotate assembled contigs or synthetic constructs where no reference annotation exists, and to supply TSS positions (`tss_position`) to [expression](#expression) when they are not known in advance. #### Usage tips - **The floor is 1,000 bp**, the highest of the five non-expression tasks. - **One submission finds both strands.** Submit the plus-strand region; each transcript carries its own `strand`, relative to the sequence as submitted. - **This is the slowest task, and the only predict operation with a sync cap.** Above 200,000 bp a synchronous JSON request is `413 sync_too_large`; send `Prefer: respond-async` and poll. Below the cap async is a latency preference, not a requirement. - **`reverse_complement: false` is a faster single pass**, at some cost in minus-strand recall. ### Find genes and predict expression `POST /v1/workflows/find-genes-and-predict-expression` — a composite that chains the two tasks server-side: annotate the region, cut a window around each found gene's TSS, and score each gene with the API's default expression model (or the one named in `options.expression_model`), using as much flank around each TSS as the submitted region holds, so longer regions give better predictions. One round trip, no intermediate results shuttled back to your client, and no `tss_index` to compute. It is a published operation on the same bearer key as everything else; nothing needs enabling. - `sequence`: **1,000–500,000 bp** — annotation's floor, since the workflow cannot find a gene in less sequence than the gene finder looks at. - `options` (**required**), and `options.description` (**required** — the expression stage is conditioned on it; missing or empty is `422 validation_failed`, "options.description is required (cell type / assay context)"). Also accepts `annotation_model`, `expression_model`, `shift_coordinates`. Closed, like every other `options`. - Above **50,000 bp** synchronous delivery is refused with `413 sync_too_large`, `details` = `{sequence_length, threshold}`. Resend the identical body with `Prefer: respond-async` and poll `GET /v1/tasks/jobs/{job_id}` (see [Asynchronous jobs](rest-api.md#asynchronous-jobs)). This is the lower of the contract's two sync caps; [annotation](#annotation) carries the other, at 200,000 bp. Output: `data.expression_predictions[]`, one entry per gene found; a gene the workflow could not score carries a `skip_reason`. `meta.task_specific_counts` = `{genes_found, genes_predicted, genes_skipped}`, with `genes_predicted + genes_skipped == genes_found`. Unlike the direct expression endpoint, the workflow pads a TSS window with `N` up to half its width rather than dropping a gene near the edge of your region. JSON only. #### API reference **Python client** ```python # client = Client(api_key=os.environ["GI_API_KEY"]), as in Promoter accepted = client.find_genes_and_predict_expression(region, description="K562 cells", async_=True) result = client.wait_for_job(accepted["data"]["job_id"]) for gene in result["data"]["expression_predictions"]: print(gene.get("skip_reason") or gene["expression"]) ``` **MCP** Ask the [MCP server](mcp.md): *"Find the genes in chr8:127,680,000-127,800,000 and predict each one's expression in K562."* #### Applications Use it when the TSS positions are not known in advance: it annotates and scores a whole locus in one call, rather than you chaining [annotation](#annotation) into [expression](#expression) yourself. #### Usage tips - **The floor is 1,000 bp** (annotation's), and the ceiling is this endpoint's own 500,000 bp, which is not the expression model's window. - **Above 50,000 bp, go async.** A synchronous request is `413 sync_too_large`; resend the identical body with `Prefer: respond-async`. This is the lower of the contract's two sync caps. - **A gene near the edge of your region is still scored:** its window is padded with `N` rather than the gene dropped. A gene the workflow could not score carries `skip_reason`, and `genes_predicted + genes_skipped == genes_found`. - **JSON only.** Unlike the predict operations it has no `?format=` parameter. ### Genomic variant interpretation `POST /v1/workflows/genomic-variant-interpretation` — the one operation that does not take a DNA `sequence`. You give it the `s3://` URI of a VCF in your own object storage; it scores the variants that fall near a transcription start site and writes an **annotated copy beside it, named after it**. The JSON you get is a receipt: where the annotated file is, and how the run went. You never parse a VCF to drive the workflow, and the annotation format inside it can change without breaking anything you built. :::caution[Under development] This workflow is not finished. The contract below is real and will not change silently, but the per-tissue values in an annotated file are **not final and are not yet to be read as results**. A run is model output when, and only when, the response carries `meta.model` and the annotated VCF carries a `##GEXModel` header line — until both appear, treat the numbers as format rather than findings. It also needs a grant on your bucket before it will run for you, so [talk to us](resources/support.md) rather than integrating against it unannounced. ::: **Asynchronous only.** A whole-exome case runs for hours, well past any proxy timeout, so `Prefer: respond-async` is **required**; a request without it is `400 bad_request`. There is no callback — submit, then poll `GET /v1/tasks/jobs/{job_id}` (see [Asynchronous jobs](rest-api.md#asynchronous-jobs)). ```http POST /v1/workflows/genomic-variant-interpretation Authorization: Bearer gi_... Prefer: respond-async Content-Type: application/json ``` ```json { "input": { "type": "s3_object", "uri": "s3://your-bucket/cases/CASE-00123/sample.vcf.gz" }, "client_ref": "CASE-00123", "options": { "genome_build": "GRCh37" } } ``` **You name the VCF itself**, not a folder — nothing else in the prefix is listed or read, so a manifest, an index, or a second VCF beside it are all irrelevant, and the format of your own case metadata stays yours. Everything the analysis needs arrives as typed `options`. The key must end in `.vcf`, `.vcf.gz` or `.vcf.bgz`; uncompressed, `bgzip`- and plain `gzip`-compressed files are all accepted and you never need to recompress anything. **The annotated copy is written beside the input, named after it and after the job**: `sample.vcf.gz` becomes `sample.annotated..vcf.gz` in the same prefix, where `` is the first eight characters of the `job_id`. **Read the exact name from `data.output.uri` rather than constructing it.** The job is in the name because the input alone does not identify a run: analysing one VCF against two different panels produces two different results, and under an input-only name the second would overwrite the first while the first receipt — retained for 24 hours — still pointed at it. Two VCFs in one folder are likewise two independent cases. A resubmission resolves to the same job and so rewrites the same object rather than accumulating copies. Grant the service `s3:GetObject` on the object and `s3:PutObject` on its prefix. **No `s3:ListBucket` is needed**, because nothing searches. - `input.type`: `s3_object` today. The field is a discriminated union so another kind of input — an inline VCF, a presigned URL — can be added without breaking this one. - `options.genome_build` (**required**): `GRCh37`. A VCF header declares its assembly only sometimes, and guessing misplaces every window. - `options.window`: bp from a start site within which a variant is scored. Default `5000`, range 1–100,000. - `options.tissues`: cell-type contexts, one scoring run each. Default `["heart", "liver", "brain"]`, 1–16 entries. The expression model is conditioned on these strings and the exact wording moves the result. - `options.genes`: restrict scoring to a panel. Accepts HGNC symbols (`BRCA1`) or Ensembl gene ids with or without a version (`ENSG00000141510`, `ENSG00000141510.17`); symbols are case-insensitive, up to 1,000 entries. Omit it to score every gene near a variant. - `client_ref`: an opaque string of yours, ≤128 characters, echoed back. It carries your case identity so this API never has to model a case. **The request is validated before the job is accepted.** All of these are `400 bad_request` on the POST, so a typo costs a second rather than a poll cycle through a job that fails minutes later: a URI that is not `s3://bucket/key`; one naming a prefix rather than an object; a key not ending `.vcf`, `.vcf.gz` or `.vcf.bgz`; an object this service cannot read (check the `s3:GetObject` grant); an empty VCF, or one over 2 GiB; a `genes` identifier matching no gene; a `genome_build` with no published start-site catalogue. Anything that goes wrong after acceptance is a job failure visible on the poll — including a file that turns out to be unreadable, or to already carry `GEX_*` fields, neither of which can be known until it is opened. **A panel is the difference between a long case and a short one.** Unrestricted, a whole exome scores tens of thousands of allele-to-start-site pairs; restricted to a handful of genes it scores a handful. Records near a start site that is *not* in your panel are still written to the output, flagged `NO_REQUESTED_GENE_IN_WINDOW` — deliberately distinct from `OUTSIDE_TSS_WINDOW`, because "you did not ask about this gene" and "there was no start site here" are different answers, and a narrow panel should not read as a coverage gap. The resolved panel is echoed in `meta.options_applied.genes` and recorded in the output VCF's `##GEXRequestedGenes` header, so a restricted run cannot later be mistaken for a whole-genome one. An identifier matching no MANE Select gene is a `400` naming every unresolved one — a panel silently missing a gene would return a result that looks complete and is not. **Submitting the same case twice gives you the same job.** The `job_id` is derived from your key, `input.uri`, the input object's ETag, `client_ref` and `options`, so a retry after an ambiguous failure — or a restarted integration — resolves to the run you already have rather than starting a second hours-long pass over the same object. There is no idempotency header to send. Two consequences worth knowing: a **failed** job re-runs on resubmission, and to deliberately re-run a case that **succeeded**, change `client_ref`. Replacing the VCF under an unchanged path also yields a new job, since its ETag is part of the derivation. Accepted submissions return `202` with `data = {job_id, status: "accepted", links}`, plus `X-Job-Id` and `Content-Location`. On completion the poll returns: ```json { "data": { "task": "genomic_variant_interpretation", "client_ref": "CASE-00123", "status": "ok", "output": { "type": "s3_object", "uri": "s3://your-bucket/cases/CASE-00123/sample.annotated.3eaecf69.vcf.gz" }, "counts": { "variants_in": 73771, "annotated": 12721, "not_run": 61050, "not_run_reasons": { "OUTSIDE_TSS_WINDOW": 61050 }, "annotated_alleles": 12725, "associations": 14698, "skipped_alleles": 10 } }, "meta": { "task": "genomic_variant_interpretation", "genome_build": "GRCh37", "job_id": "…", "request_id": "…", "input": { "type": "s3_object", "uri": "s3://your-bucket/cases/CASE-00123/sample.vcf.gz" }, "gene_annotation": { "build": "v50lift37", "md5": "bed31c2cead98e9e1989ef7943fb3206", "transcripts": "MANE Select", "start_sites": 19153 }, "options_applied": { "window": 5000, "tissues": ["heart", "liver", "brain"], "genes": null } } } ``` **Every input record reaches the output**, scored or not, so `annotated + not_run == variants_in` and you can diff input against output record for record. A record that could not be scored is flagged in place with `GEX_NOT_RUN` and a reason in `GEX_NOT_RUN_REASON` — `OUTSIDE_TSS_WINDOW`, `NO_TSS_ON_CONTIG`, `NO_SUPPORTED_ALT`, or `NO_REQUESTED_GENE_IN_WINDOW` when you sent a panel — rather than dropped. The same four appear in `counts.not_run_reasons`, which sums to `not_run`. A record with some usable and some unusable ALT alleles — a symbolic allele beside a plain one, say — lists the unusable ones in `GEX_SKIPPED_ALT` and is still annotated for the rest, so a record can carry both keys. Scored records carry `GEX_ANN`, one VEP-style entry per supported ALT allele and nearby transcript: `Allele|Gene|Gene_ID|Transcript_ID|TSS|Strand|TSS_distance|` then one log2 fold-change field per requested tissue. Distances are strand-aware, negative upstream, and the output header records the convention along with the window and the GENCODE release the start sites came from — and the model, once one is named. `meta.input` echoes the object you named, so a stored receipt names both what was read and what was written. `counts.associations` is the **unit of scoring work** — allele-to-start-site pairs, not records — so it is the number to reason about when sizing a case, and `meta.gene_annotation` is the machine-readable form of that provenance. **`meta.model` tells you whether these are model output.** While this workflow is under development the field is absent, as is the annotated VCF's `##GEXModel` header line — the run is not attributed to a model that did not produce the values. Both appear, naming the model, once it is. Everything around them is real today: your file is read, every record is matched against GENCODE v50lift37 MANE Select start sites, every record is written back, and the counts are computed from it. Submitting a VCF that already carries `GEX_*` fields — an annotated copy from a previous run, for instance — is a `400`: submit the original. Results are retained for **24 hours** and then return `410`. The annotated file in your own bucket is not on that clock. A job does not survive a deployment of this service: in-flight work is lost and the poll reports `503` with a message to resubmit, so retries belong to you. This workflow is REST-only — it is not exposed as an [MCP](mcp.md) tool. #### API reference **Python client** The kit client does not wrap this workflow. Post it with `requests` and poll with the client: ```python import os, requests from gi_client import Client key = os.environ["GI_API_KEY"] r = requests.post( "https://api.genomicintelligence.ai/v1/workflows/genomic-variant-interpretation", headers={"Authorization": f"Bearer {key}", "Prefer": "respond-async"}, json={ "input": {"type": "s3_object", "uri": "s3://your-bucket/cases/CASE-00123/sample.vcf.gz"}, "client_ref": "CASE-00123", "options": {"genome_build": "GRCh37"}, }, timeout=60, ) receipt = Client(api_key=key).wait_for_job(r.json()["data"]["job_id"], max_wait=6 * 3600) print(receipt["data"]["output"]["uri"]) ``` **MCP** This workflow is REST-only; it is not exposed as an [MCP](mcp.md) tool. #### Applications Use it to score the variants in a case's VCF that fall near a transcription start site, across the tissues you name, and get the annotated VCF back in your own bucket beside the input, where the rest of your pipeline already reads. #### Usage tips - **Async only.** `Prefer: respond-async` is required; without it the request is `400 bad_request`. - **Send a gene panel when you have one.** Restricted to a handful of genes a case scores a handful of allele-to-start-site pairs instead of tens of thousands. - **The same case twice is the same job.** To deliberately re-run a case that succeeded, change `client_ref`. - **`tissues` are conditioning text.** The exact wording moves the prediction, as with expression's `description`. - **Not results yet.** Until the response carries `meta.model` and the VCF a `##GEXModel` header, treat the values as format rather than findings. --- Next: [Limits](reference/limits.md) for caps and latency, or the [REST API guide](rest-api.md) for the call walkthrough.