Chat Completions

Complete reference for the POST /v1/chat/completions endpoint, including all parameters, streaming, and AllRoutes-specific extensions.

Endpoint

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

Authentication

Authorization: Bearer allroutes_sk_...
Content-Type: application/json

Request Body

Core Fields

ParameterTypeRequiredDescription
modelstringYesModel identifier (e.g., gpt-4o, claude-sonnet-4-20250514, gemini-2.0-flash)
messagesarrayYesArray of message objects with role and content
streambooleanNoEnable streaming via Server-Sent Events (default: false)

Sampling Parameters

ParameterTypeDefaultDescription
temperaturefloatModel defaultSampling temperature (0-2). Lower is more deterministic.
max_tokensintegerModel defaultMaximum number of tokens to generate
top_pfloat1.0Nucleus sampling: consider tokens with cumulative probability up to top_p
top_kinteger--Limit sampling to top K tokens (supported by some providers)
frequency_penaltyfloat0Penalize tokens by frequency (-2 to 2)
presence_penaltyfloat0Penalize tokens by presence (-2 to 2)
repetition_penaltyfloat--Alternative repetition penalty (some providers)
min_pfloat--Minimum probability threshold for sampling
seedinteger--Seed for deterministic sampling (where supported)
stopstring or array--Stop sequences to halt generation
logit_biasobject--Map of token IDs to bias values

Function / Tool Calling

ParameterTypeDescription
toolsarrayList of tool definitions (function calling)
tool_choicestring or objectControl tool use: "none", "auto", "required", or {type: "function", function: {name: "..."}}
parallel_tool_callsbooleanAllow multiple tool calls in a single response

Structured Output

ParameterTypeDescription
response_formatobjectForce output format: {"type": "json_object"} or {"type": "json_schema", "json_schema": {...}}

Reasoning / Thinking

ParameterTypeDescription
reasoningobjectConfigure reasoning/thinking tokens (Anthropic, DeepSeek, etc.)
include_reasoningbooleanLegacy flag to include reasoning in response
interleaved_thinkingbooleanEnable interleaved thinking for supported models

AllRoutes-Specific Fields

ParameterTypeDescription
modelsarrayFallback model array. Tries each in order if the previous fails.
providerobjectProvider routing preferences (see Smart Routing)
pluginsarrayPlugins to apply: [{"id": "web"}, {"id": "response-healing"}]
web_search_optionsobjectConfiguration for the web search plugin
cache_controlobjectAnthropic-style per-block prompt caching configuration
presetstringName or ID of a saved preset to apply
guardrailstringGuardrail profile ID to enforce on this request
traceobjectCustom metadata passed to broadcast/observability destinations
session_idstringGroup requests into a session for analytics
route_explainbooleanReturn verbose routing explanation in response headers
transformsarrayMessage transforms to apply before sending to provider
routestringRouting hint (e.g., "fallback")
metadataobjectArbitrary key-value metadata for logging
userstringEnd-user identifier for per-user analytics
debugobjectDebug configuration for verbose logging

Output Modalities

ParameterTypeDescription
modalitiesarrayOutput types: ["text"], ["text", "image"]
image_configobjectImage generation settings when image modality is enabled

Stream Options

ParameterTypeDescription
stream_optionsobjectConfigure stream behavior (e.g., include usage in final chunk)

Message Format

{
  "messages": [
    {"role": "system", "content": "You are a helpful assistant."},
    {"role": "user", "content": "Hello!"},
    {"role": "assistant", "content": "Hi there! How can I help?"},
    {"role": "user", "content": "What is 2+2?"}
  ]
}

Supported roles: system, user, assistant, tool.

Response Format

{
  "id": "chatcmpl-abc123",
  "object": "chat.completion",
  "created": 1714000000,
  "model": "gpt-4o",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "The answer is 4."
      },
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 24,
    "completion_tokens": 8,
    "total_tokens": 32
  }
}

Model Fallbacks

Use the models array to define an ordered list of fallback models. AllRoutes tries each model in sequence if the previous one fails:

{
  "models": ["gpt-4o", "claude-sonnet-4-20250514", "gemini-2.0-flash"],
  "messages": [{"role": "user", "content": "Hello!"}]
}

When using models, the model field is ignored.

Streaming (SSE)

Set stream: true to receive Server-Sent Events. Each event is a JSON object prefixed with data: :

data: {"id":"chatcmpl-abc","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"content":"Hello"},"finish_reason":null}]}

data: {"id":"chatcmpl-abc","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"content":" there"},"finish_reason":null}]}

data: {"id":"chatcmpl-abc","object":"chat.completion.chunk","choices":[{"index":0,"delta":{},"finish_reason":"stop"}],"usage":{"prompt_tokens":10,"completion_tokens":5,"total_tokens":15}}

data: [DONE]

AllRoutes-Specific Response Headers

HeaderDescription
X-AllRoutes-Request-IDUnique request identifier
X-AllRoutes-ProviderProvider that served the request
X-AllRoutes-ModelResolved model identifier
X-AllRoutes-Cachehit or miss (if caching is enabled)
X-AllRoutes-Cache-SavingsCost saved via cache hit (USD)
X-AllRoutes-Latency-MsTotal request latency in milliseconds
X-AllRoutes-CostRequest cost in USD
X-RateLimit-LimitRate limit ceiling for the key
X-RateLimit-RemainingRemaining requests in the current window
X-RateLimit-ResetUnix timestamp when the rate limit resets

Example: Full Request

curl https://api.allroutes.ai/v1/chat/completions \
  -H "Authorization: Bearer allroutes_sk_..." \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gpt-4o",
    "messages": [
      {"role": "system", "content": "You are a helpful assistant."},
      {"role": "user", "content": "Summarize the theory of relativity."}
    ],
    "temperature": 0.7,
    "max_tokens": 1000,
    "stream": false,
    "plugins": [{"id": "web"}],
    "provider": {
      "order": ["openai", "azure"],
      "allow_fallbacks": true
    }
  }'

Error Codes

StatusMeaning
400Invalid request body (bad parameter, malformed messages)
401Missing or invalid API key
402Insufficient credits or per-key budget exhausted
403Key lacks chat:completions scope or model not allowed
404Unknown model ID
408Request timeout (provider did not respond)
429Rate limit exceeded -- check Retry-After header
499Client closed the connection mid-stream
500/502/503Upstream provider error -- AllRoutes auto-retries on idempotent retries

See Error Handling for patterns and the canonical error envelope.

See Also

  • Streaming -- SSE protocol, chunk format, and [DONE] handling
  • Responses API -- the new stateful conversation endpoint
  • Smart Routing -- provider field, fallback chains, A/B testing
  • Plugins -- web search, file parser, response healing
  • Caching -- cache_control and 3-tier cache behavior
  • Guardrails -- guardrail field and compliance profiles
  • OpenAI SDK Drop-in -- swap base_url and reuse existing OpenAI code