Skip to content

OpenAI-compatible Advisor endpoint

Polaris exposes the Advisor (the read/serve agent) over an OpenAI Chat Completions–compatible surface, so any OpenAI client (SDKs, TUIs, curl) can query a published brain with no Polaris-specific code.

Endpoint

POST /v1/brains/{brain_id}/chat/completions
  • Brain-scoped: the brain comes from the path. Clients point their base_url at http://<host>:8088/v1/brains/<brain_id>; the SDK appends /chat/completions.
  • Deployed hosts drop the port. Where the gateway sits behind a reverse proxy the base URL is just https://<host>/v1/brains/<brain_id> — the reference deployment publishes /v1/ through nginx behind a Tailscale Funnel. See Edge & Tailscale.
  • The OpenAI model field is echoed, not used for routing (pick any value).
  • Only the answer verb is served (grounded, cite-then-verified answers from the published brain).
  • The Advisor may ask a follow-up question before it answers; see Follow-up questions.
  • The brain needs its own OpenRouter key; see The brain needs its own OpenRouter key.
  • stream: true returns SSE chat.completion.chunk events ending in data: [DONE]. stream: false returns a single chat.completion object.
  • Every response also carries the Advisor's structured metadata (citations, confidence, guardrail, brain_version) — see Structured metadata.

Auth — long-lived API keys

Send Authorization: Bearer <key>. The key is a long-lived API key (sk-polaris-…) or a normal Polaris access JWT. API keys don't expire (good for standing integrations); JWTs expire (~1h).

A key does only what its scopes allow. Each key carries a scopes list. This endpoint (and /v1/me) needs advisor:read, which is what a key gets by default. Other scopes open other surfaces: the Questions Framework API and its MCP endpoint (questions:read, eval:run, …) and the operator MCP server (mcp:invoke, …). A key presented to a route its scopes don't cover, or to the web app's own routes (which take only a signed-in session), is 403 insufficient_scope. So a leaked advisor:read key can ask questions but can't manage the brain. See Access, flags and scopes for every scope.

The brain needs its own OpenRouter key

The Advisor runs on the brain's own OpenRouter key. A brain without one has no Advisor: every request is refused with HTTP 403 in the OpenAI error format, and nothing is answered:

{
  "error": {
    "message": "This brain's Advisor needs an OpenRouter key. An admin can add one under Settings → Model providers.",
    "type": "permission_error",
    "code": "openrouter_key_required"
  }
}

The fix is a brain admin's: add the key under Settings → Model providers.

Error codes

Auth failures return the gateway's envelope {"error":{"code":…,"message":…,"detail":…}} with a distinct code so clients can react precisely. (Errors about the request itself, such as a bad body, use the OpenAI format {"error":{"message":…,"type":…}}; see Request errors.)

Code HTTP Meaning
unauthorized 401 No/Bearer-less Authorization header.
invalid_api_key 401 sk-polaris-… token doesn't match any key.
revoked_api_key 401 Key exists but was revoked.
insufficient_scope 403 Key lacks the advisor:read scope.
brain_forbidden 403 Key/JWT is bound to a different brain than the path.

Which brain is my key bound to? — GET /v1/me

A key is bound to one brain_id. Hit the wrong brain in the path and you get 403 brain_forbidden — which, on its own, doesn't tell you the right brain. Rather than guess, introspect your own credential:

GET /v1/me      Authorization: Bearer <sk-polaris-… or JWT>
{
  "auth": "api_key",                 // "api_key" | "jwt"
  "actor": "reader@acme.example",
  "brain_id": "calliope",            // ← the brain this credential can reach
  "role": "Reader",
  "account_type": "tenant_user",
  "scopes": ["advisor:read"],        // a JWT reports ["*"] (unrestricted)
  "advisor_base_url": "/v1/brains/calliope",   // ← paste this as your OpenAI base_url
  "version": "0.5.1",                // platform (application) version — the deployed Polaris build
  "brain": {                         // bound brain identity + published knowledge version
    "brain_id": "calliope",
    "display_name": "Calliope Finance — Lending Compliance",
    "status": "active",
    "tenant_type": "customer",
    "published_version": "147676ad69c2a14afbde0113b4e92de336d55d88",  // published corpus SHA (null if unpublished)
    "published_version_num": 34,
    "published_at": "2026-07-25T03:23:43Z"
  },
  "api_key": { "id": 14, "label": "tickle-tui", "last_used_at": "2026-07-27T21:49:55Z" }
}

