Fall Back to a Second Provider from the OpenAI SDK

A worked example: one endpoint that asks gpt-6.1-sol first and claude-fable-5-1 when that fails, called from the OpenAI SDK with nothing changed but its base URL and key.

The Route: Support bot

The request goes to OpenAI first, and to Anthropic only when that fails.

Requestfrom your SDK
Fallbackeach in turn
1stOpenAIgpt-6.1-sol
2ndAnthropicclaude-fable-5-1
Requestfrom your SDK
Fallbackeach in turn
1stOpenAIgpt-6.1-sol
2ndAnthropicclaude-fable-5-1

Set up the providers and the endpoint

You need a Model Waygate account and an API key of your own with each provider. Model Waygate stores the provider keys encrypted and uses them only to forward your requests; your application only ever holds a gateway key.

  • 1. Add the providers: on the dashboard's Providers page, add an OpenAI provider named OpenAI with your OpenAI key, then an Anthropic provider named Anthropic with your Anthropic key. Each row's Test button asks the provider for its models, which proves the key works before any request depends on it.
  • 2. Name the endpoint: open New endpoint and name it Support bot. The slug fills in as support-bot and becomes part of the endpoint's URL, never to change.
  • 3. Pick the route: choose A backup model. Tries the first model, and the backup whenever the first fails, for whatever reason.
  • 4. Choose the models: Provider OpenAI, Model gpt-6.1-sol; Backup provider Anthropic, Backup model claude-fable-5-1. The wizard suggests each provider's own models and refuses a backup that is the same provider and model as the first.
  • 5. Mint a key: Create Endpoint opens the endpoint's page. Mint a gateway key there (it starts with mw_ and is shown once) and copy the endpoint's URL beside it.

The route the wizard draws

The diagram above is the endpoint's whole route: the request goes into a fallback, which asks its first child and moves to the second only when the first fails. It opens in the route editor like any route you draw yourself, so you can change it later; each change you publish becomes a new version, deployed when you choose.

  • The route taken: every request records the way it went, on the dashboard's Usage page and on the request's own page: fallback#1 → OpenAI (gpt-6.1-sol) when the first model answered, fallback#2 → Anthropic (claude-fable-5-1) when the backup did.
  • The answer says who answered: the response's model field names the provider model that actually answered, so your code can tell a backup answer from a first-choice one without asking the dashboard.

Send a request with the OpenAI SDK

Point the SDK at the endpoint's URL, https://modelwaygate.com/USER_ID/support-bot/api/v1, with the gateway key in place of an OpenAI key. USER_ID is your account's public id, which the endpoint's URL on the dashboard already carries. Nothing else in your code changes, and the same code keeps working when the first provider is down.

  • model: the field is required, but the route decides which model answers, so its value is only a label. Sending the endpoint's slug keeps your logs readable.
  • One dialect, both providers: the request is Chat Completions whichever provider the route reaches. When it reaches Anthropic, the gateway translates it into Anthropic's Messages API and the answer back, so the reply your code reads has the same shape either way.
  • No real keys here: mw_your_gateway_key stands for the key you minted. Keep it in an environment variable or a secret store, never in source control.

Code Examples

curl https://modelwaygate.com/USER_ID/support-bot/api/v1/chat/completions \
  -H "Authorization: Bearer mw_your_gateway_key" \
  -H "Content-Type: application/json" \
  -d '{
  "model": "support-bot",
  "messages": [
    {"role": "system", "content": "You answer questions about orders in one short paragraph."},
    {"role": "user", "content": "Where is order 1042?"}
  ]
}'
from openai import OpenAI

client = OpenAI(base_url="https://modelwaygate.com/USER_ID/support-bot/api/v1", api_key="mw_your_gateway_key")

response = client.chat.completions.create(
    model="support-bot",
    messages=[
        {"role": "system", "content": "You answer questions about orders in one short paragraph."},
        {"role": "user", "content": "Where is order 1042?"},
    ],
)
print(response.model, response.choices[0].message.content)
import OpenAI from "openai";

const client = new OpenAI({ baseURL: "https://modelwaygate.com/USER_ID/support-bot/api/v1", apiKey: "mw_your_gateway_key" });

const response = await client.chat.completions.create({
  model: "support-bot",
  messages: [
    { role: "system", content: "You answer questions about orders in one short paragraph." },
    { role: "user", content: "Where is order 1042?" },
  ],
});
console.log(response.model, response.choices[0].message.content);
OkHttpClient client = new OkHttpClient();

String json = "{\"model\": \"support-bot\", \"messages\": ["
    + "{\"role\": \"system\", \"content\": \"You answer questions about orders in one short paragraph.\"}, "
    + "{\"role\": \"user\", \"content\": \"Where is order 1042?\"}]}";

