API documentation

Call Portal from curl, Python, Node.js or an OpenAI-compatible client. Set the base URL and your key, then choose a model from the list available to that key.

Quickstart

Create a key in the dashboard's API Keys tab and store it in PORTAL_API_KEY. First call GET /v1/models with that key:

curl https://api.portal.ai/v1/models \
  -H "Authorization: Bearer $PORTAL_API_KEY"

Copy an id from the response into PORTAL_MODEL, then make your first call. This also works for a key limited to private model ids; a public catalog id may not be enabled for your key.

export PORTAL_MODEL="MODEL_ID_FROM_YOUR_KEY_CATALOG"
curl https://api.portal.ai/v1/chat/completions \
  -H "Authorization: Bearer $PORTAL_API_KEY" \
  -H "Content-Type: application/json" \
  --data-binary @- <<JSON
  {
    "model": "$PORTAL_MODEL",
    "messages": [
      { "role": "user", "content": "Say hello from Portal." }
    ]
  }
JSON

The examples below reuse that selected model. See Choosing the model for context windows, effort and access.

Base URL

Point any OpenAI-compatible client at Portal's inference endpoint:

Base URL
https://api.portal.ai/v1

All inference routes live under /v1 - for example /v1/chat/completions and /v1/models.

The machine-readable description of this surface is https://api.portal.ai/openapi.json (OpenAPI 3.1): every route, header, query parameter and typed error.code, generated from the gateway's own routes. Point a client generator or a validator at it; the sections below stay the human reading.

There is no embeddings endpoint. POST /v1/embeddings answers 404, and GET /v1/models lists no embedding model.

Authentication

Authenticate every request with a bearer token in the Authorization header:

Authorization: Bearer sk-portal-...

Keys carry the sk-portal- prefix and are created in the dashboard's API Keys tab. The full secret is shown once at creation - store it somewhere safe. You can revoke a key anytime; revoked keys immediately return 401.

A key can carry its own spend caps, set in the dashboard's API Keys tab: Max budget (USD, optional) at creation, and Monthly limit (USD) and Lifetime cap (USD) under Spend limits. To rotate, create the new key, move traffic, then revoke the old one; a revoked key answers 401 at once.

A new key inherits the models enabled on your account. To enable another model, ask your own Portal bot. It passes the request to Portal's Operator, who enables the model on the account. Check GET /v1/models with the key you intend to use.

Never ship a secret key in client-side code or commit it to source control. Read it from an environment variable (for example PORTAL_API_KEY) on your server.

Choosing the model

GET /v1/models, authenticated with your key, is the list of models that key can call. Pass an exact returned id in the request's model field. Read context_window and effort from the same response.

The public Models catalog contains four Portal-branded routes:

  • portal/m2-25 - Portal M2-25 (200K context).
  • portal/m2-25-fast - Portal M2-25, priority tier (higher throughput, higher price).
  • portal/m3-55-xh-1m - Portal M3-55 XH, Extra-High reasoning with a 1M context window.
  • portal/m3-500k-fast - Portal M3 256K, frontier reasoning at standard speed. The model id is retained for compatibility.

Your key may instead have a different list, including private ids and variants with different context windows, reasoning effort or service speed. A restricted key can contain only those variants. Read the descriptors returned for your key and use only its listed ids; this does not expand the public catalog.

Level ids

An id is grok-4.7, optionally followed by a hyphen and a level (low, medium, high, or xhigh; extra-high is the same level as xhigh), and optionally followed by -fast. An id with -fast runs the same model on the priority lane at the fast price. An id without -fast runs at standard speed and price, except the bare id grok-4.7, which is medium reasoning on the fast lane and is billed at the fast price. The spellings grok-4.7-extra-high and grok-4.7-extra-high-fast name the xhigh level. A reasoning_effort field in the body does not change the level an id names. GET /v1/models lists a 256,000-token context window for each. Per million tokens as of 2026-11-22, cache writes are billed as input, the level does not change the price, and each call's charge is on its Usage row:

LaneInputCached inputOutput
Standard (an id without -fast, other than the bare id)$1.40$0.35$4.20
Fast (an id with -fast, and the bare id grok-4.7)$2.80$0.70$8.40

A new key inherits the account's enabled models. To add a model, ask your own Portal bot; Portal's Operator enables it on your account. Then check the list with your key. The public catalog remains Portal-branded; underlying routing and availability may change.

curl https://api.portal.ai/v1/models \
  -H "Authorization: Bearer $PORTAL_API_KEY"

Chat completions

POST https://api.portal.ai/v1/chat/completions

Send a list of messages and receive a completion. The request and response shapes match the OpenAI Chat Completions API.

cURL
curl https://api.portal.ai/v1/chat/completions \
  -H "Authorization: Bearer $PORTAL_API_KEY" \
  -H "Content-Type: application/json" \
  --data-binary @- <<JSON
  {
    "model": "$PORTAL_MODEL",
    "messages": [
      { "role": "system", "content": "You are a precise senior engineer." },
      { "role": "user", "content": "Write a haiku about portals." }
    ]
  }
JSON
Python - OpenAI SDK
import os
from openai import OpenAI

client = OpenAI(
    base_url="https://api.portal.ai/v1",
    api_key=os.environ["PORTAL_API_KEY"],
    timeout=3780.0,
)
model_id = os.environ["PORTAL_MODEL"]  # an id returned by GET /v1/models

resp = client.chat.completions.create(
    model=model_id,
    messages=[
        {"role": "user", "content": "Write a haiku about portals."},
    ],
)

print(resp.choices[0].message.content)
Node.js - OpenAI SDK
import OpenAI from "openai";

const client = new OpenAI({
  baseURL: "https://api.portal.ai/v1",
  apiKey: process.env.PORTAL_API_KEY, // sk-portal-...
  timeout: 3_780_000,
});

const resp = await client.chat.completions.create({
  model: process.env.PORTAL_MODEL, // an id returned by GET /v1/models
  messages: [
    { role: "user", content: "Write a haiku about portals." },
  ],
});

console.log(resp.choices[0].message.content);

Install the SDK with pip install openai or npm install openai.

Streaming