version is the deployed platform build; brain.published_version is the brain's content version (the published corpus SHA) — the two are independent. The brain block is omitted for an unbound platform-admin token.

/v1/me is advisor-scoped like /chat/completions (so an advisor key is accepted) and reveals only the caller's own binding — never other keys or brains. Point your client's base_url at the returned advisor_base_url and you're done. advisor_base_url is null for a platform-admin token (not bound to a single brain) — pass the brain explicitly in that case.

curl -s https://<host>/v1/me -H "Authorization: Bearer $POLARIS_API_KEY"

Older tenants may predate /v1/me (it returns 404). In that case ask the tenant admin to look up the binding — bb apikey list / GET /v1/brains/{brain_id}/api-keys (Admin JWT) — or to mint you a Reader key for the brain you should be using.

Managing keys

From the SPA: Settings → API keys (tenant Admin or platform admin). Create shows the raw sk-polaris-… once; the list is metadata-only (label, scopes, created, last used) with a revoke action. Revocation takes effect on the very next request.

Over REST (JWT session; Admin/platform-admin — a key cannot manage keys):

POST   /v1/brains/{brain_id}/api-keys      {"label": "tickle-tui"}   → { …metadata, "key": "sk-polaris-…" }
GET    /v1/brains/{brain_id}/api-keys                                 → { "items": [ …metadata ] }
DELETE /v1/brains/{brain_id}/api-keys/{id}                            → { "id": …, "revoked": true }

From the CLI (every DB-touching command needs APP_CONFIG):

APP_CONFIG=$(pwd)/env/local/app.env uv run python -m app.cli apikey mint \
  --brain-id calliope --role Reader --label tickle-tui   # → sk-polaris-xxxx (printed once)
APP_CONFIG=$(pwd)/env/local/app.env uv run python -m app.cli apikey list [--brain-id calliope]
APP_CONFIG=$(pwd)/env/local/app.env uv run python -m app.cli apikey revoke <id>

A key is bound to its brain_id; it cannot drive another brain's path (403). Only the sha256 hash is stored — the raw token is shown once and is unrecoverable.

Scoping a question to a subject

A question rarely names the citations it needs, and similarity search cannot bridge the gap because a provision's text does not repeat its own citation. A topic card closes it: a curator names a kind of question and the provisions its answers turn on, and scoping supplies those provisions' verbatim text by exact key.

Pass topic_ids. Card ids come from the MCP topic_cards tool or GET /v1/brains/{brain_id}/topic-cards — see Advisor MCP.

curl https://<host>/v1/brains/<brain_id>/chat/completions \
  -H "Authorization: Bearer sk-polaris-…" -H "Content-Type: application/json" \
  -d '{
        "messages": [{"role": "user",
                      "content": "We declined an applicant because their credit score was below our threshold. What notices do we owe?"}],
        "topic_ids": ["denying-an-application-the-notices-we-owe"]
      }'

From an OpenAI SDK, it rides extra_body:

client.chat.completions.create(
    model="polaris-advisor",
    messages=[{"role": "user", "content": "…"}],
    extra_body={"topic_ids": ["denying-an-application-the-notices-we-owe"]},
)

Both forms are accepted. Top-level topic_ids is what extra_body produces and what most callers reach for; {"polaris": {"topic_ids": […]}} is the symmetric form, matching the polaris object on the response. If both are sent the namespaced one wins.

  • Optional — omitting it changes nothing. An unscoped request retrieves exactly as before.
  • At most 8 ids per request, the same cap the interactive surface enforces.
  • An unknown id is ignored, not an error — a stale id degrades to an unscoped answer.
  • Every other unrecognised field is still ignored, so the long tail of OpenAI sampling parameters keeps passing through untouched.

