# AI

Source: https://developers.swell.is/apps/ai

An app can use AI through Swell. It calls OpenAI or Anthropic models with their official SDKs, pointed at Swell's AI gateway, and authenticates with its own secret key. The store pays for what the app uses, billed as AI usage based on the AI provider's prices. When a store installs the app, AI is on unless the merchant turns it off.

Merchants turn AI on in the new Swell dashboard, on stores that have AI. Partner development stores have it.

## Declaring AI

Add `ai` to [swell.json](https://developers.swell.is/apps/swell-json) with a `description` of what the app uses AI for. Merchants see it when they turn AI on for the app.

```json
{
  "id": "my_app",
  "ai": {
    "description": "Writes product descriptions and suggests tags from your catalog."
  }
}
```

- `description` is required, up to 200 characters. `ai` takes no other keys.
- `swell app push` syncs it, and each version keeps its own. Removing `ai` and pushing turns AI off on the app's development installs.

## Turning AI on

When a store installs an app that declares `ai`, AI is on for it by default, if the person installing may allow AI: the store owner, or a user who can manage apps. Each installation has its own switch, and an app's test and live installations are switched separately. The same people can turn it off, or back on:

- **Allow AI** in the app's install dialog, which shows the app's description and that AI usage is billed to the store based on the AI provider's prices.
- **Allow this app to use AI** in the AI card on the app's page in the dashboard.

The switch can stay on only while the installed version declares `ai`: installing a version without it turns AI off. A store can also turn off AI for every app in **Settings › Usage › AI setup** (**Use AI in this store**).

### During development

`swell app push` creates the app's test installation with AI off. To try your AI features, open the app's page in the new Swell dashboard, in the test environment of a store that has AI, such as a partner development store, and turn AI on there. AI calls from a test installation are billed to the store like any other.

## Calling AI

Point the official SDK at the store's AI gateway and pass the app's secret key as the API key. The key decides which installation and environment a call belongs to.

| Provider API | Base URL | SDK |
| --- | --- | --- |
| OpenAI | https://<store-id>.swell.store/ai/openai/v1 | openai, with baseURL |
| Anthropic | https://<store-id>.swell.store/ai/anthropic | @anthropic-ai/sdk, with baseURL (the SDK adds /v1) |

In a [function](https://developers.swell.is/apps/functions), the secret key is `req.accessToken` and the store id is `req.store.id`. An app's [frontend](https://developers.swell.is/apps/frontend) gets the key in the `Swell-Access-Token` header of each request; keep it on the server. Any other key is refused with `invalid_api_key`.

```typescript
import Anthropic from '@anthropic-ai/sdk';

export const config: SwellConfig = {
  description: 'Suggest a product description',
  route: { methods: ['post'] },
};

export default async function (req: SwellRequest) {
  const client = new Anthropic({
    apiKey: req.accessToken,
    baseURL: `https://${req.store.id}.swell.store/ai/anthropic`,
  });

  const message = await client.messages.create({
    model: 'swell-data',
    max_tokens: 1024,
    messages: [{ role: 'user', content: `Describe this product: ${req.data.name}` }],
  });

  return { text: message.content[0].type === 'text' ? message.content[0].text : '' };
}
```

```typescript
import OpenAI from 'openai';

const client = new OpenAI({
  apiKey: req.accessToken,
  baseURL: `https://${req.store.id}.swell.store/ai/openai/v1`,
});

