# Music API

> **Not generally available.** The Music 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: **"Music generation"**

The Demeterics Music API turns a text prompt into a music clip or a full song through one endpoint, while tracking usage and cost and storing the generated audio.

## Overview

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

**Providers:**

| Provider | Models | Output |
|----------|--------|--------|
| `gemini` (default) | `lyria-3.5` (full song, default), `lyria-3-clip-preview` (30 s clip) | Native vendor format, MP3 or WAV |
| `vertex` | `lyria-002` (30 s clip, `negative_prompt`) | WAV |
| `elevenlabs` | `music_v1` (you set the length) | MP3 |

**Features:** per-user cache ($0 replays), re-roll controls (`cache: false`, `variant`, `seed`), `Idempotency-Key`, BYOK (not for `vertex`), 15-minute signed audio URLs.

Audio is returned in the vendor's native format and is **not transcoded**. Read the `Content-Type` header to know whether you got MP3 or WAV.

## Access

Access has two gates, and both must be open:

1. **User opt-in.** Your account needs the `FeatureMusic` 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`. `GET /music/v1/models` lists what is enabled 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/music/v1/generate \
  -H "Authorization: Bearer dmt_your_api_key" \
  -H "Content-Type: application/json" \
  -d '{"provider":"gemini","model":"lyria-3-clip-preview","prompt":"slow instrumental piece for solo cello and soft piano, 70 bpm, minor key, warm room reverb"}' \
  --output clip.mp3
```

### Bring Your Own Key (BYOK)

```bash
curl -X POST https://api.demeterics.com/music/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]`. BYOK works for `gemini` and `elevenlabs`. The `vertex` provider runs on Demeterics credentials only and rejects a BYOK key with 400 `byok_unsupported`.

## Endpoints

### Generate music

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

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

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `prompt` | string | Yes | The music, described by its sound. See Prompt guidance. `/// APP`, `/// FLOW`, `/// ENV`, `/// USER` tag lines are removed before the vendor sees it. |
| `provider` | string | No | `gemini` (default), `vertex` or `elevenlabs` |
| `model` | string | No | Defaults per provider (see the table above) |
| `duration_seconds` | number | `elevenlabs`: yes | `elevenlabs`: 3 to 300. Omit it for every other model: clip models are fixed at 30 s and full songs are sized by the vendor (a couple of minutes), so passing it is a 400. |
| `negative_prompt` | string | No | `vertex` only. What to avoid. |
| `force_instrumental` | boolean | No | `elevenlabs` only. No vocals. |
| `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. |
| `cache` | boolean | No | Default `true`. `false` skips the cache. |

**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, when known. **Absent for full songs**, whose length the vendor decides. |
| `X-Cache` | `HIT`, `MISS` or `BYPASS` |
| `X-Transaction-ID` | Transaction ID |

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

```json
{
  "id": "music_...",
  "provider": "gemini",
  "model": "lyria-3-clip-preview",
  "duration_seconds": 30,
  "cost_usd": 0.0,
  "cache": "MISS",
  "audio_url": "https://storage.googleapis.com/...",
  "usage": { "unit": "clip", "billed_units": 1 },
  "metadata": { "format": "mp3", "generation_ms": 21000 }
}
```

`audio_url` is signed and valid for 15 minutes. If no URL could be signed, `audio_base64` is returned instead. `cost_usd` above is a placeholder, not a price.

### List models

`GET /music/v1/models` returns the enabled models with `pricing_unit` and `price_per_unit_usd`. Rates are per unit.

## Cache (per user)

With `cache: true` (default) the result is stored for 30 days under a key built from **your user ID**, key type (managed or BYOK) and every parameter that changes the audio, including `seed` and `variant`. Nobody else can hit your entries.

| `X-Cache` | Meaning |
|-----------|---------|
| `MISS` | Generated now and billed |
| `HIT` | Replayed from your cache: no vendor call, **$0** |
| `BYPASS` | `cache: false` without an `Idempotency-Key`: generated and billed |

The same body returns the same audio. To get a new take, change `variant` or `seed`, or send `cache: false`.

## Idempotency-Key

Send `Idempotency-Key: <1 to 255 printable ASCII characters>` with `cache: false` to make a retry safe. With the default `cache: true` the content cache already protects you, and the header is ignored.

- The first request generates and bills once. A retry with the same key and body replays the audio (`X-Cache: HIT`, $0) for 24 hours.
- A request that fails before it is billed releases the key. A request that succeeded and was billed keeps it, 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 belongs to another provider |
| 400 | `model_not_enabled` | The model is not enabled by Demeterics |
| 400 | `recitation_risk` | Google refused the prompt (it probably names an artist, a show or copyrighted lyrics). **Not charged.** See Prompt guidance. |
| 400 | `byok_unsupported` | `vertex` does not accept a BYOK key |
| 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 `FeatureMusic` |
| 409 | `request_in_progress` | An identical request 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 songs 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. |
| 501 | `provider_not_configured` | The `vertex` provider is not set up on this server |
| 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 |

Honor `Retry-After` on every 409 and 429. Demeterics never retries a vendor call for you. If the vendor may have generated audio and the reply was then lost or unusable (an upstream timeout after the request was sent, a provider 5xx, or a reply with no usable audio), the call is billed 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**:

| Model | Unit | What is billed |
|-------|------|----------------|
| `lyria-3.5` | `song` | One song per request |
| `lyria-3-clip-preview` | `clip` | One 30 s clip per request |
| `lyria-002` (vertex) | `clip` | One 30 s clip per request |
| `music_v1` (elevenlabs) | `seconds` | The requested length rounded **up to whole minutes**, in seconds, times the per-second rate. A 10 s request bills 60 s. |

For current rates see [Available Models](https://demeterics.ai/docs/models) or `GET /music/v1/models`. Rates are set conservatively and the vendors report no cost in the response, so the charge is the rate times the units above, plus a service fee (managed or BYOK, as for other APIs). Cache hits and idempotent replays are $0. A prompt refused as `recitation_risk` is not charged. See [Credits & Pricing](https://demeterics.ai/docs/credits).

## Prompt guidance

- **Describe acoustic ingredients**: instruments, tempo (bpm), key or mode, mood, texture, room, production style. "Slow instrumental for solo cello and soft piano, 70 bpm, minor, close and warm" works better than a genre label alone.
- **Never name living composers, artists or bands, and never name TV or film titles.** Google blocks these prompts, and you get `recitation_risk` (no charge). Do not paste lyrics either. Demeterics does not keep a name list, so a rewrite is on you: replace the name with what you hear ("sweeping brass fanfare, steady snare, heroic" instead of a film title).
- Do not stack band-specific words with low-end words. As with sound effects, a prompt of "sub-bass" plus "sparse midrange" can push the energy below 100 Hz, where you hear almost nothing. Say what the bass does and keep the midrange alive.
- Full songs are sized by the vendor (about two minutes). Shape the structure in the prompt ("short intro, one verse, one chorus, quick ending"). For a fixed length use `lyria-3-clip-preview` (30 s) or ElevenLabs with `duration_seconds`.
- Re-roll with `variant` to compare takes without changing the prompt.

## See also

- [Sound Effects API](https://demeterics.ai/docs/sfx.md)
- [Speech Generation](https://demeterics.ai/docs/speech.md)
