---
title: TypeSafe API with AI Gateway
description: Point an existing TypeSafe client at AI Gateway by changing its base URL to route System One decision requests through it.
url: "https://vercel.com/docs/ai-gateway/sdks-and-apis/typesafe"
last_updated: 2026-10-05
related:
  - /docs/ai-gateway/modalities/decision
  - /docs/ai-gateway/authentication-and-byok/byok
  - /docs/ai-gateway/models-and-providers/decision-fallbacks
  - /docs/ai-gateway/sdks-and-apis/rest-api
  - /docs/ai-gateway/models-and-providers
install_vercel_plugin: npx plugins add vercel/vercel-plugin
search_with_vercel_cli: npx vercel@latest docs search "<query>"
search_kb_with_vercel_cli: npx vercel@latest kb search "<query>"
---

# TypeSafe API with AI Gateway

Keep using the [TypeSafe SDK](https://docs.typesafe.ai/introduction) and route requests through AI Gateway by changing one setting.

Requests are billed through AI Gateway and appear in your usage and observability alongside every other model you call.

If you are writing new code instead of migrating, use the [Decision API](/docs/ai-gateway/modalities/decision). It is the same capability without TypeSafe-specific naming.

## Base URL

The TypeSafe-compatible API is available at the following base URL:

```
https://ai-gateway.vercel.sh/typesafe
```

## Authentication

The TypeSafe-compatible API supports the same authentication methods as the main AI Gateway:

- **API key**: Use your AI Gateway API key with the `Authorization: Bearer <token>` header
- **OIDC token**: Use your Vercel OIDC token with the `Authorization: Bearer <token>` header

You only need one of these. This is the credential AI Gateway authenticates you with, not the credential used to call the model.

To bill the provider directly instead of through AI Gateway, add a TypeSafe key under [BYOK](/docs/ai-gateway/authentication-and-byok/byok).

## Migrating an existing client

Change the base URL and the API key:

```diff filename="client.ts"
  import { TypeSafeClient } from '@typesafe-ai/sdk';

  const client = new TypeSafeClient({
-   apiKey: process.env.TYPESAFE_API_KEY,
+   apiKey: process.env.AI_GATEWAY_API_KEY,
+   baseURL: 'https://ai-gateway.vercel.sh/typesafe',
  });
```

Everything else stays the same:

```typescript filename="triage.ts"
const result = await client.systemOne({
  state: 'I was charged twice for my subscription.',
  questions: {
    refund: { type: 'noul', instructions: 'Is the customer asking for money back?' },
    department: {
      type: 'choice',
      instructions: 'Which team should handle this?',
      criteria: { billing: 'Charges and refunds', technical: 'Bugs and outages' },
    },
  },
});

console.log(result.answers.refund); // { type: 'noul', noul: 0.98 }
```

## Supported endpoints

- `POST /typesafe/v1/systemone` answers typed questions about state
- `GET /typesafe/v1/models` lists the decision models available to you

## Request and response format

This API implements the TypeSafe request and response shapes.

#### cURL

```bash filename="systemone.sh"
curl https://ai-gateway.vercel.sh/typesafe/v1/systemone \
  -H "Authorization: Bearer $AI_GATEWAY_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "typesafe-ai/jev",
    "state": "I was charged twice for my subscription.",
    "questions": {
      "refund": {
        "type": "noul",
        "instructions": "Is the customer asking for money back?"
      }
    }
  }'
```

#### TypeScript

```typescript filename="systemone.ts"
import { TypeSafeClient } from '@typesafe-ai/sdk';

const client = new TypeSafeClient({
  apiKey: process.env.AI_GATEWAY_API_KEY,
  baseURL: 'https://ai-gateway.vercel.sh/typesafe',
});

const result = await client.systemOne({
  model: 'typesafe-ai/jev',
  state: 'I was charged twice for my subscription.',
  questions: {
    refund: {
      type: 'noul',
      instructions: 'Is the customer asking for money back?',
    },
  },
});
```

#### Python

```python filename="systemone.py"
import os
import requests

response = requests.post(
    "https://ai-gateway.vercel.sh/typesafe/v1/systemone",
    headers={
        "Authorization": f"Bearer {os.environ['AI_GATEWAY_API_KEY']}",
        "Content-Type": "application/json",
    },
    json={
        "model": "typesafe-ai/jev",
        "state": "I was charged twice for my subscription.",
        "questions": {
            "refund": {
                "type": "noul",
                "instructions": "Is the customer asking for money back?",
            }
        },
    },
)

print(response.json()["answers"])
```

The response uses TypeSafe's field names:

```json
{
  "model": "typesafe-ai/jev",
  "answers": {
    "refund": { "type": "noul", "noul": 0.98 }
  },
  "usage": { "input_tokens": 275, "output_tokens": 20 },
  "provider_metadata": {
    "gateway": {
      "routing": {
        "originalModelId": "typesafe-ai/jev",
        "resolvedProvider": "typesafe-ai",
        "canonicalSlug": "typesafe-ai/jev",
        "finalProvider": "typesafe-ai"
      },
      "cost": "0.00001155",
      "marketCost": "0.00001155",
      "surchargeCost": "0",
      "gatewayCost": "0.00001155",
      "generationId": "gen_..."
    }
  }
}
```

## Decision fallbacks

Decision fallbacks are an AI Gateway extension to the TypeSafe request. Add one conditional object to `providerOptions.gateway.models` to rerun a successful but uncertain decision with another model.

The official TypeSafe SDK forwards additional request properties at runtime, but its request type does not currently include `providerOptions`. Supply the extension through an intermediate object:

```typescript filename="typesafe-decision-fallback.ts" {21-30}
import { TypeSafeClient } from '@typesafe-ai/sdk';

const client = new TypeSafeClient({
  apiKey: process.env.AI_GATEWAY_API_KEY,
  baseURL: 'https://ai-gateway.vercel.sh/typesafe',
});

const request = {
  model: 'typesafe-ai/jev',
  state: 'I was charged twice and cannot sign in.',
  questions: {
    intent: {
      type: 'choice' as const,
      instructions: 'Which team should handle this?',
      criteria: {
        billing: 'Charges and refunds',
        account: 'Sign-in and account access',
      },
    },
  },
  providerOptions: {
    gateway: {
      models: [
        {
          model: 'openai/gpt-6-astra',
          when: { question: 'intent', confidenceBelow: 0.6 },
        },
      ],
    },
  },
};

const result = await client.systemOne(request);
```

> **💡 Note:** If a language model returns the final Choice or Score answer, `confidence: 0`
> and `probabilities: {}` mean those values are unavailable. They do not mean
> the model measured zero confidence. Native decision-model fallbacks preserve
> native confidence and probabilities.

Noul returns the fallback model's final `P(true)` normally. The response's top-level `model` echoes the model ID you requested when the primary answered, and names the fallback model whenever a fallback answered. AI Gateway routing metadata lists each model attempt and marks the one your condition triggered. Triggered requests bill both stages and report their combined usage.

When a condition matches, the response also carries these headers, listed in `Access-Control-Expose-Headers` so browser clients can read them:

| Header | Value |
| --- | --- |
| `x-ai-gateway-decision-fallback-triggered` | `true` |
| `x-ai-gateway-decision-fallback-final-model` | The model that produced the returned answers |
| `x-ai-gateway-decision-fallback-primary-model` | The primary model whose answers matched the condition |
| `x-ai-gateway-decision-fallback-triggering-questions` | A percent-encoded JSON array of the question IDs that matched. Read it with `JSON.parse(decodeURIComponent(value))` |
| `x-ai-gateway-decision-fallback-triggering-questions-truncated` | `true` when the question list was cut short. `provider_metadata.gateway.routing` has the full list |

AI Gateway omits these headers when the condition doesn't match. Use them to detect a fallback when your client only reads TypeSafe's typed response fields.

AI Gateway also sends the deprecated `x-ai-gateway-evaluation-fallback-*` headers with identical values. Read the `x-ai-gateway-decision-fallback-*` headers in new code.

See [Decision Fallbacks](/docs/ai-gateway/models-and-providers/decision-fallbacks#use-the-typesafe-compatible-api) for Boolean probability conditions, compound policies, virtual models, the complete sentinel response, and two-stage cost and latency.

## Errors

On `POST /typesafe/v1/systemone`, request validation and authentication errors use TypeSafe's shape, with a machine-readable code alongside the message:

```json
{
  "message": "Authentication failed",
  "error_type": "authentication_error"
}
```

Errors such as insufficient credits, an unknown model, or a model provider failure use the [standard AI Gateway error format](/docs/ai-gateway/sdks-and-apis/rest-api#error-responses) instead: an `error` object with `message` and `type` fields. `GET /typesafe/v1/models` returns its errors in the standard format. If your code reads `message` or `error_type` from an error response, also check for the `error` object and read `error.message` and `error.type`.

## Related

- [Decision](/docs/ai-gateway/modalities/decision) for the HTTP API and the AI SDK
- [Decision Fallbacks](/docs/ai-gateway/models-and-providers/decision-fallbacks) for successful-response escalation
- Learn how to [classify, route, and score with Jev and AI SDK](/kb/guide/typesafe-jev-and-ai-sdk) and [route form submissions](/kb/guide/jev-ai-sdk-form-router)
- Learn how to [automatically approve tool calls in eve with Jev](/kb/guide/auto-approve-tool-calls-eve-jev)
- [Models and providers](/docs/ai-gateway/models-and-providers) for the full catalog

## Search the docs from your terminal

Search the Vercel docs and read pages as Markdown with the Vercel CLI. No login required.

```bash
# Find docs pages by keyword
npx vercel@latest docs search "environment variables"
npx vercel@latest docs search "function timeout"

# Print a docs page as Markdown, by path or URL
npx vercel@latest docs inspect <page>
```

## Search guides from your terminal

Search the Knowledge Base and read guides as Markdown with the Vercel CLI. No login required.

```bash
# Find guides by keyword
npx vercel@latest kb search "rewrites and redirects"
npx vercel@latest kb search "AI SDK streaming"

# Show the latest guides
npx vercel@latest kb

# Print a guide as Markdown, by slug or URL
npx vercel@latest kb inspect <guide>
```

---

[View full sitemap](/docs/sitemap)


If you encounter incorrect information, can’t find what you need, need a capability Vercel doesn’t currently offer, or have any other feedback to report, please do it by following the instructions at https://vercel.com/feedback.md.