Follow-up questions

Before it answers, the Advisor works out whether a question is one of the brain's published Questions, and whether it knows the facts that Question's answer turns on (its slots). If it needs something from the person, it asks instead of answering. This happens only where the brain has the advisor_question_routing flag on. The design is in Advisor question routing.

A follow-up is an ordinary assistant message: its content is the question, so a plain OpenAI client just shows it and the person replies in the next turn. The text ends with a short reference, (ref: 3fa9c2d81b7e). Keep it in the history you send back: that is how the endpoint recognises the reply.

For clients that want to show choices, the structured form rides a top-level needs_input field (on the completion, or on the final chunk when streaming). It is absent on an ordinary answer.

Field Meaning
reason choose_question (which of candidates is meant) or slots (facts the answer turns on).
token Pass back in route_resume.token to reply explicitly.
question_id The Question, for slots.
candidates For choose_question: question_id, text (what to show), probability.
slots For slots: each name, type, ask_text, required, and values (allowed values; empty for free text).
message Why the Advisor is asking, when there is more to say (for example a required fact answered "I don't know").

Replying

There are two ways, and you can mix them across turns:

  • Implicitly, with no client changes. Send the history back with the person's reply as the last user message. If the last assistant message before it carries a follow-up's (ref: …), that user message is the reply. The reference is then spent. Only the same API key (or the same signed-in user) can reply to its own follow-up, and a reference expires with its route after 30 minutes.
  • Explicitly, for a client that showed the choices: add route_resume to the request body ({"token": …, "question_id": …} or {"token": …, "slots": {…}}, or {"token": …, "reply": …}). It also works as polaris.route_resume, and it wins over a (ref: …) in the history. A malformed one is 400 with "param": "route_resume".

question_id: "none" means none of the candidates: the question is answered as asked. In slots, pass the person's own words, "I don't know" included. A route allows at most three replies.

A worked round trip

1. Ask.

curl -s http://localhost:8088/v1/brains/calliope/chat/completions \
  -H "Authorization: Bearer $POLARIS_API_KEY" -H "Content-Type: application/json" \
  -d '{"messages": [{"role": "user", "content": "What notices do we owe when we decline someone?"}]}'

The question could be one of two Questions, so the Advisor asks which:

{
  "id": "chatcmpl-…",
  "object": "chat.completion",
  "choices": [{
    "index": 0,
    "message": { "role": "assistant",
                 "content": "Which of these do you mean?\n1. Adverse action notice for a declined consumer credit application\n2. Adverse action notice when a credit report contributed to the decline\nOr none of these.\n\n(ref: 3fa9c2d81b7e)" },
    "finish_reason": "stop"
  }],
  "usage": { "…": "…" },
  "polaris": { "citations": [], "confidence": null,
               "guardrail": { "status": "pass", "rule_id": null, "message": null },
               "brain_version": "147676ad69c2…" },
  "needs_input": {
    "reason": "choose_question",
    "token": "u2Q8m0kXr4V…",
    "question_id": null,
    "candidates": [
      { "question_id": "Q-dee-48", "text": "Adverse action notice for a declined consumer credit application", "probability": 0.52 },
      { "question_id": "Q-fcra-615a", "text": "Adverse action notice when a credit report contributed to the decline", "probability": 0.31 }
    ],
    "slots": [],
    "message": ""
  }
}

2. Choose, explicitly. Your app showed the two choices as buttons and the person picked the first:

{
  "messages": [
    { "role": "user", "content": "What notices do we owe when we decline someone?" },
    { "role": "assistant", "content": "Which of these do you mean?\n1. …\n2. …\nOr none of these.\n\n(ref: 3fa9c2d81b7e)" },
    { "role": "user", "content": "The first one." }
  ],
  "route_resume": { "token": "u2Q8m0kXr4V…", "question_id": "Q-dee-48" }
}

The Advisor now needs a fact:

