Skip to main content

Chat completions

/v1/chat/completions is the endpoint most applications use to talk to a model. You send the conversation so far as a list of messages and get the model's next reply back. The gateway accepts the OpenAI chat completion request format and returns the OpenAI response format for every provider, including providers with very different native APIs such as Anthropic, Bedrock, Vertex AI and self-hosted servers. An application written for the OpenAI SDK works unchanged, and switching models is a matter of changing the model field, because the gateway does the translation, the routing, the cost tracking and the access checks.

Scenario​

A support team wants its ticket assistant to draft replies with a Claude model today and to be able to switch to another provider later without touching the application. The platform admin registers the model under a public name, hands the team a virtual key with a budget, and the team's application calls /v1/chat/completions with the OpenAI SDK pointed at the gateway. When a cheaper model comes along, the admin changes the deployment behind the public name and the application keeps working.

Steps​

  1. Register the model. In the Admin UI open Models + Endpoints (/ui/models-and-endpoints), click the Add Model tab, pick the Provider (for example Anthropic), choose the model under Spanway Model Name(s), set the Public Model Name in Model Mappings to the name clients will send, such as claude-sonnet-5-5, set Mode to Chat - /chat/completions, enter the provider credential and click Add Model.

  2. Create a key for the team. Open Virtual Keys (/ui/api-keys), click + Create New Key, give it a Key Name, pick the model under Models, set a budget under Optional Settings if you want one, click Create Key and copy the key from the Save your Key dialog.

  3. Send a request with the key.

    curl -X POST http://localhost:4000/v1/chat/completions \
    -H "Authorization: Bearer $SPANWAY_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{
    "model": "claude-sonnet-5-5",
    "messages": [
    {"role": "system", "content": "You are a concise assistant."},
    {"role": "user", "content": "Explain what a model group is."}
    ],
    "temperature": 0.2,
    "max_tokens": 300
    }'
  4. Try the same request from the browser. Open Playground (/ui/playground), keep Endpoint Type on /v1/chat/completions, pick the model under Select Model, type a message and send it. The reply, the latency and the cost appear in the conversation area.

  5. Check the log. Open Logs (/ui/logs) and find the request in the Request Logs tab. The row shows the key, the model, the tokens and the cost, and the detail drawer shows the request and the response.

Expected result​

The gateway answers with a chat completion object. choices[0].message.content holds the reply, usage holds the token counts, and the response headers carry x-spanway-response-cost, x-spanway-model-id and x-spanway-call-id.

{
"id": "chatcmpl-8f6c2a1e",
"object": "chat.completion",
"created": 1760441234,
"model": "claude-sonnet-5-5",
"choices": [
{"index": 0, "message": {"role": "assistant", "content": "A model group is a public name for one or more deployments.", "tool_calls": null, "function_call": null}, "finish_reason": "stop"}
],
"usage": {"prompt_tokens": 31, "completion_tokens": 58, "total_tokens": 89}
}

The shape is the same for every provider. Provider specific extras such as reasoning content or citations are added as extra fields rather than changing the standard ones, see output format.

Request fields​

model is a public model name from the gateway's model_list. The gateway supports the OpenAI parameters messages, temperature, top_p, n, stream, stream_options, stop, max_tokens, max_completion_tokens, presence_penalty, frequency_penalty, logit_bias, user, response_format, seed, tools, tool_choice, parallel_tool_calls, logprobs, top_logprobs, reasoning_effort, verbosity, modalities, audio, prediction, web_search_options, service_tier, store, prompt_cache_key and safety_identifier. Which of them a model honours depends on the provider, see input parameters.

Streaming​

Set "stream": true to receive server-sent events with chat.completion.chunk objects. Add "stream_options": {"include_usage": true} to get a final chunk with token usage, which the gateway fills in for providers that do not report it natively.

Tools and structured output​

tools and tool_choice work across providers, with the gateway translating tool definitions and tool call responses. response_format with json_schema is forwarded to providers with native structured output and emulated for others by instructing the model and validating the result when spanway_settings.enable_json_schema_validation is on, which is off by default, see the settings reference. To fix malformed JSON replies and re-ask the model with the validation error, turn on structured output repair.

Multimodal input​

Messages can contain content parts of type text, image_url, input_audio, file and video for models that support them. The gateway converts them to each provider's format, including fetching images for providers that need base64 data.

Gateway features that apply​

Every call is authenticated with a virtual key, checked against budgets and rate limits, routed by the router, screened by guardrails, optionally served from the cache, and recorded with its cost. The request may carry metadata, tags, cache, guardrails, fallbacks and prompt_id fields that only the gateway reads and never forwards to the provider.

Errors​

