# Sound Effects API

> **Not generally available.** The Sound Effects API is in private beta and is **not yet enabled in production**. Access is by request only, per user. No model is switched on until Demeterics enables it, so calls return an error today.
>
> To request access, email **sales@demeterics.com** with:
> - Subject: "Feature Access Request"
> - Feature name: **"Sound Effects (SFX)"**

The Demeterics Sound Effects API turns a text prompt into a short audio clip (a door slam, rain on a tin roof, a looping engine hum) through one endpoint, while tracking usage and cost and storing the generated audio.

## Overview

**Base URL:** `https://api.demeterics.com/sfx/v1`

**Providers:** `elevenlabs` (default) and `stability`.

**Features:**
- **One request shape** for both providers
- **Per-user cache**: an identical request is served again for $0
- **Re-roll controls**: `cache: false`, `variant` and `seed`
- **Idempotency**: safe retries with an `Idempotency-Key` header
- **BYOK**: use your own provider key
- **Audio storage**: generated audio is stored in GCS and returned by 15-minute signed URL on request

## Access

Access has two gates, and both must be open:

1. **User opt-in.** Your account needs the `FeatureSFX` grant. It is off by default and is given per user. Without it you get HTTP 403 `feature_access_required`.
2. **Model enabled.** Demeterics enables each model individually. A model that is not enabled returns HTTP 400 `model_not_enabled`. Use `GET /sfx/v1/models` to see what is enabled for the service right now (an empty list means nothing is live).

Zero Data Retention (ZDR) accounts cannot use this endpoint, because the prompt is sent to the vendor.

## Authentication

### Managed Keys (Default)

```bash
curl -X POST https://api.demeterics.com/sfx/v1/generate \
  -H "Authorization: Bearer dmt_your_api_key" \
  -H "Content-Type: application/json" \
  -d '{"provider":"elevenlabs","prompt":"heavy wooden door slam in a stone hallway","duration_seconds":2}' \
  --output door.mp3
```

### Bring Your Own Key (BYOK)

Send both keys, separated by a semicolon:

```bash
curl -X POST https://api.demeterics.com/sfx/v1/generate \
  -H "Authorization: Bearer dmt_your_api_key;your_provider_key" \
  -H "Content-Type: application/json" \
  -d '{...}'
```

The format is `[demeterics_api_key];[provider_api_key]`. Provider costs are then billed by the provider to your own account, and the BYOK service fee applies instead of the managed one.

## Endpoints

### Generate a sound effect

`POST /sfx/v1/generate` (also available at `/api/sfx/v1/generate`)

**Request body** (unknown fields are rejected with 400):

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `prompt` | string | Yes | What the sound is. `/// APP`, `/// FLOW`, `/// ENV`, `/// USER` tag lines are removed before the vendor sees the prompt. |
| `duration_seconds` | number | Yes | `elevenlabs`: 0.5 to 22. `stability`: whole seconds, 1 to 190. |
| `provider` | string | No | `elevenlabs` (default) or `stability` |
| `model` | string | No | `elevenlabs`: `eleven_text_to_sound_v3` (default), `eleven_text_to_sound_v2` (deprecated by the vendor, removal 2027-03-01). `stability`: `stable-audio-2`. Stability picks the model by endpoint, so never send anything else. |
| `output_format` | string | No | `mp3` (default) or `wav`. ElevenLabs returns `wav` only for non-looping effects. |
| `loop` | boolean | No | `elevenlabs` only. Ask for a seamless loop (use with `mp3`). |
| `prompt_influence` | number | No | `elevenlabs` only, 0 to 1. Higher follows the prompt more literally. |
| `steps` | integer | No | `stability` only. Diffusion steps. |
| `seed` | integer | No | Part of the cache key. It is **not** sent to the vendor. |
| `variant` | integer | No | Re-roll number. A new value is a new take. See Cache. |
| `cache` | boolean | No | Default `true`. `false` skips the cache. |

A parameter that belongs to the other provider is a 400 `validation_error`.

**Response (default):** raw audio bytes (`audio/mpeg` or `audio/wav`).

| Header | Meaning |
|--------|---------|
| `X-Cost-USD` | What this request cost you, in USD. `0.000000` on a cache hit. |
| `X-Duration-Seconds` | Duration of the clip |
| `X-Cache` | `HIT`, `MISS` or `BYPASS` (see Cache) |
| `X-Transaction-ID` | Transaction ID (`sfx_...`) |

**Response with `?response_format=json`:**

```json
{
  "id": "sfx_01...",
  "provider": "elevenlabs",
  "model": "eleven_text_to_sound_v3",
  "duration_seconds": 2,
  "cost_usd": 0.0,
  "cache": "MISS",
  "audio_url": "https://storage.googleapis.com/...",
  "usage": { "unit": "seconds", "billed_units": 2 },
  "metadata": { "format": "mp3", "generation_ms": 3100 }
}
```

`audio_url` is a signed URL valid for 15 minutes. Only if no URL could be signed does the response carry `audio_base64` instead. (`cost_usd` above is a placeholder, not a price.)

### List models

`GET /sfx/v1/models` returns the models that are enabled right now, each with `pricing_unit`, `price_per_unit_usd`, and its duration limits. Rates are always per unit, never per request.

## Cache (per user)

By default (`cache: true`) the result of a request is stored for 30 days under a key built from **your user ID**, your key type (managed or BYOK) and every parameter that changes the audio: provider, model, cleaned prompt, duration, `loop`, `prompt_influence`, `steps`, `output_format`, `seed` and `variant`. Nobody else can read or hit your entries.

