# Audio chat and music

A spoken answer, a song, on one route.

1. [Pick a music model](#1-pick-a-music-model).
2. [Describe the piece](#2-describe-the-piece).
3. [Save what comes back](#3-save-what-comes-back).

## 1. Pick a music model

A music model makes one finished piece from a description. There is no music route: the piece comes from `/v1/chat/completions`, with `modalities` set to `["audio"]`. Copy its model ID from its page in *Models* and send it in `model` as it stands.

| Model | Makes |
|---|---|
| `google/lyria-3-pro-preview` | a full song |
| `google/lyria-3-clip-preview` | a clip of 30 seconds |

## 2. Describe the piece

Describe the piece in the user message: the style, the instruments, the length. Yacine wants music for the clothing shop in Oran that his Souk Bot answers for, and sends one line.

```python
import base64
import json
import os
import urllib.request

API_KEY = os.environ["OPENDUNES_API_KEY"]
ADDRESS = "https://opendunes.com/v1/chat/completions"
MODEL = "google/lyria-3-pro-preview"
PROMPT = "An upbeat raï track, brass and darbuka, two minutes."

request = urllib.request.Request(
    ADDRESS,
    data=json.dumps(
        {
            "model": MODEL,
            "messages": [{"role": "user", "content": PROMPT}],
            "modalities": ["audio"],
            "audio": {"format": "mp3"},
        }
    ).encode(),
    headers={
        "Authorization": "Bearer " + API_KEY,
        "Content-Type": "application/json",
    },
)
with urllib.request.urlopen(request) as response:
    answer = json.load(response)

audio = answer["choices"][0]["message"]["audio"]
with open("song.mp3", "wb") as f:
    f.write(base64.b64decode(audio["data"]))
print(answer["usage"]["cost"])
```

```javascript
import { writeFile } from "node:fs/promises";

const API_KEY = process.env.OPENDUNES_API_KEY;
const ADDRESS = "https://opendunes.com/v1/chat/completions";
const MODEL = "google/lyria-3-pro-preview";
const PROMPT = "An upbeat raï track, brass and darbuka, two minutes.";

const response = await fetch(ADDRESS, {
  method: "POST",
  headers: {
    Authorization: `Bearer ${API_KEY}`,
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    model: MODEL,
    messages: [{ role: "user", content: PROMPT }],
    modalities: ["audio"],
    audio: { format: "mp3" },
  }),
});
const answer = await response.json();

const audio = answer.choices[0].message.audio;
await writeFile("song.mp3", Buffer.from(audio.data, "base64"));
console.log(answer.usage.cost);
```

```go
package main

import (
	"bytes"
	"encoding/base64"
	"encoding/json"
	"fmt"
	"net/http"
	"os"
)

const (
	address = "https://opendunes.com/v1/chat/completions"
	model   = "google/lyria-3-pro-preview"
	prompt  = "An upbeat raï track, brass and darbuka, two minutes."
)

func main() {
	apiKey := os.Getenv("OPENDUNES_API_KEY")

	body, err := json.Marshal(map[string]any{
		"model": model,
		"messages": []map[string]string{
			{"role": "user", "content": prompt},
		},
		"modalities": []string{"audio"},
		"audio":      map[string]string{"format": "mp3"},
	})
	if err != nil {
		panic(err)
	}

	req, err := http.NewRequest("POST", address, bytes.NewReader(body))
	if err != nil {
		panic(err)
	}
	req.Header.Set("Authorization", "Bearer "+apiKey)
	req.Header.Set("Content-Type", "application/json")

	res, err := http.DefaultClient.Do(req)
	if err != nil {
		panic(err)
	}
	defer res.Body.Close()

	var answer struct {
		Choices []struct {
			Message struct {
				Audio struct {
					Data string `json:"data"`
				} `json:"audio"`
			} `json:"message"`
		} `json:"choices"`
		Usage struct {
			Cost json.Number `json:"cost"`
		} `json:"usage"`
	}
	if err := json.NewDecoder(res.Body).Decode(&answer); err != nil {
		panic(err)
	}
	data := answer.Choices[0].Message.Audio.Data
	song, err := base64.StdEncoding.DecodeString(data)
	if err != nil {
		panic(err)
	}
	if err := os.WriteFile("song.mp3", song, 0o644); err != nil {
		panic(err)
	}
	fmt.Println(answer.Usage.Cost)
}
```

```bash cURL
ADDRESS="https://opendunes.com/v1/chat/completions"
MODEL="google/lyria-3-pro-preview"

curl "$ADDRESS" \
  -H "Authorization: Bearer $OPENDUNES_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "'"$MODEL"'",
    "messages": [
      {
        "role": "user",
        "content": "An upbeat raï track, brass and darbuka, two minutes."
      }
    ],
    "modalities": ["audio"],
    "audio": {
      "format": "mp3"
    }
  }'
```

| You send | Holds |
|---|---|
| `model` | a music model's ID: a song or a clip |
| `messages` | the description of the piece |
| `modalities` | `["audio"]`: asks for a piece, not words |
| `audio.format` | the container of the piece, such as `mp3` |

Every field: [Chat](/docs/reference/chat-completions).

<div class="watch-out">
<p>Without <code>"modalities": ["audio"]</code>, a music model refuses the request.</p>
</div>

<div class="buttons">
<a href="/models?modality=audio" class="button primary">Browse music models</a>
</div>

## 3. Save what comes back

`200`, with the whole piece inside the answer. Decode `audio.data` from base64 and write it to a file, as the samples do.

| Field | Holds |
|---|---|
| `choices[0].message.audio.data` | the piece, base64, in the format asked for |
| `choices[0].message.audio.file_id` | the stored copy of the piece, kept in your files: [Files and storage](/docs/files-and-storage) |
| `choices[0].message.audio.expires_at` | when the provider drops its own copy; ours stays |
| `usage` | `cost`: the charge, in DA. Tokens may ride along; they are not the charge |

Two headers come back.

| Header | Holds |
|---|---|
| `X-Generation-Id` | the request's receipt: [Receipt](/docs/reference/generation) |
| `X-Balance-Available` | your balance after this charge, in µDA |

## A spoken answer

The same route answers in a voice: a conversation with `modalities` set to `["text", "audio"]`, and `audio.voice` naming the voice. The reply's words come back in `audio.transcript`, beside the audio.

<div class="good-to-know">
<p>No model that answers in a voice is on sale now. To turn text you already have into an audio file, see <a href="/docs/speech">Speech</a>.</p>
</div>

## What it cost

One piece, one charge, in DA, from your balance once the piece is delivered. The model is the price: a song on one, a clip on the other. The description's length and the piece's length never move it. `usage.cost` carries the charge; the model's page in *Models* gives the price.

These charge nothing:

| Case | Charged |
|---|---|
| the generation fails | nothing |
| a `200` with no audio | nothing |
| the stream is cut before the piece ends | nothing: a partial piece is not a piece |

## Errors

The body says why.

| Status | When |
|---|---|
| 400 | `model` or `messages` is missing, or a field has the wrong type |
| 401 | the key is missing, wrong, disabled or expired |
| 402 | your balance is at zero or below, cannot pay the request's hold, or the key's cap is spent; `error.metadata.limit_source` names which, and `deposit_url` or `key_url` says where to lift it. After up to 60 seconds of waiting for money your running requests hold, the 402 carries `Retry-After: 60` |
| 404 | `model` is not a model on sale |
| 429 | the API key's own rate limit is reached (`metadata.limit_source` is `key`), or the provider is limiting its rate; `Retry-After` says how many seconds to wait |
| 502 | the model is down, or answered with nothing usable |

What to do on each: [Errors and retries](/docs/errors-and-retries).