StatusWhat it meansFix
400 invalid_request_error/chat/completions: Missing required parameter: 'messages'., or a parameter is not supported by the provider and drop_params is off.Fix the body, or turn on drop params.
400 a guardrail's messageA guardrail blocked the prompt.Change the prompt, or read the guardrail result in Logs.
400 Mock testing request params are disabled on this proxy: ...The body carries mock_timeout, mock_delay or a mock_testing_* field and the gateway does not allow them.Remove the field. Only a staging gateway with general_settings.dangerously_allow_mock_testing_request_params: true accepts them.
400 BadRequestErrorNo deployment carries this public model name. The message reads Invalid model name passed in model=<name>.Call GET /v1/models with the same key and use a name from the list.
401 AuthenticationErrorThe key is missing, wrong, expired or blocked.Send Authorization: Bearer <key> with a live key from Virtual Keys.
403 PermissionDeniedErrorThe key may not call this model, and the message reads The requested model '<model>' is not available for this API key, or the model name is invalid.Add the model to the key's Models.
403 Model is blockedEvery deployment of the model group is paused.Unpause a deployment on Models + Endpoints.
422 UnprocessableEntityErrorThe key, team, user or organization has spent its budget. The message starts with Budget has been exceeded!Raise the budget or wait for it to reset. An admin can set budget_exceeded_status_code: 429 to answer 429 instead.
429 RateLimitErrorThe key or team is over its rate limit, the provider is throttling, or every deployment is cooling down.Raise the limit on the key, or add a fallback deployment.
408 Timeout, 503 APIConnectionErrorThe provider did not answer in time or could not be reached.Retries and fallbacks in reliability cover this automatically.

Every error body has the OpenAI shape, {"error": {"message", "type", "param", "code"}}, and the mapping from provider errors is described in exception mapping. The client error reference lists the exception each SDK raises for every status, and connect any client covers base URL and header problems.

Logs​

Each call writes one row to the spend log, which the Logs page (/ui/logs) shows with the key, team, model group, deployment, tokens, cost, latency and status. A failed call is a row too, with the error. Prompt and response text is stored only when the gateway is set to keep it, see what the gateway stores. Operator log lines for routing, retries and fallbacks are in the log reference.

Providers​

The gateway's endpoint support matrix marks 147 provider integrations as supporting this endpoint:

A2A (Agent-to-Agent), Abliteration, AI21, AI21 Chat, AIHubMix (aihubmix), AI/ML API, Amazon Nova, Anthropic, Anthropic Text, Apertis (apertis), AssemblyAI (assemblyai), Auto Router (auto_router), Azure, Azure AI, Azure AI Foundry Agents, Azure Text, Baseten, AWS - Bedrock, Bedrock Mantle, Bytez, Cerebras, Charity Engine (charity_engine), ChatGPT Subscription, Chutes (chutes), Clarifai, Cloudflare AI Workers, Codestral, Cognition, Cohere, Cohere Chat, CometAPI, CompactifAI, Cortecs, Crusoe (crusoe), Cursor BYOK, Custom, Custom OpenAI (custom_openai), Darkbloom, Dashscope, Databricks, DataRobot, Deepgram, DeepInfra, Deepseek, Docker Model Runner, Eden AI, ElevenLabs, EmpirioLabs (empiriolabs), Empower, Fal AI, Featherless AI, Fireworks AI, FriendliAI, Galadriel, Google Distributed Cloud (GDC) (gdc), Google AI Studio - Gemini, GigaChat, GitHub Models, GitHub Copilot, GMI Cloud, GradientAI, Groq AI, Helicone, Heroku, Hosted VLLM, Huggingface, Hyperbolic, Inception (inception), IONOS AI Model Hub, Lambda AI, LangFlow (langflow), LangGraph, Lemonade, LibertAI, Llamafile, LlamaGate, LM Studio, Manus, Maritalk, Meta Model API (meta), Meta - Llama API, Microsoft 365 Copilot (microsoft_365_copilot), Minimax, Mistral AI API, ModelScope, Moonshot, Morph, Nadir (nadir), NanoGPT (nanogpt), Nebius AI Studio, Neosantara, NLP Cloud, Novita AI (novita), Nscale, Nvidia NIM, OCI, Ollama, Ollama Chat, Oobabooga (oobabooga), OpenAI, OpenRouter, OVHCloud AI Endpoints, Parasail (parasail), Perplexity AI, Petals, Pinstripes, Poe (poe), Predibase, Prism, PublicAI, Qianwen AI Platform, QwenCloud, RAGFlow, Reka, Replicate, AWS - Sagemaker, Sagemaker Chat, Sail, Sambanova, SAP Generative AI Hub, Sarvam, ScaleDown, Scaleway, SCX.ai, Snowflake, Spanway Proxy, STACKIT AI Model Serving, Synthetic (synthetic), Tencent TokenHub (tencent), Tensormesh (tensormesh), Text Completion Codestral, Text Completion OpenAI, Together AI, Triton, V0, Venice.ai, Vercel AI Gateway, Google - Vertex AI, Vertex AI Agent Engine, VLLM, Volcengine, WandB Inference, IBM - Watsonx.ai, Watsonx Text, xAI, Xiaomi Mimo, Z.AI (Zhipu AI).