const response = await client.responses.create({
  model: 'gpt-6.1-sol',
  input: 'Suggest five tags for a linen summer dress.',
});
```

Responses stream as they do from the provider, in its own format.

### Endpoints

| Gateway | Endpoints |
| --- | --- |
| OpenAI | GET /v1/models, GET /v1/status, POST /v1/responses, POST /v1/chat/completions, POST /v1/images/generations, POST /v1/images/edits (multipart) |
| Anthropic | GET /v1/models, POST /v1/messages |

Embeddings aren't available. To check status from an app that uses Claude, call the OpenAI gateway's `/v1/status` with the same key.

### Models

`GET /v1/models` lists the models an app can call. A model that isn't listed is refused with `model_not_found`. They currently include:

- Claude: `claude-opus-5-5`, `claude-sonnet-5-5`, `claude-haiku-5-5`, `claude-fable-5-2` and `claude-fable-5-1`.
- OpenAI text: `gpt-6.1-sol` and `gpt-6-astra`. Images: `gpt-image-2`.
- `swell-design` and `swell-data`: the model the store has chosen for design work and for data work in its AI setup. Use them to follow the merchant's choice rather than naming a model.

Each model in the OpenAI gateway's list has `swell_pricing`: what the store pays per million tokens.

### Request rules

The gateway refuses a request that breaks these rules, with the provider's error format:

- Responses: no `background`, `previous_response_id` or `conversation`; `store` is always false; output is capped at 32,768 tokens.
- Chat completions: `n` is 1 and `store` is false; streams include usage.
- Responses and chat completions: function tools only; `service_tier` `auto` or `default`; no audio output.
- Images: `n` is 1; sizes `auto`, `1024x1024`, `1536x1024` or `1024x1536`; quality `auto`, `low`, `medium` or `high`; `b64_json` only; no streaming. An edit is multipart, up to 25 MB.
- Messages: `max_tokens` up to 32,000, refused above it; custom tools only, with no server tools, computer use or bash; no `mcp_servers`, `container` or `speed`.
- JSON request bodies up to 10 MB.
- Up to 4 calls in flight per installation, and 10 per store across its apps.

### Checking status

`GET /v1/status` on the OpenAI gateway tells an app what to show before a merchant starts something:

| Field | Description |
| --- | --- |
| available | The store has AI. When false, every call is refused: hide your AI features. |
| ai_enabled | AI is on for this installation. When false, say it's turned off for the app and where to turn it on. |
| store_enabled | The store's own switch for AI in every app. |
| instructions | How the store wants AI to behave, from its AI setup. Follow them in your prompts. |
| status, balance_micros, min_balance_micros | The store's AI account. |
| can_spend | A call would be accepted now. |

## Billing

The store pays for its apps' AI usage; the app pays nothing. Each call is charged when it ends, from the usage the provider reports, or estimated from its length when a stream is cut off. The charge appears with the store's other usage as AI usage, based on the AI provider's prices, within the store's monthly AI limit.

Calls from a test installation cost the same as live ones, and are labeled test.

## Errors

Errors come in each SDK's own shape, with a stable `code`. Match on the code, not the message:

| Status | Code | Meaning |
| --- | --- | --- |
| 401 | invalid_api_key | The key isn't the app's secret key. |
| 403 | ai_not_available | The store doesn't have AI. |
| 403 | ai_not_enabled | AI is turned off for this app. The merchant turns it on on the app's page. |
| 403 | ai_turned_off | AI is turned off for the whole store, in AI setup. |
| 403 | ai_paused | AI is paused for the store. |
| 402 | ai_monthly_limit_reached | The store reached its monthly AI limit. The merchant can raise it in Settings › Usage. |
| 402 | ai_paid_plan_required | The store used its included AI and needs a paid plan. |
| 402 | ai_no_card | The store needs a payment card. |
| 402 | ai_usage_paused | A payment failed. The merchant retries it in billing. |
| 404 | model_not_found | The model isn't one the gateway lists. |
| 429 | too_many_ai_requests | Too many calls in flight for the installation or the store. |
| 429 | rate_limit_exceeded | The provider's rate limit. |
| 502, 503, 500 | upstream_error, ai_unavailable, server_error | Try again later. |

Show the merchant what to do and where: for example, link `ai_monthly_limit_reached` to the store's usage settings and `ai_not_enabled` to the app's page.

## Example: Wave

[Wave](https://developers.swell.is/storefronts/wave-app) uses both gateways. Its agent calls Claude with the Anthropic SDK and `swell-design`, and it generates images with the OpenAI SDK and `gpt-image-2`. It reads `/v1/status` when its editor opens, hides AI when `available` is false, says when AI is off for the app, and turns each refusal into a link to the right place in the dashboard.
