HTTP API
tur serve exposes an OpenAI-compatible API for one chat model and, with --whisper, one speech-to-text model. Chat requests carry text, plus images and video for models with a vision encoder (Qwen3.5 and Gemma 4) and audio for models with an audio encoder (Gemma 4 E2B and E4B). Requests and responses follow OpenAI's shapes, with a few extra fields for the chat template and prefix reuse. Request bodies may be up to 64 MiB.
GET /v1/models
Lists the served chat model, and the transcription model when one is loaded:
{"object":"list","data":[{"id":"qwen","object":"model","created":1792867193,"owned_by":"tur","revision":"2fc06364715b967f1860aea9cf38778875588b17"}]}
revision is the checkpoint's immutable revision, so a client can tell exactly what is answering it.
POST /v1/chat/completions
curl http://127.0.0.1:8080/v1/chat/completions \
-H 'Content-Type: application/json' \
-d '{
"model": "qwen",
"messages": [{"role": "user", "content": "Say hi"}],
"max_tokens": 16,
"temperature": 0,
"thinking": false
}'
Request
| Field | Type | Default | Meaning |
|---|---|---|---|
messages |
array | required, non-empty | Conversation turns, see below |
model |
string | served model | If present, must equal --served-model-name (otherwise 404) |
max_tokens |
integer > 0 | 1024, or what the context leaves | Most tokens to generate, counting EOS. An explicit value must fit the context |
max_completion_tokens |
integer > 0 | max_tokens |
OpenAI's newer name for max_tokens, which newer clients send; it wins when both are set |
stop |
string or array | none | End the answer before the first of these texts (up to 16, each up to 1024 bytes). The text is left out, and finish_reason is stop |
stream |
bool | false | Server-sent events instead of one JSON response |
temperature |
number ≥ 0 | checkpoint | 0 is greedy |
top_k |
integer > 0 | checkpoint | |
top_p |
number in (0, 1] | checkpoint | |
repetition_penalty |
number > 0 | none | Above 1 discourages any token already in the prompt or output |
presence_penalty, frequency_penalty |
number | none | OpenAI semantics over generated tokens |
seed |
integer | 299792458 | Seed of the request's random stream; other requests in the batch don't affect it |
tools |
array | none | {type:"function",function:{name,description,parameters}} |
tool_choice |
"auto", "none", "required" or {"type":"function","function":{"name":...}} |
"auto" |
See Structured output |
response_format |
{"type":"text"}, {"type":"json_object"}, {"type":"json_schema","json_schema":{"schema":...}} or {"type":"grammar","syntax":...,"definition":...} |
text | See Structured output |
logprobs |
bool | false | Return each generated token's log probability |
top_logprobs |
integer, at most 20 | 0 | Also return this many likeliest tokens at each position; needs logprobs |
thinking (alias enable_thinking) |
bool | template default | Passed to the chat template |
reasoning_effort |
low, medium, xhigh |
template default | Passed to the chat template |
preserve_thinking |
bool | template default | Passed to the chat template |
cache_salt |
string | none | Prefix-reuse namespace: only requests with the same salt share cached prompts |
Each message has a role of system, developer (read as system), user, assistant or tool. content is a string or an array of {"type":"text","text":...} parts. Assistant turns may carry reasoning_content and tool_calls (function calls with JSON-encoded arguments), and tool results are tool turns. The checkpoint's own chat template renders all of them.
User content may also hold audio parts, in OpenAI's input_audio form or as an audio_url holding a data: URL:
{"role": "user", "content": [
{"type": "input_audio", "input_audio": {"data": "<base64 WAV>", "format": "wav"}},
{"type": "text", "text": "Transcribe this audio."}
]}
Audio must be WAV (integer PCM or float, any rate and channel count) and 40 ms to 30 s long. Only models with an audio encoder accept it; others answer 400. Remote URLs are rejected, since the server never fetches media. Audio positions count toward prompt_tokens, 25 per second. See Audio.
Images go in OpenAI's image_url part, holding a data: URL:
{"role": "user", "content": [
{"type": "image_url", "image_url": {"url": "data:image/png;base64,<base64 file>"}},
{"type": "text", "text": "What is in this picture?"}
]}
Images must be PNG, JPEG, WebP or GIF, and are scaled down to 1,048,576 pixels at most. Only models with a vision encoder accept them; others answer 400. detail is accepted and ignored. Image positions count toward prompt_tokens: one per 32×32 pixels on Qwen3.5, and up to 280 on Gemma 4. See Images and video.
Videos go in a video_url part, also holding a data: URL:
{"type": "video_url", "video_url": {"url": "data:video/mp4;base64,<base64 file>"}}
Videos must be H.264 or HEVC in an MP4 file, within the 64 MiB body limit once encoded. tur serve --video-input=false answers these parts with 400 before reading them. Each sampled step adds its soft tokens and a timestamp to prompt_tokens: up to 2048 soft tokens on Qwen3.5, and 70 per frame for up to 32 frames on Gemma 4.
Prompts containing a placeholder token without its image, video or clip are rejected.
Response
{
"id": "chatcmpl-5973f2662efe4acba8df912a7343688c",
"object": "chat.completion",
"created": 1792867193,
"model": "qwen",
"choices": [{
"index": 0,
"message": {"role": "assistant", "content": "Hello! How can I help you today?"},
"finish_reason": "stop"
}],
"usage": {
"prompt_tokens": 14, "completion_tokens": 12, "total_tokens": 26,
"prompt_tokens_details": {"cached_tokens": 0}
}
}
finish_reason is stop when the model ends its turn, length when it hits max_tokens, or tool_calls. completion_tokens counts sampled tokens, including the end-of-turn token. cached_tokens counts prompt tokens restored from a prefix snapshot rather than computed, which is a quick way to check that prefix reuse is working.
When a model reasons, message.reasoning_content holds the reasoning and content only the answer, without the tags that delimit the reasoning. gpt-oss writes reasoning on a separate Harmony channel, Inkling 2 in a thinking message of its own, Gemma in a thought channel, and Qwen between <think> and </think> once the prompt opens thinking, which thinking: true does and Qwen3.8's template does by default. Send the reasoning back in reasoning_content on later turns with tool calls, and the template replays it.
When the model emits complete function calls, Tur parses them against each tool's parameter schema and returns them as tool_calls. Text the model wrote before its calls stays in content, which is null when the reply is only calls. A call that max_tokens cut off isn't a call, so it comes back as text with finish_reason length. Tur never runs the tools itself.
On Qwen, a parameter is read as JSON when its schema says it can't be a string. A schema with several types, in a type list or in anyOf or oneOf alternatives as MCP servers often write optional parameters, is read as JSON when the text parses as one of its other types. So 7 for {"anyOf": [{"type": "integer"}, {"type": "null"}]} arrives as the number 7.
With logprobs, choices[0].logprobs.content lists a token, logprob, bytes and top_logprobs for every generated token except the end-of-turn token. The numbers describe the model's own distribution, before penalties, temperature, truncation and grammar masks, so top_logprobs can name a token that a grammar forbade. The list also covers reasoning and any text a stop sequence removed. Asking for log probabilities doesn't change which tokens a seed produces.
Structured output
A grammar built from the request masks every token the output may not contain, so the result matches its format even at high temperature. Grammars and structured output has examples and advice. If max_tokens runs out first, the output is cut off and finish_reason is length.
curl http://127.0.0.1:8080/v1/chat/completions \
-H 'Content-Type: application/json' \
-d '{
"messages": [{"role": "user", "content": "Describe Ada Lovelace as JSON."}],
"response_format": {"type": "json_schema", "json_schema": {"name": "person", "schema": {
"type": "object",
"required": ["name", "born"],
"properties": {"name": {"type": "string"}, "born": {"type": "integer"}}
}}}
}'
response_format forces compact JSON in content: any object with json_object, or a match for the schema with json_schema. grammar, a Tur extension, forces text matching a definition whose syntax is regex or lark. The model isn't told about the format, so say what you want in a message too. An invalid schema or grammar answers 400. response_format can't be combined with tools, because the model could never reach them, unless tool_choice is none.
tool_choice decides what happens to tools:
| Value | Effect |
|---|---|
auto |
The template lists the tools and the model decides. Its text isn't constrained, but on Qwen and Gemma a grammar holds each call to its schema from the call's opening token. If a tool's schema can't be enforced, as below, calls run unconstrained instead of failing. gpt-oss calls have no such opening token, so they run unconstrained too, and malformed ones come back as text |
none |
The tools are left out of the prompt |
required |
The output is one or more calls to any of the tools. gpt-oss ends its turn after one call |
{"type":"function","function":{"name":"f"}} |
The output is one call to f |
Forced calls come back as tool_calls and match the tool's parameters: gpt-oss writes them as JSON, and the others in their own formats. On Qwen, a parameter whose type isn't number, integer, boolean, object, array or null is free text unless it has a string enum. On Gemma, the schema may use only type, enum, properties, required, items and annotations such as description, and any other keyword answers 400 so that nothing goes unenforced.
Forced output can follow reasoning, whose text is unconstrained and counts toward max_tokens. gpt-oss reasons first unless thinking is false. Qwen and Gemma run with thinking off unless thinking is true. In every case the reasoning comes back in reasoning_content, apart from the answer. Allow generous max_tokens when reasoning is on.
A mask can't make a model want what it allows. If a schema ends where the model meant to keep writing, it can pick the next legal token again and again, as Gemma E2B did with thinking on by filling an integer with digits until max_tokens. Keep schemas close to what you ask for in the prompt, and bound what can grow, with maximum, maxLength or maxItems.
Tokens the grammar alone decides, such as JSON keys, are published without sampling and then run together as one pass, so key-heavy output is several times faster. They arrive in bursts. logprobs needs each position's logits, so it turns this off, and it also adds about 6% per token with one request and 25% with eight.
Constrained requests are never drafted (see Speculative decoding).
Streaming
With "stream": true, the response is text/event-stream:
- A chunk with
delta: {"role": "assistant"}. - Text chunks with
delta.content, one per model pass at most. Reasoning a model separates arrives the same way indelta.reasoning_content. - With
logprobs, one chunk holding all of them inchoices[0].logprobs, because text fragments don't line up with tokens. - Tool-call chunks, if any, one per call. A call's raw text never appears in
delta.content: on Qwen and Gemma the worker keeps every token from a call's opening marker to its closing one out of the text, and gpt-oss writes calls on their own channel. - A final chunk with
finish_reasonandusage. data: [DONE].
The server sends a keep-alive comment every 15 seconds. If generation fails mid-stream, it sends an error object as a data event, then [DONE].
A slow client never holds up other requests. Each stream has a small bounded queue, and text that doesn't fit waits in a buffer. If a client falls more than 16 KiB behind, the server cancels its request with a slow_client error and frees its memory. A disconnected client is noticed within one pass.
POST /v1/responses
OpenAI's Responses API, for clients such as the OpenAI Agents SDK and Codex that speak it instead of chat completions. It runs the same generation as chat completions, so models, templates, tool parsing and grammars behave the same. Tur stores no responses: send the whole conversation in input each time, as clients do with "store": false.
curl http://127.0.0.1:8080/v1/responses \
-H 'Content-Type: application/json' \
-d '{
"instructions": "Use tools when they help.",
"input": "What is the weather in Paris?",
"tools": [{"type": "function", "name": "get_weather",
"parameters": {"type": "object", "properties": {"city": {"type": "string"}}, "required": ["city"]}}]
}'
{
"id": "resp_3daa...", "object": "response", "created_at": 1793708914, "status": "completed", "model": "qwen",
"output": [
{"type": "function_call", "id": "fc_a094...", "call_id": "call_e36c...", "name": "get_weather",
"arguments": "{\"city\":\"Paris\"}", "status": "completed"}
],
"usage": {"input_tokens": 277, "input_tokens_details": {"cached_tokens": 0}, "output_tokens": 26,
"output_tokens_details": {"reasoning_tokens": 0}, "total_tokens": 303},
"incomplete_details": null, "error": null
}
To continue, append the response's output items to input as they came, then a function_call_output item with the same call_id for each call, and send the request again.
| Field | Meaning |
|---|---|
input |
A string, read as one user message, or a list of items: messages (type may be left out) with a role of system, developer, user or assistant, function_call, function_call_output and reasoning |
instructions |
A system message ahead of input |
tools |
Function tools: {"type":"function","name":...,"description":...,"parameters":...} |
tool_choice |
"auto", "none", "required" or {"type":"function","name":...}, as in Structured output |
text.format |
{"type":"text"}, {"type":"json_object"} or {"type":"json_schema","schema":...}, like response_format |
max_output_tokens |
Like max_tokens |
temperature, top_p |
As for chat completions |
reasoning.effort |
Like reasoning_effort |
thinking (alias enable_thinking) |
A Tur extension, as for chat completions |
prompt_cache_key |
Partitions prefix reuse like cache_salt |
stream |
Server-sent events instead of one JSON response |
Message content is a string or a list of input_text, output_text, refusal and input_image parts, where an image is a data: URL. A function_call_output's output is a string or such a list. A reasoning item's text, its content if present or else its summary, goes to the assistant turn after it. Other fields, such as store, include and parallel_tool_calls, are ignored.
The output list holds a reasoning item when the model separates its reasoning, then a message with one output_text part unless the reply is only calls, then a function_call item per call. status is completed, or incomplete with incomplete_details.reason max_output_tokens when the limit cut the reply off. reasoning_tokens isn't counted apart from output_tokens and reads 0.
Requests Tur can't honor answer 400: previous_response_id, because nothing is stored; hosted tools such as mcp, web_search or file_search, because Tur never runs tools (an agent runs its MCP tools itself and offers them as functions); and a function_call_output whose call_id no earlier function_call in input has.
With "stream": true, every event carries its type as the SSE event name and a sequence_number from 0:
response.createdandresponse.in_progress, with an emptyoutput.- For reasoning and then the answer:
response.output_item.added,response.content_part.added, aresponse.reasoning_text.deltaorresponse.output_text.deltaper model pass at most, then the matching.doneevent,response.content_part.doneandresponse.output_item.done. - For each call:
response.output_item.added, oneresponse.function_call_arguments.deltaholding all the arguments,response.function_call_arguments.doneandresponse.output_item.done. response.completed, orresponse.incomplete, with the whole response. Its items, ids included, are the ones streamed.
If generation fails, the stream ends with response.failed, whose response holds the error code and message. Keep-alives and slow clients are handled as for chat completions.
POST /v1/audio/transcriptions
Transcribes speech with the --whisper model. The body is multipart/form-data, as OpenAI's API takes it:
curl http://127.0.0.1:8080/v1/audio/transcriptions \
-F model=whisper-1 -F file=@speech.wav -F language=en
{"text": "The quick brown fox jumps over the lazy dog."}
| Field | Default | Meaning |
|---|---|---|
file |
required | A WAV file |
model |
the transcription model | Must equal --transcription-model-name (otherwise 404) |
language |
detected | ISO 639-1 code such as en |
response_format |
json |
json, text, verbose_json, srt or vtt |
timestamp_granularities[] |
segment |
segment or word; word needs verbose_json and adds a words list |
prompt |
none | Text the decoder reads before every window, for names and style |
condition_on_previous_text |
false |
true also reads the text decoded so far (a Tur extension) |
temperature |
0 | 0 decodes greedily and retries doubtful windows at rising temperatures; up to 1 samples at that temperature, without retries |
verbose_json adds the task, language, duration in seconds and timed segments:
{"task": "transcribe", "language": "en", "duration": 2.66, "text": "The quick brown fox jumps over the lazy dog.",
"segments": [{"id": 0, "seek": 0, "start": 0.0, "end": 2.66, "text": " The quick brown fox jumps over the lazy dog.", "tokens": [50365, 440, 1702]}]}
Silent windows produce no text. Clips longer than 30 s are transcribed window by window, each resuming where the last complete segment of the one before it ended, so no word is cut between them. The 64 MiB request limit bounds a clip's length. A full transcription queue answers 429.
POST /v1/audio/translations
Takes the same form and returns English text translated from the speech. Whisper large-v3-turbo was not trained for translation, so prefer a multilingual checkpoint such as large-v3 for this endpoint.
POST /v1/decisions
Answers typed questions about an input with a probability per option, in the shape of OpenAI's Decisions API, so the OpenAI SDKs work by pointing base_url at the server. It needs a decision checkpoint, a model trained to answer this way instead of generating text. Tur serves Intern-Decision, an Apache-2.0 fine-tune of Qwen3.5 whose authors report it 9.4 points behind TypeSafe's Jev at 0.8B (79.4 against 88.7 on their seven-benchmark average) and 1.3 ahead at 4B. Other models answer 400.
tur serve internlm/Intern-Decision-0.8B --revision 42457fafd13d10d0b0d9be46cb30a23caa409994
from openai import OpenAI
client = OpenAI(base_url="http://127.0.0.1:8080/v1", api_key="unused")
decision = client.decisions.create(
model="Intern-Decision-0.8B",
input="The package arrived with a broken screen. I want my money back.",
questions=[
{"type": "predicate", "name": "damaged", "instructions": "Does the customer report a damaged item?"},
{"type": "choice", "name": "queue", "instructions": "Which team should handle this ticket?",
"choices": [{"value": "billing", "description": "Refunds and payments"},
{"value": "shipping", "description": "Delivery and damaged items"}]},
{"type": "score", "name": "urgency", "instructions": "How urgent is this ticket?",
"levels": [{"label": "low"}, {"label": "medium"}, {"label": "high"}]},
{"type": "predicate", "name": "praise", "instructions": "Is the customer praising the product?"},
],
)
The 0.8B checkpoint answers:
{"model": "Intern-Decision-0.8B",
"answers": [
{"type": "predicate", "name": "damaged", "probability": 0.87},
{"type": "choice", "name": "queue", "choice": "billing", "confidence": 0.56,
"probabilities": [{"value": "billing", "probability": 0.56}, {"value": "shipping", "probability": 0.44}]},
{"type": "score", "name": "urgency", "score": 1.23, "confidence": 0.43,
"probabilities": [{"value": 0, "label": "low", "probability": 0.17}, {"value": 1, "label": "medium", "probability": 0.43}, {"value": 2, "label": "high", "probability": 0.40}]},
{"type": "predicate", "name": "praise", "probability": 0.25}],
"usage": {"input_tokens": 335, "output_tokens": 0, "total_tokens": 335,
"input_tokens_details": {"cached_tokens": 0, "cache_write_tokens": 0},
"output_tokens_details": {"reasoning_tokens": 0}}}
All questions go into one prompt. The user turn shows the state and lists each question's options under the symbols A, B, C and so on; the assistant turn is a JSON object whose values are the checkpoint's <decision> token. A question's answer is the softmax over its symbols' logits at the token before its marker, tempered by the temperature the checkpoint's authors fitted (2.75 for the 0.8B). Nothing is generated, so output_tokens is 0. The prompt matches the checkpoint's own inference.py token for token, and the probabilities match its reference within 0.002 with F32 weights and 0.03 with the default Q8_0.
| Field | Meaning |
|---|---|
model |
As for chat completions; must be a decision checkpoint |
input |
The state. A string, or messages with content as a string or input_text, output_text, input_json and input_image parts. Images (up to 8, data: URLs) go to the model in order as Picture 1, Picture 2 and so on. A single user message with one other part is passed as that value, so input_json reaches the model as JSON; anything else becomes a list of {role, content} turns |
questions |
1 to 16 questions, answered in order. Each has type, instructions and an optional name; unnamed questions are called q1, q2 and so on by position, and names must be unique |
prompt_cache_key |
Partitions prefix reuse like cache_salt |
type |
Extra fields | Answer |
|---|---|---|
predicate |
none | probability that the answer is yes |
choice |
choices: 2 to 62 {value, description?}, values strings or booleans and distinct as text |
choice, confidence, probabilities per value |
score |
levels: 2 to 10 {label, description?}, lowest first |
score (the probability-weighted level index from 0), confidence, probabilities per level |
confidence is the probability of the likeliest option, and ties go to the smallest value. Every question is read in the passes that prefill the prompt, so a request costs what its prompt does: on an M1 one question about the ticket above (194 tokens) takes about 205 ms, and all four (335 tokens, split into two passes at the 256-token snapshot boundary) about 300 ms. Prefix reuse applies to the input, so repeating a 1,900-token state with new questions restored 1,792 tokens and took 0.25 s. With the fixture image of colour ramps and a stripe, the 0.8B answers that it mainly shows stripes (0.81) and bright colours (0.82). The temperature is known only for the published 0.8B; a local copy reads uncalibrated. Function-call input items, refusals and streaming aren't supported.
Operating the server
These endpoints have no authentication, like the rest of the API, so keep the port away from untrusted clients.
GET /health
Liveness. Returns 200 with {"status":"ok"} while the process answers and every worker runs, and 503 with {"status":"worker_stopped","workers":[...]} once one has stopped. Nothing restarts a stopped worker, so restart the server when this fails.
GET /ready
Readiness. Returns 200 with {"status":"ready"} when new requests would be served, and 503 for a stopped worker or a server that is draining. The listener opens only after every model has loaded, so a server that accepts connections has finished loading.
GET /metrics
Counters and gauges in Prometheus text format. The ones you'll usually want:
| Metric | Meaning |
|---|---|
tur_requests_total{model,outcome} |
Finished requests: ok, cancelled or an error code. It counts failures mid-stream, which HTTP status can't show |
tur_http_requests_total{path,status} |
Finished HTTP exchanges by route |
tur_request_duration_seconds, tur_time_to_first_token_seconds |
Latency histograms of successful requests |
tur_requests_running, tur_requests_waiting |
Current load |
tur_prompt_tokens_total, tur_cached_prompt_tokens_total, tur_generated_tokens_total |
Token counts of finished requests |
tur_preemptions_total |
Recomputations forced by memory pressure; a steady rise means the pool is too small for the load |
tur_kv_pages_leased, tur_kv_pages_peak, tur_kv_pages_capacity |
State pool occupancy |
tur_context_tokens, tur_memory_plan_*_bytes |
What startup planned |
tur_device_allocated_bytes, tur_process_resident_bytes |
What is actually allocated |
tur_system_spare_memory_bytes, tur_system_swapouts_total |
Memory pressure on the machine; swap is counted from server start |
tur_pass_phase_seconds_total{phase}, tur_device_seconds_total |
Where pass time goes |
tur_model_info{source,revision} |
The served checkpoint, as labels |
GET /diagnostics
One JSON document for a person debugging the server: version, process ID, uptime and system memory, then for each model its revision, weight and K/V formats, context limit, the whole memory plan, scheduler limits, device capabilities and kernel tuning, pool occupancy, latency histograms, and sampling, prefix and speculation counters. tur status and tur top are built on it. context reads:
{"limit_tokens": 8192, "full_contexts": 4, "sized_for_tokens": 8192, "max_running": 4}
limit_tokens is the most one request may hold, and full_contexts is how many requests of sized_for_tokens the pool holds at once. When full_contexts is below max_running, some requests wait or recompute at full length.
Errors
Errors use OpenAI's shape:
{"error": {"message": "Request queue is full: …", "type": "rate_limit_error", "code": "queue_full"}}
| Status | type / code |
Cause |
|---|---|---|
| 400 | invalid_request_error |
Empty messages, unknown role, invalid sampling values, unsupported tool_choice, a schema, grammar or tool choice that can't be honored (a grammar failing during generation has the code invalid_grammar), undecodable or unsupported audio, images or video, a decision request with too many or malformed questions or for a model that isn't a decision checkpoint, a Responses request with previous_response_id, a hosted tool or a function_call_output without its call, or a request the engine rejects (invalid_request) |
| 400 | invalid_request_error / context_length_exceeded |
The prompt and max_tokens don't fit the context the server allows |
| 404 | invalid_request_error |
Unknown model |
| 408 | timeout_error / slow_client |
A streaming client stopped reading |
| 413 | (plain text) | The body exceeds 64 MiB |
| 422 | (plain text) | The body doesn't deserialize, for example an image content part |
| 429 | rate_limit_error / queue_full |
The queue already holds --max-waiting requests |
| 503 | server_error / insufficient_memory |
The request can't fit in memory even running alone |
| 503 | server_error / worker_unavailable |
The inference worker stopped |
| 503 | server_error / server_shutting_down |
The server is draining |
| 504 | timeout_error / deadline_exceeded |
--request-timeout-secs elapsed |
| 500 | server_error / internal_error |
Anything else |
CORS is permissive, and every request is logged under the tower_http target.