| Status | Meaning | Retry? | What to do |
|---|---|---|---|
400 Bad request | Valid JSON, but not usable: outside a limit (options, levels, 64k tokens), a question without what its type needs, an unknown model or question type, a bad image, or a booster that does not exist or does not fit the request | No | Fix the request; the body or x-decisionnode-error names the problem |
401 Unauthorized | Missing or invalid API key | No | Check the Authorization header and that the key is not revoked |
402 Out of credit | An agent workspace's prepaid balance is zero (details.reason balance_empty). Not billed. The response also carries one WWW-Authenticate: Payment challenge per payment method and, when x402 is on, a PAYMENT-REQUIRED header, so an agent can buy credit by machine: see Machine payments. A workspace with members answers the plan reasons below instead | After top-up | Pay with a challenge (Machine payments), then retry |
402 Plan required | A workspace with members and no plan (details.reason plan_required); a plan whose month's allowance and purchased credit are both used (allowance_used, with resets_at); or a trial whose usage cap is used (trial_allowance_used, with trial_ends_at). Not billed | After a change | Choose a plan, start the plan now, add credit or raise the auto reload cap in the console; see Plan required |
403 Refused | Refused by the safety check under your key's policy. Not billed | No | Change what the request asks; see Safety check |
403 Suspended | The workspace is paused or frozen (error_type workspace_suspended). Not billed | After it is resumed | Check the console or contact support |
403 Booster off | A booster the request names is turned off for the workspace (error_type booster_not_enabled). Not billed | After it is on | Turn it on under Boosters in the console, or leave it out |
403 Plan required | A feature outside the workspace's plan (error_type plan_required): a booster past the day's test calls, a batch or session below Pro, a fine-tuned model below Business. details.plan names the plan that has it. Not billed | After an upgrade | Upgrade the plan, or for a booster wait for the test calls to reset; see Plan required |
404 Not found | An unknown path, a batch id your key does not own, or a session that has ended or is not your key's. An ended batch is still found, with its counters | No | Check the path and the id, and call with the key that created it |
405 Method not allowed | A known path with another method; the Allow header lists the right one | No | Use the method in Allow |
408 Request timeout | The body stopped arriving for 20 seconds, or was not complete after 300. The connection is closed | Yes | Retry the same request on a working connection |
409 Conflict | The batch is not in a state that allows the call: a batch that is no longer a draft, or results before the batch has ended | After a change | Retrieve it and act on its state; see Batch errors |
410 Gone | Batch results past their retention | No | Resubmit the requests from your own copy |
413 Payload too large | A body over its size limit: 25 MiB for a request, or a batch upload or add call over its limit. Refused before the body is read when its Content-Length is over, otherwise as soon as it passes the limit; the connection is closed | No | Send less: smaller images, or the batch in parts |
422 Unprocessable | The body failed validation, or is not JSON | No | Fix the fields listed in detail |
429 Too many requests | Over your workspace's rate limit, or a batch or session limit of your key | Yes | Wait Retry-After seconds, then retry; for batch_limit_exceeded, or session_limit_exceeded, wait for one to end |
500 Server error | A fault on our side; also a key that blocks a safety category whose check could not run | Yes | Retry with backoff and jitter |
529 Overloaded | No capacity right now; a request for DecisionNode that opted out of the fallback while it has no ready capacity; or a required booster failed (booster_unavailable) | Yes | Wait Retry-After seconds (usually 1; up to 600 while a model boots), then retry with backoff and jitter |
Error bodies#
detail is a list for 422. For 401, 402, 403, 404, 405, 408, 409, 410, 413, 429, 500 and 529 it is an object with error_type and message. A 400 can take any of three shapes: an object with error_type and message, an object with only error_type (max_tokens_exceeded), or a plain string for a question's limits. Check its type before you branch on it, and branch on error_type, never on the message: messages may be reworded.
A 422 lists every invalid field at once: loc is the path into your body (with the question's key and type), and input echoes what you sent there, so your own error message can point at the exact field.
{
"detail": [
{
"type": "missing",
"loc": ["body", "questions", "route", "choice", "criteria"],
"msg": "Field required",
"input": { "type": "choice", "instructions": "Where should this go?" }
}
]
}Error types#
| error_type | Status | Meaning |
|---|---|---|
api_usage_error | 400 | The request is well formed but cannot be used; the message says why |
max_tokens_exceeded | 400 | Over the token limit; no message, see x-decisionnode-error |
booster_unknown | 400 | A booster name that does not exist |
booster_input_mismatch | 400 | A booster that reads images on a request without any, or an images id that is not an image of the request |
image_url_refused, image_url_unreachable | 400 | An image url the fetch rules refuse (or whose media_type does not match it), or one that cannot be fetched |
upload_not_found, upload_expired, upload_consumed, upload_media_type_mismatch, upload_incomplete, upload_mismatch | 400 | An upload_id that cannot be used; see Uploads |
collection_type_mismatch | 400 | A collection that is not a face collection: "<id> is not a face collection." |
authentication_error | 401 | Missing, unknown or revoked key |
insufficient_credit | 402 | The workspace cannot pay: details.reason plan_required, trial_allowance_used or allowance_used on a workspace with members (Plan required), balance_empty on an agent workspace (Out of credit) |
refusal_error | 403 | Refused by the safety check; category names harm or self_harm |
workspace_suspended | 403 | The workspace is paused, or frozen after a payment dispute; no request runs until it is resumed |
booster_not_enabled | 403 | A booster the request names is turned off for the workspace |
plan_required | 403 | A feature outside the workspace's plan; details.feature names it and details.plan the plan that has it (Plan required) |
key_scope_denied | 403 | A call outside the key's kind: a Decisions-only key on another route ("This key may only make decisions."), a Publishable key on any route but a decision ("A publishable key may only make decisions."), or asking a face search it may not ("This key may not search collections."); a Manage device keys key outside /v1/keys and the usage routes ("This key may only manage keys."), or a Full access key on /v1/keys ("Keys are managed with a keys key, made in the console.") |
origin_not_allowed, model_not_allowed | 403 | A publishable key used from an origin, or for a model, it does not list |
not_found_error | 404 | Unknown path, batch or session |
collection_not_found, item_not_found | 404 | No such collection or item for your workspace; see Collections API |
method_not_allowed_error | 405 | Wrong method for the path |
request_timeout_error | 408 | The body did not arrive in time |
invalid_batch_state, results_not_ready | 409 | The batch is not in a state for this call |
results_expired | 410 | Batch results past retention |
request_too_large_error | 413 | The body is over its size limit |
rate_limit_error, batch_limit_exceeded, session_limit_exceeded | 429 | Over your workspace's rate (or a key's own lower limit), a batch count, or your key's open sessions |
key_spend_cap_reached | 429 | The key has spent its daily spend cap; it works again when the cap resets |
api_error | 500 | A fault on our side |
overloaded_error | 529 | No capacity right now, or DecisionNode has no ready capacity and the request opted out of the fallback |
booster_unavailable | 529 | A booster with require: true failed or ran out of time, or no server that renders the boosters' evidence is ready; retry it |
batch_failed | none | Not an HTTP error: the error.error_type of a batch whose state is failed. See the batch object |
A session's WebSocket reports its end with a close code, not an error_type; see Session errors.
The error header#
Many refusals also carry x-decisionnode-error: what is wrong, in words, such as question 'urgency': a score takes up to 10 levels, got 11 or the token count against the limit. It comes with api_usage_error, the upload errors, a malformed boosters, booster_input_mismatch, a booster timeout_ms out of range, the Collections API's own refusals, and every error the model's server sends; not with 401, 402, 403 (workspace_suspended, booster_not_enabled, key_scope_denied), 404, 405, 408, 413 or 429. Log it with the status: some bodies carry no message of their own. It is ASCII only, and never sent on a 5xx.
Over a limit: 400#
A request that parses but asks for more than a model allows, or leaves out what a question needs, is refused before any model work, and nothing is charged. The body says which rule you crossed, so log it as it is. The limits themselves are on Limits.
| Case | Body |
|---|---|
| More than 255 options | {"detail": "Too many choices. Must have at most 255 choices."} |
| A choice with no options | {"detail": "Choice question must have at least one choice: <key>"} |
| More than 10 score levels | {"detail": "Too many score levels. Must have at most 10 levels."} |
A truth question with neither instructions nor criteria | 400 with a detail message that names the question's key |
A number question without instructions | {"detail": "Number question must have instructions: <key>"} |
| Over 64k tokens | {"detail": {"error_type": "max_tokens_exceeded"}}, with the count and the limit in x-decisionnode-error |
| Unknown model, a fine-tuned version that is not deployed, or another workspace's fine-tuned model | {"detail": {"error_type": "api_usage_error", "message": "Unknown model: <name>"}}, the same in every case |
A boosters array that is not an array, holds more than 4 entries, names a booster twice, holds an entry that is neither a name nor an object with name, an object with a key other than name, images, timeout_ms, require and options, or has a key in options | {"detail": {"error_type": "api_usage_error", "message": "Invalid request."}}, with the reason in x-decisionnode-error |
| A booster name that does not exist | {"detail": {"error_type": "booster_unknown", "message": "Unknown booster: <name>"}} |
A booster that reads images on a request without any, or an images id that is not an image of the request | {"detail": {"error_type": "booster_input_mismatch", "message": "The booster 'age' needs at least one image."}}, or "Booster 'age': 'x9' is not an image of the request." |
| An unknown question type, or a body nested more than 128 objects and arrays deep | {"detail": {"error_type": "api_usage_error", "message": "Invalid request."}} |
| Bad image | The api_usage_error shape, with a message that names the problem: undecodable, an unsupported type, over 10 MB or over 40 megapixels |
An image id over 64 characters | The api_usage_error shape, with a message that names the image |
A picture sent by url that a booster read and that came back different when the model fetched it | {"detail": {"error_type": "api_usage_error", "message": "the picture at that URL changed during the request"}}. Serve pictures from an address that does not change, or send them as uploads |
A browser's cross-origin preflight (OPTIONS with Origin and Access-Control-Request-Method; any other OPTIONS is a 405) | The plain text Disallowed CORS origin, unless it is for POST /v1/decide from an origin a publishable key lists, which gets 204: call it from your server |
Invalid fields: 422#
A field that is missing or has the wrong type, such as a choice without criteria or a state that is a bare number, gets 422 with one entry per invalid field, up to 1,000. A value that may be a string, an object or an array gets three entries, one per allowed form, ending in "str", "dict[any,any]" and "list[any]". Very large echoed values are cut short: past a size limit, later entries come without input.
{
"detail": [
{
"type": "json_invalid",
"loc": ["body", 0],
"msg": "JSON decode error",
"input": {},
"ctx": { "error": "Expecting value" }
}
]
}A number question needs min at or below max and a step above 0, and uses no criteria: its grid is the set of answers. Grids of up to 256 values are one question, and finer or wider grids are composed in the same call, up to 4,096 values in all. A grid that cannot be built is a 422 with one entry per faulty field, the question's path in loc: a min, max or step that is not a number (a string or a boolean) has the type float_type, min above max less_than_equal on min (ctx.le is the max), a step of 0 or below greater_than on step (ctx.gt is 0), a min or step with more than 6 decimals decimal_max_places, a min or max beyond plus or minus 2^53 greater_than_equal or less_than_equal, and a grid over the limit, such as 0 to 1000 at step 0.1 (10,001 values), too_long, with the grid's size in ctx.actual_length: narrow the range or widen the step. Every faulty field of every number question is listed in the same 422.
A missing state is read as an empty state, so a request of questions alone is answered.
Out of credit: 402#
An agent workspace, made by a machine payment and with no members, runs on prepaid credit alone. When its balance reaches zero, every call that puts work in returns HTTP 402 with {"detail": {"error_type": "insufficient_credit", "message": "...", "details": {"reason": "balance_empty"}}} until credit is added (GET /v1/models always answers), so a runaway job stops at a zero balance. A workspace with members answers its own reasons instead, plan_required, trial_allowance_used or allowance_used: see Plan required. A refused request is not billed and runs no model work.
Do not retry a 402 in a loop: it keeps failing until the workspace can pay again. On a workspace with members, keep auto reload on under Billing so credit is bought before it runs out, and alert on any 402 your service still sees. Pricing and billing has the details.
The balance_empty answer also carries one WWW-Authenticate: Payment challenge per payment method and, when x402 is on, a PAYMENT-REQUIRED header, so an agent without a person at hand can buy credit by machine and retry the same call with the credential: see Machine payments. So does a plan's allowance_used; plan_required and trial_allowance_used carry none.
Refused by the safety check: 403#
Every request passes an automatic safety check. By default it only flags, and every request is answered. A key set to block refuses what its policy blocks: choosing, ranking or targeting people to be harmed, or help to self-harm, above the threshold set for it. Detecting a risk is never refused: asking whether a message shows a risk of self-harm, or whether a post is a threat, is answered as usual.
A refused request returns HTTP 403 with {"detail": {"error_type": "refusal_error", "message": "...", "category": "harm"}} (or "self_harm") instead of answers, with x-decisionnode-refusal naming the category, and x-decisionnode-safety marking it ;blocked. A refusal is not billed. Nothing about it is worth retrying: the same request is refused again.
A refusal can also come back as answers. On /v1/decide, send the header x-decisionnode-refusals: per-question: a refused request is then a 200 whose every answer is {"type": "refusal", "category": "harm"} (or "self_harm") under its id, with usage.input_tokens the billed tokens. Without the header, /v1/decide answers the 403 above. See Safety check.
Workspace suspended: 403#
A workspace that is paused, or frozen after a payment dispute, answers every request with HTTP 403 and {"detail": {"error_type": "workspace_suspended", "message": "This workspace is suspended. Contact hello@bynn.com."}}, with no category. Nothing runs and nothing is billed. Do not retry it: it keeps failing until the workspace is resumed. Check the console or contact support, and alert on it like a 402.
Plan required: 402 and 403#
Every workspace you sign up for is on a plan. A request the plan does not cover is refused before anything runs, is not billed, and names what to do. Branch on error_type and details, never on the message.
| Status | error_type | details | When |
|---|---|---|---|
402 | insufficient_credit | {"reason": "plan_required"} | A workspace with members and no plan: sign-up not finished, a trial cancelled, a plan ended or its payment failed. Every decision answers this until an Owner, Admin or Billing member chooses a plan on the console's start step |
402 | insufficient_credit | {"reason": "trial_allowance_used", "trial_ends_at": "...", "start_now": true} | A trial whose usage cap is used. trial_ends_at is when the trial converts; start_now says Start Pro now in the console ends the trial at once and charges the first month, with its full allowance |
402 | insufficient_credit | {"reason": "allowance_used", "resets_at": "...", "auto_reload": "capped"} | A plan whose month's allowance and purchased credit are used. resets_at is the period end; auto_reload says why no credit was bought: off, capped (the month's cap is reached) or failed |
403 | plan_required | {"feature": "booster:knowledge", "plan": "pro", "resets_at": "..."} | A feature outside the plan: booster:<name> past the day's test calls (resets_at is when they reset), batch, sessions or fine_tuning. plan is the lowest plan that includes it |
HTTP/1.1 403 Forbiddenx-decisionnode-plan-required: booster:knowledgecontent-type: application/json{"detail": {"error_type": "plan_required", "message": "The knowledge booster is in the Pro plan. Today's test calls are used; they reset at 00:00 UTC. Upgrade at decisionnode.com/console/plan.", "details": {"feature": "booster:knowledge", "plan": "pro", "resets_at": "2026-10-28T00:00:00Z"}}}- Do not retry them in a loop. A
402answers again until a plan is chosen or started, credit is added, the cap is raised, the trial converts or the period resets; a403 plan_requireduntil the plan changes or, for a booster, the test calls reset. The SDKs never retry them. - Every booster stays testable. Leave the booster out of production requests, or keep it to the day's test calls, until the plan includes it.
- Upgrades take effect at once. A request sent after the upgrade is paid runs under the new plan. See Changing or cancelling a plan.
- The
allowance_usedanswer carries the same payment challenges as an empty balance, so an agent can buy credit by machine: see Machine payments.
Booster errors#
A request that names boosters can get five errors of its own: booster_unavailable (529, retry it), booster_not_enabled (403), and booster_unknown, booster_input_mismatch and a malformed array's api_usage_error (400). The x-decisionnode-boosters header is on every response of such a request, errors included, and says which booster did what.
| Status | Type | When | What to do |
|---|---|---|---|
400 | api_usage_error | boosters is malformed: not an array, more than 4 entries, a name twice, an entry that is neither a name nor an object with name, an object with a key other than name, images, timeout_ms, require and options, a key in options the booster does not take, a threshold outside 0 to 1, a prompt that is not a string of at most 2,000 characters, a bynn_depth grid_size outside 2 to 16, a bynn_segment entry without a prompt, or with a prompt or setting out of its range (its refusals) | Fix the array; x-decisionnode-error says what is wrong |
400 | booster_unknown | A name that is not a booster | Use age, ai_generated, face_detection, face_recognition, ocr, bynn_depth, bynn_segment or knowledge |
400 | booster_input_mismatch | A booster that reads images on a request without any, or an images id that is not an image of the request | Add the image, or fix the id |
403 | booster_not_enabled | The booster is turned off for your workspace. Nothing runs and nothing is billed | Turn it on in the console under Boosters, or leave it out |
529 | booster_unavailable | A booster with require: true failed or ran out of time, with Retry-After and retry-after-ms | Retry after the wait; the booster calls that read are billed, and so are the retry's |
A booster without require that fails never fails the request: the decision runs without its reading, and its evidence entry says timeout or error. A 402 comes before any booster runs.
Batch errors#
The batch endpoints answer with the same body. Their own types:
| Status | Type | When | What to do |
|---|---|---|---|
400 | api_usage_error | An upload that cannot be read; a custom_id missing, over 512 characters or repeated; more than 10,000 requests; finalizing an empty batch or one whose lines name a retired pinned model id; a query value that cannot be read | Fix the call: nothing from it was applied |
404 | not_found_error | No batch with this id belongs to your key | Check the id and the key |
409 | invalid_batch_state | Adding to or finalizing a batch that is no longer a draft; cancelling one that has already ended | Retrieve the batch and act on its state |
409 | results_not_ready | Asking for results before the batch has ended | Poll until results_url is set |
410 | results_expired | Results asked for more than 7 days after the batch ended | Resubmit from your own copy of the requests |
413 | request_too_large_error | An upload over 256 MiB, an add call over 10 MiB, or one line over 25 MiB or over 17,767,680 bytes escaped as a JSON string, an inline image's base64 included; nothing from the call is applied | Split it; send large images as uploads and name them by upload_id |
429 | batch_limit_exceeded | Your key would pass 10 active batches, or 100,000 requests across its active batches (checked when you create, add and finalize) | Wait for a batch to end, or cancel a draft |
429 | rate_limit_error | Over your workspace's request rate (or your key's own lower limit): batch calls count against it | Wait Retry-After seconds, then retry |
500 | api_error | A fault on our side. The call may have taken effect before it | Retry with backoff; before you create again, cancel any draft the failed create left |
529 | overloaded_error | The API cannot take the call right now. Nothing from the call was applied | Wait Retry-After seconds, then retry |
A 5xx or a client timeout can arrive after a batch call took effect, so a retry may find the work done. Reads are safe to retry as they are. A retried add whose lines are already in the draft gets 400 for the repeated custom_id values, and a retried finalize that already went through gets 409 invalid_batch_state: in both cases retrieve the batch and carry on from its state and counters. A retried cancel is harmless. A retried create makes a second draft, so list your batches first and cancel the draft you will not use: a draft never runs and costs nothing, but it counts toward your active batches. Batch jobs has a program that does all of this.
Inside a batch, each request keeps the live errors above: its result line carries the live status and body, such as a 400 for a request over a limit or a 403 refusal, and only lines with status 200 are billed. See Get batch results.
Session errors#
Opening a session answers with the statuses of /v1/decide, plus 429 session_limit_exceeded when your key already holds its open sessions (4 unless we set yours otherwise) and 529 overloaded_error when there is no room for another session. A window outside 1 to 64 or a ttl_seconds outside 1 to 3,600 is a 422, and boosters on an open is a 400 api_usage_error, "boosters are not available on sessions". Connecting to the stream is refused with a close code, not an HTTP status: 4401 (the key is missing or unknown), 4404 (no open session with this id for your key) or 4409 (a socket is already connected).
On the open socket, a frame the API cannot answer gets {"seq": 21, "error": {"error_type": "...", "message": "..."}} and the socket stays open: api_usage_error, rate_limit_error, overloaded_error, api_error or refusal_error. A frame error always has a message, since a socket has no headers; a refusal adds category to error, and a rate_limit_error or overloaded_error comes with retry_after_ms, the wait before sending the frame again. When the session ends, the socket closes with a code that says why; 1006 is what your library reports when the network drops.
| Code | When | What to do |
|---|---|---|
1000 | The session ended on purpose: you closed the socket, or it was ended with DELETE /v1/sessions/{id} | Open a new session when you need one |
1001 | The server holding the session is going away. During a session it has then ended; sent as soon as a connection opens (the server is draining), the session is untouched | Open a new session with the same body; it opens on a server that is up |
1006 | The connection dropped without a close frame: a network fault or a proxy reset. Your WebSocket library reports this code; the server never sends it. The session has ended | Open a new session with the same body, after a capped backoff with jitter |
1008 | A Decisions-only key, sent as soon as the connection opens ("this key may only make decisions"; the session is untouched). Or your client broke a rule of the stream: it stopped reading replies until 256 messages or 16 MiB piled up, sent more than 100 messages in one second that were not valid frames, had 64 frames that name uploads waiting for answers, or sent more than 64 messages or 8 MiB before the session was ready for them. The session has ended | Fix the client: read every reply, send valid frames, and wait for replies before sending more images |
1009 | A message over 1 MiB. The session has ended | Send the frame's image by upload_id |
1011 | Something failed on our side. The session has ended, unless it came as the connection opened while our registry could not be read | Open a new session with the same body, after a capped backoff with jitter |
1013 | Sent as soon as the connection opens: the server is busy, your workspace's or key's request rate is reached (a connect counts as one request), or our key store is busy. The session is still open | Connect again to the same stream_url after a capped backoff with jitter |
4401 | The key is missing or unknown, sent as soon as the connection opens; or the key was revoked during the session (it is checked every second), which has then ended | Check the Authorization header; opening again with the same key will not help |
4402 | Your workspace's prepaid balance is empty: checked at once after the connection opens, then during the session. The session has ended | Add credit; opening a session gets 402 until then |
4403 | Your workspace is suspended: checked at once after the connection opens, then during the session. The session has ended | Contact us; opening a session gets 403 |
4404 | No open session with this id for your key where the connection landed: it ended, expired, never existed or belongs to another key. Sent as soon as the connection opens | Open a new session with the same body |
4408 | No frame arrived for idle_timeout_seconds (120 seconds). Pings do not count. The session has ended | Open a new session with the same body when your next frame is ready |
4409 | Another socket holds this session: one is already connected, or an earlier connection of yours still holds it after that connection dropped. Sent as soon as the connection opens; the session is untouched and the socket holding it keeps it. An earlier connection's hold lapses within 60 seconds of the drop, and the session is then gone: a connect after that gets 4404 | Use the socket you have. Holding no other socket for this session, connect once more after about 60 seconds, and open a new session on the 4404 that follows |
4410 | The session reached expires_at. The session has ended | Open a new session with the same body at once; set ttl_seconds up to 3,600 for longer runs |
Retrying#
Retry 408, 429, 529 and every 5xx; retry 402 once you have added credit; fix the request for the other 4xx. On a 429 or 529 wait at least what retry-after-ms (or Retry-After, in seconds) says. Answers are deterministic, so a retried request returns exactly what the first would have.
Set a client timeout of 10 seconds per attempt, as the code below does. The server answers or refuses a request inside that window: when the work already waiting leaves no room to answer yours in time, it says so at once with a 529, rather than holding the connection until a deadline passes. A timeout on your side therefore usually means a network fault, and it is safe to retry like a 5xx. The exception is a request naming the ocr booster, which can take longer: give it 30 seconds per attempt, as the SDKs do unless you set your own, and do not retry it after a timeout, since the attempt you gave up on may still be answered and billed. Uploads of large images count separately: the time a body takes to arrive is not part of the server's window (see Limits).
import random, time, requests
RETRY = {408, 429, 529}
def wait_for(r, attempt):
"""The server's wait on 429 and 529, else exponential backoff."""
backoff = min(8.0, 0.25 * 2 ** attempt)
if "retry-after-ms" in r.headers:
server = int(r.headers["retry-after-ms"]) / 1000
elif "Retry-After" in r.headers:
server = float(r.headers["Retry-After"])
else:
return backoff
return max(server, backoff) if r.status_code == 529 else server
def decide(body, key, attempts=5):
for attempt in range(attempts):
try:
r = requests.post(
"https://api.decisionnode.com/v1/decide",
json=body,
headers={"Authorization": f"Bearer {key}"},
timeout=10,
)
except (requests.Timeout, requests.ConnectionError):
# a network fault, not an answer: safe to send again
time.sleep(min(8.0, 0.25 * 2 ** attempt) + random.random() / 4)
continue
if r.ok:
return r.json()
if r.status_code in RETRY or r.status_code >= 500:
time.sleep(wait_for(r, attempt) + random.random() / 4)
continue
# 400, 401, 402, 403, 404, 413, 422: retrying will not help.
# (402 clears only once credit is added.)
# detail is a list, an object or a string: log it whole.
reason = r.headers.get("x-decisionnode-error", "")
raise RuntimeError(f"{r.status_code}: {r.json().get('detail')!r} {reason}")
raise RuntimeError("DecisionNode: out of retries")