{
  "choices": [{ "index": 0, "finish_reason": "stop",
    "message": { "role": "assistant",
                 "content": "Before I answer, I need to know:\n- Is the credit for personal, family or household use, or for a business? (consumer, business)\n\n(ref: 8b04d1e6c2a9)" } }],
  "needs_input": {
    "reason": "slots",
    "token": "u2Q8m0kXr4V…",
    "question_id": "Q-dee-48",
    "candidates": [],
    "slots": [
      { "name": "credit_purpose", "type": "credit_purpose",
        "ask_text": "Is the credit for personal, family or household use, or for a business?",
        "required": true, "values": ["consumer", "business"] }
    ],
    "message": ""
  }
}

3. Fill the slot, implicitly. The person types their answer. The client just sends the history; the (ref: 8b04d1e6c2a9) in the last assistant message marks this as the reply:

{
  "messages": [
    { "role": "user", "content": "What notices do we owe when we decline someone?" },
    { "role": "assistant", "content": "Which of these do you mean?\n1. …\n2. …\nOr none of these.\n\n(ref: 3fa9c2d81b7e)" },
    { "role": "user", "content": "The first one." },
    { "role": "assistant", "content": "Before I answer, I need to know:\n- Is the credit for personal, family or household use, or for a business? (consumer, business)\n\n(ref: 8b04d1e6c2a9)" },
    { "role": "user", "content": "It's consumer credit." }
  ]
}

The explicit form works here too: "route_resume": {"token": "u2Q8m0kXr4V…", "slots": {"credit_purpose": "consumer"}}.

4. The answer. No needs_input. The content ends with a note saying which facts it used, then the sources:

{
  "choices": [{ "index": 0, "finish_reason": "stop",
    "message": { "role": "assistant",
                 "content": "You must send the applicant an adverse action notice within 30 days … (12 CFR 1002.9(a)(1)).\n\nThis answer is based on:\n- You told me: credit purpose: consumer.\n\nSources:\n- 12 CFR Part 1002 — Equal Credit Opportunity Act (Regulation B) — §1002.9 · source (https://www.ecfr.gov/…)" } }],
  "polaris": { "citations": [ … ], "confidence": 0.82,
               "guardrail": { "status": "pass", "rule_id": null, "message": null },
               "brain_version": "147676ad69c2…" }
}

The note lists what the person told the Advisor, defaults it assumed ("Assumed, because it wasn't known: …"), and facts it hedged over ("Not known, so the answer covers each case: …"). Facts the question itself stated need no note.

If the person types a new question instead of answering, the Advisor drops the follow-up and answers the new question. If a follow-up has expired, the Advisor says so and asks the person to ask again.

Request errors

Errors about the request use the OpenAI error format:

HTTP type When
400 invalid_request_error The body isn't valid, there is no user message, response_format is json_schema, or route_resume is malformed ("param": "route_resume").
403 permission_error (code: openrouter_key_required) The brain has no OpenRouter key of its own.
502 server_error The Advisor failed while answering. Retry.

Structured metadata

The Advisor grounds and cite-then-verifies every answer, so each response carries more than text. That metadata is exposed two ways:

1. The polaris object (always present)

Every chat.completion (and the final streaming chat.completion.chunk) includes a top-level polaris object. Standard OpenAI clients ignore the unknown field; metadata-aware clients and agents read the grounded citations:

{
  "id": "chatcmpl-…",
  "object": "chat.completion",
  "choices": [{ "index": 0, "message": {"role": "assistant", "content": "…answer…"}, "finish_reason": "stop" }],
  "usage": { "prompt_tokens": 812, "completion_tokens": 143, "total_tokens": 955 },
  "polaris": {
    "citations": [
      {
        "source_id": "12 CFR Part 1026 — Truth in Lending (Regulation Z)",
        "kind": "passage",
        "quote": "(1) Act means the Truth in Lending Act (15 U.S.C. 1601 et seq.).",
        "locator": "§1026.2",
        "score": 0.71,
        "verified": true,
        "verification": { "method": "entailment", "score": 1.0 },
        "provenance": {
          "source_doc_pk": 48,
          "doc_title": "12 CFR Part 1026 — Truth in Lending (Regulation Z)",
          "origin_url": "https://www.ecfr.gov/current/title-12/chapter-X/part-1026",
          "jurisdiction": "US-FED"
        },
        "wiki": [
          { "entity": "Regulation Z", "ref": "/v1/brains/calliope/wiki/Regulation%20Z" }
        ],
        "concept_refs": ["Regulation Z", "Truth in Lending Act"]
      }
    ],
    "confidence": 0.82,
    "guardrail": { "status": "pass", "rule_id": null, "message": null },
    "brain_version": "a1b2c3d…"
  }
}

