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 .
OpenAI endpoint Supported Notes GET /v1/modelsYes POST /v1/chat/completionsYes Streaming supported. See Chat completions POST /v1/completionsYes POST /v1/responsesYes POST /v1/embeddingsYes POST /v1/images/generationsYes POST /v1/videos (generate)Partial Path is POST /v1/videos/generations, plus POST /v1/videos/generations/stream GET /v1/videos/{id} (retrieve)Partial Path is GET /v1/videos/generations/{id} GET /v1/videos/{id}/content (download)Partial Path 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 use the same host and virtual-key JWT as the other inference endpoints. The tenant token does not authenticate this call.
Method POSTPath /v1/chat/completionsAuth Authorization: Bearer <virtual-key-jwt> (also x-bf-vk / x-api-key)Content-Type application/json
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
}'
Field Type Description modelstring Model 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 messagesarray Conversation turns. Each item needs a role (system, user, assistant, tool, or developer)
Field Type Description streamboolean When true, the response is Server-Sent Events (text/event-stream) temperaturenumber Sampling temperature (0–2) top_pnumber Nucleus sampling (0–1) max_completion_tokensinteger Max tokens to generate. Legacy max_tokens is mapped to this field stopstring or string array Up to 4 stop sequences tools / tool_choiceobject Function/tool calling (OpenAI-compatible) response_formatobject Structured output / JSON mode when supported by the model fallbacksstring array Fallback models in provider/model form external_idstring Optional client correlation id. When set, it becomes the request id used for billing correlation (InferenceUsage.externalTransactionId) stream_options.include_usageboolean Include a final usage chunk when streaming userstring End-user identifier forwarded where supported
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
}
}
Field Type Description idstring Completion id objectstring Always chat.completion for non-streaming createdinteger Unix timestamp (seconds) modelstring Model returned by the provider / gateway system_fingerprintstring Provider fingerprint when available service_tierstring Optional service tier (auto, default, flex, priority, provisioned) choicesarray One or more completion choices usageobject Token and cost accounting extra_fieldsobject Gateway metadata (provider, latency, resolved model) search_results / citations / videosarray Provider-specific extras (for example Perplexity)
Field Type Description indexinteger Choice index finish_reasonstring Why generation stopped: stop, length, tool_calls, or provider-specific values messageobject Assistant message (role, content, optional tool_calls, refusal, reasoning, annotations) logprobsobject Present only when logprobs were requested deltaobject Used only in streaming chunks (not in non-streaming responses)
Field Type Description prompt_tokensinteger Input tokens (includes prompt-cache tokens when reported) completion_tokensinteger Output tokens total_tokensinteger prompt_tokens + completion_tokensprompt_tokens_detailsobject Optional breakdown (text_tokens, cached_read_tokens, cached_write_tokens, …) completion_tokens_detailsobject Optional breakdown (reasoning_tokens, audio_tokens, …) costobject Gateway cost estimate when pricing is configured (input_tokens_cost, output_tokens_cost, total_cost, …)
Field Type Description request_typestring For example chat_completion providerstring Provider that served the request (openai, anthropic, bedrock, …) original_model_requestedstring Model string from the client request resolved_model_usedstring Actual model id sent to the provider (after alias / routing resolution) latencyinteger Latency in milliseconds chunk_indexinteger 0 for non-streaming; chunk ordinal when streamingcache_debugobject Present when semantic cache debugging is enabled raw_request / raw_responseobject Included only when raw capture is enabled on the gateway
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]
Field Type Description rolestring Usually present on the first chunk (assistant) contentstring Incremental text tool_callsarray Incremental tool-call fragments refusalstring Refusal text when applicable reasoning / reasoning_detailsstring / array Reasoning 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:
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"
}
}
Field Type Description typestring Machine-readable decision / error class when set by governance (for example budget_exceeded, rate_limited, virtual_key_not_found) status_codeinteger HTTP status mirrored in the response error.messagestring Human-readable reason. Always present for handler-generated errors error.type / error.code / error.paramstring Optional provider or validation detail extra_fieldsobject Provider / model / request-type context when available
Status Typical type / cause Example error.message 400Invalid JSON, missing model/messages, billing metadata incomplete messages is required for chat completion, model is required, Model '…' is not mapped to a billing service401Missing or unknown virtual key virtual 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 key429rate_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 failure Internal error detail
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 runs on every chat completion (unless the call is a metadata path that skips budgets).
Decision HTTP typeVirtual key missing / not found 401virtual_key_required / virtual_key_not_foundInactive VK, provider/model not allowed, MCP tool blocked 403virtual_key_blocked / provider_blocked / model_blocked / mcp_tool_blockedRate / token / request limits 429rate_limited / token_limited / request_limitedSpend / wallet budget exceeded 402budget_exceededIncomplete billing identity 400For example missing_service_id, account_ambiguous, wallet_insufficient, missing_account_external_id
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.