Request request = new Request.Builder()
    .url("https://modelwaygate.com/USER_ID/support-bot/api/v1/chat/completions")
    .header("Authorization", "Bearer mw_your_gateway_key")
    .post(RequestBody.create(json, MediaType.get("application/json")))
    .build();

try (Response response = client.newCall(request).execute()) {
    System.out.println(response.body().string());
}
import Data.Aeson (encode, object, (.=))
import Network.HTTP.Client
import Network.HTTP.Client.TLS (tlsManagerSettings)

main :: IO ()
main = do
  manager <- newManager tlsManagerSettings
  initial <- parseRequest "POST https://modelwaygate.com/USER_ID/support-bot/api/v1/chat/completions"
  let turn role content = object ["role" .= (role :: String), "content" .= (content :: String)]
      body = object ["model" .= ("support-bot" :: String), "messages" .= [turn "system" "You answer questions about orders in one short paragraph.", turn "user" "Where is order 1042?"]]
      request = initial{requestHeaders = [("Authorization", "Bearer mw_your_gateway_key"), ("Content-Type", "application/json")], requestBody = RequestBodyLBS (encode body)}
  response <- httpLbs request manager
  print (responseBody response)

When the first provider fails

The wizard's fallback moves on after any failure short of an answer, and your code sees only the backup's answer. The first provider's failure is recorded on the request's page, beside the call that answered.

  • What moves on: OpenAI cannot be reached, has not started answering within 2 minutes or finished a buffered answer within 5 minutes, answers any 4xx (a 429 or a refused key included) or 5xx, redirects, or answers a 2xx that cannot be read or that holds no answer (no text, no tool call, and no finish such as your own token limit to explain it). Each of those sends the same request to Anthropic.
  • When both fail: the caller gets the backup's error. A provider's own 4xx comes back with its status; any other failure of a provider's is a 502, upstream_error when it answered and upstream_unreachable when it could not be reached.
  • What it costs: only bytes beyond the free monthly allowance carry a Waygate fee ($0.03 per MB). The failed call the fallback moved past carries none, and a request whose every provider failed carries none. Each provider bills you directly for whatever its own API charges.
  • A slow first provider: a provider that hangs delays the backup until the first fails. In the route editor, give the first output a timeout of its own (1 to 300 seconds) so the fallback moves on sooner, or route the two through a hedge instead, which asks the backup once the first has kept you waiting a delay you choose, without waiting for it to fail.

Failures that do not fall back

A fallback only judges what its children answer. Some failures happen before the route runs, or stop the whole request, and a backup cannot help with them.

  • Refused before the route: an unknown or disabled gateway key (401), a spend cap reached (402), a rate limit (429) or a request too large (413) is answered by the gateway itself, and neither provider is asked.
  • The request's own limits: the route's deadline, its call limit, its upstream budget and a closed task session stop the whole request, whatever any fallback would do.
  • A stream that has begun: see Streaming below.
  • A selective fallback: in the route editor a fallback can be made selective, so it moves on only after the failures you tick. It starts on unreachable, server_error, rate_limited, empty_reply, circuit_open, limit_refused: an outage, exhausted quota, an empty reply or a full concurrency limit, where a backup helps. A request the first provider refused as invalid (400) or a key it refused (401) then comes back at once with that provider's status, rather than being sent to a backup that would most likely refuse it too, and the backup is not called.

Streaming

Add stream=True (stream: true) and the same route streams from whichever provider it reaches, in OpenAI's event format either way. A stream can fall back only until it begins.

  • Before the stream begins: a stream begins when a provider answers 2xx with an event stream. Every failure before that, a refusal, an outage or a 2xx that is not an event stream, moves on to the backup exactly as a buffered request does.
  • After it begins: once events have started reaching your code nothing is retried and the backup is not asked. A provider that fails partway ends the stream with an error event in OpenAI's format, and so does one whose stream ends without any answer in it, so handle an error event as well as an error status. A stream that began is billed for what it sent, unless it ended without an answer.
  • Its time limits: a provider has 2 minutes to begin a stream, which a shorter output timeout replaces; once it has begun, it may fall silent for up to 2 minutes at a time and run for 60 minutes in all.

Other shapes with a backup

The wizard offers three more starting routes with a backup, each drawn the same way and editable afterwards.

  • Retried, then backup: Retries the first model up to three times on a transient failure, and sends the request to the backup once every try has failed, or at once on any other failure.
  • Circuit breaker with backup: Tries the first model, and sends the request to the backup when it fails; after five failures in a row the circuit breaker opens and sends requests straight to the backup until it recovers.
  • Concurrency limit with backup: Lets at most 4 requests at a time through to the first model and sends the rest straight to the backup, without waiting; the limit's side panel in the editor changes how many.

Ready to get started?

Create Your API Key