Text
Create Message
Creates a message using the Anthropic Messages API format
Overview
This endpoint accepts the native Anthropic Messages format, so the Anthropic SDKs and tools built on them work with the TokenLab base URL. It works with models whose accepted_request_formats lists anthropic_messages: Claude models and some other models.
messages holds user and assistant turns. Put system instructions in the top-level system field. max_tokens is required. For OpenAI-style messages with roles such as system or tool, use Chat Completions.
Base URL for Anthropic SDK: https://api.tokenlab.sh (no /v1 suffix)
Request Headers
Your TokenLab API key. Send either x-api-key or Authorization: Bearer <API_KEY>. If you send both with different values, TokenLab uses x-api-key.
Anthropic API version. Anthropic SDKs send it for you; use 2023-06-01 when you call the API directly.
Anthropic beta feature names, separated by commas. TokenLab passes the header on, and whether a beta feature works depends on the model. Content that references a file_id needs files-api-2025-04-14.
Request Body
Supported optional parameters, accepted values, and defaults depend on the selected model. Check its model details before setting sampling, reasoning, or tool options.
ID of a model that supports the anthropic_messages format. Check its model details for current capabilities.
Array of message objects with role (user or assistant) and content. Up to 100,000 messages.
content can be a plain string or an array of content blocks. To send images, use structured content blocks rather than placing image URLs or Base64 strings directly into plain text. Other native blocks, such as tool_use, tool_result, thinking, and document, are accepted for models that support them.
Example content blocks:
- text block:
{ "type": "text", "text": "Describe this image" } - image block via URL:
{ "type": "image", "source": { "type": "url", "url": "https://example.com/image.jpg" } } - image block via Base64:
{ "type": "image", "source": { "type": "base64", "media_type": "image/png", "data": "iVBORw0KGgoAAA..." } }
Maximum tokens to generate. Required: TokenLab does not add a default. The usable maximum depends on the model; see max_output_tokens in its model details. A large value raises the amount TokenLab holds from your balance while the request runs, and a balance that cannot cover the hold returns 402.
System prompt as a string or an array of text content blocks, separate from the messages array.
Sampling temperature. Support, allowed values, and the default depend on the selected model; omit this field to use its default.
falseReturn the response as a stream of server-sent events. See Streaming.
Native thinking configuration, for example {"type":"enabled","budget_tokens":10000}. Supported modes, budgets, and combinations with other parameters depend on the selected model. For a model that is known to reject a manual budget, TokenLab runs {"type":"enabled"} as adaptive thinking and ignores budget_tokens.
Available tools for the model. Support depends on the selected model.
Native tool-choice object, for example {"type":"auto"}. Supported types depend on the selected model.
Prompt-caching marker, for example {"type":"ephemeral"}; add "ttl": "1h" for a one-hour cache. At the top level it turns on automatic caching. You can also set it on system blocks, tools, and content blocks. Support depends on the model; models that support it list prompt-cache in capabilities.
Nucleus sampling parameter. Use either temperature or top_p, not both. Support depends on the selected model.
Only sample from the top K options for each token. Support depends on the selected model.
Custom stop sequences that will cause the model to stop generating. Up to 8,191 entries.
Request metadata in the Anthropic format. user_id is an opaque identifier for your end user.
Only auto and standard_only take effect. TokenLab prices the standard tier only and ignores any other value.
Response
Unique message identifier.
Always message.
Always assistant.
Array of content blocks, such as text, thinking, or tool_use.
Model that produced the response.
Reason generation stopped, such as end_turn, max_tokens, stop_sequence, or tool_use. A model can return other values, for example refusal.
The stop sequence that ended generation, or null.
Token usage with input_tokens and output_tokens. When the model reports prompt-cache tokens, usage also has cache_creation_input_tokens and cache_read_input_tokens.
Every response carries the request ID in the request-id and X-Request-ID headers. Quote it when you contact support.
Request
curl -X POST "https://api.tokenlab.sh/v1/messages" \
-H "x-api-key: sk-your-api-key" \
-H "anthropic-version: 2023-06-01" \
-H "Content-Type: application/json" \
-d '{
"model": "claude-sonnet-5",
"max_tokens": 1024,
"system": "You are a helpful assistant.",
"messages": [
{"role": "user", "content": "Hello, Claude!"}
]
}'Response
{
"id": "msg_abc123",
"type": "message",
"role": "assistant",
"content": [
{
"type": "text",
"text": "Hello! How can I help you today?"
}
],
"model": "claude-sonnet-5",
"stop_reason": "end_turn",
"usage": {
"input_tokens": 15,
"output_tokens": 10
}
}Vision Input Example
For Claude models with vision support, place images inside messages[].content as structured image blocks.
{
"model": "claude-sonnet-5",
"max_tokens": 1024,
"messages": [
{
"role": "user",
"content": [
{
"type": "text",
"text": "Please describe this image."
},
{
"type": "image",
"source": {
"type": "url",
"url": "https://example.com/demo.jpg"
}
}
]
}
]
}{
"model": "claude-sonnet-5",
"max_tokens": 1024,
"messages": [
{
"role": "user",
"content": [
{
"type": "text",
"text": "Please describe this image."
},
{
"type": "image",
"source": {
"type": "base64",
"media_type": "image/jpeg",
"data": "/9j/4AAQSkZJRgABAQ..."
}
}
]
}
]
}Extended Thinking Example
Use a model with the reasoning capability. Adjust max_tokens and budget_tokens to the model's limits; some models need a different thinking configuration.
from anthropic import Anthropic
client = Anthropic(
api_key="sk-your-api-key",
base_url="https://api.tokenlab.sh"
)
message = client.messages.create(
model="claude-sonnet-5",
max_tokens=16000,
thinking={
"type": "enabled",
"budget_tokens": 10000
},
messages=[{"role": "user", "content": "Solve this math problem..."}]
)
for block in message.content:
if block.type == "thinking":
print(f"Thinking: {block.thinking}")
elif block.type == "text":
print(f"Response: {block.text}")Streaming
Set "stream": true to receive Anthropic server-sent events: message_start, content_block_start, content_block_delta, content_block_stop, message_delta, and message_stop. Token usage arrives in message_start and message_delta.
from anthropic import Anthropic
client = Anthropic(
api_key="sk-your-api-key",
base_url="https://api.tokenlab.sh"
)
with client.messages.stream(
model="claude-sonnet-5",
max_tokens=1024,
messages=[{"role": "user", "content": "Tell me a story"}],
) as stream:
for text in stream.text_stream:
print(text, end="", flush=True)- While the model works, the stream can carry SSE comment lines such as
: keep-alive. SDKs ignore them. - The HTTP status can already be
200when a failure happens. A failure after the stream has started arrives as anevent: errorevent with the same error body as below.
Errors
Errors use the Anthropic error format. request_id is the TokenLab request ID. Some errors add fields such as code and hint.
{
"type": "error",
"error": {
"type": "invalid_request_error",
"message": "max_tokens: Required. /v1/messages follows the native Anthropic contract and does not infer a default max_tokens value."
},
"request_id": "req_01JEXAMPLE"
}| Status | error.type | Typical cause |
|---|---|---|
| 400 | invalid_request_error | A missing or invalid field, an unknown model, or a model that does not accept the Messages format |
| 401 | authentication_error | The API key is missing or invalid |
| 402 | billing_error | The balance cannot cover the request (error.code is insufficient_balance). An API key at its spending limit also gets 402, with error.code quota_exceeded and error.type rate_limit_error |
| 403 | permission_error | The API key cannot use the requested model, or the account is suspended or restricted |
| 409 | conflict_error | A retry with the same Idempotency-Key. See Retry safely with an idempotency key |
| 413 | request_too_large | The request input is too large |
| 429 | rate_limit_error | Too many requests |
| 500, 502, 503 | api_error or overloaded_error | The request could not be completed, or no route is available for it now. Retry later |
| 504 | timeout_error | The request timed out |
Related interfaces
- Count message tokens: estimate the input tokens of a request before you send it.
- Message Batches run many Messages requests asynchronously: create, list, retrieve, cancel, get results, and delete.
Authorization
BearerAuth API Key authentication. Create or manage API keys in Dashboard > API > API Keys.
In: header
Headers
Per-request Delivery policy. Overrides the API key and Workspace defaults. Auto tries TokenLab Verified first and may switch once to Official only before output, request acceptance, or persistent resource creation.
Value in
- "auto"
- "verified"
- "official"
Optional key that stops a second run of the same request. Send a new unique value, such as a UUID, for each request, and keep it for retries after a timeout. A retry with the same key does not run again: it returns 409 with idempotency_replay_unavailable, or usually idempotency_conflict when the body changed. Exception: when a non-stream result finished after the client disconnected, a retry with the same key and body within 24 hours returns that result (up to 1 MB) with the header Idempotent-Replayed: true and no second charge. A key longer than 255 characters is ignored, and the request then has no idempotency protection. See Retry safely with an idempotency key.
1 <= length <= 255Request Body
application/json
Response
application/json
application/json
application/json
application/json
application/json
application/json
application/json
application/json
application/json
application/json
application/json