# Adding AI to your app, with a backup

> When your app calls an AI model, those requests run only on your server—sending traffic first to Tokentide for lower prices and zero data retention, and switching automatically to Vercel AI Gateway whenever capacity is full so your users still get an answer without interruption.

## Analogy

Think of a bakery that buys flour from a trusted local mill at a great price, but keeps a second supplier on standby. If the mill runs out on a busy morning, the delivery truck switches to the second supplier automatically and the bread still comes out on time.

## How it works

AI calls always happen on your backend (in a Server Action, Route Handler or background job), never in the visitor's browser, so your api-key stays secret and protected by a rate-limit. Every text request sets `max_completion_tokens`—about twice the longest expected answer—so a single runaway response can never drain your balance.

Your primary provider is **Tokentide** (`https://api.tokentide.app/v1`), which is up to ~63% below list price and keeps zero copies of your prompts or answers. You set `maxRetries: 0` on the Tokentide client so that if capacity is temporarily full (`503`), rate-limited (`429`), out of credit (`402`), or returns a server error (`500`/`502`/`504`) or timeout, it doesn't wait—it hands the request straight to your fallback, **Vercel AI Gateway** (`https://ai-gateway.vercel.sh/v1`), and honors `Retry-After` before trying the primary again.

Not every error should trigger the backup. If your key is wrong (`401 invalid_api_key`) or restricted (`403 ip_not_allowed` or `account_restricted`), your app falls back so users aren't stuck AND alerts you to fix the key. But if the request itself is broken—like `403 model_not_allowed` or any other `4xx`—your app does not fall back; your agent fixes the request and checks the model pair in both catalogs.

To keep user data private and outputs safe, your log records the cost (`X-Tokentide-Charge-USD`), request ID (`X-Request-Id`), feature name and answering provider—never the prompt or the model's answer. And because model output is untrusted, your code validates and escapes it before showing or saving it.

## In your project

Your agent uses the `tokentide-api` and `ai-sdk` skills to wire both providers with matching model IDs, and you paste `TOKENTIDE_API_KEY` and `AI_GATEWAY_API_KEY` into `.env.local` and Vercel (using low-cap keys for local work). Before merging, your agent tests the fallback in a preview by pointing the Tokentide client at a dead address and confirming the Gateway answers cleanly.

## Copy for your agent

```text
Set up our AI helper on the server using the tokentide-api and ai-sdk skills: Tokentide first with maxRetries: 0, Vercel AI Gateway as fallback, max_completion_tokens set, and logging only cost and provider—never prompts or outputs.
```

---
Source: [Agentic Makers](https://agenticmakers.app/en/learn/adding-ai-to-your-app) · License: CC BY 4.0
