Skip to main content

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​

HTTPtypecodeWhat happenedWhat to do
400invalid_request_errorinvalid_requestThe request was malformed: a missing field, a value the model does not accept, a bad image.Fix the request. Do not retry as-is.
400not_found_errormodel_not_foundThe model name does not exist.Pick a name from GET /v1/models.
402insufficient_creditsinsufficient_creditsYour available credits are exhausted. Nothing ran and nothing was charged.Add credits, then retry.
402insufficient_creditskey_budget_exceededThis 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.
402insufficient_creditsrequest_exceeds_balanceYour 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.
400insufficient_creditstrial_video_daily_limitFree 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.
400content_policy_violationcontent_filteredA 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.
401authentication_errorinvalid_api_keyNo key, an unknown key, or a deleted key.Check the Authorization: Bearer sk-... header.
401authentication_errorkey_expiredThe key's expiration date has passed.Create a new key.
403permission_errormodel_not_allowedThe key is valid but this model is outside your account's allowed set.Use a model from GET /v1/models.
403permission_errorforbiddenThe 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.
404not_found_errornot_foundUnknown path, or a video / job id that does not exist.Check the URL and the id.
409idempotency_erroridempotency_key_reusedThe Idempotency-Key was already used with a different body.Use a fresh key for a new request. See Retries.
409idempotency_erroridempotency_key_in_progressThe first request with this key is still running.Wait for Retry-After seconds, then retry the same request.
409idempotency_erroridempotency_result_unavailableThe 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.
409invalid_request_errorconflictThe 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.
429rate_limit_errorrate_limitedYou exceeded your key's requests- or tokens-per-minute limit.Back off until Retry-After; see Limits.
429rate_limit_errorconcurrency_limitedToo 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.
429rate_limit_errorprovider_overloadedEvery channel of the model is at capacity right now. See Retries and failover.Retry with backoff, or switch models.
501invalid_request_errornot_supportedThe 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.
503api_errortemporarily_unavailableThe 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.
503api_errormoderation_unavailableThe 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.
5xxapi_errorprovider_errorThe model failed, after the gateway's own retry and failover. Not charged.Retry with backoff; if it persists, switch models.
408api_errortimeoutA stream received nothing from the model for 120 seconds after it started.Retry with backoff.
504api_errortimeoutThe 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_progress with Retry-After.
  • If the first request succeeded but its response could not be kept, a retry gets 409 idempotency_result_unavailable and is not run or charged again.
  • A 5xx answer, 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:

CaseOpenAIOceanToken
Balance used up429 insufficient_quota402 insufficient_credits
Unknown model404 model_not_found400 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 on content_filtered. Its values are in the table below.
  • character (string, optional) names the character, for example "Superman". It appears only when reason is copyrighted_character and 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.

reasonWhat it means
copyrighted_characterThe content may involve a copyrighted character.
copyrighted_contentThe content may involve copyrighted material, such as a brand, a logo, music or lyrics.
real_personThe content may show a real, identifiable person: a face, a likeness or a voice.
sexualFlagged as sexual content.
violenceFlagged as violence.
hateFlagged as hate.
self_harmFlagged as self-harm.
prompt_flaggedThe prompt text failed content review.
input_media_flaggedA reference image, video or audio failed content review.
output_flaggedThe generated result failed content review.
prompt_attackThe prompt looks like a jailbreak or a prompt injection.
other_policyRefused 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.