Cookbook: Custom fallback logic
The Fallback Model policy covers a fixed backup and quota fallback. When the backup should be chosen dynamically—the cheapest available model, a provider-specific preference, whatever is currently active—a custom chain policy can replace it using the same public primitives.
A fallback policy enriches the selection an earlier policy created. Because
AIGatewayModelRouting.set() replaces the complete stored selection rather than
partially updating it, the policy must read, merge, and set. It should also
leave the request unchanged when no earlier policy created a selection—so a
misplaced chain entry doesn't bypass model filtering—and when the chosen backup
equals the current main model, which set() rejects.
The policy
This example adds the first active Anthropic completions model as the backup, with a 30-second timeout:
Code
Declare and use it
Code
Add add-fallback to an app's chain directly after Model Filtering, replacing
the Fallback Model policy. Keep the no-selection guard at the top of the
policy—it prevents a misplaced entry from creating a primary selection and
bypassing filtering.
Next steps
- Fallback Models: the built-in fallback and quota-fallback behavior
- Cookbook: Dynamic model routing: create the primary selection from code
- Custom Policies: the full custom-policy quickstart