PlatformXeDocs
Get API Key

AI

SDK methods for the AI & Vision gateway — chat completion (with tool calling), native Claude messages, server-side platform tools, structured extraction, knowledge retrieval, your AI profile and usage.

The client.ai namespace reaches the PlatformXe AI gateway (Gemini, Grok and Claude through Vercel AI Gateway, every request under zero data retention). Every call runs under the AI profile for (your API key's caller service, featureKey) — PlatformXe owns the profile's policy, provider and model allow-lists, size limits and daily caps; your app owns its prompts. See Product AI & Vision for how profiles, limits and quotas work. Available in TypeScript, Python, and Go SDKs.

SDKInstallNamespace
TypeScriptnpm install @caldera/platformxe-sdk (1.8.0+; messages and aiTools from 1.20.0)client.ai, client.aiTools
Pythonpip install platformxe (1.7.0+; messages and ai_tools from 1.16.0)client.ai, client.ai_tools, client.knowledge
Gogo get github.com/calderaxe/platformxe-go@v1.7.1 (Messages and AiTools from v1.16.0)client.Ai, client.AiTools, client.Knowledge

The TypeScript client.knowledge namespace and tool-calling fields ship with the next TypeScript SDK release (types 3.6.0).

The ai.* methods require the ai:complete scope and share the 600 requests/hr per-key rate tier; the knowledge.* methods require ai:knowledge (1,200 requests/hr per key); aiTools.list requires tools:platform.read (the default 1,000 requests/hr per key).

Chat completion

Run one chat turn. provider is gemini, grok or claude (claude from types 3.7.0); model optionally overrides the profile default and must be on both allow-lists. A caller that should not choose a provider itself can read allowedProviders from its profile (client.ai.profile) and send the first one — the xAdmin document converter does. A profile allowing more than 4,096 output tokens gets a 120 s gateway timeout instead of 55 s.

const reply = await client.ai.complete({
  featureKey: 'guest-concierge',
  provider: 'gemini',
  messages: [
    { role: 'system', content: 'You are the concierge for 12 Admiralty Way.' },
    { role: 'user', content: 'What time is check-out?' },
  ],
});

console.log(reply.content);           // "Check-out is at 11:00."
console.log(reply.model);             // "google/gemini-2.5-flash"
console.log(reply.usage?.totalTokens);
reply = client.ai.complete(
    feature_key="guest-concierge",
    provider="gemini",
    messages=[
        {"role": "system", "content": "You are the concierge for 12 Admiralty Way."},
        {"role": "user", "content": "What time is check-out?"},
    ],
)
print(reply["content"])
reply, err := client.Ai.Complete(platformxe.AiCompleteInput{
    FeatureKey: "guest-concierge",
    Provider:   "gemini",
    Messages: []platformxe.AiMessage{
        {Role: "system", Content: "You are the concierge for 12 Admiralty Way."},
        {Role: "user", Content: "What time is check-out?"},
    },
})
fmt.Println(reply.Content)

Structured extraction

Send prompts (and up to 4 images, when the profile allows images) and get a JSON object back, validated against your JSON Schema. modelTier is FAST or PREMIUM; temperature is 0–2 (default 0.2).

const result = await client.ai.extract({
  featureKey: 'document.freeform',
  systemPrompt: 'Extract the invoice fields.',
  userPrompt: invoiceText,
  images: [{ url: 'https://cdn.example.com/invoice.jpg' }],
  outputJsonSchema: {
    type: 'object',
    properties: { invoiceNumber: { type: 'string' }, total: { type: 'number' } },
    required: ['invoiceNumber', 'total'],
  },
  modelTier: 'FAST',
});

console.log(result.data.total);
result = client.ai.extract(
    feature_key="document.freeform",
    system_prompt="Extract the invoice fields.",
    user_prompt=invoice_text,
    images=[{"url": "https://cdn.example.com/invoice.jpg"}],
    output_json_schema={
        "type": "object",
        "properties": {"invoiceNumber": {"type": "string"}, "total": {"type": "number"}},
        "required": ["invoiceNumber", "total"],
    },
    model_tier="FAST",
)
print(result["data"]["total"])
temperature := 0.0
result, err := client.Ai.Extract(platformxe.AiExtractInput{
    FeatureKey:   "document.freeform",
    SystemPrompt: "Extract the invoice fields.",
    UserPrompt:   invoiceText,
    Images:       []platformxe.AiImageInput{{URL: "https://cdn.example.com/invoice.jpg"}},
    OutputJSONSchema: map[string]interface{}{
        "type":     "object",
        "required": []string{"invoiceNumber", "total"},
    },
    ModelTier:   "FAST",
    Temperature: &temperature, // a pointer, so 0 is sent
})
fmt.Println(result.Data["total"])

If the model answers in a shape that does not match outputJsonSchema, the call fails with 422 AI_OUTPUT_INVALID and error.details.path — the JSON Pointer of the first failing value. Read it from err.details.path (TypeScript), err.details["path"] (Python) or apiErr.Details["path"] (Go).

Tool calling

When your profile allows tools (allowTools), complete can offer the model up to 16 function tools. PlatformXe passes the tools through and returns the model's tool calls — it never executes a tool. Your app runs each call through its own permission-checked code, then sends the result back in the next turn: the assistant message carrying toolCalls, followed by one role: "tool" message per call with its toolCallId. A profile without allowTools refuses tools (and tool messages) with 400 BAD_REQUEST "tools not enabled for this feature".

  • tools[]: name (1–64 of A-Z a-z 0-9 _ . -, unique), optional description (≤ 1,024 characters), optional parameters (a JSON Schema object — a schema that does not compile is a 400).
  • toolChoice: "auto" (default), "none", "required", or { name } to force one tool.
  • The result adds toolCalls ([{ id, name, arguments }], arguments a JSON string) and finishReason (stop, length, tool_calls, content_filter, other); content is "" when the model only called tools.
  • Safety applies to tool traffic too: input screening and PII redaction cover tool results and earlier call arguments, and output screening covers every returned call's arguments.
const turn = await client.ai.complete({
  featureKey: 'ai-canvas',
  provider: 'gemini',
  messages: [{ role: 'user', content: 'How many leave days does Ada have left?' }],
  tools: [{
    name: 'hr.leave_balance',
    description: 'Remaining annual leave days for one employee.',
    parameters: { type: 'object', properties: { employeeRef: { type: 'string' } }, required: ['employeeRef'] },
  }],
});

if (turn.finishReason === 'tool_calls') {
  // Run each call yourself — permission checks and audit are yours.
  const results = await Promise.all(turn.toolCalls!.map(runToolWithPermissions));
  const answer = await client.ai.complete({
    featureKey: 'ai-canvas',
    provider: 'gemini',
    tools,
    messages: [
      ...previous,
      { role: 'assistant', content: '', toolCalls: turn.toolCalls },
      ...results.map((r) => ({ role: 'tool' as const, toolCallId: r.id, content: JSON.stringify(r.data) })),
    ],
  });
}
turn = client.ai.complete(
    feature_key="ai-canvas",
    provider="gemini",
    messages=[{"role": "user", "content": "How many leave days does Ada have left?"}],
    tools=[{"name": "hr.leave_balance", "parameters": {"type": "object", "properties": {"employeeRef": {"type": "string"}}}}],
    tool_choice="auto",
)
for call in turn.get("toolCalls", []):
    ...  # run it, then send {"role": "tool", "toolCallId": call["id"], "content": ...}
turn, err := client.Ai.Complete(platformxe.AiCompleteInput{
    FeatureKey: "ai-canvas",
    Provider:   "gemini",
    Messages:   []platformxe.AiMessage{{Role: "user", Content: "How many leave days does Ada have left?"}},
    Tools:      []platformxe.AiToolDefinition{{Name: "hr.leave_balance"}},
    ToolChoice: "auto",
})
// turn.ToolCalls, turn.FinishReason

Native Claude messages

ai.messages (POST /api/v1/ai/messages) takes the Anthropic Messages request shape on the Claude 5.5 models (claude-haiku-5-5, claude-sonnet-5-5, claude-opus-5-5, as your profile allows), for an app already written against that shape. It is governed by your AI profile exactly as complete: allow-lists and limits, PII redaction before the model and restore after, input safety, daily caps and spend budgets before the call, and output screening. Scope ai:complete, the same 600 requests/hr tier.

  • featureKey (required; no sourceApp alias) and messages (the first and the last are the user's; content is a string or content blocks).
  • system: a string or text blocks. effort: low to max, capped by the profile's maxEffort (absent: maxEffort).
  • outputSchema: structured output, when the profile's allowStructuredOutput is on. The schema needs an object root, and every object node needs additionalProperties: false (required is optional). Accepted: pattern, minProperties / maxProperties, minItems 0 or 1, and format one of date-time, time, date, duration, email, hostname, uri, ipv4, ipv6, uuid. Refused with 400 naming the keyword: numeric bounds (minimum, maximum, exclusiveMinimum, exclusiveMaximum, multipleOf), string lengths (minLength, maxLength), maxItems, uniqueItems, minContains / maxContains, minItems above 1, and any other format. The request limits also apply: at most 24 optional parameters and 16 union-type parameters (anyOf or a type array) across the schema and any strict tools.
  • tools: your own tools (name, description, input_schema), when the profile's allowTools is on. The model's tool_use blocks come back for you to run. toolChoice is auto or none; forcing a tool is refused (400). With toolsets, toolChoice must be auto or left out (400 otherwise).
  • toolsets: PlatformXe's own read-only tools (see Server-side tools).
  • maxTokens: at most the profile's maxTokens.

The reply is { message: { id, role, content, stop_reason, stop_details }, model, usage, toolRuns? }. usage adds cacheReadTokens and cacheWriteTokens; model is the model that answered. Pass thinking blocks back unchanged in the next turn. After a server-side fallback (a declined request answered by another model), content starts at the last fallback block, that block included, so the declining model's partial output never reaches you; send the turn back as returned. A fallback block's trigger you send back is at most 512 characters as JSON (400 otherwise), and only its type (a short lowercase code) and category (at most 64 characters, or null) are kept. There is no streaming, and one call has a 120 s deadline. A model refusal is never a result field: it is 422 AI_REFUSED, no content is returned, and the call is billed.

const reply = await client.ai.messages({
  featureKey: 'ops-assistant',
  model: 'claude-sonnet-5-5',
  system: 'Answer in two sentences.',
  messages: [{ role: 'user', content: 'Summarise this incident note: ...' }],
  effort: 'medium',
});
for (const block of reply.message.content) if (block.type === 'text') console.log(block.text);
reply = client.ai.messages(
    feature_key="ops-assistant",
    model="claude-sonnet-5-5",
    system="Answer in two sentences.",
    messages=[{"role": "user", "content": "Summarise this incident note: ..."}],
    effort="medium",
)
text = "".join(b["text"] for b in reply["message"]["content"] if b["type"] == "text")
reply, err := client.Ai.Messages(platformxe.AiMessagesInput{
    FeatureKey: "ops-assistant",
    Model:      "claude-sonnet-5-5",
    System:     "Answer in two sentences.",
    Messages:   []platformxe.AiNativeMessage{{Role: "user", Content: "Summarise this incident note: ..."}},
    Effort:     "medium",
})

Server-side tools

With toolsets (today one toolset, platform.read), PlatformXe runs its own read-only platform tools for the model in a bounded loop: your webhooks and their deliveries, the event log, the messaging log (metadata, never message bodies or SMS / WhatsApp text), issues and usage, of your own organisation only. It works on ai.messages, and on ai.complete with a Claude 5.5 model (there the gateway slug, e.g. anthropic/claude-sonnet-5.5; ai.messages takes the Anthropic id, e.g. claude-sonnet-5-5); not together with your own tools (400), and toolChoice must be auto or left out (400 otherwise).

  • Every toolset must be on the AI profile (toolsets), and your key needs the tools:platform.read scope; otherwise 403 AI_TOOLSET_DENIED. A platform key, and an end-user-facing profile, get no platform tools.
  • A tool is refused when it would carry a data class the profile does not allow (allowedDataClasses). Its result is returned to the model as data, wrapped and checked, and personal data in it is always redacted before the model sees it. On a profile without PII redaction the reply keeps those placeholders (‹EMAIL_1› …); one sent back in a later request is never resolved again.
  • The loop runs at most the profile's maxToolTurns turns within 120 s: past that, 422 AI_LOOP_LIMIT with details.reason TURNS, CALLS or DEADLINE. A tool that fails, times out or is denied goes back to the model as an error result (and is listed in toolRuns); 502 AI_TOOL_FAILED means the tool round trip itself broke, and stops the request.
  • The answer's toolRuns lists every tool call: toolName, toolVersion, status (OK, DENIED, FAILED, TIMEOUT), denyReason (TENANT, SCOPE, TOOLSET, DATA_CLASS, PERMISSION, BUDGET, SPOKE), isError, latencyMs, outputBytes. Never the tool's input or output.
  • The whole loop is metered on one usage row, kind complete_with_tools (or messages).

aiTools.list (GET /api/v1/ai/tools, scope tools:platform.read) answers the tools your key may use: name, version, description, the full inputSchema, dataClasses, toolset, sourceApp (platformx, or the Caldera app that serves the tool) and requiredPermission (or null). No profile is read there, so a profile can narrow the list at call time.

Acting for a person (actor)

Caldera's own apps can offer their own read-only tools to their own features (for example ErrandOne's desk tools, toolset concierge.desk-read, scope tools:concierge.read). Such a tool runs only for the app's own key, and only for a person: pass actor on ai.messages.

  • ref: the person's id in your app, 1 to 64 of A-Z a-z 0-9 _ - (recorded on the tool call, never a name).
  • permissions: at most 32 canonical permission keys with an app prefix (for example CN:REQUESTS:VIEW). A tool is offered to the model only when the list holds its requiredPermission; the app checks the person again on every call.
  • grant: optional, at most 4,096 base64url characters, opaque to PlatformXe: forwarded only to the tool's own app, never stored, logged, returned or sent to the model.

Any other field or a value outside these limits is 400 BAD_REQUEST naming the field. Without actor, no such tool is offered. A refusal by the app comes back to the model as an error result with denyReason SPOKE.

Caldera's operator console (actors)

Caldera's own operator console (xAdmin's AI Canvas) calls with a platform key and can use each Caldera app's read tools (Lettings, ErrandOne, Chats and xAdmin's own) for the person signed in, and only what that person may see in each app. It sends actors instead of actor: one entry per app (xadmin, lettings, concierge, chats), each with that app's ref, at most 64 permissions carrying that app's prefix (XA:, LT:, CN:, CH:) and that app's own grant (required). Each entry is forwarded only to its own app's tools.

  • actor and actors cannot be combined (400). actors from an organisation key, and actor from a platform key, are 400.
  • Only Caldera's operator console key may use actors; any other platform key gets no app tool (denyReason TENANT).