Each citation is a navigable entry point back into the knowledge base:

Field Meaning
source_id, quote, locator The cited source and its verbatim supporting span (the entailing sentence, not a prefix).
kind passage (verbatim source chunk — strongest) or entity (graph/entity summary — contextual).
score Retrieval relevance of the source (0–1).
verified / verification verification.method is entailment (LLM judge) / lexical / lexical_fallback (judge errored → unconfirmed) / unverified, with a score.
provenance Hard provenance — source_doc_pk + origin_url (the source document's root URL) + jurisdiction, to deep-link the evidence.
wiki Deep links into the published Wiki (Reader) for each cited concept: GET /v1/brains/{brain_id}/wiki/{entity}.
concept_refs Entity names for graph traversal from the answer into the knowledge base.

In streaming, the polaris object rides the final finish_reason: "stop" chunk.

2. response_format: {"type": "json_object"}

Send this and the message content itself becomes the full envelope as a JSON string — handy when your client wants one structured payload instead of text + a side channel:

// choices[0].message.content (stringified):
{ "answer": "…", "citations": [ … ], "confidence": 0.82, "guardrail": { … }, "brain_version": "a1b2c3d…" }

response_format: {"type": "json_schema", …} is not supported (HTTP 400): the Advisor's output schema is fixed (grounded envelope) and cannot be coerced to an arbitrary caller-defined schema — forcing one would bypass grounding and verification.

Usage

usage reports real token counts, summed from the metered LLM calls behind the answer. For streaming, send stream_options: {"include_usage": true} to receive a final usage-only chunk. (When metering is disabled for the brain, usage is zeros.)

Using it from tickle-tui

In tickle-tui's providers.yaml:

polaris-calliope:
  name: "Polaris — Calliope"
  base_url: "http://localhost:8088/v1/brains/calliope"
  is_openai_compatible: true
  api_key_env: "POLARIS_API_KEY"     # env var holding the minted sk-polaris-… key
  models:
    - id: "polaris-advisor"          # cosmetic
      name: "Polaris Advisor"

Then export POLARIS_API_KEY=sk-polaris-… and run the TUI. The TUI always streams, which this endpoint supports.

Quick check with curl

curl -N http://localhost:8088/v1/brains/calliope/chat/completions \
  -H "Authorization: Bearer $POLARIS_API_KEY" -H "Content-Type: application/json" \
  -d '{"model":"polaris-advisor","stream":true,
       "messages":[{"role":"user","content":"Do I need a CA lender license?"}]}'

Verify end-to-end (no dependencies)

cookbooks/verify_completions.py (in the repo) is a standard-library-only script (runs as-is on Windows and Linux, any Python 3.8+) that discovers your brain via /v1/me, runs a real grounded answer, and prints the citations — mapping every auth error to a one-line "what to do next":

python cookbooks/verify_completions.py \
  --base-url https://<tenant-host> \
  --key-file ~/.secrets/my-key
# or: --key sk-polaris-…   |   or set POLARIS_API_KEY
# pass --brain-id <brain> to skip discovery; --json for the structured envelope.

Limits (current)

Single answer verb only; brain-scoped path only (no model→brain mapping); no /v1/models, embeddings, or tools/function-calling; response_format supports json_object but not json_schema (fixed output schema). Streaming is pseudo-streaming — the full grounded answer is computed (cite-then-verify needs the whole answer), then emitted as deltas.