Skip to main content

Chat/completions API

This page documents the 4 gateway endpoints tagged chat/completions in the gateway's OpenAPI document. Every example targets a gateway on http://localhost:4000 and authenticates with the SPANWAY_API_KEY environment variable, which holds the master key or a virtual key that has access to the route. Request and response fields are taken from the schema the running gateway publishes at /openapi.json, and the same document is bundled with this site as openapi.json.

MethodPathSummary
POST/chat/completionsCreate a chat completion
POST/v1/chat/completionsCreate a chat completion
POST/openai/deployments/{model}/chat/completionsCreate a chat completion
POST/engines/{model}/chat/completionsCreate a chat completion

Endpoints​

POST /chat/completions​

Create a chat completion

Send a conversation to a model and get its reply, in the OpenAI chat completions format, so any OpenAI client works unchanged. Name a model group from GET /v1/models as model. Set stream: true to receive the reply as server-sent chunks. Provider specific fields pass through to the provider. Any virtual key that may use the named model can call it. The gateway checks the key's budget, rate limits and guardrails first, sends the request to one of the model group's deployments with retries and fallbacks, and records the cost and usage in the spend logs. Nothing else changes.

Parameters:

NameInTypeRequiredDescription
x-spanway-routing-skipsheaderenum: "true"NoSend true to get the candidates the router skipped in the answer headers. See https://docs.spanway.ai/docs/proxy/routing_headers

Request body (application/json, object):

FieldTypeRequiredDescription
context_fitboolean or "middle_out" or object or nullNoHow to fit a prompt that is longer than the context window
transformsarray of stringNoAnother way to ask for context fit: ["middle-out"] turns it on and [] turns it off
modelstringYesModel
messagesarray of ChatCompletionUserMessage or ChatCompletionAssistantMessage or ChatCompletionToolMessage or ChatCompletionSystemMessage or ChatCompletionFunctionMessage or ChatCompletionDeveloperMessageYesMessages
frequency_penaltynumber or nullNoFrequency Penalty
logit_biasobject or nullNoLogit Bias
logprobsboolean or nullNoLogprobs
top_logprobsinteger or nullNoTop Logprobs
max_tokensinteger or nullNoMax Tokens
ninteger or nullNoN
presence_penaltynumber or nullNoPresence Penalty
response_formatobject or nullNoResponse Format
seedinteger or nullNoSeed
service_tierstring or nullNoService Tier
stopstring or array of string or nullNoStop
stream_optionsobject or nullNoStream Options
temperaturenumber or nullNoTemperature
top_pnumber or nullNoTop P
toolsarray of object or nullNoTools
tool_choicestring or object or nullNoTool Choice
parallel_tool_callsboolean or nullNoParallel Tool Calls
function_callstring or object or nullNoFunction Call
functionsarray of object or nullNoFunctions
userstring or nullNoUser
streamboolean or nullNoStream
metadataobject or nullNoMetadata
guardrailsarray of string or nullNoGuardrails
cachingboolean or nullNoCaching
num_retriesinteger or nullNoNum Retries
context_window_fallback_dictobject or nullNoContext Window Fallback Dict
fallbacksarray of string or nullNoFallbacks
prompt_idstring or nullNoStored prompt to render into the messages, by id
prompt_variablesobject or nullNoValues for the stored prompt's variables
prompt_versioninteger or nullNoVersion of the stored prompt to use. Leave out for the latest
prompt_environmentstring or nullNoEnvironment label of the stored prompt to use, such as production
vector_store_idsarray of string or nullNoVector stores to search and add to the context before the model call
thinkingobject or nullNoExtended thinking for models that support it, e.g. {"type": "enabled"}
top_kinteger or nullNoSample only from the top k tokens, for providers that support it
cacheobject or nullNoPer-request cache controls such as ttl, no-cache or use-cache
providerobject or nullNoProvider preferences for this request, such as sort, only or ignore
max_tool_callsinteger or nullNoMost server tool calls the gateway runs for this request
structured_output_repairenum: "off", "repair", "retry", "repair_and_retry" or nullNoRepair or re-ask when a JSON reply fails its schema
structured_output_max_retriesinteger or nullNoMost re-asks when structured_output_repair retries

