API Reference

Inference

OpenAI-compatible inference on the AI gateway, authenticated with a virtual-key JWT.

Inference

The Token Factory AI gateway exposes OpenAI-compatible inference endpoints. Call them on the AI gateway host (not the tenant host) with the virtual-key JWT issued by the Keys API, sent as Authorization: Bearer <virtual-key-jwt> (also accepted as x-bf-vk or x-api-key). Errors use the envelope described under Error response.

Supported endpoints

OpenAI endpointSupportedNotes
GET /v1/modelsYes
POST /v1/chat/completionsYesStreaming supported. See Chat completions
POST /v1/completionsYes
POST /v1/responsesYes
POST /v1/embeddingsYes
POST /v1/images/generationsYes
POST /v1/videos (generate)PartialPath is POST /v1/videos/generations, plus POST /v1/videos/generations/stream
GET /v1/videos/{id} (retrieve)PartialPath is GET /v1/videos/generations/{id}
GET /v1/videos/{id}/content (download)PartialPath is GET /v1/videos/generations/{id}/content

Partial means the endpoint is available, but on a different path from the OpenAI one. Point your client at the gateway path shown in Notes.

Chat completions

Chat completions use the same host and virtual-key JWT as the other inference endpoints. The tenant token does not authenticate this call.

MethodPOST
Path/v1/chat/completions
AuthAuthorization: Bearer <virtual-key-jwt> (also x-bf-vk / x-api-key)
Content-Typeapplication/json

Example request

curl -s "https://YOUR_GATEWAY_URL/v1/chat/completions" \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer YOUR_VIRTUAL_KEY_JWT" \
  -d '{
    "model": "openai/gpt-4o-mini",
    "messages": [
      {"role": "system", "content": "You are a helpful assistant."},
      {"role": "user", "content": "Hello"}
    ],
    "stream": false,
    "temperature": 0.7,
    "max_completion_tokens": 256
  }'

Required fields

FieldTypeDescription
modelstringModel id. Prefer provider/model (for example openai/gpt-4o-mini). If the provider prefix is omitted, the gateway resolves a provider from the model catalog when possible
messagesarrayConversation turns. Each item needs a role (system, user, assistant, tool, or developer)

Common optional fields

FieldTypeDescription
streambooleanWhen true, the response is Server-Sent Events (text/event-stream)
temperaturenumberSampling temperature (0–2)
top_pnumberNucleus sampling (0–1)
max_completion_tokensintegerMax tokens to generate. Legacy max_tokens is mapped to this field
stopstring or string arrayUp to 4 stop sequences
tools / tool_choiceobjectFunction/tool calling (OpenAI-compatible)
response_formatobjectStructured output / JSON mode when supported by the model
fallbacksstring arrayFallback models in provider/model form
external_idstringOptional client correlation id. When set, it becomes the request id used for billing correlation (InferenceUsage.externalTransactionId)
stream_options.include_usagebooleanInclude a final usage chunk when streaming
userstringEnd-user identifier forwarded where supported

Success response

Non-streaming responses use Content-Type: application/json and object: "chat.completion".

{
  "id": "chatcmpl-...",
  "object": "chat.completion",
  "created": 1710000000,
  "model": "gpt-4o-mini",
  "system_fingerprint": "",
  "choices": [
    {
      "index": 0,
      "finish_reason": "stop",
      "message": {
        "role": "assistant",
        "content": "Hello! How can I help you today?"
      }
    }
  ],
  "usage": {
    "prompt_tokens": 18,
    "completion_tokens": 10,
    "total_tokens": 28,
    "cost": {
      "input_tokens_cost": 0.000003,
      "output_tokens_cost": 0.000006,
      "total_cost": 0.000009
    }
  },
  "extra_fields": {
    "request_type": "chat_completion",
    "provider": "openai",
    "original_model_requested": "openai/gpt-4o-mini",
    "resolved_model_used": "gpt-4o-mini",
    "latency": 412,
    "chunk_index": 0
  }
}

Top-level fields

FieldTypeDescription
idstringCompletion id
objectstringAlways chat.completion for non-streaming
createdintegerUnix timestamp (seconds)
modelstringModel returned by the provider / gateway
system_fingerprintstringProvider fingerprint when available
service_tierstringOptional service tier (auto, default, flex, priority, provisioned)
choicesarrayOne or more completion choices
usageobjectToken and cost accounting
extra_fieldsobjectGateway metadata (provider, latency, resolved model)
search_results / citations / videosarrayProvider-specific extras (for example Perplexity)

choices[]

FieldTypeDescription
indexintegerChoice index
finish_reasonstringWhy generation stopped: stop, length, tool_calls, or provider-specific values
messageobjectAssistant message (role, content, optional tool_calls, refusal, reasoning, annotations)
logprobsobjectPresent only when logprobs were requested
deltaobjectUsed only in streaming chunks (not in non-streaming responses)

usage

FieldTypeDescription
prompt_tokensintegerInput tokens (includes prompt-cache tokens when reported)
completion_tokensintegerOutput tokens
total_tokensintegerprompt_tokens + completion_tokens
prompt_tokens_detailsobjectOptional breakdown (text_tokens, cached_read_tokens, cached_write_tokens, …)
completion_tokens_detailsobjectOptional breakdown (reasoning_tokens, audio_tokens, …)
costobjectGateway cost estimate when pricing is configured (input_tokens_cost, output_tokens_cost, total_cost, …)