The clock that ends a long stream is your client's, not ours. The stock OpenAI-compatible client libraries (the openai packages for Python and Node) wait 600 seconds by default (their timeout): a request without stream: true that has not answered in ten minutes ends there. A total deadline in your own code (asyncio.wait_for, an HTTP client's total timeout, a workflow engine's request deadline) ends even a stream that is still delivering: on 2026-10-30 one grok-4.7-high-fast stream had delivered 14.8 MB when the caller closed it at 599.9 seconds; the server had not stopped. This API puts no total wall on a stream. When the model sends nothing, the proxy writes a keepalive comment after 15 seconds without a byte; the longest gap measured on these streams was 15.001 seconds (15.002 seconds on the medium control). A per-read timeout longer than that gap did not fire; one of 15 seconds or less can. If you hold the socket, set every client clock above 3720 seconds. If you would rather not hold it, create a background run and poll (Resume a stream).

A client that hands the openai package the global fetch gets undici's headersTimeout, which ends a silent request at 300 seconds unless an undici Agent with a longer headersTimeout is passed.

Set "stream": true to receive tokens as server-sent events as they're generated, instead of waiting for the full response.

Python
stream = client.chat.completions.create(
    model=model_id,
    messages=[{"role": "user", "content": "Stream a short poem."}],
    stream=True,
    stream_options={"include_usage": True},
)

for chunk in stream:
    if chunk.usage:
        print("\nUsage:", chunk.usage)
    if not chunk.choices:
        continue
    delta = chunk.choices[0].delta.content
    if delta:
        print(delta, end="", flush=True)
cURL
curl --no-buffer https://api.portal.ai/v1/chat/completions \
  -H "Authorization: Bearer $PORTAL_API_KEY" \
  -H "Content-Type: application/json" \
  --data-binary @- <<JSON
  {
    "model": "$PORTAL_MODEL",
    "stream": true,
    "stream_options": { "include_usage": true },
    "messages": [{ "role": "user", "content": "Stream a short poem." }]
  }
JSON

The stream ends with a final data: [DONE] event. Set stream_options.include_usage to true to request a usage chunk before it. That chunk can have an empty choices array, so check it before reading a delta. Without this option, usage is omitted. An interrupted stream may end before its final usage chunk arrives.

usage.prompt_tokens counts upstream SDK runtime context as well as your messages and supplied tool schemas. Disabling Portal web tools removes their schemas and web instructions, but upstream SDK context can still be metered on a raw call.

Resume a stream