Example request:

curl -X POST "http://localhost:4000/chat/completions" \
-H "Authorization: Bearer $SPANWAY_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "claude-sonnet-5-5",
"messages": [
{
"role": "user",
"content": "What is a model group?"
}
],
"max_tokens": 256
}'

Responses:

StatusDescriptionBody
200The completion in the OpenAI chat completion shape, or a stream of chat.completion.chunk events.application/json object
400The request is invalid, for example a missing or unsupported parameter, a prompt longer than the model's context window, content a guardrail or the provider refused, or no deployment that satisfies the data policy of the key, team or organization (No deployment of model 'gpt-5.5' satisfies the data policy: ...). error.message says which.application/json ProxyError
401No valid key was sent, or the key has expired or is blocked.application/json ProxyError
403The key is valid but may not use this model, route or feature. A guardrail block is a 400, not a 403.application/json ProxyError
404The route or resource does not exist, or this key cannot see it. An unknown model name is a 400 (Invalid model name passed in model=...).application/json ProxyError
408The provider did not answer before the request timed out.application/json ProxyError
413The request body is larger than max_request_size_mb (100 MB by default), or an upload is larger than its own limit. The gateway refused it before reading the key. Docsapplication/json object
422The request body does not have the expected shape, or structured output repair is on and the reply still did not match the requested JSON after the allowed retries (StructuredOutputRepairError).application/json ProxyError or HTTPValidationError
429Too many requests. A provider limit or a gateway limit (requests or tokens per minute, or parallel requests) refused the call, and error.type says which. A gateway limit also sends the RateLimit headers and x-spanway-rate-limited-by. Docs With access requests licensed, a key or team limit refusal also carries error.request_increase, which names the access request to file for a higher limit. Ask from an errorapplication/json ProxyError
500The gateway or the provider failed unexpectedly, or the gateway could not reach the provider. Retry, and quote the request id if it keeps failing.application/json ProxyError
502The provider, or a proxy in front of it, answered with something that is not a valid response.application/json ProxyError
503The provider is overloaded or unavailable. With Redis rate limiting, a 503 also means the gateway could not check the rate limit counters and refused the request, because fail_closed_rate_limit_enforcement is on. Docsapplication/json ProxyError

Response fields (200):

FieldTypeRequiredDescription
idstringYesId
createdintegerYesCreated
modelstring or nullNoModel
objectstringYesObject
system_fingerprintstring or nullNoSystem Fingerprint
choicesarray of objectYesChoices

POST /v1/chat/completions​

Create a chat completion

Send a conversation to a model and get its reply, in the OpenAI chat completions format, so any OpenAI client works unchanged. Name a model group from GET /v1/models as model. Set stream: true to receive the reply as server-sent chunks. Provider specific fields pass through to the provider. Any virtual key that may use the named model can call it. The gateway checks the key's budget, rate limits and guardrails first, sends the request to one of the model group's deployments with retries and fallbacks, and records the cost and usage in the spend logs. Nothing else changes.

Parameters:

NameInTypeRequiredDescription
x-spanway-routing-skipsheaderenum: "true"NoSend true to get the candidates the router skipped in the answer headers. See https://docs.spanway.ai/docs/proxy/routing_headers

Request body (application/json, object):

