AI Gateway · Exercise 04
Route and fall back
Move model selection out of your Worker and into a versioned gateway route that branches on metadata, falls back on failure, and updates without redeploying your app.
Paste this into your agent
Copied! Now paste it into your agent. No agent yet? Here's how to get one.
Route and fall back
When a model name is hardcoded in your application, every model upgrade, tier change, or provider outage requires a code change and a deployment across every service that calls it. Moving model choice into a versioned route in AI Gateway lets the gateway pick the model from request metadata, fall back automatically if a primary model fails, and swap or roll back models without touching your application code.
What you’ll build
A gateway route named dynamic/support that sends interns to a fast economical model and escalations to a larger model with an automatic fallback. Then you’ll deploy a second version of the route and watch the model change with zero Worker redeploy.
Prerequisites
- You’ve completed Cap requests and spend and still have that Worker and gateway.
Moving model choice into a route
Instead of naming a specific model in code, your Worker calls "dynamic/support" and passes who’s asking in metadata:
src/index.tsconst result = await env.AI.run(
"dynamic/support",
{ messages: [{ role: "user", content: prompt }] },
{
gateway: {
id: "dev-school-gateway",
metadata: { user, team },
},
},
);
Inside AI Gateway, the support route replaces the single model provider at the end of the pipeline from Exercise 3 with a versioned decision graph: it checks metadata.team, routes each team to the right model, falls back to a backup model if the primary model fails or times out, and lets you publish a new version of the route without redeploying your Worker: