Responses and Messages APIs
Rendered from docs/protocols.md at commit 813abb1662f7. The repository file is authoritative.
ModelSaar's native surface is OpenAI Chat Completions (POST /v1/chat/completions). Two further
protocols are accepted as stateless, fail-closed translations onto that same path: the request is
translated, then routed, admitted, dispatched and committed by exactly the code that serves chat
completions (server.py::_chat_core), and the answer is translated back. No protocol gets a second,
weaker routing path, and nothing is renamed to look stateful.
Fail-closed means: a field or item that would change what the model is asked, or that depends on state
or tools hosted by the original provider, is refused with a typed 400 before any backend is
contacted. Two purely advisory markers are recorded as translation notes on the routing decision
(compat.protocol_notes, visible with modelsaar decisions <request-id>) instead of being refused.
Evidence: tests/test_protocol_translations.py (real HTTP against the controlled fake backend) and
scripts/protocol_sdk_check.py (the installed modelsaar serve driven by the official openai and
anthropic Python SDKs — real client libraries, simulated models; record in
docs/live-runs/2026-12-04-roadmap/protocol-sdk-check.txt). Not run: a real model behind either
protocol, and any real agent client (Codex CLI, Claude Code) end to end.
POST /v1/responses — stateless subset
| request | disposition |
|---|---|
input string; items message (input_text, output_text, input_image with a data: URL), function_call, function_call_output (string output), reasoning with plain reasoning_text |
translated (reasoning → reasoning_content of the following assistant turn, which requires the continuation capability like any replayed reasoning) |
instructions |
system message |
tools of type function; tool_choice auto/none/required/{type: function, name}; parallel_tool_calls |
translated; the backend path's own limits still apply (Ollama: no required/named) |
text.format text / json_object / json_schema |
response_format; a schema is routed only to a deployment with verified json_schema |
max_output_tokens, temperature, top_p, reasoning.effort, metadata, user, stream |
translated |
store omitted or false |
accepted; the response object says "store": false |
store: true, previous_response_id |
default: 400 unsupported_stateful_feature; with the opt-in local response store (below) they are real state |
conversation |
400 unsupported_stateful_feature in 0.2.0 and by default; accepted with the opt-in Conversations API (after 0.2.0, below) |
background, prompt, item_reference items, encrypted reasoning items |
400 unsupported_stateful_feature (always) |
include, truncation: auto, input_file/audio parts, top_logprobs, service_tier, unknown fields |
400 unsupported_responses_feature / unsupported_content_type |
hosted tools (file_search, mcp, modelsaar_http), max_tool_calls |
400 in 0.2.0 and by default; with the opt-in catalogue (after 0.2.0, hosted-tools.md) the gateway runs them |
web_search, code_interpreter, computer_use, image_generation, any other tool type |
400 unsupported_responses_feature (always) |
GET/DELETE /v1/responses/{id} |
501 by default; served from the opt-in local response store when enabled |
/v1/responses/{id}/cancel, /input_items |
501 unsupported_protocol (always) |
Response: a response object (output items reasoning, message with output_text, function_call
with the backend's call_id), usage mapped from the backend, status completed or incomplete
(max_output_tokens when the backend stopped on length). Streaming emits the typed, sequence-numbered
events (response.created … response.output_text.delta … response.function_call_arguments.delta …
response.completed/response.incomplete). A backend failure after the response was committed ends the
stream with response.failed carrying the gateway's diagnostics — never response.completed, never a
second model's text.
Stateful Responses: the opt-in local response store
The original build brief lists stateful Responses as later work and forbids emulating it "by renaming Chat Completions fields". It is therefore implemented as actual state, and only when an operator turns it on:
protocols:
responses_store:
enabled: true # default false
ttl_s: 86400 # stored responses expire
max_bytes: 2000000
max_chain: 64
store: truepersists the finished response object and that turn's input in the gateway's state database, scoped to the calling API key. This is the one place where the gateway keeps prompts and answers at rest; it is per request (storeomitted = not stored), time-limited and deletable.previous_response_idcontinues from a stored response of the same key: the stored turns are replayed as ordinary history (text and tool calls) before the newinput, and the request is routed and filtered like any other. A chain is one affinity session, so follow-up turns prefer the deployment that answered before. Unknown, expired or foreign ids →404 previous_response_not_found; longer thanmax_chain→400.GET /v1/responses/{id}returns the stored object;DELETEremoves it (and breaks continuation from it).- A failed or truncated stream is never stored. Stored
reasoningitems are returned on retrieval but are not replayed into the next turn (recorded as a protocol note on the decision). - Still not state this gateway has, and still refused: background runs,
prompttemplates,item_reference, encrypted reasoning,/cancel,/input_items. Hosted tools are a separate opt-in (hosted-tools.md). The Conversations API is refused in 0.2.0 and exists as a separate opt-in after it (next section).
Evidence: tests/test_responses_store.py (5); live on the GX10 (owner's check, 2026-12-05): create, GET,
previous_response_id recalled a synthetic word, DELETE → 404.
Conversations API (opt-in; unreleased, after 0.2.0)
protocols:
responses_store: {enabled: true} # required: conversations are stored state
conversations:
enabled: true # default false -> every /v1/conversations route is 501, `conversation` is 400
ttl_s: 604800 # since the last write; expiry removes the conversation and its items
max_items: 500 # per conversation
max_item_bytes: 200000 # UTF-8 bytes of the item as it is stored
max_conversations_per_key: 1000
turn_timeout_s: 600 # a response's hold on its conversation, counted from its last sign of life
A conversation is an ordered list of items — the item shapes POST /v1/responses takes as input and
returns as output — owned by the API key that created it.
| route | behaviour |
|---|---|
POST /v1/conversations {items?, metadata?} |
creates it; returns {id: "conv_…", object: "conversation", created_at, metadata} |
GET / POST / DELETE /v1/conversations/{id} |
retrieve; update metadata; delete with all items |
POST /v1/conversations/{id}/items {items: [...]} (≤ 20 per call) |
appends; returns the stored items with their ids |
GET /v1/conversations/{id}/items?limit=&order=&after= |
cursor pagination (limit 1–100, default 20; order desc by default; after = an item id); {object: "list", data, first_id, last_id, has_more} |
GET / DELETE /v1/conversations/{id}/items/{item_id} |
one item |
POST /v1/responses with conversation: "conv_…" (or {"id": …}) |
replays the stored items as history in front of input, then appends this turn's input items and output items; the response carries conversation: {id} |
Rules:
- Caller isolation. Every route is scoped to the calling key; a conversation of another key is
404("not found for this API key") on read, write, delete and use — its existence is not revealed. - History is replayed as stored. In order and unmodified: no summarising, no truncation. A history that
no longer fits a deployment's context is an ordinary routing refusal (
422); a conversation atmax_itemsrefuses the next turn with400 conversation_fullbefore anything is dispatched. - One writer at a time. A response holds its conversation's turn from before the history is read
until its items are committed. A second response, an append, an item delete or the conversation's delete
during that time is
409 conversation_locked— nothing can change the history a running response was given. The hold is released when the turn ends, however it ends. - Long streams keep their turn; dead requests do not block. Every stream frame renews the hold; it
expires
turn_timeout_safter the last sign of life. A conversation does not expire (TTL) under a turn in progress. - Atomic, owner-only commit. A turn's input and output items are inserted in one transaction together
with the bound check and the TTL renewal — all of them or none. Before that the gateway checks that this
request still owns the turn. If its hold ran out and another writer used the conversation meanwhile,
the history it was given is no longer the stored one: the turn is not stored and the caller is told —
409 conversation_turn_lostfor a non-streamed response, a terminalresponse.failedwith that code for a stream (neverresponse.completed). A hold that ran out without anyone else using the conversation still commits. A turn is never interleaved with another and never dropped silently. - A turn joins the conversation only if it produced a response. A refused or failed turn adds nothing; a
response cut by the output limit (
status: incomplete) is stored as it was returned. Instructions (instructions) are per request and are not stored. - Item ids. The output items of a response keep, in the conversation, the ids the response carried: an
id from
outputcan be retrieved, deleted and used as a pagination cursor. Appended items and a turn's input items get their ids from the gateway; anidsupplied by the caller is not kept. - An answer that cannot be replayed is not stored. The output of a turn is checked against the same
replay contract as appended items before it is committed. A
refusalpart cannot be replayed through chat completions, and a stored one would make every later turn fail; so that turn is not stored —422 conversation_output_not_replayable(the message carries the model's refusal text), or a terminalresponse.failedon a stream — and the conversation is unchanged and usable. Outside a conversation a refusal is returned as an ordinary answer. A streaming response carries the refusal fragments inresponse.refusal.deltaand the complete refusal inresponse.refusal.done. - One stored representation. An item is serialised once, as compact UTF-8 JSON;
max_item_bytesis the size of exactly those bytes (three-byte characters count as three), and those bytes are what is stored. - Storable items are the ones the Responses translation can replay:
message(text and inline image parts),function_call,function_call_output, and the hosted-tool items a turn of this gateway produced (hosted-tools.md; a caller cannot append one of its own).reasoningitems, files, audio anditem_referenceare refused at the door (400 unsupported_conversation_item), not at the next turn. Outputreasoningitems of a turn are returned in that response and not stored. conversationandprevious_response_idare two ways to continue; sending both is400.store: truestill stores the response object independently.- Affinity. One conversation is one affinity session, so later turns prefer the deployment that answered before; hard filters still apply.
- Content at rest. Items are prompts, answers and tool data in the gateway's state database, until the
TTL passes or you delete them (
docs/privacy.md).
Not provided: background runs, items of other types, conversation search or listing across a
key. The turn hold lives in the gateway process, which matches one gateway process per state database; two
processes sharing a database would each grant a turn. Evidence: tests/test_conversations.py (18, fixture
models); live on the GX10 (owner's check, 2026-12-05): a stored fact recalled in a later turn, ownership
(404 for another key), stable pagination, delete → 404.
POST /v1/messages — Anthropic Messages
Authentication accepts x-api-key: <ModelSaar key> or Authorization: Bearer; anthropic-version is
accepted and ignored. Errors use Anthropic's envelope ({"type": "error", "error": {...}}) and keep the
gateway's code and modelsaar diagnostics.
| request | disposition |
|---|---|
system (string or text blocks); messages with text, image (base64 → data: URL), tool_use, tool_result (string or text blocks), thinking blocks |
translated (thinking → reasoning_content, needs continuation) |
tools (custom tools with input_schema); tool_choice auto/any/tool/none, disable_parallel_tool_use |
translated (any → required; refused on a backend path that cannot honour it, never weakened) |
max_tokens (required), temperature, top_p, stop_sequences, metadata.user_id, stream |
translated |
cache_control markers |
recorded note: advisory, the backend manages its own cache; not forwarded |
tool_result.is_error |
recorded note: the result text is forwarded unchanged; the flag is not representable |
thinking budgets (enabled/adaptive), top_k, server/client-defined tools (web_search_*, bash_*, computer_*, text_editor_*, code_execution_*), mcp_servers, container, context_management, output_config, service_tier, document/file blocks, images inside tool results, citations, unknown fields |
400 unsupported_messages_feature / unsupported_content_type |
redacted_thinking blocks |
400 unsupported_stateful_feature (opaque provider state) |
/v1/messages/count_tokens, /v1/messages/batches |
501 unsupported_protocol |
Response: a message with thinking (from the backend's reasoning_content, empty signature), text
and tool_use blocks; stop_reason end_turn/max_tokens/tool_use. A tool call whose arguments are not
a JSON object cannot be a tool_use.input and is answered 502 upstream_bad_response rather than repaired.
Streaming emits message_start, strictly sequential content_block_* events, message_delta,
message_stop. Chat tool-call deltas may interleave across calls, which Anthropic's sequential blocks
cannot express, so each tool_use block is emitted whole at the end of the turn (one input_json_delta
per call). A post-commit backend failure ends the stream with an error event and no message_stop.
What the translations do not establish
Protocol acceptance only. A local model's tool-calling or reasoning behaviour is whatever that deployment does under Chat Completions; a client built around a hosted provider's model (prompt formats, hosted tools, thinking signatures) may still behave differently. Per-client compatibility remains a tested property of an exact client, gateway and deployment combination.