FieldTypeRequiredDescription
context_fitboolean or "middle_out" or object or nullNoHow to fit a prompt that is longer than the context window
transformsarray of stringNoAnother way to ask for context fit: ["middle-out"] turns it on and [] turns it off
modelstringYesModel
messagesarray of ChatCompletionUserMessage or ChatCompletionAssistantMessage or ChatCompletionToolMessage or ChatCompletionSystemMessage or ChatCompletionFunctionMessage or ChatCompletionDeveloperMessageYesMessages
frequency_penaltynumber or nullNoFrequency Penalty
logit_biasobject or nullNoLogit Bias
logprobsboolean or nullNoLogprobs
top_logprobsinteger or nullNoTop Logprobs
max_tokensinteger or nullNoMax Tokens
ninteger or nullNoN
presence_penaltynumber or nullNoPresence Penalty
response_formatobject or nullNoResponse Format
seedinteger or nullNoSeed
service_tierstring or nullNoService Tier
stopstring or array of string or nullNoStop
stream_optionsobject or nullNoStream Options
temperaturenumber or nullNoTemperature
top_pnumber or nullNoTop P
toolsarray of object or nullNoTools
tool_choicestring or object or nullNoTool Choice
parallel_tool_callsboolean or nullNoParallel Tool Calls
function_callstring or object or nullNoFunction Call
functionsarray of object or nullNoFunctions
userstring or nullNoUser
streamboolean or nullNoStream
metadataobject or nullNoMetadata
guardrailsarray of string or nullNoGuardrails
cachingboolean or nullNoCaching
num_retriesinteger or nullNoNum Retries
context_window_fallback_dictobject or nullNoContext Window Fallback Dict
fallbacksarray of string or nullNoFallbacks
prompt_idstring or nullNoStored prompt to render into the messages, by id
prompt_variablesobject or nullNoValues for the stored prompt's variables
prompt_versioninteger or nullNoVersion of the stored prompt to use. Leave out for the latest
prompt_environmentstring or nullNoEnvironment label of the stored prompt to use, such as production
vector_store_idsarray of string or nullNoVector stores to search and add to the context before the model call
thinkingobject or nullNoExtended thinking for models that support it, e.g. {"type": "enabled"}
top_kinteger or nullNoSample only from the top k tokens, for providers that support it
cacheobject or nullNoPer-request cache controls such as ttl, no-cache or use-cache
providerobject or nullNoProvider preferences for this request, such as sort, only or ignore
max_tool_callsinteger or nullNoMost server tool calls the gateway runs for this request
structured_output_repairenum: "off", "repair", "retry", "repair_and_retry" or nullNoRepair or re-ask when a JSON reply fails its schema
structured_output_max_retriesinteger or nullNoMost re-asks when structured_output_repair retries

Example request:

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": "user",
"content": "What is a model group?"
}
],
"max_tokens": 256
}'

Responses:

StatusDescriptionBody
200The completion in the OpenAI chat completion shape, or a stream of chat.completion.chunk events.application/json object
400The request is invalid, for example a missing or unsupported parameter, a prompt longer than the model's context window, content a guardrail or the provider refused, or no deployment that satisfies the data policy of the key, team or organization (No deployment of model 'gpt-5.5' satisfies the data policy: ...). error.message says which.application/json ProxyError
401No valid key was sent, or the key has expired or is blocked.application/json ProxyError
403The key is valid but may not use this model, route or feature. A guardrail block is a 400, not a 403.application/json ProxyError
404The route or resource does not exist, or this key cannot see it. An unknown model name is a 400 (Invalid model name passed in model=...).application/json ProxyError
408The provider did not answer before the request timed out.application/json ProxyError
413The request body is larger than max_request_size_mb (100 MB by default), or an upload is larger than its own limit. The gateway refused it before reading the key. Docsapplication/json object
422The request body does not have the expected shape, or structured output repair is on and the reply still did not match the requested JSON after the allowed retries (StructuredOutputRepairError).application/json ProxyError or HTTPValidationError
429Too many requests. A provider limit or a gateway limit (requests or tokens per minute, or parallel requests) refused the call, and error.type says which. A gateway limit also sends the RateLimit headers and x-spanway-rate-limited-by. Docs With access requests licensed, a key or team limit refusal also carries error.request_increase, which names the access request to file for a higher limit. Ask from an errorapplication/json ProxyError
500The gateway or the provider failed unexpectedly, or the gateway could not reach the provider. Retry, and quote the request id if it keeps failing.application/json ProxyError
502The provider, or a proxy in front of it, answered with something that is not a valid response.application/json ProxyError
503The provider is overloaded or unavailable. With Redis rate limiting, a 503 also means the gateway could not check the rate limit counters and refused the request, because fail_closed_rate_limit_enforcement is on. Docsapplication/json ProxyError

Response fields (200):