Tools unavailable: fall back only on SOURCE_UNAVAILABLE. When none of the requested toolsets has a tool open to your key and actor, the request answers 403 AI_TOOLSET_DENIED before any model call (nothing is spent), and error.details.reason says why:

details.reasonMeaningWhat to do
SOURCE_UNAVAILABLEThe app's tools are not there: switched off by Caldera, or not readable on that instance (a switch-off reaches every instance within 60 s)Treat it, like 503 AI_NOT_CONFIGURED, as "tools unavailable": fall back to a path without tools
DATA_CLASSEvery tool was refused by the AI profile's allowed data classesDo not fall back: the profile says this data may not reach the model
NOT_ALLOWEDThe toolset is not on the profile, or your key or actor may use none of its toolsDo not fall back: fix the key, the profile or the actor

When you request several toolsets and any one of them still has a usable tool, the request is not refused: it runs, and is billed, with the tools that are there. 502 AI_TOOL_FAILED comes after the model was called and is billed; do not fall back on it.

const reply = await client.ai.messages({
  featureKey: 'desk-brief',
  messages: [{ role: 'user', content: JSON.stringify({ subject: { kind: 'ISSUE', id: 'iss_1' } }) }],
  toolsets: ['concierge.desk-read'],
  actor: { ref: 'adm_123', permissions: ['CN:ISSUES:VIEW', 'CN:REQUESTS:VIEW'], grant },
});
reply = client.ai.messages(
    feature_key="desk-brief",
    messages=[{"role": "user", "content": '{"subject":{"kind":"ISSUE","id":"iss_1"}}'}],
    toolsets=["concierge.desk-read"],
    actor={"ref": "adm_123", "permissions": ["CN:ISSUES:VIEW", "CN:REQUESTS:VIEW"], "grant": grant},
)
reply, err := client.Ai.Messages(platformxe.AiMessagesInput{
    FeatureKey: "desk-brief",
    Messages:   []platformxe.AiNativeMessage{{Role: "user", Content: `{"subject":{"kind":"ISSUE","id":"iss_1"}}`}},
    Toolsets:   []string{"concierge.desk-read"},
    Actor:      &platformxe.AiToolActor{Ref: "adm_123", Permissions: []string{"CN:ISSUES:VIEW", "CN:REQUESTS:VIEW"}, Grant: grant},
})
const { items } = await client.aiTools.list();
const reply = await client.ai.messages({
  featureKey: 'ops-assistant',
  messages: [{ role: 'user', content: 'How many webhook deliveries failed today?' }],
  toolsets: ['platform.read'],
});
console.log(reply.toolRuns?.map((r) => `${r.toolName}: ${r.status}`));
tools = client.ai_tools.list()
# ai.complete takes the gateway slug ("anthropic/claude-sonnet-5.5");
# ai.messages takes the Anthropic id ("claude-sonnet-5-5").
reply = client.ai.complete(
    feature_key="ops-assistant", provider="claude", model="anthropic/claude-sonnet-5.5",
    messages=[{"role": "user", "content": "Summarise the open issues."}],
    toolsets=["platform.read"],
)
print(reply.get("toolRuns"))
tools, err := client.AiTools.List()
reply, err := client.Ai.Messages(platformxe.AiMessagesInput{
    FeatureKey: "ops-assistant",
    Messages:   []platformxe.AiNativeMessage{{Role: "user", Content: "How many webhook deliveries failed today?"}},
    Toolsets:   []string{"platform.read"},
})
// reply.ToolRuns

