Errors
Every failure is a JSON body with an HTTP status. This is the answer to a request sent without a key:
{
"error": {
"message": "Missing API key. Send it as: Authorization: Bearer <your OceanToken key>.",
"type": "authentication_error",
"param": null,
"code": "invalid_api_key"
}
}
On /v1/messages, the same object is wrapped as {"type":"error","error":{…}}.
Branch on code. It is a fixed vocabulary that we keep stable; message is for people and its wording may change. type groups codes into families that are handled the same way. The HTTP status tells you the same thing at a coarser grain, so existing clients that branch on it keep working.
Codes
| HTTP | type | code | What happened | What to do |
|---|---|---|---|---|
| 400 | invalid_request_error | invalid_request | The request was malformed: a missing field, a value the model does not accept, a bad image. | Fix the request. Do not retry as-is. |
| 400 | not_found_error | model_not_found | The model name does not exist. | Pick a name from GET /v1/models. |
| 402 | insufficient_credits | insufficient_credits | Your available credits are exhausted. Nothing ran and nothing was charged. | Add credits, then retry. |
| 402 | insufficient_credits | key_budget_exceeded | This key's own credit limit is used up (your account may still have credits). | Raise the key's limit, wait for its reset, or use another key. |
| 402 | insufficient_credits | request_exceeds_balance | Your balance is above $0, but what is left after your requests in progress have reserved their share is less than this request could cost at most. That worst case is the input at the full input price plus max_tokens of output (held to the model's output limit; without max_tokens, that limit, at most 16,384 tokens), times n, plus any per-request or search fee, at the highest price any of the model's channels could bill, long-context and reasoning prices included. Nothing ran and nothing was charged. | Lower max_tokens or shorten the input, or add credits. |
| 400 | insufficient_credits | trial_video_daily_limit | Free credit only: 3 videos have been created in the last 24 hours. The error carries videos_per_24h and next_video_at (UTC), when the next video can be created. Nothing ran and nothing was charged. | Wait until next_video_at, or add credits: the limit applies only while free credit is all you have. |
| 400 | content_policy_violation | content_filtered | A safety check refused the request or the model's answer. A refusal of the request itself is not charged; if the answer is refused after the model produced it, the output generated so far may be billed. | Change the input. Retrying the same input gives the same answer. |
| 401 | authentication_error | invalid_api_key | No key, an unknown key, or a deleted key. | Check the Authorization: Bearer sk-... header. |
| 401 | authentication_error | key_expired | The key's expiration date has passed. | Create a new key. |
| 403 | permission_error | model_not_allowed | The key is valid but this model is outside your account's allowed set. | Use a model from GET /v1/models. |
| 403 | permission_error | forbidden | The key may not perform this operation. Managing API keys is one: an API key cannot create, change, rotate or delete keys. | Manage keys in the console; otherwise use a key with the right scope. |
| 404 | not_found_error | not_found | Unknown path, or a video / job id that does not exist. | Check the URL and the id. |
| 409 | idempotency_error | idempotency_key_reused | The Idempotency-Key was already used with a different body. | Use a fresh key for a new request. See Retries. |
| 409 | idempotency_error | idempotency_key_in_progress | The first request with this key is still running. | Wait for Retry-After seconds, then retry the same request. |
| 409 | idempotency_error | idempotency_result_unavailable | The request with this key already ran and was charged, but its response could not be kept for a replay. This retry was not run or charged. | Look up the result instead, for example the job in the console's Logs. A new key runs the request, and charges it, again. |
| 409 | invalid_request_error | conflict | The request clashes with the current state, for example a code that was already used or the same call already running. You sent no Idempotency-Key, or this is not about it. The message says what clashed. | Read the message. Retrying the same request gives the same answer. |
| 429 | rate_limit_error | rate_limited | You exceeded your key's requests- or tokens-per-minute limit. | Back off until Retry-After; see Limits. |
| 429 | rate_limit_error | concurrency_limited | Too many of your account's requests, or of its video, image and 3D jobs, are running at the same time. Nothing ran and nothing was charged. (Video and 3D create calls are queued instead of refused; see Jobs running at the same time.) | Retry after Retry-After seconds, or when one of your running requests or jobs finishes. |
| 429 | rate_limit_error | provider_overloaded | Every channel of the model is at capacity right now. See Retries and failover. | Retry with backoff, or switch models. |
| 501 | invalid_request_error | not_supported | The endpoint is not offered: batches (/v1/batches), fine-tuning (/v1/fine_tuning), and listing, reading or deleting files under /v1/files. | Do not retry. Send each request to its regular endpoint instead. |
| 503 | api_error | temporarily_unavailable | The gateway could not check what it needs to accept the request, such as your organization's balance, just now. Or the model is paused for a while: the message then says the model is temporarily unavailable and to use another one, and Retry-After is an hour. Nothing ran and nothing was charged. | Retry after Retry-After seconds. For a paused model, switch to another model. |
| 503 | api_error | moderation_unavailable | The content check could not run just now. This is not a refusal of your content. Before the answer starts, streamed or not, this is an ordinary error response: nothing ran and nothing was charged. While a response is streaming, the stream ends with this error as its final chunk, and the output already streamed is billed as usual. This is rare. | Retry. |
| 5xx | api_error | provider_error | The model failed, after the gateway's own retry and failover. Not charged. | Retry with backoff; if it persists, switch models. |
| 408 | api_error | timeout | A stream received nothing from the model for 120 seconds after it started. | Retry with backoff. |
| 504 | api_error | timeout | The request ran past the 240-second window. | Stream the response, shorten the request, or use an asynchronous endpoint. |
Anything not in this table is an api_error. New codes may be added; existing ones are not renamed or removed.
The request ID
Responses to model requests carry the header x-oceantoken-request-id. Log it with your errors and quote it when you write to us. A 401 response carries it too, but a 401 never reached a model, so it is not in Logs.
A successful response also has an id in its body, and every chunk of a stream carries the same id. That is the Request ID the console shows under Logs, with the request's status, latency and cost, and the id that GET /v1/usage/{request_id} looks up.
Retries
Before an error reaches you, the gateway has already retried it and, where the model has another channel, moved the request there. Retries and failover explains what it handles and what it leaves to you.
Retry only on these: 408; 429; any 5xx except 501; 409 idempotency_key_in_progress, after Retry-After; a network failure (a dropped connection, a client-side timeout). Every other 4xx, and 501 not_supported, will fail the same way again until the request or the account changes.
Use exponential backoff with jitter, starting around one second and capping at about thirty; when the response carries Retry-After (a number of seconds), wait at least that long.
Retry-After is guaranteed only on 409 idempotency_key_in_progress; on a 429 or a 503 it may be absent, so fall back to your own backoff.
# Retry only what can succeed on a second try: 429, 408 (timeout), every 5xx
# except 501 (an endpoint that is not offered) and network failures,
# with exponential backoff and jitter, honouring Retry-After when it is sent.
import os
import random
import time
from openai import APIConnectionError, APIStatusError, OpenAI
client = OpenAI(
base_url=os.getenv("OCEANTOKEN_BASE_URL", "https://api.oceantoken.ai/v1"),
api_key=os.environ["OCEANTOKEN_API_KEY"],
max_retries=0, # the loop below does the retrying
)
def with_retries(call, attempts=5):
for attempt in range(attempts):
try:
return call()
except APIConnectionError:
if attempt == attempts - 1:
raise
delay = None # network failure: back off and try again
except APIStatusError as e:
retryable = e.status_code in (408, 429) or (e.status_code >= 500 and e.status_code != 501)
if not retryable or attempt == attempts - 1:
raise
retry_after = e.response.headers.get("retry-after")
delay = float(retry_after) if retry_after else None
time.sleep(delay if delay is not None else min(30, 2**attempt) + random.random())
models = with_retries(lambda: client.models.list())
print(len(models.data), "models")
Retrying a request that costs money
Image, video and speech requests are charged when they run. A retry after a network timeout would otherwise run them a second time. Send an Idempotency-Key header (any unique string, up to 255 characters, for example a UUID) on POST /v1/images/generations, /v1/images/edits, /v1/videos and /v1/audio/speech:
- The first request runs normally and its response is kept for 24 hours.
- A retry with the same key and the same body gets that response back, marked with the header
Idempotency-Replayed: true. Nothing runs and nothing is charged. Successes are kept, and so are refusals the same request would get again, such as a malformed body or an unknown model. - The same key with a different body is refused with
409 idempotency_key_reused. - A retry while the first request is still running gets
409 idempotency_key_in_progresswithRetry-After. - If the first request succeeded but its response could not be kept, a retry gets
409 idempotency_result_unavailableand is not run or charged again. - A
5xxanswer, or a refusal for your key, a rate limit or your balance, is not kept, so a retry runs again.
Keys are scoped to your API key. The header is ignored on every other endpoint, and on the endpoints above a request without it behaves exactly as before. Responses above 8 MB are not kept; the request still runs, only the replay does not apply.
Errors while streaming
With "stream": true, an error that occurs before the first token is an ordinary JSON error response with the status above. An error after the stream has started arrives as a final data: chunk whose payload is the same error object, and then the stream ends.
A stream that ends early, because the connection broke, you disconnected, or an error cut it off, is billed at the model's usual prices for:
- its prompt, in full;
- the output streamed up to that point. A reasoning model's streamed reasoning counts as output, even when no answer text had arrived yet.
A stream that ended before producing any output is not billed at all.
If you cancel a stream (you close the connection before it ends), some channels keep generating, and the model provider charges for that output. On those channels the request is billed for the output the provider recorded, which can be more than what reached you, by at most $0.10. Where there is no such record, the rules above apply. A stream cut off by an error or by the channel is billed only for what was streamed.
Balance exhausted
When your balance is at or below $0, every request to a paid model is refused with 402 insufficient_credits. Nothing is run and nothing is charged. Add credits and retry. Models whose ID ends in :free still work at a $0 balance.
When your balance is above $0 but less than a request could cost at most, that request alone is refused with 402 request_exceeds_balance; smaller requests still run.
The message says what the request could cost and what your balance is.
Lower max_tokens or shorten the input to run it within your balance, or add credits.
Migrating from OpenAI
Error bodies have the same error object as OpenAI's.
Two cases answer with a different status or code:
| Case | OpenAI | OceanToken |
|---|---|---|
| Balance used up | 429 insufficient_quota | 402 insufficient_credits |
| Unknown model | 404 model_not_found | 400 model_not_found |
The code values are ours throughout; Codes lists them.
A few statuses carry our own meaning: a model at capacity is 429 provider_overloaded (OpenAI answers 503), 408 timeout is a stream that went quiet, 409 is an idempotency conflict, and 501 not_supported is an endpoint we do not offer.
If your code reads 429 insufficient_quota as out of money, look for 402 insufficient_credits instead; it is not a 429, so a retry loop does not spin on it.
An unknown model is a 400, so a handler that waits for a 404 does not see it; branch on code and the check works on both.
Content policy
Requests and answers that trip a safety check are refused with 400 content_filtered. A refusal of the request itself is not charged. If the answer is refused after the model produced it, the output generated so far may be billed. If the check itself cannot run, the request fails with 503 moderation_unavailable instead. That is not a refusal. Before the answer starts, nothing ran and nothing was charged; while an answer is streaming, the stream ends with this error and the output already streamed is billed as usual. It is rare; retry.
Refusal reasons: error.reason and error.character
A content refusal keeps code content_filtered and the same HTTP status, and adds two fields to the error object:
{
"error": {
"message": "The request was rejected because it violated the content policy. The content may involve a copyrighted character (e.g. Superman).",
"type": "content_policy_violation",
"param": null,
"code": "content_filtered",
"reason": "copyrighted_character",
"character": "Superman"
}
}
reason(string) is always present oncontent_filtered. Its values are in the table below.character(string, optional) names the character, for example"Superman". It appears only whenreasoniscopyrighted_characterand the character is named.
message may also end with an English sentence that gives the reason (never for prompt_attack or other_policy). Its wording may change like any message; branch on reason.
reason | What it means |
|---|---|
copyrighted_character | The content may involve a copyrighted character. |
copyrighted_content | The content may involve copyrighted material, such as a brand, a logo, music or lyrics. |
real_person | The content may show a real, identifiable person: a face, a likeness or a voice. |
sexual | Flagged as sexual content. |
violence | Flagged as violence. |
hate | Flagged as hate. |
self_harm | Flagged as self-harm. |
prompt_flagged | The prompt text failed content review. |
input_media_flagged | A reference image, video or audio failed content review. |
output_flagged | The generated result failed content review. |
prompt_attack | The prompt looks like a jailbreak or a prompt injection. |
other_policy | Refused by the content policy, with no more specific reason. |
Treat any value not in this table as other_policy; the list may grow.
A failed video job carries the same two fields on the job's error (see The job). When moderation refuses a video job as it is created, so that the POST /v1/videos request itself fails, the code stays invalid_request, and the error may also carry reason. Read reason whenever it is there, whatever the code.
Finding a failed request
Apart from a 401, every failure is recorded in the console under Logs with its status and the response body. Find it by its time and model, and quote its x-oceantoken-request-id when you write to us.