FieldTypeRequiredDescription
idstringYesId
createdintegerYesCreated
modelstring or nullNoModel
objectstringYesObject
system_fingerprintstring or nullNoSystem Fingerprint
choicesarray of objectYesChoices

POST /openai/deployments/{model}/chat/completions​

Create a chat completion

Send a conversation to a model and get its reply, in the OpenAI chat completions format, so any OpenAI client works unchanged. Name a model group from GET /v1/models as model. Set stream: true to receive the reply as server-sent chunks. Provider specific fields pass through to the provider. Any virtual key that may use the named model can call it. The gateway checks the key's budget, rate limits and guardrails first, sends the request to one of the model group's deployments with retries and fallbacks, and records the cost and usage in the spend logs. Nothing else changes.

Parameters:

NameInTypeRequiredDescription
modelpathstring or nullYes
x-spanway-routing-skipsheaderenum: "true"NoSend true to get the candidates the router skipped in the answer headers. See https://docs.spanway.ai/docs/proxy/routing_headers

Request body (application/json, object):

FieldTypeRequiredDescription
context_fitboolean or "middle_out" or object or nullNoHow to fit a prompt that is longer than the context window
transformsarray of stringNoAnother way to ask for context fit: ["middle-out"] turns it on and [] turns it off
modelstringYesModel
messagesarray of ChatCompletionUserMessage or ChatCompletionAssistantMessage or ChatCompletionToolMessage or ChatCompletionSystemMessage or ChatCompletionFunctionMessage or ChatCompletionDeveloperMessageYesMessages
frequency_penaltynumber or nullNoFrequency Penalty
logit_biasobject or nullNoLogit Bias
logprobsboolean or nullNoLogprobs
top_logprobsinteger or nullNoTop Logprobs
max_tokensinteger or nullNoMax Tokens
ninteger or nullNoN
presence_penaltynumber or nullNoPresence Penalty
response_formatobject or nullNoResponse Format
seedinteger or nullNoSeed
service_tierstring or nullNoService Tier
stopstring or array of string or nullNoStop
stream_optionsobject or nullNoStream Options
temperaturenumber or nullNoTemperature
top_pnumber or nullNoTop P
toolsarray of object or nullNoTools
tool_choicestring or object or nullNoTool Choice
parallel_tool_callsboolean or nullNoParallel Tool Calls
function_callstring or object or nullNoFunction Call
functionsarray of object or nullNoFunctions
userstring or nullNoUser
streamboolean or nullNoStream
metadataobject or nullNoMetadata
guardrailsarray of string or nullNoGuardrails
cachingboolean or nullNoCaching
num_retriesinteger or nullNoNum Retries
context_window_fallback_dictobject or nullNoContext Window Fallback Dict
fallbacksarray of string or nullNoFallbacks
prompt_idstring or nullNoStored prompt to render into the messages, by id
prompt_variablesobject or nullNoValues for the stored prompt's variables
prompt_versioninteger or nullNoVersion of the stored prompt to use. Leave out for the latest
prompt_environmentstring or nullNoEnvironment label of the stored prompt to use, such as production
vector_store_idsarray of string or nullNoVector stores to search and add to the context before the model call
thinkingobject or nullNoExtended thinking for models that support it, e.g. {"type": "enabled"}
top_kinteger or nullNoSample only from the top k tokens, for providers that support it
cacheobject or nullNoPer-request cache controls such as ttl, no-cache or use-cache
providerobject or nullNoProvider preferences for this request, such as sort, only or ignore
max_tool_callsinteger or nullNoMost server tool calls the gateway runs for this request
structured_output_repairenum: "off", "repair", "retry", "repair_and_retry" or nullNoRepair or re-ask when a JSON reply fails its schema
structured_output_max_retriesinteger or nullNoMost re-asks when structured_output_repair retries

Example request:

curl -X POST "http://localhost:4000/openai/deployments/model-123/chat/completions" \
-H "Authorization: Bearer $SPANWAY_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "claude-sonnet-5-5",
"messages": [
{
"role": "user",
"content": "What is a model group?"
}
],
"max_tokens": 256
}'

Responses:

StatusDescriptionBody
200The completion in the OpenAI chat completion shape, or a stream of chat.completion.chunk events.application/json object
400The request is invalid, for example a missing or unsupported parameter, a prompt longer than the model's context window, content a guardrail or the provider refused, or no deployment that satisfies the data policy of the key, team or organization (No deployment of model 'gpt-5.5' satisfies the data policy: ...). error.message says which.application/json ProxyError
401No valid key was sent, or the key has expired or is blocked.application/json ProxyError
403The key is valid but may not use this model, route or feature. A guardrail block is a 400, not a 403.application/json ProxyError
404The route or resource does not exist, or this key cannot see it. An unknown model name is a 400 (Invalid model name passed in model=...).application/json ProxyError
408The provider did not answer before the request timed out.application/json ProxyError
413The request body is larger than max_request_size_mb (100 MB by default), or an upload is larger than its own limit. The gateway refused it before reading the key. Docsapplication/json object
422The request body does not have the expected shape, or structured output repair is on and the reply still did not match the requested JSON after the allowed retries (StructuredOutputRepairError).application/json ProxyError or HTTPValidationError
429Too many requests. A provider limit or a gateway limit (requests or tokens per minute, or parallel requests) refused the call, and error.type says which. A gateway limit also sends the RateLimit headers and x-spanway-rate-limited-by. Docs With access requests licensed, a key or team limit refusal also carries error.request_increase, which names the access request to file for a higher limit. Ask from an errorapplication/json ProxyError
500The gateway or the provider failed unexpectedly, or the gateway could not reach the provider. Retry, and quote the request id if it keeps failing.application/json ProxyError
502The provider, or a proxy in front of it, answered with something that is not a valid response.application/json ProxyError
503The provider is overloaded or unavailable. With Redis rate limiting, a 503 also means the gateway could not check the rate limit counters and refused the request, because fail_closed_rate_limit_enforcement is on. Docsapplication/json ProxyError

Response fields (200):

FieldTypeRequiredDescription
idstringYesId
createdintegerYesCreated
modelstring or nullNoModel
objectstringYesObject
system_fingerprintstring or nullNoSystem Fingerprint
choicesarray of objectYesChoices

POST /engines/{model}/chat/completions​

Create a chat completion

Send a conversation to a model and get its reply, in the OpenAI chat completions format, so any OpenAI client works unchanged. Name a model group from GET /v1/models as model. Set stream: true to receive the reply as server-sent chunks. Provider specific fields pass through to the provider. Any virtual key that may use the named model can call it. The gateway checks the key's budget, rate limits and guardrails first, sends the request to one of the model group's deployments with retries and fallbacks, and records the cost and usage in the spend logs. Nothing else changes.

Parameters:

NameInTypeRequiredDescription
modelpathstring or nullYes
x-spanway-routing-skipsheaderenum: "true"NoSend true to get the candidates the router skipped in the answer headers. See https://docs.spanway.ai/docs/proxy/routing_headers

Request body (application/json, object):