Knowledge retrieval

The client.knowledge namespace indexes your documents into PlatformXe and searches them, so answers can cite your own data. It uses its own scope, ai:knowledge (1,200 requests/hr per key). Documents belong to your API key's caller service; another service never sees them.

MethodRoute
knowledge.upsertDocument / upsert_document / UpsertDocumentPUT /api/v1/ai/knowledge/documents
knowledge.deleteDocument / delete_document / DeleteDocumentDELETE /api/v1/ai/knowledge/documents?collection=&sourceRef=
knowledge.listDocuments / list_documents / ListDocumentsGET /api/v1/ai/knowledge/documents?collection=&cursor=&limit=
knowledge.search / search / SearchPOST /api/v1/ai/knowledge/search

Indexing. upsertDocument takes featureKey (the AI profile the embedding spend is metered against), collection, your own sourceRef, title, optional url and acl, and text (markdown or plain, ≤ 400,000 characters). The text is chunked by heading (~800 tokens, 100-token overlap, code fences never split); a re-upsert with the same text changes metadata only (changed: false). A document records your API key's organisation. Until the contract migration that keys documents by organisation alone, a collection + sourceRef is unique per caller service: a document indexed before documents recorded an organisation is taken over by the first organisation key that writes it, and one held by another organisation is refused with 409 CONFLICT. After that migration each organisation holds its own document for the same collection + sourceRef. pendingEmbeddings counts chunks still waiting for an embedding — search works lexically meanwhile.

