Hedge a Slow Provider from the OpenAI SDK

A worked example: one endpoint that asks gpt-6.1-sol first, asks claude-fable-5-1 too when the first has not answered within 2 seconds, and answers with whichever full reply comes first.

The Route: Order status

The request goes to OpenAI first, and to Anthropic as well when OpenAI is still answering after 2000 ms. The first full answer wins.

Requestfrom your SDK
Hedgebackup after 2000ms
primaryOpenAIgpt-6.1-sol
backupAnthropicclaude-fable-5-1
Requestfrom your SDK
Hedgebackup after 2000ms
primaryOpenAIgpt-6.1-sol
backupAnthropicclaude-fable-5-1

Set up the providers and draw the route

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. The wizard has no hedge among its starting routes, so you start from the input alone and draw the hedge in the route editor.

  • 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 Order status. The slug fills in as order-status and becomes part of the endpoint's URL, never to change.
  • 3. Start from the input: choose Draw it myself. Create Endpoint opens the route editor with the input alone.
  • 4. Add the hedge and its outputs: in the toolbar's Add, press Hedge, then Output twice. The editor names them hedge-1, output-1 and output-2. Select the input and set Routes to hedge-1.
  • 5. Choose the models: select output-1 and set Provider OpenAI, Model gpt-6.1-sol; select output-2 and set Provider Anthropic, Model claude-fable-5-1.
  • 6. Set up the hedge: select hedge-1, set Primary to output-1 and Backup to output-2, and Backup delay (milliseconds) to 2000. Then tick the box that says "The backup is a second, separate call to its provider. Both calls may be charged to your provider keys, and both count against their rate limits." A hedge cannot be saved until it is ticked.
  • 7. Publish and deploy: Save Draft, then Publish Version, and deploy that version from the endpoint's Versions. Until it is deployed no request takes the route.
  • 8. Mint a key: on the endpoint's page, mint a gateway key (it starts with mw_ and is shown once) and copy the endpoint's URL beside it.

The route you draw

The diagram above is the endpoint's whole route: the request goes into a hedge, which asks its primary and, only if that is still pending after the delay, its backup as well. Most requests are answered inside the delay and make one call; the hedge only pays for a second call on the slow tail.

  • The route taken: every request records the way it went, on the dashboard's Usage page and on the request's own page: hedge hedge-1 primary started → OpenAI (gpt-6.1-sol) → hedge hedge-1 won when OpenAI answered inside the delay, and hedge hedge-1 backup after 2000ms → Anthropic (claude-fable-5-1) → hedge hedge-1 won; other cancelled when Anthropic was asked after it and answered first.
  • The race, call by call: the request's page lists both calls under a line naming the leg that won and what became of the other, and GET /requests/{id} in the control API gives each call its hedge_leg and hedge_result.
  • The answer says who answered: the response's model field names the provider model that actually answered, so your code can tell the backup's answer from the primary's without asking the dashboard.

Send a request with the OpenAI SDK

Point the SDK at the endpoint's URL, https://modelwaygate.com/USER_ID/order-status/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: the hedge happens inside the gateway, and your code waits for one answer as it always did.

  • 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.
  • Buffered, not streamed: the race only runs for a buffered request, as here: no stream field, or stream: false. Embeddings are raced too. See Streams below for what a hedge does with a stream.

Code Examples

curl https://modelwaygate.com/USER_ID/order-status/api/v1/chat/completions \
  -H "Authorization: Bearer mw_your_gateway_key" \
  -H "Content-Type: application/json" \
  -d '{
  "model": "order-status",
  "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/order-status/api/v1", api_key="mw_your_gateway_key")

response = client.chat.completions.create(
    model="order-status",
    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/order-status/api/v1", apiKey: "mw_your_gateway_key" });

const response = await client.chat.completions.create({
  model: "order-status",
  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\": \"order-status\", \"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/order-status/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/order-status/api/v1/chat/completions"
  let turn role content = object ["role" .= (role :: String), "content" .= (content :: String)]
      body = object ["model" .= ("order-status" :: 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)

How the race runs

A hedge is not a fallback: it does not wait for the first provider to fail before asking the other. It waits a fixed delay, then asks both, and takes whichever full reply comes first.

  • The primary answers inside the delay: the usual case. OpenAI answers within 2 seconds, the answer goes back to your code, and Anthropic is never called.
  • The primary is still pending at the delay: the same request goes to Anthropic as well, and the first acceptable reply answers: one the provider sent in full, read and parsed. The other call is then cancelled and its connection closed. If OpenAI finishes first after all, it still wins.
  • The primary fails before the delay: Anthropic is asked at once, without waiting out the delay, as a fallback's backup would be.
  • Both fail: the request fails with whichever failure came last, as a fallback's would.
  • A hung primary: a provider that never answers is still given up on at its own limits, 2 minutes to begin answering, or an output timeout you set (1 to 300 seconds), but by then the backup has long since been asked.

What a hedge costs

The backup is a second, separate call. The editor says so beside the box you ticked, and it is the price of a faster slow tail.

  • Your providers may charge for both calls: each provider bills you directly for whatever its own API charges. That includes the losing call: one that answered after the winner, one that failed, and one cancelled partway, which a provider may still bill for the tokens it generated before the connection closed. Both calls count against each provider's rate limits.
  • Model Waygate charges once: the Waygate fee is only for the reply you are sent, and only for bytes beyond the free monthly allowance ($0.03 per MB). A losing call is never billed by Model Waygate, though both requests sent upstream count against the request's upstream budget.
  • Nothing happens twice: the gateway runs no tools and keeps no provider-side state, so a second call never makes anything happen twice; it can only cost twice.

Choosing the delay

The delay decides how often you pay for a second call. Too short, and most requests make two; too long, and the slow ones wait almost as long as they did without a hedge.

  • Start from the primary's 95th percentile: the dashboard's Health page shows each provider model's duration p50 and p95 over your own requests. Set the delay near the primary's p95, and about one request in twenty pays for a second call while the slowest twentieth is answered by whichever provider is quicker.
  • Its limits: the delay is 50 to 60000 milliseconds, and must be shorter than the primary output's timeout when you give it one, or the hedge cannot be saved.
  • Watch it after deploying: the editor shows above each node how many requests passed through it and how many it answered, a leg cancelled after losing the race counted as cancelled. output-2's counts are how often the backup was asked and how often it won. When it wins most races it is simply the faster provider, and may be worth making the primary.

Streams

Hedging is for buffered requests only. A streamed request is never raced: nothing is sent twice, and nothing is cancelled.

  • A stream walks the hedge in turn: with stream=True (stream: true) the hedge acts as a two-child fallback. OpenAI is asked, and Anthropic only if OpenAI fails before anything has reached your code. The route taken says so: hedge hedge-1 backup in turn (stream).
  • Once it has begun: a stream that has started reaching your code is never moved to the backup; a failure partway ends it with an error event in OpenAI's format.

When the backup is not sent

The backup is optional while the primary can still answer, so none of these stops the request: it waits for the primary alone, and the route taken says why, such as hedge hedge-1 backup not launched (call cap).

  • The call limit: the primary was the last of the request's 32 calls.
  • A deadline: the route's deadline, or the task session's, has passed.
  • An open circuit breaker: a breaker in front of the backup is open.
  • The upstream budget: sending the request again would take it past its upstream budget.

Ready to get started?

Create Your API Key