Integrate: handle Forgebench refusals

Forgebench can refuse a call before it reaches the provider. Handle each status in code instead of retrying blindly.

Detect

Find the model calls and any existing error handling around them:

grep -rnoE "except .*(openai|Error)|catch \(|RateLimitError|APIStatusError|retry" --include='*.py' --include='*.ts' --include='*.js' --include='*.tsx' --exclude-dir={node_modules,.git,.venv,dist,build} .

Generic retry-on-any-error wrappers need a change: a 402 or 403 will fail again the same way.

Change

Branch on the status code. Do not loop on 402 or 403.

Report errors the way the app already does. The snippets re-raise 401 and 403 because a rejected key or a model that is not allowed is a configuration problem that should be loud. If the app instead returns an error message to its caller, or logs and carries on, do the same here, so a refusal does not end the process with a traceback.

Keep the model name the app already uses wherever a snippet shows YOUR_MODEL, and take model names from the Gateway model catalog. mock-gpt is only for the Verify step.

Python

The OpenAI client already retries 429, 5xx and connection errors (max_retries=2), so a 429 that reaches your code has used its retries. Handle it as "try again later", not with another retry loop.

import openai

def ask(messages):
    try:
        resp = client.chat.completions.create(model="YOUR_MODEL", messages=messages)
    except openai.AuthenticationError:        # 401: key missing, wrong, rotated or revoked
        log.error("forgebench key rejected")
        raise
    except openai.PermissionDeniedError:      # 403: model, scope or tool not allowed
        log.error("not authorized for this request")
        raise
    except openai.RateLimitError:             # 429: still limited after the client's own retries
        return queue_for_later(messages)
    except openai.APIStatusError as e:
        if e.status_code == 402:              # budget refused, not transient
            return fallback_or_tell_user(messages)
        raise
    return resp.choices[0].message.content

TypeScript

import OpenAI from "openai";

async function ask(messages) {
  try {
    const res = await client.chat.completions.create({ model: "YOUR_MODEL", messages });
    return res.choices[0].message.content;
  } catch (e) {
    if (e instanceof OpenAI.APIError) {
      if (e.status === 401) throw e;                        // key rejected
      if (e.status === 402) return degrade(messages);       // budget refused, do not retry
      if (e.status === 403) throw e;                        // not allowed
      if (e.status === 429) return queueForLater(messages); // still limited after the client's own retries
    }
    throw e;
  }
}

With the Forgebench SDKs use the typed errors instead: BudgetExceededError (402), AuthenticationError (401), PermissionDeniedError (403), RateLimitError (429).

curl

curl -s -o /dev/null -w "%{http_code}\n" -X POST "$FORGEBENCH_BASE_URL/v1/chat/completions" \
  -H "Authorization: Bearer $FORGEBENCH_API_KEY" -H "Content-Type: application/json" \
  -d '{"model":"YOUR_MODEL","messages":[{"role":"user","content":"ping"}]}'

Env

FORGEBENCH_API_KEY and FORGEBENCH_BASE_URL, as in the connect recipe. Read them from the environment with no default value, add .env to .gitignore first, and name both in .env.example (no values).

Verify

Run the call with a deliberately wrong key. It must return 401 and your code must take the 401 branch:

curl -s -w "\n%{http_code}\n" -X POST "$FORGEBENCH_BASE_URL/v1/chat/completions" \
  -H "Authorization: Bearer sk_invalid" -H "Content-Type: application/json" \
  -d '{"model":"mock-gpt","messages":[{"role":"user","content":"ping"}]}'

A wrong key is refused before the call is tied to a workspace, so it does not appear in the refusal records: judge it by the status code and by what your code does. Refusals for a real key, such as a budget, a model allowlist or a rate limit, are recorded. After one happens, call forgebench_integrate verify: each cause appears as a refusal_<cause> check, with what to do about it.

What you get

Policy refusals tied to an authenticated workspace are recorded with their cause. A refusal before provider dispatch has no provider usage. A tool or output-guardrail refusal can happen after the model answers, so that provider usage is still metered.

Pitfalls

  • 402: the budget gate compares spent plus the projected cost with the cap, so a call can be refused while headroom still shows. Queue it, use a cheaper model or tell the user. Never retry in a loop.
  • A 403 can mean a denied model, unauthorized tool, missing scope, module restriction, or a credential used with an unsupported protocol. Read the body. Repeating a call to an unauthorized tool escalates to a 429 circuit breaker.
  • 400 with provider_key_missing means no required workspace provider credential is stored. Ask an admin to add it in the console; do not retry.
  • 400 with a code ending in _streaming_unsupported means the request cannot be streamed under this workspace's policy. Repeat it with stream=false. See the streaming recipe.
  • 429 is a request-rate or tool-call ceiling, not money. Back off and retry.
  • The client's built-in retries do not apply once a stream has started. See the streaming recipe.
  • Keep the client's built-in retries (the OpenAI clients retry 429, 5xx and connection errors by default, max_retries=2). Do not set them to 0 and rebuild that logic: they never retry 401, 402 or 403, which is what you want. Only add handling for those three, plus whatever you do after the retries are used up.
  • A 401 right after a key rotation means a service still has the old secret.

Cookie settings

Our Cookie Policy lists every cookie and what it does.