Text is stored as you send it. PlatformXe applies no PII redaction at index time — never index Tier-1 / Tier-2 personal data. Documents live until you delete them; when a source is removed on your side, call deleteDocument. listDocuments (compare contentHash) lets you reconcile.

ACLs. acl is a list of opaque tags you own (for example role:hr). A search sees a document when its aclTags hold any of the document's tags; a document with no tags is visible to every search of your service.

Search. Postgres full-text and trigram matching pick the candidates; when embeddings are available the query is embedded and cosine similarity is fused with the lexical ranks (reciprocal rank fusion) — mode: "hybrid", otherwise "lexical". Each hit carries sourceRef, ordinal and heading for citations. The query is screened like any AI input (403 AI_POLICY_DENIED).

await client.knowledge.upsertDocument({
  featureKey: 'ai-canvas',
  collection: 'hr-policies',
  sourceRef: 'policy/annual-leave',
  title: 'Annual leave policy',
  acl: ['role:hr'],
  text: '# Annual leave\n\nEvery full-time employee earns 20 working days a year.',
});

const { mode, hits } = await client.knowledge.search({
  featureKey: 'ai-canvas',
  collections: ['hr-policies'],
  query: 'how many days of annual leave do I get',
  aclTags: ['role:hr'],
  k: 5,
});
hits.forEach((h) => console.log(`${h.title} [${h.sourceRef}#${h.ordinal}]`, h.text));
client.knowledge.upsert_document(
    feature_key="ai-canvas", collection="hr-policies", source_ref="policy/annual-leave",
    title="Annual leave policy", text="# Annual leave\n\n20 working days a year.", acl=["role:hr"],
)
result = client.knowledge.search(
    feature_key="ai-canvas", collections=["hr-policies"], query="annual leave", acl_tags=["role:hr"], k=5,
)
page = client.knowledge.list_documents("hr-policies")          # {items, nextCursor}
client.knowledge.delete_document("hr-policies", "policy/annual-leave")
_, err := client.Knowledge.UpsertDocument(platformxe.KnowledgeUpsertDocumentInput{
    FeatureKey: "ai-canvas", Collection: "hr-policies", SourceRef: "policy/annual-leave",
    Title: "Annual leave policy", ACL: []string{"role:hr"}, Text: "# Annual leave\n\n20 working days a year.",
})
res, err := client.Knowledge.Search(platformxe.KnowledgeSearchInput{
    FeatureKey: "ai-canvas", Collections: []string{"hr-policies"}, Query: "annual leave", ACLTags: []string{"role:hr"}, K: 5,
})

