Heimdall
API v1 http://localhost:8000

Client guide

Your SDK. Your accounts.

Heimdall speaks the OpenAI, Anthropic and Google Gemini APIs. Keep your SDK and your code. Change the base URL and the key, and your calls run on the Claude, ChatGPT and Google accounts you connected in the portal. Model ids are the real vendor ids, so going to production later is the same change in reverse.

Base URL

Examples use http://localhost:8000, the API address on a default install (the installer prints it). Use your own address if you changed it. Keys start with cgw_; create them in the portal under API keys. Keep keys on your server, never in a browser or mobile app.


Connect your SDK

OpenAI SDK (base URL ends in /v1):

python · openai
from openai import OpenAI

client = OpenAI(base_url="http://localhost:8000/v1", api_key="cgw_...")
r = client.chat.completions.create(model="gpt-5.6-luna", messages=[{"role": "user", "content": "Say hi"}])
print(r.choices[0].message.content)

Anthropic SDK (base URL without /v1):

python · anthropic
from anthropic import Anthropic

client = Anthropic(base_url="http://localhost:8000", api_key="cgw_...")
r = client.messages.create(model="claude-sonnet-5-5", max_tokens=300, messages=[{"role": "user", "content": "Say hi"}])
print(r.content[0].text)

Google GenAI SDK:

python · google-genai
from google import genai

client = genai.Client(api_key="cgw_...", http_options={"base_url": "http://localhost:8000"})
r = client.models.generate_content(model="gemini-3-flash", contents="Say hi")
print(r.text)

JavaScript is the same change: new OpenAI({ baseURL: "http://localhost:8000/v1", apiKey }) and new Anthropic({ baseURL: "http://localhost:8000", apiKey }). LangChain: ChatOpenAI(base_url=".../v1") and ChatAnthropic(base_url="..."). Vercel AI SDK: createOpenAI and createAnthropic both take baseURL: ".../v1".

