OpenAI Chat API
POST /v1/chat/completions on sference: the OpenAI Chat Completions shape, with priority and flex processing, tools, structured output, vision, and streaming.
OpenAI Chat API
POST https://api.sference.com/v1/chat/completions is the OpenAI Chat Completions shape, served natively. It is the surface the widest set of clients already speak, so most migrations are a base URL and a model id.
curl https://api.sference.com/v1/chat/completions \
-H "Authorization: Bearer $SFERENCE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "zai-org/GLM-5.3",
"messages": [{"role": "user", "content": "Say hello in one sentence."}]
}'Base URL and authentication
| Endpoint | POST https://api.sference.com/v1/chat/completions |
| Base URL for OpenAI SDKs | https://api.sference.com/v1 |
| Auth | Authorization: Bearer sk_... |
| Key format | sference keys (sk_...), minted in the console |
import os
from openai import OpenAI
client = OpenAI(
base_url="https://api.sference.com/v1",
api_key=os.environ["SFERENCE_API_KEY"],
)
response = client.chat.completions.create(
model="zai-org/GLM-5.3",
messages=[{"role": "user", "content": "Say hello in one sentence."}],
)
print(response.choices[0].message.content)Model ids are catalog ids
There are no gpt-* aliases. Pass a sference catalog id such as zai-org/GLM-5.3 or moonshotai/Kimi-K3. GET /v1/models lists what your key can call, with capabilities and rates.
To make a retry safe after a timeout or dropped connection, send an Idempotency-Key header — see Idempotency keys.
Request fields
Core
| Field | Notes |
|---|---|
model | Catalog id |
messages | system / user / assistant / tool roles; content may be a string or a list of parts |
stream | SSE stream of chat.completion.chunk objects |
stream_options.include_usage | Emits a final usage chunk — required to read token counts while streaming |
temperature, top_p | Standard sampling |
top_k, min_p | Additional sampling controls beyond OpenAI's set |
presence_penalty, frequency_penalty, repetition_penalty | Penalties |
max_tokens, max_completion_tokens | Output cap. Thinking is on by default, and reasoning tokens count toward this cap |
stop, seed | Stop sequences and deterministic sampling |
Tools and structured output
| Field | Notes |
|---|---|
tools, tool_choice | OpenAI tool-calling shape, served natively |
response_format | {"type": "json_schema", ...} or {"type": "json_object"} — see Structured outputs |
Reasoning
Thinking is on by default
Thinking is on by default, and reasoning tokens count toward max_tokens. A small cap can finish during reasoning and come back with empty content. With structured output, models other than Kimi and GLM (for example DeepSeek V4) default thinking off.
On chat completions, turn thinking off with enable_thinking: false or reasoning_effort: "none". On /v1/messages, send thinking: {"type": "disabled"}. chat_template_kwargs is ignored, not rejected.
The GLM 5.3 family, including GLM 5.3 Flash, cannot turn thinking off and returns 400. The zai-org/GLM-5.2 alias is served by those same weights, so it returns 400 too. That alias is the CLI default for Codex, opencode, and Pi. On those models, set reasoning_effort to "low" on chat completions, or raise max_tokens.
| Field | Notes |
|---|---|
reasoning_effort | Named levels minimal / low / medium / high / xhigh / max, or "none" to turn thinking off, are accepted on every thinking model. Each model maps a named level to its own behavior. An integer budget from 1 to 100 is DeepSeek V4.1 only; other models return 400 for an integer. The GLM 5.3 family, including GLM 5.3 Flash and the zai-org/GLM-5.2 alias (GLM 5.3 weights; the CLI default for Codex, opencode, and Pi), returns 400 for "none" — use "low" or raise max_tokens |
enable_thinking | false turns thinking off. The same GLM 5.3 family, including the zai-org/GLM-5.2 alias, returns 400 for false |
sference extensions
| Field | Notes |
|---|---|
service_tier | "flex" selects flex processing at 0.7 × list; "priority" jumps the pending queue at 1.3 × list (priority-enabled orgs). Other accepted values serve as default |
prompt_cache_key | Stable per-session id. Routes the request to a warm worker; there is no retention or TTL — see Prompt caching |
max_queue_wait_s | 5–300s admission bound; fails fast under congestion — see Max queue wait |
Streaming
stream = client.chat.completions.create(
model="zai-org/GLM-5.3",
messages=[{"role": "user", "content": "Write a haiku about GPUs."}],
stream=True,
stream_options={"include_usage": True},
)
for chunk in stream:
if chunk.choices and chunk.choices[0].delta.content:
print(chunk.choices[0].delta.content, end="", flush=True)Set stream_options.include_usage if you need the token counts — without it the final usage chunk is omitted.
Tool calling
tools = [{
"type": "function",
"function": {
"name": "get_weather",
"description": "Return the current weather for a city.",
"parameters": {
"type": "object",
"properties": {"city": {"type": "string"}},
"required": ["city"],
},
},
}]
response = client.chat.completions.create(
model="zai-org/GLM-5.3",
messages=[{"role": "user", "content": "What is the weather in Ljubljana?"}],
tools=tools,
)
tool_call = response.choices[0].message.tool_calls[0]
# Run the tool, append the assistant turn and a {"role": "tool", ...} message, call againTool reliability varies by model
Open models call tools less consistently than frontier closed models on long loops. moonshotai/Kimi-K3 and zai-org/GLM-5.3 are the strongest tool callers in the catalog; validate a tool-heavy workflow on your own prompts.
Vision
Send images as content parts when the model supports it:
messages=[{
"role": "user",
"content": [
{"type": "text", "text": "What is the total on this invoice?"},
{"type": "image_url", "image_url": {"url": f"data:image/png;base64,{b64}"}},
],
}]Check capabilities.image_input.supported on GET /v1/models first — the platform rejects an image sent to a text-only model. See Images and vision.
Response shape
Standard OpenAI Chat Completions: id, object, created, model, choices[] with message and finish_reason, and a usage block.
{
"id": "chatcmpl-...",
"object": "chat.completion",
"model": "zai-org/GLM-5.3",
"choices": [{
"index": 0,
"message": { "role": "assistant", "content": "Hello!" },
"finish_reason": "stop"
}],
"usage": {
"prompt_tokens": 18,
"completion_tokens": 3,
"total_tokens": 21,
"prompt_tokens_details": { "cached_tokens": 0 }
}
}usage.prompt_tokens_details.cached_tokens is the number of prompt tokens served from the prefix cache. Reasoning models may also return reasoning_content on the message.
Processing modes
/v1/chat/completions runs realtime by default and supports priority and flex:
response = client.chat.completions.create(
model="zai-org/GLM-5.3",
messages=[{"role": "user", "content": doc}],
service_tier="priority", # 1.3x list, jumps the pending queue (priority-enabled orgs)
)Priority buys queue position, not speed: the request is granted ahead of queued default-tier traffic and is never turned away because the queue is full, but running requests are never preempted. With no queue, priority changes nothing. The response echoes the tier actually served in service_tier.
Flex is the opposite trade — a discount for waiting:
response = client.chat.completions.create(
model="zai-org/GLM-5.3",
messages=[{"role": "user", "content": doc}],
service_tier="flex", # 0.7x list, may queue up to 30 minutes
)Background execution and batches are on the OpenAI Responses API surface and the Batch API.
Errors
Every HTTP error on /v1/chat/completions uses the OpenAI error envelope, so the OpenAI SDKs raise their typed exceptions with type, code, and param filled in. The same envelope applies to /v1/responses, /v1/embeddings, and /v1/models.
{
"error": {
"message": "Model \"acme/unknown\" is not available for inference. Choose a model with platform_status=available.",
"type": "not_found_error",
"param": "model",
"code": "model_not_found",
"extra": { "param": "model", "code": "model_not_found" }
}
}In HTTP error bodies, message, type, param, and code are always present; param and code are null when they do not apply. Errors the platform raises with metadata also repeat it under error.extra. A model called on the wrong endpoint, for example, returns:
{
"error": {
"message": "...",
"type": "invalid_request_error",
"param": "model",
"code": null,
"extra": { "param": "model" }
}
}Spend limits and model-access policy put their details there too: {"code": "MEMBER_MONTHLY_LIMIT", "limit_micros": 1000000, "spent_micros": 1000250, "flavor": "monthly", "limit_source": "..."} on a 402, or {"code": "TEAM_MODEL_POLICY", "blocked_by": "org", "model": "..."} on a 403. Streaming error frames are shaped differently; see Errors while streaming.
| Status | type | code | When | OpenAI SDK exception |
|---|---|---|---|---|
| 400 | invalid_request_error | null, or context_length_exceeded (param: "messages"), invalid_request_parameters, structured_output_schema_unsupported, sync_output_budget_exceeded (param: "max_tokens"), idempotency_key_invalid (param: "Idempotency-Key") | Malformed body (param is the field path, such as messages[0].content, and message starts with it), a model called on the wrong endpoint (param: "model"), thinking that cannot be turned off, priority not enabled for your organization, a prompt longer than the context window, a parameter the engine refused, an output cap that did not fit the sync window (see below), or an Idempotency-Key that is empty or over 256 characters | openai.BadRequestError |
| 401 | authentication_error | null | Missing, invalid, or revoked key | openai.AuthenticationError |
| 402 | insufficient_quota | insufficient_quota for an exhausted balance, or the spend-limit code: TEAM_, DEPARTMENT_, MEMBER_, MEMBER_MODEL_, or API_KEY_ followed by MONTHLY_LIMIT or DAILY_LIMIT (for example MEMBER_MODEL_DAILY_LIMIT) | Team balance exhausted, or a spend limit reached. Stays 402, so the SDKs do not retry it | openai.APIStatusError with status_code == 402 |
| 403 | permission_error | null, or TEAM_MODEL_POLICY | The model is blocked by an organization or member allowlist, or is not available to your account | openai.PermissionDeniedError |
| 404 | not_found_error | model_not_found (param: "model") | Unknown, retired, or unavailable model id | openai.NotFoundError |
| 408 | invalid_request_error | null | A flex request did not complete inside the 1800s flex window. The SDKs retry 408 automatically | openai.APIStatusError |
| 409 | invalid_request_error | idempotency_key_in_progress, idempotency_key_reused, idempotency_result_unavailable (all param: "Idempotency-Key") | Idempotency conflicts, or a replay whose result zero data retention already scrubbed. See Idempotency keys | openai.ConflictError |
| 413 | request_too_large | null | Request body over the size limit | openai.APIStatusError |
| 429 | rate_limit_error | max_queue_wait_exceeded (param: "max_queue_wait_s"), rate_limit_exceeded | Your own max_queue_wait_s bound fired, or the per-team image budget is used up. Sent with Retry-After | openai.RateLimitError |
| 500 | server_error | null, or the worker's failure code | Inference failed on our side. Safe to retry | openai.InternalServerError |
| 503 | server_error | max_queue_wait_exceeded (param: null), model_at_capacity, image_processing_at_capacity, or null | Platform capacity: the admission ceiling fired, the model's realtime queue is full, realtime dispatch is restarting, the worker running the request went away, image processing is at capacity, or (code: null) the stream relay is unavailable. Sent with Retry-After; model fallback can absorb these | openai.InternalServerError |
| 504 | server_error | null | Inference did not finish within the 1200s synchronous wait. The request is cancelled server-side | openai.InternalServerError |
sync_output_budget_exceeded is returned on a non-streaming request when you set an output cap above the default and generation ran past half of the sync window (see the 504 timeout above). Stream, use background mode on /v1/responses, or lower the cap. param is "max_tokens" even when you sent max_completion_tokens. If your cap is at or below the default, or generation had not yet run for half the window, the same timeout is a 504 instead. It is a 400, so the SDKs do not re-run a request that already used the whole window.
Branch on the exception class or status_code first, then on code. The subclasses all extend openai.APIStatusError, so catch that last:
import os
import openai
client = openai.OpenAI(
base_url="https://api.sference.com/v1",
api_key=os.environ["SFERENCE_API_KEY"],
)
try:
response = client.chat.completions.create(
model="zai-org/GLM-5.3",
messages=[{"role": "user", "content": "Say hello."}],
)
except openai.NotFoundError as e:
# 404 model_not_found: not a catalog id. List valid ids with GET /v1/models.
raise SystemExit(e.message)
except openai.RateLimitError as e:
# 429: your max_queue_wait_s bound fired, or the image budget is used up.
retry_after = e.response.headers.get("retry-after")
raise
except openai.BadRequestError as e:
if e.code == "context_length_exceeded":
... # trim messages and retry
raise
except openai.APIStatusError as e:
if e.status_code == 402:
# Balance exhausted (code "insufficient_quota") or a spend limit
# (code "MEMBER_MONTHLY_LIMIT", "TEAM_DAILY_LIMIT", ...). Not retryable.
...
raiseErrors while streaming
A request that fails before the stream starts gets an ordinary HTTP error from the table above: authentication, validation, billing, and unknown models. A max_queue_wait_exceeded rejection also arrives as HTTP when it lands while the API is still holding the response headers. That happens when you set max_queue_wait_s (the hold lasts up to your bound plus 15 seconds), or within the first second of an unbounded realtime request. create(..., stream=True) raises these before you read a chunk.
After the stream has started, a failure ends it with a data: {"error": {...}} frame followed by data: [DONE]. error.type is one of:
error.type | Meaning | Other fields |
|---|---|---|
invalid_request_error | A fault in the request found during generation | code is context_length_exceeded or invalid_request_parameters; param is "messages" or null |
rate_limit_error | Your own max_queue_wait_s bound fired after the stream started | code: "max_queue_wait_exceeded", param: "max_queue_wait_s", retry_after_s, source: "client" |
server_error | The platform ceiling or a capacity condition rejected the request after the stream started, or the API itself failed | Ceiling: code: "max_queue_wait_exceeded", param: null, retry_after_s, source: "ceiling". API failure: code: "server_error", param: null, message "Internal server error" |
inference_error | Generation failed on the worker or engine | Only message: the engine's own text, or "Inference failed" |
timeout | No result arrived before the stream's time budget, or the stream ended without a final frame | Only message: "inference timed out" |
code and param appear only on client faults, queue-wait rejections, and the API-failure frame. For example:
data: {"error": {"message": "...", "type": "inference_error"}}
data: [DONE]The OpenAI SDKs raise openai.APIError from the iterator when they read that frame. Chunks you received before the error are still valid output.
Not supported
| Field | Why |
|---|---|
n (multiple completions) | One completion per request. Fan out with concurrent requests |
logprobs, top_logprobs | Not exposed by the serving engines |
logit_bias | Not supported |
chat_template_kwargs | Ignored, not rejected. Turn thinking off with enable_thinking or reasoning_effort |
The full grid, including what is ignored rather than rejected, is on API compatibility.
API surfaces
sference serves three request shapes — the OpenAI Chat API, the OpenAI Responses API, and the Anthropic Messages API — over one catalog, one key, and one bill.
OpenAI Responses API
POST /v1/responses on sference: the OpenAI Responses shape with background execution, streams, the 24h window, and the events API.