> ## Documentation Index
> Fetch the complete documentation index at: https://docs.base44.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Generate music with the AI Gateway

> Generate songs and instrumental tracks from your backend functions through the AI Gateway's music endpoint.

The [AI Gateway](https://docs.base44.com/developers/references/sdk/docs/interfaces/ai-gateway.md) serves a music endpoint, so your app can turn a text prompt into a song or an instrumental track, with control over its style, lyrics, and length. Requests are billed to your app's credits, with no separate provider account or API key.

> [!TIP]
>
> **Before you begin:**
>
> * Call the gateway server-side, such as from a [backend function](https://docs.base44.com/developers/backend/resources/backend-functions/overview.md), rather than the browser. This lets you check who's calling and control usage before a request is billed to your app.
> * Get the `baseURL`, `token`, and `headers` from [`base44.asServiceRole.aiGateway.connection()`](https://docs.base44.com/developers/references/sdk/docs/interfaces/ai-gateway#connection).
> * Calls from the browser or with a user's token get a `403` and the error code `ai_gateway_requires_service_role`.

Music generation is synchronous. The request stays open until the track is ready, which can take a minute or more, and then returns a link to the finished MP3. There's no job to poll.

## Endpoint

| Endpoint | Description |
| - | - |
| `POST {baseURL}/audio/music` | Generates a track from a prompt and returns its `url`. |

The endpoint accepts JSON. Authenticate with `Authorization: Bearer {token}`. OpenAI's API has no music endpoint, so the request and response format is Base44's own, and errors follow OpenAI's format like the rest of the gateway.

## Generate a song

Send a prompt that describes the style and mood, and any lyrics, to `POST /audio/music`. The gateway stores the MP3 in your app's files and returns its `url`.

```typescript Generate a song theme={null}
import { createClientFromRequest } from "npm:@base44/sdk";

export default async function (req: Request): Promise<Response> {
  const base44 = createClientFromRequest(req);
  const user = await base44.auth.me();
  if (!user) return Response.json({ error: "Unauthorized" }, { status: 401 });

  const { lyrics } = await req.json();
  const { baseURL, token, headers } = base44.asServiceRole.aiGateway.connection();

  const response = await fetch(`${baseURL}/audio/music`, {
    method: "POST",
    headers: { ...headers, Authorization: `Bearer ${token}`, "Content-Type": "application/json" },
    body: JSON.stringify({
      model: "automatic",
      prompt: `An upbeat acoustic pop song with handclaps. Lyrics:\n${lyrics}`,
      duration_seconds: 60,
    }),
  });

  const song = await response.json();
  // { model: "lyria_3_5", url: "https://...mp3", duration_seconds: 60, usage: { base44_credits: ... } }

  return Response.json({ url: song.url });
}
```

Save `song.url` on an entity rather than downloading the file and uploading it again. The file is already in your app's storage.

To use the OpenAI SDK instead of `fetch()`, call the endpoint with `client.post()`. Set a long `timeout` so the client waits for the track, and turn off automatic retries so a slow request isn't sent and billed twice.

```typescript Generate a song with the OpenAI SDK theme={null}
import OpenAI from "npm:openai";

const { baseURL, token, headers } = base44.asServiceRole.aiGateway.connection();
const client = new OpenAI({ baseURL, apiKey: token, defaultHeaders: headers, maxRetries: 0, timeout: 300_000 });

const song = await client.post("/audio/music", {
  body: { model: "automatic", prompt, duration_seconds: 30 },
});
```

## Write the prompt

The prompt carries everything about the track, including its genre, mood, instruments, tempo, and lyrics. Mark lyric sections with tags such as `[Verse]` and `[Chorus]`.

```text Prompt with lyrics theme={null}
A dreamy synth-pop song with a slow build and a female vocal.

[Verse]
Streetlights hum a quiet tune
...

[Chorus]
...
```

Music generation takes no image or audio input. To write a song about a photo or a story, first send the image or text to a [chat model](https://docs.base44.com/developers/references/sdk/docs/interfaces/ai-gateway.md#openai-compatible-models) and ask it for short lyrics and a style description, then put them in the music prompt.

> [!WARNING]
>
> Don't name a real artist or include copyrighted lyrics. The model refuses these prompts, and the request fails with a `400`.

### Instrumental tracks

Set `instrumental` to `true` to ask for a track without vocals. On `lyria_3_5`, this is best effort, and the track can still have vocals. Leave lyrics out of the prompt for an instrumental track.

### Duration

Set `duration_seconds` to a whole number from 5 to 180. It defaults to 30. On `lyria_3_5`, the duration is a target rather than an exact length, and the track can run longer than you asked. The `duration_seconds` in the response is the length you requested, not the length of the file.

## Models

Set `model` to `automatic` or leave it out to let Base44 choose, or pin a model ID. `automatic` always uses `lyria_3_5`. Music models are separate from the [chat models](https://docs.base44.com/developers/references/sdk/docs/interfaces/ai-gateway.md#openai-compatible-models), [image models](https://docs.base44.com/developers/references/sdk/getting-started/ai-gateway-images.md#models), and [video models](https://docs.base44.com/developers/references/sdk/getting-started/ai-gateway-video.md#models) the gateway serves.

| Model ID | Provider | Duration in `duration_seconds` | Exact duration | Instrumental |
| - | - | - | - | - |
| `lyria_3_5` | Google | `5` to `180` | No, approximate | Best effort |

## Play the track

The `url` points to an MP3 file, so you can play it like any other audio file. On the web, render it with an `<audio>` element.

```tsx Play a generated song theme={null}
<audio controls src={song.url} />
```

Browsers often block autoplay, so let the person start playback. Because generation takes a while, show a loading state in your app while the backend function waits for the track.

## Request parameters

| Parameter | Type | Description |
| - | - | - |
| `prompt` | `string` | Required. The style, mood, and any lyrics, up to 4,000 characters. |
| `model` | `string` | Model ID from [Models](#models). Defaults to `automatic`. |
| `duration_seconds` | `integer` | Length of the track, within the range the model supports. Defaults to `30`. |
| `instrumental` | `boolean` | Whether to ask for a track without vocals. Defaults to `false`. |
| `response_format` | `string` | Format of the file. Only `mp3` is supported, and it's the default. |
| `dry_run` | `boolean` | Returns the model that would run and its cost without generating a track. See [Estimate the cost](#estimate-the-cost). |

Fields that aren't listed here are ignored.

## Response

```json theme={null}
{
  "model": "lyria_3_5",
  "url": "https://...music_3f9a1c2e.mp3",
  "duration_seconds": 60,
  "usage": { "base44_credits": 32 }
}
```

The `url` points to a file stored in your app's public file storage.

## Estimate the cost

Set `dry_run` to `true` to see which model a request would run on and what it would cost, without generating a track or using credits.

```typescript Estimate the cost of a request theme={null}
const response = await fetch(`${baseURL}/audio/music`, {
  method: "POST",
  headers: { ...headers, Authorization: `Bearer ${token}`, "Content-Type": "application/json" },
  body: JSON.stringify({ model: "automatic", prompt, duration_seconds: 120, dry_run: true }),
});

const { model, usage } = await response.json();
// { dry_run: true, model: "lyria_3_5", usage: { base44_credits: ... } }
```

Music requests use your app's credits, the same shared quota as the rest of the [AI Gateway](https://docs.base44.com/developers/references/sdk/docs/interfaces/ai-gateway.md#billing-and-limits). `lyria_3_5` is billed per track, so a longer track costs the same as a shorter one. A request that fails isn't billed.

## Limits

| Limit | Value |
| - | - |
| Prompt | 4,000 characters |
| Duration | 5 to 180 seconds on `lyria_3_5` |
| Music requests | 20 per minute per app |
| Requests | 200 per minute per app, shared with all AI Gateway requests |

## Errors

Errors use OpenAI's format, `{ "error": { "message", "type", "code", "param" } }`, so client libraries report them like any other OpenAI error.

| Status | Cause |
| - | - |
| `400` | An empty or too-long prompt, a `duration_seconds` outside the model's range, a `response_format` other than `mp3`, or a prompt the model refused. The message names the problem, and `param` names the field. |
| `402` | Your app is out of credits. |
| `404` | The model ID doesn't exist. |
| `429` | Your app is generating music faster than 20 requests per minute, or the model provider is rate limiting requests. Retry after a short wait. |
| `502` | The model provider failed to generate the track or took too long. |

## See also

* [ai-gateway](https://docs.base44.com/developers/references/sdk/docs/interfaces/ai-gateway.md): Get connection details and use chat models through the gateway.
* [Generate images](https://docs.base44.com/developers/references/sdk/getting-started/ai-gateway-images.md): Generate and edit images through the gateway.
* [Generate video](https://docs.base44.com/developers/references/sdk/getting-started/ai-gateway-video.md): Generate video from a prompt, an image, or existing media.
* [Backend functions](https://docs.base44.com/developers/backend/resources/backend-functions/overview.md): Write the server-side code that calls the gateway.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.