Any model works through any of the three SDKs: claude-sonnet-5-5 through the OpenAI SDK, gemini-3-flash through the Anthropic SDK, and so on. Send model: "auto" to let Heimdall pick. Heimdall accepts the key the way each SDK sends it: Authorization: Bearer, X-API-Key (also the Anthropic SDK's x-api-key), x-goog-api-key or ?key=.

Production

Point base_url back at the vendor and use your paid API key. Model ids stay the same. Only auto and models from another vendor (for example a Claude model through the OpenAI SDK) need changing.


What works

A test script runs every client below against all three providers for plain, streaming, tool and JSON-schema calls, and writes the result to docs/product/parity.md. A pass also requires that the provider under test answered (no silent failover). The tables below are copied from that file; if they differ, the file wins.

Generated by tests/sdk/run.py on 2026-10-14 17:30 UTC (run c3cecd0a). Models: claude haiku, codex gpt-5.6-luna, agy gemini-3-flash.

Clientclaude plainclaude streamclaude toolsclaude jsoncodex plaincodex streamcodex toolscodex jsonagy plainagy streamagy toolsagy json
openai-py✅✅✅✅✅✅✅✅✅✅✅✅
anthropic-py✅✅✅✅✅✅✅✅✅✅✅✅
google-genai-py✅✅✅✅✅✅✅✅✅✅✅✅
langchain-openai✅✅✅✅✅✅✅✅✅✅✅✅
langchain-anthropic✅✅✅✅✅✅✅✅✅✅✅✅
openai-js✅✅✅✅✅✅✅✅✅✅✅✅
anthropic-js✅✅✅✅✅✅✅✅✅✅✅✅
vercel-ai-openai✅✅✅✅✅✅✅✅✅✅✅✅
vercel-ai-anthropic✅✅✅✅✅✅✅✅ retry✅✅✅✅
SurfaceFeatureStatusNote
OpenAI chatn > 1unsupportedHTTP 400
OpenAI chatlogprobsunsupportedaccepted, not returned
OpenAI chatjson_object modebest-effortprompt-guided; returned valid JSON
OpenAI responsesprevious_response_idunsupportedstateless: send the whole conversation
OpenAI responsesbuilt-in tools (web_search…)unsupportedHTTP 400
OpenAI embeddingsdimensions other than 1024unsupportedself-hosted multilingual-e5-large, 1024-d; ≤64 inputs per call
Anthropic/v1/messages/count_tokensunsupportedHTTP 404
Anthropicserver tools (web_search…)unsupportedHTTP 400
GeminicountTokensunsupportedHTTP 404
APIEndpoints
OpenAIPOST /v1/chat/completions · POST /v1/responses · GET /v1/models · POST /v1/embeddings · POST /v1/images/generations · POST /v1/images/edits
AnthropicPOST /v1/messages · GET /v1/models
GeminiPOST /v1beta/models/{model}:generateContent · :streamGenerateContent?alt=sse · GET /v1beta/models

Unknown endpoints (batches, files, moderations, ...) return a 404 in that vendor's error shape.

Images. /v1/images/generations and /v1/images/edits make images on your accounts. The default is Google's gemini-3.1-flash-image (fast, JPEG). Send quality: "high" or a gpt-image-* model for ChatGPT images (PNG, about 30 s). Edits take one or more reference images, no masks. Only b64_json output. A free Google account makes about 13 images per 5 hours; when every account is at its limit you get 429 image_quota_exhausted.

Embeddings

/v1/embeddings needs the optional embeddings add-on (see INSTALL.md). Whatever model you name, you get the self-hosted multilingual-e5-large: 1024 numbers per vector, not OpenAI's 1536. Build a new 1024-dimension index and re-embed your documents. dimensions must be 1024 or left out. At most 64 inputs per call (in LangChain set chunk_size to 64 or less). Send "input_type": "query" (in extra_body) for search queries; the default is "passage".


Models

GET /v1/models lists the models your connected accounts can serve now, in the asking SDK's shape. Heimdall re-checks each vendor's model list once a day and tests new models with one tiny call before listing them. Today's list on this install (last checked 2026-11-27 21:00 UTC):

ProviderEffort fieldModels
claudeyesclaude-haiku-4-5 · claude-haiku-4-5-20251001 · claude-haiku-5-5 · claude-opus-4-5-20251101 · claude-opus-4-6 · claude-opus-4-7 · claude-opus-4-8 · claude-opus-5 · claude-opus-5-5 · claude-sonnet-4-6 · claude-sonnet-5 · claude-sonnet-5-5 · haiku · opus · sonnet
codexyesgpt-5.6-luna · gpt-5.6-sol · gpt-5.6-terra · gpt-6-astra · gpt-6-luna · gpt-6-sol · gpt-6.1-sol · gpt-6.1-terra · gpt-6.2-astra · gpt-6.2-sol
agybaked inclaude-opus-4-6-thinking · claude-sonnet-4-6 · gemini-2.5-flash · gemini-2.5-flash-lite · gemini-2.5-flash-thinking · gemini-3-flash · gemini-3.1-flash-image · gemini-3.1-flash-lite · gemini-3.5-flash-lite · gemini-3.8-flash-high · gemini-3.8-flash-low · gemini-3.8-flash-medium · gemini-3.8-flash-tiered · gemini-4-hydrogen-sonar · gpt-oss-120b-medium
  • claude is your Claude account, codex your ChatGPT account, agy your Google (Antigravity) account.
  • auto: Heimdall sizes the request and picks a model. Fine for trying things; pin a real id before production.
  • Claude aliases sonnet, opus, haiku resolve to the latest model of each family.
  • Google models have no effort setting; the effort is in the name (gemini-3.8-flash-low / -medium / -high).
  • A model no longer in the list returns 404 model_not_found.

Each project has a Caller picks the model switch (portal, Projects). It is on for projects you create on your own install. Turn it off and every call routes automatically: a Claude model you name is ignored, and naming a ChatGPT or Google model returns 403 provider_not_permitted.


What the response tells you

Non-streaming answers carry an extra heimdall field: provider, model, api_equivalent_usd (what the call would have cost on the vendor's paid API) and job_id. Every answer has a request-id and x-request-id header; quote it when you report a problem.

Failover is never silent. If an account or provider failed or was at its limit and another one answered, the response says so:

  • header X-Heimdall-Failover: claude=invalid_output, codex=codex_cooling (every surface, streaming too);
  • and, where the body has a heimdall field, heimdall.failover = [{from, account, code, reason, resets_at, transport}] (account is set when one of several accounts of the same provider was skipped).

heimdall.provider and heimdall.model name what actually answered.

Heimdall extras in the request

  • transport (body field; extra_body in the SDKs): how the call reaches the vendor. See How calls run.
  • X-User-ID header: a stable id for one of your own end users. Usage is broken down per user; leave it out and the call counts for the project as a whole.

Caching

SDK calls run fresh, as they would against the vendor. To reuse an identical answer, send Cache-Control: max-age=<seconds> (capped at 30 days). Add no-cache to run fresh and store the new answer; no-store skips the cache.


Advanced API

Quickstart: /v1/run

The SDK endpoints above are the main way in. The endpoints below are Heimdall's own API: a multipart /v1/run with files, JSON-schema output on any model, response caching on by default, async jobs and webhooks. Requests are multipart/form-data (use -F in curl), so files and text use one code path.

curl
curl http://localhost:8000/v1/run \
  -H "X-API-Key: $HEIMDALL_KEY" \
  -F 'prompt=Summarize the theory of relativity in one sentence.'

output is the answer. meta says which provider, model and effort produced it (effort is null for Google models), how it was routed, and the token counts:

200 · json
{
  "status": "completed",
  "output": "Relativity holds that space and time form a single fabric…",
  "meta": {
    "provider": "codex",
    "model": "gpt-5.6-terra",
    "effort": "medium",
    "routed_by": "classifier",
    "input_tokens": 28,
    "output_tokens": 41
  }
}

Routing & failover

With provider=auto (the default), a small classifier model rates the request trivial, standard or hard and routes it to a model that fits. If that account is at its limit, the call moves to the next account, then the next provider, in the order set in the portal. The answer's meta and the failover header say where it went.

Effort

The effort field (low, medium, high; default medium) sets how hard reasoning models think. It applies to Claude and ChatGPT models; Google models ignore it.

trivial

Fast

Classification, extraction, short rewrites: mini/flash-class models.

standard

Balanced

Most everyday generation and reasoning.

hard

Deep

Long context, multi-step reasoning: the strongest tier.


How calls run

Heimdall reaches each provider in one of two ways, with the same signed-in accounts:

  • Direct: Heimdall calls the vendor's API itself. Fast; supports streaming, tool calls and images.
  • CLI: Heimdall runs the vendor's command-line tool (claude, codex). Slower and returns the final text only.

By default calls run hybrid: direct first, and the CLI only if the vendor changed its API in a way Heimdall doesn't handle yet. Choose per call with transport:

transportWhat happens
hybrid (default)Direct, falling back to the CLI when the direct call can't be made.
directDirect only. A vendor change shows up as an error instead of a slower answer.
cliEvery call runs through the vendor's CLI. A request with tools is refused on cli.
passthroughSends the call to the vendor's paid API with your own API key, billed by the vendor: a last check before production. Needs GATEWAY_CLAUDE_API_KEY or GATEWAY_CODEX_API_KEY set on the gateway; otherwise 400 passthrough_not_configured. Claude and OpenAI models only.
choose the path
# /v1/run and /v1/run-async: a form field
curl http://localhost:8000/v1/run -H "X-API-Key: $HEIMDALL_KEY" \
  -F 'prompt=Summarize this.' -F 'transport=cli'

# the SDKs: a body field, via extra_body
client.chat.completions.create(model="auto", messages=[...], extra_body={"transport": "cli"})

On /v1/run, meta.transport says which path ran (direct or cli) and meta.transport_fallback explains a hybrid fallback. An unknown value returns invalid_transport (422 on /v1/run, 400 on the SDK endpoints).


Structured output

Pass a JSON Schema in schema and output comes back as the parsed object. Provider quirks ($ref inlining, array-root envelopes, prose-wrapped JSON) are handled for you.

curl
curl http://localhost:8000/v1/run \
  -H "X-API-Key: $HEIMDALL_KEY" \
  -F 'prompt=Extract the person and their role: "Ada Lovelace, mathematician."' \
  -F 'schema={"type":"object","properties":{"name":{"type":"string"},"role":{"type":"string"}},"required":["name","role"]}'
200 · json
{ "status": "completed",
  "output": { "name": "Ada Lovelace", "role": "mathematician" } }
Note

If the schema's root is an array, the result comes back as {"value": [ … ]}: providers reject bare-array roots.


Model selection on /v1/run

You sendProject without Caller picks the modelProject with it
provider=auto (default)Classifier and failover choose.
provider=codex / agy + model403 provider_not_permittedRuns on that model
provider=claude + a modelFalls back to auto-routingRuns on that model
provider=codex / agy without model422 invalid_model

Run a prompt

post/v1/runmultipart/form-data

Synchronous by default; mode=async queues the job and you poll it.

Request fields

FieldTypeNotes
promptstringone ofThe instruction. Send exactly one of prompt or pipeline_slug.
schemastring (JSON)optionalJSON Schema for structured output. Invalid JSON → 422 invalid_schema.
providerstringoptionalauto (default), claude, codex (ChatGPT), agy (Google).
modelstringoptionalPin a model; see Models.
effortstringoptionallow · medium (default) · high.
transportstringoptionalhybrid (default) · direct · cli · passthrough. See How calls run.
filesfile[]optionalAttachments, up to 20 MiB in total; more → 413 too_large. Images (png/jpg/jpeg/gif/webp) are seen by all three providers.
modestringoptionalsync (default) or async.
cacheablebooloptionalIdentical requests without files are cached by default. Send false to force a fresh run.
cache_ttl_secondsintoptionalCache lifetime, default 24 h, capped at 30 days. Ignored with a schema: those cache for 30 days.

Responses

  • 200 sync: { "status": "completed", "output", "meta" }
  • 202 async: { "job_id", "status": "queued" }; poll GET /v1/jobs/{job_id}

A "warning": "approaching token budget" field appears when the project nears its budget; the request still runs.


Run with a callback

post/v1/run-asyncmultipart/form-data

For callers behind a short HTTP timeout (serverless functions). Returns 202 at once and POSTs the result to your callback_url when the job ends, on success and on failure.

Request fields

FieldTypeNotes
promptstringrequiredEmpty → 422 invalid_request.
callback_urlstringoptionalWhere the result is POSTed. Leave it out and no callback fires.
job_idstringoptionalYour own reference, echoed in the response and the callback.
tokenstringoptionalEchoed in the callback body; check it to confirm the callback is genuine.
provider · model · effort · schema · transport—optionalAs on /v1/run.
curl
curl http://localhost:8000/v1/run-async \
  -H "X-API-Key: $HEIMDALL_KEY" \
  -F 'prompt=Draft a product changelog from these commits…' \
  -F 'job_id=changelog-4821' \
  -F 'token=whsec_9c2f…' \
  -F 'callback_url=https://your-app.com/hooks/heimdall'
202 · accepted
{ "accepted": true, "job_id": "changelog-4821", "gateway_job_id": "a1b2c3d4" }

The callback we send you

Up to 3 attempts while your endpoint answers non-2xx:

POST → your callback_url
{
  "job_id": "changelog-4821",   // your job_id, echoed
  "token":  "whsec_9c2f…",     // your token, echoed: check it
  "status": "done",            // "done" or "failed"
  "output": "…",               // null on failure
  "meta": { "provider": "claude", "model": "sonnet", "effort": "medium", "routed_by": "classifier" },
  "error": null              // the message when status is "failed"
}
Verify

Check the echoed token before you trust a callback. Return any 2xx to acknowledge.


Embeddings

post/v1/embedapplication/json

Needs the embeddings add-on. 1024-dimension vectors from multilingual-e5-large, computed on your machine. Use type: "query" for search queries and type: "passage" (default) for documents. Vectors are not unit-normalized: compare them with cosine similarity.

curl
curl http://localhost:8000/v1/embed \
  -H "X-API-Key: $HEIMDALL_KEY" \
  -H "Content-Type: application/json" \
  -d '{"texts": ["first document", "second document"], "type": "passage"}'
200 · json
{ "model": "intfloat/multilingual-e5-large", "dim": 1024,
  "vectors": [ [0.013, -0.047, …], [0.008, 0.052, …] ] }

texts takes a string or an array, at most 8 per request (more → 413 batch_too_large).

It runs on the CPU: about 1.1 s per ~350-token passage, 0.1–0.2 s for a short query. Texts are cut at 512 tokens. Requests run one at a time. Set your client timeout to at least 60 s (the gateway's own limit). For a large document, send batches of 8 one after another. A timeout or a stopped add-on returns 502 embed_unavailable; retry with backoff.


Jobs

Async runs (and mode=async) make a job you can poll, list or cancel.

get/v1/jobs/{job_id}

Status, and once completed, output and meta. A failed job carries an error.

200 · json
{
  "job_id": "a1b2c3d4",
  "status": "completed",       // queued · running · completed · failed
  "created_at": "2026-08-09T04:12:07Z",
  "provider": "codex",
  "requested_model": null,
  "routed_model": "gpt-5.6-terra",
  "routed_by": "classifier",   // caller · classifier · pipeline · default
  "output": "…", "meta": { … }
}
post/v1/jobs/{job_id}/cancel

Cancels a running job. Safe to repeat; a finished job returns cancelled: false with a reason.

get/v1/jobs

Your recent jobs as { job_id, status, created_at }. Filter with ?status= and ?user_id=.


Usage & health

get/v1/usage

The project's last 30 days: request counts and token totals by provider.

get/healthno key

200 when the gateway is healthy, 503 otherwise. The body has providers (per provider enabled / ok), accounts (sign-in state per Claude and ChatGPT account) and embed (the embeddings add-on).

embed.ok is false when the add-on is off, loading, or slow (p95 over 3 s per text, last ping over 2 s, or a timeout in the last 10 minutes; embed.reason says which). It does not change the top-level ok.


Errors

Heimdall's own endpoints (/v1/run, /v1/run-async, /v1/embed, jobs) answer { "status": "failed", "error": { "code", "message" } }. The OpenAI, Anthropic and Gemini endpoints answer in that vendor's error shape, so your SDK raises its usual exception, with the same codes inside.

StatusCodeMeaning
401unauthorizedMissing or unknown key.
403provider_not_permittedNamed a ChatGPT or Google model in a project without Caller picks the model.
422invalid_model(/v1/run) Model missing for codex/agy, or not in the current list.
422invalid_schema · invalid_provider · invalid_effortA field failed validation.
422 / 400invalid_transportUnknown transport (422 on /v1/run, 400 on the SDK endpoints).
400passthrough_not_configuredtransport=passthrough without that vendor's API key on the gateway.
400invalid_request · unsupported_content(SDK endpoints) A field the endpoint doesn't support, e.g. n > 1, built-in/server tools, audio or document parts.
404model_not_found(SDK endpoints) The model isn't in the current list.
413too_large · batch_too_largeUpload over 20 MiB, or too many texts in one embeddings request.
429image_quota_exhaustedEvery image account is at its limit until its reset.
429budget_exceededThe project hit its budget.
429all_subscription_seats_busy · all_providers_coolingEvery account that could answer is busy or at its limit. Retry with backoff.
502{provider}_failedThe call failed on every account and provider it tried.
502embed_unavailableThe embeddings add-on is off, unreachable or timed out.
504*_timeoutThe vendor timed out.
Retrying

429 and 5xx can succeed on retry; use exponential backoff. 401, 403, 404, 413 and 422 won't; fix the request.


Model changes

  • 2026-10-15: Google's Gemini models are gemini-3.8-flash-low / -medium / -high. The older gemini-3.6-flash-* and gemini-3.1-pro-* ids were retired by Google.
  • 2026-10-14: the paid gemini provider is gone; provider=gemini returns 422 invalid_provider. Gemini models run on Google accounts (provider=agy).
  • ChatGPT's gpt-6 models are never picked by auto; name one to use it. By default auto uses gpt-5.6-luna, gpt-5.6-terra and gpt-5.6-sol for trivial, standard and hard work.