| `X-Cache` | Meaning |
|-----------|---------|
| `MISS` | Generated now and billed. |
| `HIT` | Replayed from your cache. No vendor call, **$0**. A $0 row is still logged for the request. |
| `BYPASS` | Neither cache nor idempotency was used (`cache: false` without an `Idempotency-Key`). Generated and billed. |

**Getting a different take.** Asking again with the same body returns the same audio. To re-roll, change `variant` (for example 1, 2, 3) or `seed`, or send `cache: false`. A QC retake loop should bump `variant` on each retry, so a bad take is never served again.

## Idempotency-Key

Send `Idempotency-Key: <1 to 255 printable ASCII characters>` together with `cache: false` to make a retry safe without caching the content. With the default `cache: true` the content cache already gives the same protection and the header is ignored.

- The first request with a key generates and bills once. A retry with the same key and the same body replays the stored audio (`X-Cache: HIT`, $0). The replay window is 24 hours.
- A request that fails **before** it is billed releases the key, so you can retry it. A request that succeeded and was billed keeps the key, so a lost response replays instead of billing twice.
- A request that **fails after the provider may already have charged for the work** (an upstream timeout after the request was sent, a provider 5xx, or a reply with no usable audio) is billed as a failure and also **releases the key and the cache entry**. A retry is then a new generation and is **billed again**.
- If your client disconnects while a cached or keyed request is running, the generation still completes, is billed once and is stored. The retry gets 409 while it runs, then a $0 replay.
- If the stored audio of a cache entry or key is no longer available, the retry generates and bills again instead of failing.
- Keys are scoped to your user and to managed versus BYOK.

## Errors

Errors are JSON: `{"error": {"message": "...", "type": "<code>", "code": "<code>"}}`.

| HTTP | Code | Meaning |
|------|------|---------|
| 400 | `invalid_request` | Malformed JSON or an unknown field |
| 400 | `validation_error` | A field is missing, out of range, or for the other provider |
| 400 | `model_not_enabled` | The model is not enabled by Demeterics |
| 400 | `invalid_idempotency_key` | Key is empty, over 255 characters or not printable ASCII |
| 400 | `no_provider_key` | No managed key for this provider; send a BYOK key |
| 400 | `upstream_rejected` | The vendor refused the request before generating. Not charged. |
| 401 | `authentication_required` | Missing or invalid API key |
| 402 | `insufficient_credits` | Balance is below the estimated cost |
| 403 | `feature_access_required` | Your account does not have `FeatureSFX` |
| 409 | `request_in_progress` | Another request with the same cache entry or key is still running. Retry after the `Retry-After` delay (5 s). |
| 422 | `idempotency_key_reused` | The key was already used with a different body |
| 429 | `too_many_in_flight` | More than 4 effects generating at once for your user. `Retry-After` is set. |
| 429 | `upstream_rate_limited` | The vendor rate limit. The vendor's `Retry-After` is passed through. |
| 502 | `upstream_error` | The vendor failed, or rejected the provider key (HTTP 401/403). On the managed key the message is generic and quotes a transaction id for support; with BYOK it carries the vendor's reply. |
| 503 | `pricing_unavailable`, `pricing_misconfigured`, `cache_unavailable`, `cache_read_failed` | A server-side problem; the request was not processed |

**Retries.** Honor `Retry-After` on every 409 and 429. Demeterics never retries a vendor call for you, and neither should a tight loop. If the vendor may have generated the audio and the response was then lost or unusable (an upstream timeout after the request was sent, a provider 5xx, or a broken audio read), the call is billed, the error `type` carries a `_billed` suffix in the usage log, and the cache entry or key is released, so a retry is billed again.

## Pricing

Each model has a **pricing unit**, and the rate is shown **per that unit**, not per token and not per request:

| Provider | Unit | What is billed |
|----------|------|----------------|
| `elevenlabs` | `seconds` | The requested `duration_seconds`, rounded **up** to a whole second, times the per-second rate |
| `stability` | `clip` | One generation, times the per-clip rate |

For current rates see [Available Models](https://demeterics.ai/docs/models), or `GET /sfx/v1/models`. Rates are set conservatively, and the vendor reports no usage or cost for these calls, so the charge is the rate times the units above. A service fee is added (managed or BYOK, as for other APIs). Cache hits and idempotent replays are $0. See [Credits & Pricing](https://demeterics.ai/docs/credits).

## Prompt guidance

- **Describe what you would hear, not the frequency band.** In live testing, an ElevenLabs prompt that said "sub-bass" together with "sparse midrange" produced energy almost entirely below 100 Hz, which is inaudible on most speakers and headphones. Say "deep low rumble with a soft thud", or name the object and the room, and keep some midrange in the description.
- Name the source, the material, the space and the action: "metal gate slides open on a rusty rail, echoing in a parking garage".
- Match the duration to the event. A single hit needs 1 to 3 seconds. For a bed or ambience use `loop: true` with `mp3` on ElevenLabs.
- Use `prompt_influence` (ElevenLabs) to trade literal prompt-following against variety.
- To compare takes cheaply, re-roll with `variant` instead of rewriting the prompt.

## Example: retake loop

```bash
for v in 1 2 3; do
  curl -s -X POST "https://api.demeterics.com/sfx/v1/generate" \
    -H "Authorization: Bearer $DEMETERICS_API_KEY" \
    -H "Content-Type: application/json" \
    -d "{\"prompt\":\"glass bottle rolling on a wooden floor\",\"duration_seconds\":4,\"variant\":$v}" \
    -D headers_$v.txt --output take_$v.mp3
done
```

## See also

- [Music API](https://demeterics.ai/docs/music.md)
- [Speech Generation](https://demeterics.ai/docs/speech.md)
- [Authentication](https://demeterics.ai/docs/authentication)