Your AI profile

Read the calling service's own profile for one feature: status, allow-lists, limits and today's (UTC) usage. The policy text is withheld. From types 3.18.0 the view also carries the governance fields: maxEffort, allowCaching, allowStructuredOutput, fallbackModel, toolsets, maxToolTurns, endUserFacing, allowedDataClasses and strictIdRedaction.

const profile = await client.ai.profile('guest-concierge');
console.log(profile.status, profile.dailyTokenCap, profile.usedTokensToday, profile.resetsAt);
profile = client.ai.profile("guest-concierge")
profile, err := client.Ai.Profile("guest-concierge")

Usage

The calling service's own AI and vision usage, grouped by feature, kind (ai / vision / embedding / messages / complete_with_tools), provider and model. from / to are ISO-8601 — default the last 30 days, at most 92 days.

const usage = await client.ai.usage({ from: '2026-09-01T00:00:00Z', featureKey: 'guest-concierge' });
console.log(usage.totals.requests, usage.totals.costCredits);
usage = client.ai.usage(from_="2026-09-01T00:00:00Z", feature_key="guest-concierge")
usage, err := client.Ai.Usage(platformxe.AiUsageQuery{From: "2026-09-01T00:00:00Z", FeatureKey: "guest-concierge"})

Errors

CodeStatusMeaning
BAD_REQUEST400Malformed body, or a profile / hard limit breached
AI_PROFILE_NOT_FOUND403No profile for your caller service + featureKey
AI_PROFILE_DISABLED403The profile is switched off
AI_POLICY_DENIED403The input was refused by the safety screen
CONFLICT409knowledge.upsertDocument only: the collection + sourceRef is held by another organisation under your caller service; use a different sourceRef (retrying does not fix it, and no SDK retries it). Until the contract migration that keys documents by organisation alone. Go: px.ErrCodeConflict
AI_OUTPUT_BLOCKED422The model reply was refused by output screening
AI_OUTPUT_INVALID422extract only — off-schema reply (details.path)
AI_QUOTA_EXCEEDED429The profile's daily cap is reached — Retry-After runs to the next UTC midnight
AI_BUDGET_EXCEEDED429A spend budget of your organisation or caller service (UTC day or month) is spent — Retry-After runs to the period's end; details.period. details.reason is BUDGET_UNAVAILABLE (and Retry-After 60) when a hard budget could not be checked; a tool loop stopped by its budget between model calls answers details = { retryAfterSeconds: 60 } with no period. Concurrent requests can pass a hard budget by at most one model call each. Also on vision
AI_TOOLSET_DENIED403No tool of the requested toolsets can be offered. Answered before any model call (nothing spent); details.reason is SOURCE_UNAVAILABLE (a first-party app's tools are switched off or unreadable: fall back to a path without tools), DATA_CLASS (refused by the profile's data classes) or NOT_ALLOWED (not on the profile, or your key or actor may use none of its tools). Fall back only on SOURCE_UNAVAILABLE
AI_REFUSED422The model declined and no fallback answered. No content; the call is billed; details.category
AI_LOOP_LIMIT422The tool loop hit the profile's turn or call cap, or its time budget; details.reason
AI_UPSTREAM_ERROR502The model provider failed or timed out
AI_TOOL_FAILED502The server-side tool round trip itself broke; the request was stopped (a tool's own failure goes back to the model as an error result)
AI_NOT_CONFIGURED503The gateway is not configured on that deployment (key missing or rejected), or, for a Claude 5.5 model, the native route is off
AI_MODEL_UNAVAILABLE503The gateway account cannot use the requested model — paid gateway credits are required. The message is fixed ("The AI service account cannot use this model right now.") and details.model names the model; retrying does not fix it
SERVER_ERROR500Unexpected failure

AI_BUDGET_EXCEEDED and AI_TOOL_FAILED are never retried by the SDKs either (TypeScript 1.20.0, Python 1.16.0, Go v1.16.0); ai.complete, ai.extract and ai.messages are model calls the Python and Go SDKs send once. AI_QUOTA_EXCEEDED is never retried by the SDKs: in TypeScript it is a RateLimitError whose code is AI_QUOTA_EXCEEDED and whose retryAfter is the seconds to midnight; Python sets err.retry_after; Go sets apiErr.RetryAfter. A per-key 429 RATE_LIMITED is still retried by the TypeScript and Go clients.

Scopes required

MethodScopeRate limit
ai.complete()ai:complete600/hr
ai.extract()ai:complete600/hr
ai.profile()ai:complete600/hr
ai.usage()ai:complete600/hr
ai.messages()ai:complete (+ tools:platform.read with toolsets)600/hr
aiTools.list()tools:platform.read1,000/hr
knowledge.upsertDocument() / deleteDocument() / listDocuments() / search()ai:knowledge1,200/hr