extra_fields

FieldTypeDescription
request_typestringFor example chat_completion
providerstringProvider that served the request (openai, anthropic, bedrock, …)
original_model_requestedstringModel string from the client request
resolved_model_usedstringActual model id sent to the provider (after alias / routing resolution)
latencyintegerLatency in milliseconds
chunk_indexinteger0 for non-streaming; chunk ordinal when streaming
cache_debugobjectPresent when semantic cache debugging is enabled
raw_request / raw_responseobjectIncluded only when raw capture is enabled on the gateway

Streaming response

Set "stream": true. The gateway returns text/event-stream. Each event is a JSON chunk with object: "chat.completion.chunk". Content arrives in choices[].delta instead of choices[].message.

data: {"id":"chatcmpl-...","object":"chat.completion.chunk","created":1710000000,"model":"gpt-4o-mini","choices":[{"index":0,"delta":{"role":"assistant","content":"Hel"},"finish_reason":null}],"extra_fields":{...}}

data: {"id":"chatcmpl-...","object":"chat.completion.chunk","created":1710000000,"model":"gpt-4o-mini","choices":[{"index":0,"delta":{"content":"lo"},"finish_reason":null}],"extra_fields":{...}}

data: {"id":"chatcmpl-...","object":"chat.completion.chunk","created":1710000000,"model":"gpt-4o-mini","choices":[{"index":0,"delta":{},"finish_reason":"stop"}],"usage":{...},"extra_fields":{...}}

data: [DONE]

Stream delta fields

FieldTypeDescription
rolestringUsually present on the first chunk (assistant)
contentstringIncremental text
tool_callsarrayIncremental tool-call fragments
refusalstringRefusal text when applicable
reasoning / reasoning_detailsstring / arrayReasoning content when the model exposes it

If the stream fails before SSE headers are committed, the gateway returns a normal JSON error with the HTTP status code. Mid-stream failures are emitted as an SSE event:

data: {"error":{}}

Error response

All inference errors use the same JSON envelope, encoded as application/json (unless already mid-SSE).

{
  "event_id": null,
  "type": "budget_exceeded",
  "status_code": 402,
  "error": {
    "type": null,
    "code": null,
    "message": "Service-level budget exceeded: ...",
    "param": null,
    "event_id": null
  },
  "extra_fields": {
    "provider": "openai",
    "original_model_requested": "openai/gpt-4o-mini",
    "resolved_model_used": "gpt-4o-mini",
    "request_type": "chat_completion"
  }
}
FieldTypeDescription
typestringMachine-readable decision / error class when set by governance (for example budget_exceeded, rate_limited, virtual_key_not_found)
status_codeintegerHTTP status mirrored in the response
error.messagestringHuman-readable reason. Always present for handler-generated errors
error.type / error.code / error.paramstringOptional provider or validation detail
extra_fieldsobjectProvider / model / request-type context when available

HTTP status codes

StatusTypical type / causeExample error.message
400Invalid JSON, missing model/messages, billing metadata incompletemessages is required for chat completion, model is required, Model '…' is not mapped to a billing service
401Missing or unknown virtual keyvirtual key not found. The provided virtual key does not exist or has been revoked., virtual key is required. Authenticate with a tenant JWT that includes a virtualKey claim.
402budget_exceededService-level budget exceeded: …, User-level budget exceeded: …, Org-unit budget exceeded: …, Prepaid wallet check failed: …
403virtual_key_blocked, provider_blocked, model_blocked, MCP tool blockedVirtual key is inactive, Provider '…' is not allowed for this virtual key, Model '…' is not allowed for this virtual key
429rate_limited, token_limited, request_limitedProvider/model/VK/org rate-limit reasons
4xx / 5xx from providerUpstream provider failure (status forwarded when available)Provider error message in error.message
500Gateway / internal failureInternal error detail

Validation errors (400)

Returned before the provider call when the body cannot be prepared. Common messages:

  • invalid request format: …
  • model is required
  • messages is required for chat completion
  • provider is required in model field (format: provider/model) — no providers found for model "…" in model catalog to auto-resolve

Governance errors

Governance runs on every chat completion (unless the call is a metadata path that skips budgets).

DecisionHTTPtype
Virtual key missing / not found401virtual_key_required / virtual_key_not_found
Inactive VK, provider/model not allowed, MCP tool blocked403virtual_key_blocked / provider_blocked / model_blocked / mcp_tool_blocked
Rate / token / request limits429rate_limited / token_limited / request_limited
Spend / wallet budget exceeded402budget_exceeded
Incomplete billing identity400For example missing_service_id, account_ambiguous, wallet_insufficient, missing_account_external_id

Provider errors

When the upstream LLM returns an error, the gateway forwards the provider status (when known) and populates error.message from the provider payload. extra_fields.provider and the model fields identify which attempt failed. If fallbacks are configured and allowed, the gateway may retry another model before returning the final error to the client.