FieldTypeRequiredDescription
context_fitboolean or "middle_out" or object or nullNoHow to fit a prompt that is longer than the context window
transformsarray of stringNoAnother way to ask for context fit: ["middle-out"] turns it on and [] turns it off
modelstringYesModel
messagesarray of ChatCompletionUserMessage or ChatCompletionAssistantMessage or ChatCompletionToolMessage or ChatCompletionSystemMessage or ChatCompletionFunctionMessage or ChatCompletionDeveloperMessageYesMessages
frequency_penaltynumber or nullNoFrequency Penalty
logit_biasobject or nullNoLogit Bias
logprobsboolean or nullNoLogprobs
top_logprobsinteger or nullNoTop Logprobs
max_tokensinteger or nullNoMax Tokens
ninteger or nullNoN
presence_penaltynumber or nullNoPresence Penalty
response_formatobject or nullNoResponse Format
seedinteger or nullNoSeed
service_tierstring or nullNoService Tier
stopstring or array of string or nullNoStop
stream_optionsobject or nullNoStream Options
temperaturenumber or nullNoTemperature
top_pnumber or nullNoTop P
toolsarray of object or nullNoTools
tool_choicestring or object or nullNoTool Choice
parallel_tool_callsboolean or nullNoParallel Tool Calls
function_callstring or object or nullNoFunction Call
functionsarray of object or nullNoFunctions
userstring or nullNoUser
streamboolean or nullNoStream
metadataobject or nullNoMetadata
guardrailsarray of string or nullNoGuardrails
cachingboolean or nullNoCaching
num_retriesinteger or nullNoNum Retries
context_window_fallback_dictobject or nullNoContext Window Fallback Dict
fallbacksarray of string or nullNoFallbacks
prompt_idstring or nullNoStored prompt to render into the messages, by id
prompt_variablesobject or nullNoValues for the stored prompt's variables
prompt_versioninteger or nullNoVersion of the stored prompt to use. Leave out for the latest
prompt_environmentstring or nullNoEnvironment label of the stored prompt to use, such as production
vector_store_idsarray of string or nullNoVector stores to search and add to the context before the model call
thinkingobject or nullNoExtended thinking for models that support it, e.g. {"type": "enabled"}
top_kinteger or nullNoSample only from the top k tokens, for providers that support it
cacheobject or nullNoPer-request cache controls such as ttl, no-cache or use-cache
providerobject or nullNoProvider preferences for this request, such as sort, only or ignore
max_tool_callsinteger or nullNoMost server tool calls the gateway runs for this request
structured_output_repairenum: "off", "repair", "retry", "repair_and_retry" or nullNoRepair or re-ask when a JSON reply fails its schema
structured_output_max_retriesinteger or nullNoMost re-asks when structured_output_repair retries

Example request:

curl -X POST "http://localhost:4000/engines/model-123/chat/completions" \
-H "Authorization: Bearer $SPANWAY_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "claude-sonnet-5-5",
"messages": [
{
"role": "user",
"content": "What is a model group?"
}
],
"max_tokens": 256
}'

Responses:

StatusDescriptionBody
200The completion in the OpenAI chat completion shape, or a stream of chat.completion.chunk events.application/json object
400The request is invalid, for example a missing or unsupported parameter, a prompt longer than the model's context window, content a guardrail or the provider refused, or no deployment that satisfies the data policy of the key, team or organization (No deployment of model 'gpt-5.5' satisfies the data policy: ...). error.message says which.application/json ProxyError
401No valid key was sent, or the key has expired or is blocked.application/json ProxyError
403The key is valid but may not use this model, route or feature. A guardrail block is a 400, not a 403.application/json ProxyError
404The route or resource does not exist, or this key cannot see it. An unknown model name is a 400 (Invalid model name passed in model=...).application/json ProxyError
408The provider did not answer before the request timed out.application/json ProxyError
413The request body is larger than max_request_size_mb (100 MB by default), or an upload is larger than its own limit. The gateway refused it before reading the key. Docsapplication/json object
422The request body does not have the expected shape, or structured output repair is on and the reply still did not match the requested JSON after the allowed retries (StructuredOutputRepairError).application/json ProxyError or HTTPValidationError
429Too many requests. A provider limit or a gateway limit (requests or tokens per minute, or parallel requests) refused the call, and error.type says which. A gateway limit also sends the RateLimit headers and x-spanway-rate-limited-by. Docs With access requests licensed, a key or team limit refusal also carries error.request_increase, which names the access request to file for a higher limit. Ask from an errorapplication/json ProxyError
500The gateway or the provider failed unexpectedly, or the gateway could not reach the provider. Retry, and quote the request id if it keeps failing.application/json ProxyError
502The provider, or a proxy in front of it, answered with something that is not a valid response.application/json ProxyError
503The provider is overloaded or unavailable. With Redis rate limiting, a 503 also means the gateway could not check the rate limit counters and refused the request, because fail_closed_rate_limit_enforcement is on. Docsapplication/json ProxyError

Response fields (200):

FieldTypeRequiredDescription
idstringYesId
createdintegerYesCreated
modelstring or nullNoModel
objectstringYesObject
system_fingerprintstring or nullNoSystem Fingerprint
choicesarray of objectYesChoices