Anthropic Messages API
POST /v1/messages on sference: an Anthropic Messages-compatible endpoint for open models. Auth, streaming SSE, tool use, extended thinking, vision, usage, and the exact compatibility surface.
Anthropic Messages API
POST https://api.sference.com/v1/messages is an Anthropic Messages-compatible endpoint. Anything that already speaks the Anthropic Messages API points at sference by changing the base URL and the model id. The anthropic Python/TypeScript SDKs, Claude Code, LangChain's ChatAnthropic, and your own client all point at sference by changing the base URL and the model id.
The request and response bodies are Anthropic-shaped. The models behind them are open-weight checkpoints from the sference catalog, with the same logging and audit trail as every other endpoint.
Choosing between the surfaces? See API surfaces for the comparison. /v1/messages is realtime only; see Not supported.
Base URL and authentication
| Endpoint | POST https://api.sference.com/v1/messages |
| Base URL for Anthropic SDKs | https://api.sference.com |
| Auth | x-api-key: sk_... or Authorization: Bearer sk_... |
| Key format | sference keys (sk_...), minted in the console |
Both header styles work, so an Anthropic SDK configured with api_key (which sends x-api-key) and a client configured with a bearer token both authenticate unchanged. anthropic-version is accepted and ignored; there are no dated API versions on sference.
A ?beta=true query parameter is accepted and ignored; Claude Code sends it on every request.
To make a retry safe after a timeout or dropped connection, send an Idempotency-Key header — see Idempotency keys.
Your first request
curl https://api.sference.com/v1/messages \
-H "x-api-key: $SFERENCE_API_KEY" \
-H "content-type: application/json" \
-d '{
"model": "zai-org/GLM-5.3",
"max_tokens": 1024,
"messages": [
{ "role": "user", "content": "Say hello in one sentence." }
]
}'{
"id": "msg_0f8a1c2e-...",
"type": "message",
"role": "assistant",
"model": "zai-org/GLM-5.3",
"content": [{ "type": "text", "text": "Hello, good to meet you." }],
"stop_reason": "end_turn",
"usage": { "input_tokens": 14, "output_tokens": 9 }
}Anthropic Python SDK
from anthropic import Anthropic
client = Anthropic(
base_url="https://api.sference.com",
api_key="sk_...", # your sference key, not an Anthropic key
)
message = client.messages.create(
model="zai-org/GLM-5.3",
max_tokens=1024,
messages=[{"role": "user", "content": "Say hello in one sentence."}],
)
print(message.content[0].text)Anthropic TypeScript SDK
import Anthropic from "@anthropic-ai/sdk";
const client = new Anthropic({
baseURL: "https://api.sference.com",
apiKey: process.env.SFERENCE_API_KEY,
});
const message = await client.messages.create({
model: "zai-org/GLM-5.3",
max_tokens: 1024,
messages: [{ role: "user", content: "Say hello in one sentence." }],
});Model ids are sference catalog ids
Pass a catalog id such as zai-org/GLM-5.3 or moonshotai/Kimi-K3, not a Claude model name. There are no claude-* aliases; claude-sonnet-4-5 returns 404 not_found_error. Matching is case-insensitive, but the id must exist in your catalog. List what your key can reach with GET /v1/models, and see Models for how to choose.
Request fields
Supported
| Field | Notes |
|---|---|
model | Required. sference catalog id. |
max_tokens | Required, as in the Anthropic API. |
messages[] | Required. role is user or assistant; content is a string or a block array. |
system | String or text block array. Folded into one leading system message. |
stream | true emits Anthropic SSE; see Streaming. |
temperature | Forwarded to the engine. |
top_p | Forwarded to the engine. |
top_k | Forwarded to the engine (Anthropic-only knob; it has no OpenAI equivalent). |
stop_sequences[] | Forwarded as the engine's stop strings. |
tools[] | Anthropic-native (name + input_schema) and OpenAI-shaped (type: "function") definitions both accepted. |
tool_choice | auto, none, and required are honored (string or object form), as are Anthropic's {"type": "any"} and {"type": "tool", "name": "..."} and OpenAI's forced-function object. Defaults to auto when tools are present. See Tool use. |
thinking | {"type": "enabled"} / {"type": "disabled"}; see Extended thinking. |
enable_thinking | sference extension; a plain boolean, and it wins over thinking. |
max_queue_wait_s | sference extension; 5–300s admission bound — see Max queue wait. |
Content blocks
| Block | Direction | Support |
|---|---|---|
text | in / out | Full. |
tool_use | in / out | Full; see Tool use. |
tool_result | in | Full, including content block arrays. |
thinking | in / out | Text is preserved; signature is always "". |
image | in | On vision models only; see Images. |
document, redacted_thinking, search_result, server tool blocks | in | Rejected with 400 (Unsupported content block type). |
Unknown top-level fields are ignored rather than rejected, so a client that sends metadata, service_tier, or container gets a normal response; those values simply have no effect. Unknown content block types are a hard 400, because silently dropping message content would change what the model sees.
Streaming
Set stream: true to receive Server-Sent Events in Anthropic's wire format. Tokens are streamed as the engine produces them.
curl -N https://api.sference.com/v1/messages \
-H "x-api-key: $SFERENCE_API_KEY" \
-H "content-type: application/json" \
-d '{
"model": "zai-org/GLM-5.3",
"max_tokens": 1024,
"stream": true,
"messages": [{ "role": "user", "content": "Count to five." }]
}'Events emitted, in order:
| Event | Notes |
|---|---|
message_start | usage.input_tokens is populated once the prompt is tokenized; the cache counters in this frame are placeholders. |
content_block_start | For each thinking, text, and tool_use block. |
content_block_delta | thinking_delta, signature_delta (always empty), text_delta, and input_json_delta for tool arguments. |
content_block_stop | Per block. |
message_delta | Carries the final stop_reason and the authoritative usage, including cache_read_input_tokens. |
message_stop | Terminal frame. |
ping | Keepalive while the request is queued or generating, so intermediaries do not reap a healthy connection during a long time-to-first-token. |
error | Terminal. {"type": "error", "error": {"type": "...", "message": "..."}}; type is usually api_error. See Errors while streaming. |
Two details worth coding against:
- Tool arguments arrive as one
input_json_deltacontaining the complete JSON, not as incremental fragments. Clients that concatenate partials work fine; clients that try to parse each fragment as standalone JSON also work. cache_read_input_tokensonly appears onmessage_delta. The prefix-cache hit is not known whenmessage_startis written.
If a stream ends without a final frame, whether a timeout or a worker that dropped, the endpoint emits an error event before closing, so a client is never left hanging on an open connection.
Tool use
Anthropic-native tool definitions work as written:
{
"model": "moonshotai/Kimi-K3",
"max_tokens": 1024,
"messages": [{ "role": "user", "content": "What files are in the repo root?" }],
"tools": [
{
"name": "list_files",
"description": "List files in a directory",
"input_schema": {
"type": "object",
"properties": { "path": { "type": "string" } },
"required": ["path"]
}
}
]
}The model replies with stop_reason: "tool_use" and a tool_use block carrying id, name, and a parsed input object. Send the result back as a tool_result block in a user turn, keyed by tool_use_id, exactly as with Anthropic.
Notes specific to sference:
- OpenAI-shaped tools are also accepted. A
tools[]entry withtype: "function"and a nestedfunction.name/function.parametersis normalized alongside the Anthropicname/input_schemaform. Mixed arrays are fine. This exists because some Anthropic-compatible clients send the OpenAI shape. tool_choiceforcing is honored.auto,none, andrequiredare normalized and honored, in string or object form. Anthropic's{"type": "any"}is translated torequired(force some tool), and{"type": "tool", "name": "..."}to OpenAI's forced-function object (force that tool). OpenAI's{"type": "function", "function": {"name": "..."}}is accepted as well. A forced name that matches no declared tool returns 400 (tool_choice function '<name>' does not match any tool in 'tools'), and forcing with notoolsreturns 400 (tool_choice requires tools to be set).- Malformed tool arguments are repaired, not dropped. If a model emits arguments that are not valid JSON, sference retries a repair pass and, failing that, hands you
{"__malformed_arguments__": "<raw text>"}rather than an emptyinput. You always see what the model actually produced. - Tool quality tracks the model. Tool calling on open models is parser-dependent;
moonshotai/Kimi-K3andzai-org/GLM-5.3are the strongest agentic choices in the catalog today.
Extended thinking
Reasoning models return their chain of thought as a thinking block ahead of the text block, matching Anthropic's response shape.
Thinking is on by default. Reasoning tokens count toward max_tokens.
Turn it off with thinking: {"type": "disabled"}. enable_thinking: false is also accepted and overrides thinking. chat_template_kwargs is ignored, not rejected.
With structured output, models other than Kimi and GLM (for example DeepSeek V4) default thinking off.
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, raise max_tokens instead of disabling thinking. On chat completions (not this surface), reasoning_effort: "low" is the other option.
Signatures are empty
thinking blocks come back with signature: "". Anthropic's cryptographic thinking signatures are not implemented, and redacted_thinking blocks are not produced. sference re-injects inbound thinking text on multi-turn requests, but a client that validates signatures will not find a valid one.
budget_tokens, thinking: {"type": "adaptive"}, effort, and display are accepted and ignored; use max_tokens to bound total output.
Images
Image blocks are honored on vision-capable catalog models (moonshotai/Kimi-K3, deepseek-ai/DeepSeek-V4.1-Flash-1017 and zai-org/GLM-5.3-Flash today). Both base64 and url sources work, in user turns and inside tool_result content.
On a text-only model, sference does not fail the request. Image blocks are replaced with [image omitted: this model has no vision], a system notice tells the model it has no vision, and a user-turn reminder discourages retrying screenshot tools. This keeps agent loops, which happily attach screenshots, from spinning on a capability the model does not have. If you need vision, pick a vision model; if you get the sentinel, that is why.
Response shape
{
"id": "msg_<request-uuid>",
"type": "message",
"role": "assistant",
"model": "zai-org/GLM-5.3",
"content": [
{ "type": "thinking", "thinking": "...", "signature": "" },
{ "type": "text", "text": "..." },
{ "type": "tool_use", "id": "toolu_...", "name": "list_files", "input": { "path": "." } }
],
"stop_reason": "end_turn",
"usage": { "input_tokens": 812, "output_tokens": 143, "cache_read_input_tokens": 640 }
}idismsg_plus the sference request id, the same id you look up in the console and inGET /control/v1/activity/{request_id}. That makes every Anthropic-shaped call traceable in the audit trail without extra bookkeeping.stop_reasonistool_usewhen the turn ends in a tool call,max_tokenswhen the completion was truncated, otherwiseend_turn.usage.cache_read_input_tokensappears when the prefix cache served part of the prompt; cached input tokens are billed at the lower cached rate. There is nocache_creation_input_tokens; caching is automatic and never billed as a write.stop_sequenceis not returned on non-streaming responses (streamingmessage_deltacarriesstop_sequence: null).
Errors
Every HTTP error on /v1/messages uses the Anthropic error envelope, so the Anthropic SDKs raise their typed exceptions with error.type and error.message filled in:
{
"type": "error",
"error": {
"type": "not_found_error",
"message": "Model \"claude-sonnet-4-5\" is not available for inference. Choose a model with platform_status=available.",
"extra": { "param": "model", "code": "model_not_found" }
}
}The class is carried by error.type and the detail by error.message. A validation error's message starts with the offending field path, for example messages[0].content: .... Two additions to Anthropic's shape:
error.extracarries the platform'scodeandparamon errors the platform raises with metadata:model_not_foundon a 404 like the one above,{"param": "model"}on a model called on the wrong endpoint,{"code": "context_length_exceeded", "param": "messages"}on a prompt refused before it reached a worker, and spend-limit or model-access details on a 402 or 403, for example{"code": "MEMBER_MONTHLY_LIMIT", "limit_micros": 1000000, "spent_micros": 1000250, "flavor": "monthly", "limit_source": "..."}or{"code": "TEAM_MODEL_POLICY", "blocked_by": "org", "model": "..."}. Errors without platform metadata have noextra.request_idappears at the top level only on errors tied to a created request: a 400 from the worker (context length, a refused parameter, or an output cap that did not fit the sync window), amax_queue_wait_srejection decided by the scheduler, and a 500. It is the same id asmsg_<request-id>and the console activity log. Errors raised at intake, such as validation, 402, 403, 404, 504, or a 429 from a stalled queue, do not carry it.
| Status | error.type | Cause | Anthropic SDK exception |
|---|---|---|---|
| 400 | invalid_request_error | Malformed body, unsupported content block, a model called on the wrong endpoint, thinking disabled on a model that cannot turn it off, image that failed validation or fetch, a prompt longer than the context window, an Idempotency-Key that is empty or over 256 characters, or, on a non-streaming request, a max_tokens above the default whose generation ran past half of the 1200s sync window (stream, or lower max_tokens; otherwise the timeout is a 504). | anthropic.BadRequestError |
| 401 | authentication_error | Missing, invalid, or revoked key. | anthropic.AuthenticationError |
| 402 | billing_error | Team balance exhausted, or a spend limit reached. The spend-limit code is only in error.extra.code: TEAM_, DEPARTMENT_, MEMBER_, MEMBER_MODEL_, or API_KEY_ followed by MONTHLY_LIMIT or DAILY_LIMIT. Stays 402, so the SDKs do not retry it. | anthropic.APIStatusError with status_code == 402 |
| 403 | permission_error | The model is blocked by an organization or member allowlist, or is not available to your account. | anthropic.PermissionDeniedError |
| 404 | not_found_error | Unknown, retired, or unavailable model id, including any claude-* name. | anthropic.NotFoundError |
| 409 | invalid_request_error | Idempotency key conflict, or a replay whose result zero data retention already scrubbed; see Idempotency keys. | anthropic.ConflictError |
| 413 | request_too_large | Request body over the size limit. | anthropic.APIStatusError |
| 429 | rate_limit_error | Your own max_queue_wait_s bound fired, or the per-team image budget is used up. Sent with Retry-After. | anthropic.RateLimitError |
| 500 | api_error | Inference failed on our side. Safe to retry. | anthropic.InternalServerError |
| 503 | overloaded_error | 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 the stream relay is unavailable. Sent with Retry-After. | anthropic.InternalServerError |
| 504 | api_error | Inference did not complete within the 1200s sync wait. The request is cancelled server-side, so no work is billed after the timeout. | anthropic.InternalServerError |
import anthropic
try:
message = client.messages.create(
model="zai-org/GLM-5.3",
max_tokens=1024,
messages=[{"role": "user", "content": "Say hello."}],
)
except anthropic.NotFoundError as e:
# 404: not a sference catalog id. List valid ids with GET /v1/models.
raise SystemExit(e.message)
except anthropic.RateLimitError as e:
retry_after = e.response.headers.get("retry-after")
raise
except anthropic.APIStatusError as e:
if e.status_code == 402:
# billing_error. A spend limit names itself in error.extra.code.
extra = e.body["error"].get("extra") or {}
...
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_s 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 request. messages.create(..., stream=True) raises these before the first event.
After the stream has started, a failure ends it with an error event. If message_start has not been sent yet, it is sent first, so the event sequence stays valid. error.type is one of:
error.type | Meaning | error.message |
|---|---|---|
invalid_request_error | A fault in the request found during generation, such as a prompt longer than the context window | The engine's own text |
rate_limit_error | Your own max_queue_wait_s bound fired after the stream started | Human-readable detail. The error also carries code: "max_queue_wait_exceeded", retry_after_s, and source: "client" |
overloaded_error | The platform ceiling or a capacity condition rejected the request after the stream started | Human-readable detail. The error also carries code: "max_queue_wait_exceeded", retry_after_s, and source: "ceiling" |
api_error | Anything else: generation failed, the stream timed out or ended without a final frame, or the API itself failed | The engine's own text, "Inference failed", "inference timed out", or, for an API failure, "Internal server error" |
event: error
data: {"type": "error", "error": {"type": "api_error", "message": "inference timed out"}}The Anthropic SDKs raise anthropic.APIError from the stream when they read that event. Content you received before the error is still valid output.
Not supported
/v1/messages is a realtime endpoint. Anything queued, discounted, or bulk lives on the other surfaces:
Not on /v1/messages | Use instead |
|---|---|
service_tier: "flex" (ignored here) | /v1/chat/completions or /v1/responses; see processing modes |
| Background / batch execution | POST /v1/responses with background: true |
| Bulk jobs on the 24h window | POST /v1/batches |
POST /v1/messages/count_tokens | Not implemented; read usage.input_tokens off a real response |
| Batches, Files, Models list in Anthropic's shape | sference-native /v1/batches, /v1/models |
Prompt caching controls (cache_control blocks, anthropic-beta headers) | Prefix caching is automatic; hits are reported as cache_read_input_tokens |
| MCP connectors, web search, code execution, computer use | Not implemented; server-side tools are Anthropic-hosted |
Citations, document blocks, PDF input | Not implemented |
Thinking signatures, redacted_thinking | Not implemented; see Extended thinking |
Differences from api.anthropic.com at a glance
| Anthropic | sference /v1/messages | |
|---|---|---|
| Models | claude-* | sference catalog ids (open weights, pinned) |
| Auth | x-api-key | x-api-key or Authorization: Bearer |
| Versioning | anthropic-version required | Accepted and ignored |
| Unknown top-level fields | Rejected | Ignored |
| Error body | {"type": "error", "error": {...}} | Same envelope. Unknown model is 404 not_found_error; an exhausted balance is 402 billing_error; platform metadata can appear in error.extra |
| Thinking signatures | Cryptographically signed | Always "" |
| Prompt caching | Explicit cache_control | Automatic prefix cache, read-side reporting only |
| Processing tiers | Standard / batch / priority | Realtime only on this endpoint |
Next steps
Claude Code
Run Claude Code against open models: one-command launch, manual config.
Models
Catalog ids, pinning, and which checkpoints are strongest for agentic tool use.
API Reference
Generated schemas for /v1/messages and every other operation.
Quickstart
API keys, the CLI, and your first request on any endpoint.