On an account admitted to durable runs, POST /v1/responses with background: true starts a run that does not depend on your connection. Two shapes, both measured on 2026-11-02 with the stock openai client libraries (Python 2.44, Node 7.47):

  • Queued — background: true without stream: the reply is the queued response object at once (0.45 s measured), your socket is free, no reasoning reaches you. Poll GET /v1/responses/{id}/status (or the stock client's retrieve) and read the result when it is complete; that final GET is the one delivery charge. A run created this way cannot be streamed afterwards: GET …?stream=true answers 400 stream_not_enabled.
  • Streamed — background: true and stream: true: events with a sequence_number flow on the creating connection; if it drops, the run continues and GET /v1/responses/{id}?stream=true&starting_after=N resumes after the last event you processed. The run id is response.id on the first events and the X-Portal-Run-Id header.
Python · stock openai client (both shapes; tested 2026-11-02)
import time
from openai import OpenAI

client = OpenAI(api_key=PORTAL_API_KEY, base_url="https://api.portal.ai/v1", timeout=3900.0, max_retries=0)

# Queued: your socket is free; poll; the final retrieve returns the answer (that GET is the one charge).
resp = client.responses.create(model=model_id, input="Draft an article.", background=True,
                               extra_headers={"Idempotency-Key": "article-2026-11-02-001"})  # your own name; reuse it if the reply is lost
while resp.status in ("queued", "in_progress"):
    time.sleep(5)
    resp = client.responses.retrieve(resp.id)
print(resp.output_text)

# Streamed: events carry sequence_number; after a drop, resume after the last event you processed.
stream = client.responses.create(model=model_id, input="Draft an article.", background=True, stream=True,
                                 extra_headers={"Idempotency-Key": "article-2026-11-02-002"})
run_id, last_seq = None, None
for event in stream:                       # the loop ends early when your connection drops
    if getattr(event, "response", None):
        run_id = event.response.id          # resp_… (also the X-Portal-Run-Id header)
    handle(event)
    last_seq = event.sequence_number        # persist it after you processed the event

for event in client.responses.retrieve(run_id, stream=True, starting_after=last_seq):   # exclusive cursor
    handle(event)                           # ends with response.completed
TypeScript · stock openai client (both shapes; tested 2026-11-02)
import OpenAI from "openai";
const client = new OpenAI({ apiKey: PORTAL_API_KEY, baseURL: "https://api.portal.ai/v1", timeout: 3_900_000, maxRetries: 0 });

// Queued: the socket is free; poll; the final retrieve returns the answer (that GET is the one charge).
let resp = await client.responses.create(
  { model, input: "Draft an article.", background: true },
  { headers: { "Idempotency-Key": "article-2026-11-02-001" } },   // your own name; reuse it if the reply is lost
);
while (resp.status === "queued" || resp.status === "in_progress") {
  await new Promise((r) => setTimeout(r, 5000));
  resp = await client.responses.retrieve(resp.id);
}
console.log(resp.output_text);

// Streamed: events carry sequence_number; after a drop, resume after the last event you processed.
const stream = await client.responses.create(
  { model, input: "Draft an article.", background: true, stream: true },
  { headers: { "Idempotency-Key": "article-2026-11-02-002" } },
);
let runId = null, lastSeq = null;
for await (const event of stream) {        // the loop ends early when your connection drops
  if (event.response?.id) runId = event.response.id;   // resp_… (also the X-Portal-Run-Id header)
  handle(event);
  lastSeq = event.sequence_number;         // persist it after you processed the event
}
const resumed = await client.responses.retrieve(runId, { stream: true, starting_after: lastSeq });   // exclusive cursor
for await (const event of resumed) handle(event);   // ends with response.completed

Requests outside the admitted subset are refused; a regular stream without a run id has no resume guarantee.

Admission is per account and is Portal's decision, not a request parameter. POST /v1/responses is always the durable endpoint, with or without background: true: it requires an Idempotency-Key, and a first creation on an account that is not admitted answers 403 with error.code: "process_canary_not_admitted". background: true without stream returns the queued response and does not hold the connection; with stream: true the connection stays open for the event stream. A dropped connection does not cancel the run either way, because the required Idempotency-Key already opts the creation in. A chat completion without X-Portal-Durable: 1 stays an ordinary call. Ask your own Portal bot to request admission.

The failure scope today is process: a run survives the loss of the reader, the relay and the executor processes, not the loss of their host; the X-Portal-Run-Storage-Profile header on every durable reply says which scope you got. A host-loss scope is not offered on this preview.

The exact shapes — the headers, the cursor rule, every typed error code and the durable chat allowlist — are in the machine-readable description at https://api.portal.ai/openapi.json (OpenAPI 3.1).

Every durable creation requires an Idempotency-Key header. Save that operation key before the request and reuse it if the creation reply is lost.

The cursor is exclusive: starting_after=42 begins with the next event. Omit it if no complete event arrived. SSE clients can send Last-Event-ID; both cursors are validated, an invalid value answers 400 invalid_cursor even beside a valid one, and when both are valid the greater sequence wins. Keepalive comments do not advance the cursor. The stock SDK does not automatically reconnect a streaming iterator. Reuse the same idempotency key if the creation reply was lost; changing the request while reusing that key returns a conflict.

On an admitted account, opt into durable chat completions with X-Portal-Durable: 1 and an Idempotency-Key header on POST /v1/chat/completions. They retain their chat chunk format and [DONE]. Resume them with GET /v1/responses/{id}?stream=true&format=chat.completions&starting_after=42. Responses streams finish with response.completed; an error or response.failed is not a completed article.

Use GET /v1/responses/{id}/status for status without output. A normal GET can return the complete result and counts as delivery, including the final polling request. Result retrieval is available for 24 hours after the run reaches a recorded terminal state; the admission header X-Portal-Run-Retention states the rule and status reports the exact expiry once known. An authorized expired run returns HTTP 410. Every retrieval requires a currently authorized key for the same account. Automatic physical deletion at expiry is not part of this preview.

A background run finishing by itself does not incur the result-delivery charge. Result retrieval reserves its original quoted amount; insufficient available credit refuses retrieval before answer content. Complete delivery, including complete answer parts collected across reconnects, is charged once. A replay of a paid result adds no charge. A verified failure on our side before delivery is not charged; a client-aborted download can retain its reservation while delivery is reconciled. A later successful retrieval can complete the one normal charge.

Answer text and client function output are held until the run completes, output validation passes and its charge is ready. Before that, a stream can carry lifecycle or reasoning events and keepalives. Resume retrieves committed events; it does not expose unfinished answer text.

This preview limits the complete encoded delivery record to 4 MiB, including repeated event fields and metadata, so the available answer size depends on the wire format. An oversized result ends with run_artifact_too_large and is not billed; it does not publish a partial article or automatically start another generation. Safe structured recovery permits at most one provider reissue for the same run.

Closing a background stream leaves its generation running. Explicitly cancel with POST /v1/responses/{id}/cancel. Plain chat requests without background execution or an idempotency key keep their existing disconnect-cancellation behavior. The current subset rejects store:false, previous_response_id and unsupported parameters. Protected accounts require a separately enabled memory-only route. The X-Portal-Run-Storage-Profile header names the admitted failure scope: a process profile does not promise recovery after loss of its host.

Structured output (JSON)

Pass response_format: {"type": "json_object"} and describe your fields in the prompt. A successful final answer contains one JSON object in message.content. For a schema, use {"type":"json_schema","json_schema":{"name":"article","schema":{...}}}; object-root Draft-07 schemas are supported within size and depth limits, excluding patterns, references and uniqueness checks; unsupported schemas return 400.

For plain text answers, max_tokens and max_completion_tokens limit the visible text (the smaller wins if you send both), counted with the o200k_base tokenizer; reasoning is not counted. The answer stops at the limit with finish_reason "length", streamed or not. Without a limit nothing is cut.

For these JSON formats, max_tokens limits visible output using the cl100k_base tokenizer. Reasoning does not eat this budget. This is a delivery limit; upstream usage and billing can include additional generated tokens. If the complete response exceeds it, the request returns HTTP 400 output_limit_exceeded instead of truncated JSON or an empty body. If max_tokens is already below the smallest JSON object for that schema, or for the fields a json_object prompt names, the same 400 is returned before any model runs and the error names floor_tokens and max_tokens. usage.portal_output_tokens reports the visible and reasoning counts separately, with the tokenizer name. A bare max_tokens on a text request does not enable this validated-output contract.

Set stream: true with stream_options: {"include_usage": true} when you want the connection kept open. Streaming does not shorten thinking. JSON is delivered only after the complete value passes validation. Plain json_object checks only that one JSON object came back. For a structured article, send json_schema that lists every field under required and gives each one a type or an enum, so a missing or null field becomes an explicit error instead of an incomplete article. required alone accepts a field that is present but null. A mismatch returns response_schema_mismatch (HTTP 502 without streaming, an error event with streaming) and no partial article. Client libraries that retry server errors by default resend the whole request; set their retry count to 0 for these calls if you want the first error. Low is the fast start (Reasoning levels and time); check its output against your own criteria (exact strings, required lines) before relying on it. Portal supplies the format instruction and checks the final value; this route does not use native constrained decoding.

json_schema
{
  "type": "json_schema",
  "json_schema": {
    "name": "article",
    "schema": {
      "type": "object",
      "required": ["title", "trend"],
      "properties": {
        "title": { "type": "string", "minLength": 1 },
        "trend": { "enum": ["up", "down", "neutral"] }
      }
    }
  }
}

required alone would accept "trend": null. The enum rejects it.

This route currently ignores temperature. A validation error may include the rejected generation's token counts under error.usage; it contains no article content.

Reasoning levels and time

Some keys list four reasoning levels of the same model. The id is the level. A key may also list the ids without -fast, the bare id and the extra-high spellings; see Level ids. On one lab article (2026-10-28) every level above low took far longer than low, and not in level order: xhigh 11.4 minutes, medium 32 to 40, high past the 60-minute ceiling; a customer's own pipeline measured very different times for the same levels (below). A higher level does not make a structured article arrive sooner. Call GET /v1/models with your key and use an id that list actually returns.

  • grok-4.7-low-fast — the fast start for a structured article or any JSON object with a known shape. Check the output against your own criteria before relying on it.
  • grok-4.7-medium-fast — a second try, only after low fails a check you measured.
  • grok-4.7-high-fast — a third try, only after medium fails that same check.
  • grok-4.7-xhigh-fast — the deepest of the four. Not the default for a JSON article.

A customer's own measurement (2026-10-30 → 11-01; one writer → verifier pipeline on grok-4.7-fast, 2,827 calls; metadata only, no content): medium stream — 1,441 completed, median 15 s, longest 709 s; high stream — 158 completed, median 24 s, longest 1,016 s, and 7 ended at 599–602 s because the caller's own 10-minute clock closed a stream that was still delivering (one journaled at 14.8 MB); high without streaming — 175 completed, median 5 s, longest 20 s (the short verifier calls); xhigh without streaming — 1,000 completed, median 10 s, 17 of them over ten minutes, longest 1,431 s inside the 3,600-second ceiling, and 1 ended at 1,805 s on the caller's 30-minute clock. His own table for one article: medium-fast writer 12 min 26 s then a 52-second verifier that passed; high-fast writer not finished in his 30 minutes, verifier 17 min 53 s with a warning. On 2026-11-02 five grok-4.7-high-fast streaming attempts on the measured article shape (json_object) all ended with model_variance after 7–62 seconds — 0.6–8.6 thousand characters of reasoning, no JSON object — none billed; the largest gap between two events in those streams was 3.8 seconds. The same high prompt with response_format removed finished in 47 seconds with 111 characters of content, not the article. A separate grok-4.7-medium-fast stream — the same two messages plus the instruction this API adds for a JSON object, and no response_format — returned a six-field object of 8,827 characters in 31 seconds. json_schema on this fixture also ended model_variance. Every measured call that kept the JSON contract was refused and none was billed; no change of response_format measured here returned the article. The refusal is open on our side. The lab rows below are one article on one day; the level does not promise an article, and the time is not in level order.

One article on 2026-10-28 — the lab rows, not a level's time: response_format json_object, about 700–1,100 words, six field checks, max_tokens 5000. Five of the six attempts that returned an article passed those six checks. The low call without streaming failed the field-type gate before those six ran. Output tokens are usage.completion_tokens.

LevelCallTimeOutput tokensWhat came back
grok-4.7-low-faststream48 seconds4,920Valid JSON article; passed the six checks. 1,143 of the output tokens were reasoning. It appended % to the four exact decimal strings and left out a line the prompt required; the xhigh article kept both.
grok-4.7-low-fastno stream41.9 seconds4,899JSON object; one field the prompt limits to up, down or neutral came back null. A json_schema enum on that field rejects it. required alone does not.
grok-4.7-medium-fastno stream32 minutes193,450Valid JSON article.
grok-4.7-medium-faststream40 minutes245,768Valid JSON article. 55,354 reasoning tokens.
grok-4.7-high-fastno stream60 minutes—Timed out at the 3600-second ceiling. No article. Do not pick high to go faster.
grok-4.7-xhigh-fastno stream11.4 minutes89,760Valid JSON article.
grok-4.7-xhigh-faststream26.0 minutes189,812Valid JSON article. 49,649 reasoning tokens. Not a faster path.
grok-4.7-xhigh-faststream32.2 minutes—Connection closed with reasoning only: no article, no [DONE], no error event.
grok-4.7-xhigh-faststream91.6 minutesno articleReasoning only. No JSON had arrived when our measurement client stopped at its own 10 MB response limit; the server had not ended the stream. Not a faster path.

The same article at low with streaming took 48 seconds. A second low call, without streaming, took 41.9 seconds and 4,899 output tokens and returned a JSON object with one field null. Three streaming attempts at xhigh: one returned the article after 26 minutes, one closed after 32 minutes with no article, and one had delivered no JSON after 91.6 minutes, when our measurement client stopped at its own 10 MB response limit. Without streaming the same request finished in 11.4 minutes. stream: true keeps the socket open. It does not make the model think less. A stream that closes without data: [DONE] did not finish.

On grok-4.7-*-fast, a request without streaming is allowed up to 3600 seconds (60 minutes). If it has not finished by then, the call ends as a timeout: the Usage row says timeout, the charge is $0, and you do not receive a partial article. The public edge waits 3720 seconds, so a client timeout shorter than that fires first and can look like a hang while the server is still working. A buffered client that wants the full non-streaming allowance sets its own timeout above 3720 seconds. A stream has no total-duration wall; after progress starts, 200 seconds without model progress ends it (the proxy's own read gap is 600 seconds), and reasoning chunks count as progress, which is how a stream can run past an hour and still have no article. These clocks measure silence. Keepalive comments are not model progress, so a stream of only those comments still ends at 200 seconds after the first model byte, and from the start on an ordinary level (a deep level waits its first-progress allowance, 900 seconds, before that byte). A stream that is still delivering reasoning or answer text is not ended by the 200-second progress clock or the 600-second read gap; the 600- and 1,800-second endings in usage rows are the caller's own clocks (Streaming). A run that is still only reasoning past 80,000 tokens or 600,000 characters ends with reasoning_limit_exceeded, names those counts, is not billed, and does not change the reasoning level.

If visible JSON would exceed max_tokens, the response is HTTP 400 output_limit_exceeded rather than truncated JSON or an empty body. Reasoning does not consume that budget. The article above used 5000. A tiny cap is a delivery limit, not a way to make the model finish sooner.

Low is the fast start. Send json_schema with a type or an enum on every field under required, and check the output against your own criteria (exact strings, required lines) before relying on it. On this article, xhigh kept the exact strings and the required line that low missed; raise a level when a check like that fails.

Long requests

stream: true keeps the connection alive. It does not shorten thinking. The measured time for each level is in Reasoning levels and time, and it is not in level order. An active stream can continue beyond 600 seconds because reasoning and tool progress count as activity even before answer text arrives. Use streaming when the call must outlive the non-streaming ceiling, and set your client timeout above 3720 seconds if you intend to wait for that full allowance. The 600- and 1,800-second endings in usage rows are the caller's own clocks (Streaming): one measured stream was still delivering 14.8 MB when its caller closed at 599.9 seconds; a background run (Resume a stream) removes the connection from the picture.

Selected long-reasoning routes without streaming allow up to 3600 seconds. Other routes retain their existing limits; portal/m3-55-xh-1m retains its 600-second limit. Asking the proxy for more than the route allows through timeout or request_timeout in the JSON body returns HTTP 400 with a message beginning stream_required: before model dispatch. The error names the limit and stream: true. A timeout set in your client library is a separate client-side setting.

Streaming has no total-duration wall. A model run that sends no observable progress still ends: deep reasoning routes allow at least 900 seconds for first progress; ordinary routes allow 200 seconds and non-deep batch requests allow 420 seconds. After progress starts, the idle allowance is 200 seconds. The proxy allows 600 seconds between upstream reads, and transport keepalives keep the public connection open while the model is active. A buffered client that needs the full long-request allowance must use a timeout greater than 3720 seconds.

A timeout appears in Usage with the model available to your key, timeout, and a charge of $0. New receipts show the configured response or read-idle limit; older receipts show the elapsed time because their exact clock was not recorded. Timed-out requests are not billed. When the API observes a disconnect before completion, it cancels pending work and records no charge.

Input size alone does not predict completion time. A large request can stream successfully while a small request asks for an answer too long to finish within the non-streaming limit.

Tool / function calling

Portal supports OpenAI-compatible client-side tool calling, including on eligible private model routes. Describe your functions with a JSON schema and the model decides when to call them, returning structured tool_calls. Your application executes these functions and sends their results back; listing a function does not make Portal execute your code.

Python
tools = [
    {
        "type": "function",
        "function": {
            "name": "get_weather",
            "description": "Get the current weather for a city.",
            "parameters": {
                "type": "object",
                "properties": {
                    "city": {"type": "string", "description": "City name"},
                },
                "required": ["city"],
            },
        },
    }
]

resp = client.chat.completions.create(
    model=model_id,
    messages=[{"role": "user", "content": "What is the weather in Tokyo?"}],
    tools=tools,
)

for call in resp.choices[0].message.tool_calls or []:
    print(call.function.name, call.function.arguments)

Parallel tool calls are supported - the model may return several tool_calls in one response.

To continue, append resp.choices[0].message to your messages, then add one {"role":"tool", "tool_call_id":call.id, "content":"your result"} message per call. Send the updated conversation with the same model and tools.

Portal web tools — executed for you

Portal provides server-executed web search, page reading and news. On web-enabled chat routes, the model can call these tools and receive their results inside one request, then answer with source links. No tool code or second request is needed. Every active platform account can also call the tools explicitly through the API and MCP, subject to its existing model and privacy policy.

Python — use an exact model ID returned for your key by /v1/models
resp = client.chat.completions.create(
    model=model_id,
    messages=[{
        "role": "user",
        "content": "Search the web for this week's NASA news. Cite source URLs."
    }],
    tools=[],  # an empty tools list makes Portal run web research; omitting tools leaves it off
)
print(resp.choices[0].message.content)

Raw API calls omit Portal's web-tool schemas and web instructions unless you opt in. Send tools: [] for automatic research on eligible chat routes, or use X-Portal-Tool for a direct tool call. MCP portal_call opts into automatic research. Set tool_choice="none" to disable it. If you supply a nonempty list of client tools, including your own web_search, your application executes them under the client-side contract above. Protected privacy routes do not enable public-web tools.

Portal toolResultMCP name
web_searchPublic-web source URLs, titles and excerpts. Optional engine: "included" uses a bounded included search run.portal_web_search
fetch_page (alias web_fetch)Readable text from one public HTTP(S) URL.portal_fetch_page
google_newsGoogle News headlines, publisher names, dates and article links. Fetch the article separately for its full text.portal_google_news

Call a Portal tool directly

Explicit tools work with an active key and any model allowed for that key, on an ordinary privacy route. Use the same OpenAI-compatible endpoint with X-Portal-Tool and exactly one user message containing JSON arguments. Omit client tools and use stream=False. The completion content is a JSON tool result; HTTP-backed calls use zero model tokens.

Python — direct public-web search
import json

result = client.chat.completions.create(
    model=model_id,
    extra_headers={"X-Portal-Tool": "web_search"},
    messages=[{"role": "user", "content": json.dumps({"query": "NASA latest news"})}],
    stream=False,
)
print(json.loads(result.choices[0].message.content)["sources"])
# fetch_page: {"url": "https://www.nasa.gov/news/"}
# google_news: {"query": "space exploration when:1d"}
# included web_search: {"query": "NASA latest news", "engine": "included"}

For direct tool calls, set engine: "web" to use only the public-web provider and disable fallback to a search run that consumes model tokens. Automatic research keeps the documented fallback policy; the model does not select this client option.

Automatic research permits up to three Portal tool operations per request. All API and MCP operations share the same key limits: ten operations per minute and one hundred web credits per UTC day. Search uses two credits; page reads and news use one. Shared-service and provider limits can apply sooner. If the public-web provider reaches its free limit or returns a server error, search can use the included search engine and page reading can use Portal's direct public-page reader. A successful fallback uses the same operation and credits; an unsuccessful HTTP 429/5xx operation restores the key's daily credits. Attempts still count toward minute and service limits. There is no separate web-provider charge or paid search fallback. Model continuations and included search runs, including automatic fallbacks, consume model tokens at the existing rate.

Direct results identify the actual execution: public_http, included_search_run or public_http_direct. The direct page reader returns public text/HTML only, with bounded size, time and redirects. A source marked truncated: true is an excerpt. It executes no page scripts and sends no cookies or credentials; sites that require a browser may refuse the read.

An included search operation is one isolated search run, capped at forty-five seconds. Its internal searches are not individually observable, so the operation limit is a run limit. Its source list is model-reported; use fetch_page to verify page evidence. Search queries and URLs leave Portal for public-web providers. Keep private notes and credentials out of them. Page text is untrusted source material.

With stream=True, chat can stream before a tool is chosen and resume after the tool result; research progress may precede the final answer. Internal tool calls are executed by Portal and are not returned as client tool_calls. MCP model calls return the completed reply; MCP SSE is a response envelope, not token streaming. Temporary failures and quota refusals return typed errors on explicit tool calls; automatic research reports missing evidence.

Images and other tools

Image generation uses POST /v1/images/generations with {"prompt":"A red circle on white","n":1,"response_format":"b64_json"}, or MCP portal_image_generate with {"prompt":"A red circle on white"}. Image editing uses POST /v1/images/edits with reference images. These are separate image routes; model-only keys or account restrictions may deny image access. An account that Portal limits to its own model list and that has image access makes pictures only with portal-image-1 and clips only with portal-video-1, and POST /v1/images/edits and other picture models answer 403 model_not_allowed for it. Chat does not generate an image file directly.

Provider-native Live Search and native X search are not carried by the current model relay. A direct provider route needs a separate credential and its own charges; it is not enabled by default. Google News is the news feed, not a Google web-index API. Editor shell, files, browser controls and personal MCP connections are not shared with platform tenants. The public model catalog remains Portal-branded.

Images and videos

Portal's media service makes pictures and short videos. Use the same API key for creation, status checks, cancellation, and downloads: each job belongs to the key that created it. Media requires image access. A job needs a positive balance to start, and its charge is on its Usage row. Two jobs may be in progress per key, and four across the service. An account that Portal limits to its own model list and that has image access makes pictures only with portal-image-1 and clips only with portal-video-1. For a picture, choose portal-image-1:

POST /v1/images/generations
curl https://api.portal.ai/v1/images/generations \
  -H "Authorization: Bearer $PORTAL_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"model":"portal-image-1","prompt":"A red sailboat on a calm blue sea","response_format":"b64_json"}'

A completed picture returns data[0].b64_json. If it needs more time, the response is HTTP 202 with an id, status, and poll path. Read that path until the status is done, then download the file at its url.

POST /v1/videos/generations
curl https://api.portal.ai/v1/videos/generations \
  -H "Authorization: Bearer $PORTAL_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"model":"portal-video-1","prompt":"A red sailboat glides across a calm blue sea","seconds":6,"size":"720p","aspect_ratio":"16:9"}'

Video creation returns HTTP 202 with the job id, beginning with gm_ followed by 32 lowercase hexadecimal characters. Save your returned id as MEDIA_ID. For example:

{"id":"gm_0123456789abcdef0123456789abcdef","object":"media.generation","kind":"video","status":"queued"}

Duration is 1–15 seconds; size is 480p or 720p. You can also supply first_frame, last_frame, or up to 14 reference images as image data URLs or base64 bytes.

GET /v1/videos/{id}
curl "https://api.portal.ai/v1/videos/$MEDIA_ID" \
  -H "Authorization: Bearer $PORTAL_API_KEY"

Poll about every ten seconds while the status is queued or running. Running jobs carry eta_hint: "minutes": the media is being made and takes a few minutes. A completed job has status: "done" and a files list with sizes, hashes, and download URLs. A declined request has status: "refused"; an unsuccessful job has failed. These are terminal results, so stop polling.

POST /v1/videos/{id}/cancel
curl "https://api.portal.ai/v1/videos/$MEDIA_ID/cancel" \
  -H "Authorization: Bearer $PORTAL_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"why":"I no longer need this request."}'

Cancel a queued request before work has started. The optional why is 3–600 characters. A successful cancellation returns status: "cancelled"; stop polling. Once work has started, cancellation leaves it running and returns its current status. Check the returned status because work may start while your cancellation is arriving. Image jobs use POST /v1/media/{id}/cancel.

GET /v1/videos/{id}/content
curl "https://api.portal.ai/v1/videos/$MEDIA_ID/content" \
  -H "Authorization: Bearer $PORTAL_API_KEY" \
  -o video.mp4

Download completed files promptly: the default retention window is 24 hours from creation. After that the job is expired and the file is no longer available. Image jobs use the same status and download paths under /v1/media/{id}.

Errors and retries

Creating a job needs a positive balance. A job you already created stays readable: status, download and cancel through /v1/media/{id} keep working after your balance runs out. Use those paths if your credit may run out while a job is running; the /v1/videos/{id} paths check credit like a new request. Common answers:

  • 429 media_in_flight: this key has two jobs in progress, or the service has four. Retry-After: 5 is in the header only. A slot this key holds frees only when one of your own jobs ends, so poll your open jobs and do not create new ones in a loop.
  • 503 no_worker_available: no media worker is available. The response carries Retry-After: 45.
  • 503 media_unavailable or media_busy: a short failure. Retry after the Retry-After value (10 seconds).
  • 403 insufficient_balance: add credit before creating a new job.
  • 403 model_not_allowed: an account that Portal limits to its own model list and that has image access makes pictures only with portal-image-1 and clips only with portal-video-1; POST /v1/images/edits and other picture models answer this.
  • 404 not_found: the id is unknown, was swept, or was created with another key.
  • 409 media_not_ready: you asked for the download before the job finished.
  • 410 media_expired: the job expired; a status read of it answers 200 with status expired.
  • 503 image_authorization_unavailable: the admission check is down. Retry after the Retry-After value (5 seconds).

Use in Cursor Experimental

Portal is a direct HTTP API first (see the sections above). Using it inside the Cursor editor via BYOK is an experimental convenience, subject to the Cursor-side limitations below - it is not the primary way to use Portal.

Portal can be added as a custom model in Cursor via its OpenAI BYOK setting - Agent mode, tool calling, and streaming. In Settings → Models:

  • Set the OpenAI API Key to your sk-portal-… key.
  • Enable Override OpenAI Base URL and set it to https://api.portal.ai/v1.
  • Call GET /v1/models with the same key, add an exact returned id as a custom model, and select it.

The custom model's exact id selects the route and effort. Cursor's Context/Reasoning toggles do not pass through BYOK. The public routes below are usable only when they appear in your key's list; a private id from that list works in the same field.

  • portal/m2-25 - Portal M2-25 standard ($0.12 / $0.59 per 1M).
  • portal/m2-25-fast - Portal M2-25 priority ($0.70 / $3.50).
  • portal/m3-55-xh-1m - Portal M3-55 XH, deep reasoning with a 1M context window.
  • portal/m3-500k-fast - Portal M3 256K, standard speed. The model id is retained for compatibility.

Seeing "Unauthorized" after it worked?

Cursor caches an auth failure on the current chat: once a request fails (e.g. an attached image), Cursor short-circuits later sends in that chat with Unauthorized User Openai API key - they never reach Portal. Start a new chat to clear it. Set the model once and avoid switching models mid-chat.

Images / vision

Don't attach images over BYOK. For any multimodal request, Cursor runs a hardcoded key check against api.openai.com (ignoring your base URL), so it fails with Unauthorized and never reaches Portal. This is a confirmed Cursor bug affecting every BYOK provider - there is no proxy-side fix. For a message with a screenshot, switch to a Cursor built-in model for that message; keep a Portal tier (e.g. portal/m2-25) for text and coding.

Billing

BYOK requires a paid Cursor plan for Agent/Edit. You pay Portal for inference (your usage dashboard). On Team/Enterprise, Cursor also adds its own Cursor Token Rate ($0.25 / 1M tokens, incl. cached) on top - shown as "User API Key" cost on Cursor's dashboard. On the Pro individual plan there is no token fee, so you pay only Portal. Use Pro to avoid the surcharge.

Portal MCP

MCP https://api.portal.ai/mcp

Portal is also available over the Model Context Protocol (Streamable HTTP). Any MCP client - Cursor, agent frameworks, the Portal SDK - can connect and use Portal as a set of tools: run prompts on Portal models, browse marketplace offers, and search skills.

Connect

Add the server to your MCP client config (Cursor: Settings → MCP → Add server, or ~/.cursor/mcp.json):

{
  "mcpServers": {
    "portal": {
      "url": "https://api.portal.ai/mcp",
      "headers": { "Authorization": "Bearer YOUR_PORTAL_KEY" }
    }
  }
}

Any MCP client that connects to a remote Streamable HTTP server with a custom Authorization header connects the same way.

Replace YOUR_PORTAL_KEY with a key from the dashboard's API Keys tab (it starts with sk-portal-). Discovery tools work without a key. Model calls, public-web tools and image generation require the key and retain its access restrictions. A rejected or wrong key comes back as a tool error (isError: true) on HTTP 200, not HTTP 401.

MCP tools/call arguments
{"name":"portal_web_search","arguments":{"query":"NASA latest news"}}
{"name":"portal_fetch_page","arguments":{"url":"https://www.nasa.gov/news/"}}
{"name":"portal_google_news","arguments":{"query":"space exploration when:1d"}}
{"name":"portal_image_generate","arguments":{"prompt":"A red circle on white"}}

Send these as params in a JSON-RPC tools/call request. Web tools return structured sources and share the API quota. Add model from portal_models_list to select an allowed route. portal_call also inherits automatic web research on web-enabled routes: ask for current facts and source URLs.

Call portal_models_list with the same key you use for HTTP. It returns that key's exact model ids, context windows, effort and entitlement, matching GET /v1/models. A restricted key can have private ids without any public ids. Keyless discovery shows the four Portal-branded routes.

The main tool: portal_call

Runs a prompt on a model available to your key, billed per token against its wallet. Choose an id from portal_models_list; if you omit it, the tool uses the returned default_model. For a key limited to private ids, default_model is the first id of that key's own list that can be called. The public default portal/m2-25 applies only to a key that has it.

  • Input - prompt (plain text; calls are single-turn, so include all context in the prompt) and optionally model (an id from Choosing the model). Optional: system, max_tokens, temperature.
  • Output - the model's plain-text reply, with a route_receipt beside it.
  • Model selection - use the returned context window and effort to choose among the ids your key can call.
  • Long calls - portal_call does not stream and waits at most 650 seconds. Longer work goes over HTTP with streaming. Reasoning may delay the first answer text. The request limits still apply; MCP does not extend the model deadline.

All tools

The server registers 21 tools, and tools/list advertises them. portal_net_search and portal_net_listing_get appear only when the operator enables them. Read its input schemas before calling a tool; access and charges depend on the operation and your account.

ToolPurpose
portal_callRun a prompt on an allowed model; requires your key.
portal_messageSend a message to your own Portal agent and return its reply in the MCP session.
portal_models_listList models available to your key, or the public catalog without a key.
portal_capabilitiesThis key's capability document; no model charge.
portal_web_searchSearch the public web and return source URLs and excerpts.
portal_fetch_pageRead one public HTTP(S) page.
portal_google_newsFind news headlines, dates, publishers and article links.
portal_image_generateGenerate an image; requires image access. The charge is on its Usage row.
portal_image_editEdit up to three images you send. A key whose account Portal limits to its own model list cannot edit.
portal_offers_listList marketplace model offers. Those offers are the public catalog's Portal-branded routes.
portal_offer_getRead one marketplace offer.
portal_skills_searchSearch the skills catalog.
portal_skill_getRead one skill's details.
portal_skill_categoriesList skill categories and counts.
portal_skill_orderPlace an asynchronous skill order using your account's Portal credits.
supersocial_read_startStart a SuperSocial person read and receive its run id. The two supersocial_* tools are a beta for allowlisted accounts.
supersocial_read_getRetrieve that read's status or result. Beta for allowlisted accounts.
portal_activateGet the activation page for an offer or skill.
brains_topRead the current Portal Brains benchmark board.
brains_historyRead a model's recent benchmark history.
brains_checkRead benchmark degradation and recovery events.

Same wallet, same metering, same Logs as the HTTP API - MCP is a second endpoint to the exact same account.

List models

GET https://api.portal.ai/v1/models

Returns the models available to your key, in OpenAI's list format.

Request
curl https://api.portal.ai/v1/models \
  -H "Authorization: Bearer $PORTAL_API_KEY"
Example response for a key with the public catalog
{
  "object": "list",
  "data": [
    { "id": "portal/m2-25",           "object": "model", "owned_by": "portal" },
    { "id": "portal/m2-25-fast",      "object": "model", "owned_by": "portal" },
    { "id": "portal/m3-55-xh-1m",     "object": "model", "owned_by": "portal" },
    { "id": "portal/m3-500k-fast",    "object": "model", "owned_by": "portal" }
  ]
}

The returned list depends on the key. Illustrative private entry; use the actual id returned for your key:

{
  "id": "your-key-model-extra-high-fast",
  "object": "model",
  "owned_by": "portal",
  "name": "A model available to your key",
  "context_window": 256000,
  "effort": "extra-high",
  "effort_source": "id"
}

Private lists can carry entitlement: "key_scoped". An id without an effort suffix may have no effort value; do not infer one from the model family. The Models page describes the four public Portal routes; private account grants do not change that catalog.

While a newly granted entitlement is still synchronizing to your key, this endpoint answers 503 with error.code: "model_entitlement_sync_pending" and a top-level retryable: true beside the error object; there is no Retry-After header. Retry after the key's model policy has synchronized (the reconciler runs hourly). A key whose budget is exhausted still sees its menu.

Errors

Portal uses standard HTTP status codes and returns a JSON body with an error object on failure.

  • 400 - malformed request (bad JSON or missing fields).
  • 401 - missing, invalid, or revoked API key.
  • 403 with error.code and error.type both "key_model_access_denied" - this key cannot call the requested model; error.model names the refused id. This is not an outage. The message lists the ids it can call; choose one of those, or retrieve them with GET /v1/models. Retrying the same model does not change access. To enable another model on your account, ask your own Portal bot, then check the list with your key.
  • 403 with code: "model_not_allowed" - an account that Portal limits to its own model list and that has image access makes pictures only with portal-image-1 and clips only with portal-video-1; POST /v1/images/edits and other picture models answer this.
  • 403 with code: "process_canary_not_admitted" - POST /v1/responses on an account that is not admitted to durable runs.
  • 429 with Budget has been exceeded in the message - your wallet (or this key's spend cap) is empty. Retrying will not help: top up your wallet or enable auto-recharge in Billing, or raise the key's cap in Keys.
  • 429 with code: "rate_limit_exceeded" and a Retry-After header - we're briefly at full capacity; safe to retry and not billed. See When we're busy.
  • 429 with code: "media_in_flight" - two of your media jobs are in progress, or the service is at four; Retry-After: 5 is in the header only. See Images and videos.
  • 500 - transient server error; retry with backoff.
  • 503 with code: "no_worker_available" - no media worker is available; the response carries Retry-After: 45.
  • 502 with code: "upstream_error" - the model provider failed before an answer; no Retry-After is sent; safe to retry (the stock clients retry it twice by default) and not billed.
  • 502 with code: "run_budget_exceeded" - the run spent its turn or output-token budget without a final answer; code: "agent_looping" - the model was looping and the run was stopped. Neither is billed.
  • 400 with code: "model_not_found" - the requested model is not available on this endpoint; retrying the same model does not help.
  • 429 with code: "premium_pool_exhausted" - every premium seat for this model is out of quota right now; retry after the Retry-After header.
  • 404 with code: "run_not_found" on GET /v1/responses/{id} - no such run for the key presented; a refused key receives the same body as a missing run.
  • 504 with code: "run_idle_timeout" - the model sent no progress for the allowance in Long requests; not billed.
  • 400 with code: "invalid_idempotency_key" - every POST /v1/responses needs a printable Idempotency-Key of at most 200 characters; code: "stream_not_enabled" - a streamed retrieval of a durable run that was created without stream: true (fetch its result instead); code: "invalid_cursor" / "future_cursor" - a resume cursor that is not a non-negative integer or is ahead of the run.

If a stream ends below the reasoning ceiling because the model did not produce a complete JSON object, the error body carries model_variance. The HTTP status remains numeric, and the call is not billed.

Both 429 cases share one status code, so a retry loop should read the body: retry only when error.code is rate_limit_exceeded (or a Retry-After header is present on that capacity response); an out-of-credit 429 carries neither. A media 429 media_in_flight is not one of those cases; see Images and videos.

A refused key on GET /v1/models (live shape, 2026-11-02)
{
  "error": {
    "message": "Missing, invalid or revoked API key.",
    "type": "authentication_error",
    "code": "unauthorized",
    "param": null
  }
}

On POST /v1/chat/completions the proxy answers a refused key with code: "401" and type auth_error (a bearer that does not start with sk-) or token_not_found_in_db (an unknown key); POST /v1/responses answers code: "invalid_api_key". Switch on the status, then on error.code where one is present; the machine-readable list of codes is in openapi.json.

Every call - success or failure - lands in the dashboard's Logs tab: prompt, response, reasoning and tool calls, under your privacy settings.

When we're busy

Sometimes demand briefly outruns capacity. When that happens, the API answers with an honest 429 instead of leaving you hanging: your request was not processed, nothing was lost, and the failed call is not billed. The response tells you exactly when to try again, in the Retry-After header and in the body as error.retry_after (seconds, always the same value).

HTTP/1.1 429 Too Many Requests
Retry-After: 5

{
  "error": {
    "type": "rate_limit_error",
    "code": "rate_limit_exceeded",
    "message": "We're at full capacity for a brief moment. Your request is safe to retry in 5s: nothing was lost and this attempt is not billed. High demand, more capacity coming online daily. Thanks for building with us.",
    "retry_after": 5
  }
}

The retry pattern that works:

  • Single requests: wait the Retry-After seconds, then retry. One retry is usually enough.
  • Batches and parallel work: back off adaptively. On each 429, double your wait and add random jitter; after a success, shrink it back. Keep concurrency bounded.

The helper is for chat capacity 429s. A media 429 media_in_flight means two of your jobs are still open, so wait for one instead of retrying the create.

Python retry helper
import random, time

def with_retry(send, tries=5):
    for attempt in range(tries):
        resp = send()
        if resp.status_code != 429:
            return resp
        try:
            code = (resp.json().get("error") or {}).get("code")
        except ValueError:
            code = None
        if code != "rate_limit_exceeded" or "retry-after" not in resp.headers:
            return resp  # out of credit, a key cap, or media_in_flight: retrying will not help
        wait = float(resp.headers.get("retry-after", 2 ** attempt))
        time.sleep(wait + random.uniform(0, wait / 4))  # jitter
    return resp

Two commitments behind this: a paid request is never silently dropped (when we can't serve it, you get an explicit error, not a hang), and failed calls are not billed. A 429 costs you nothing but the wait.

Report a bug

Tell your own Portal bot first. It passes the issue to the team and brings the answer back to you. Include the requested model id, when the call happened, the HTTP status and any request id, plus a minimal example that reproduces the issue. Leave API keys and private prompt content out of the report.

You can also email support@portal.ai.