Jump to content

Connect SuperML | Leeroopedia MCP: Equip your AI agents with best practices, code verification, and debugging knowledge. Powered by Leeroo — building Organizational Superintelligence. Contact us at founders@leeroo.com.

Implementation:Elevenlabs Elevenlabs python MusicCustomClient

From Leeroopedia
Field Value
sources src/elevenlabs/music_custom.py
domains Music Generation, Multipart Response Parsing, Audio Composition
last_updated 2026-02-15

Overview

The MusicCustomClient module provides custom music composition clients that extend the auto-generated ElevenLabs music API clients. It adds the compose_detailed method, which calls the parent API endpoint and then parses the resulting multipart HTTP response into a structured MultipartResponse dataclass containing JSON metadata (composition plan and song metadata), raw audio bytes, and the output filename.

Both synchronous (MusicClient) and asynchronous (AsyncMusicClient) variants are provided. The module also defines two supporting dataclasses: SongMetadata for describing song attributes and MultipartResponse for holding parsed API results.

Typical usage:

from elevenlabs import ElevenLabs

client = ElevenLabs(api_key="your_api_key")
result = client.music.compose_detailed(prompt="A calm ambient track")
print(result.filename)
print(result.json)  # composition plan and song metadata
with open(result.filename, "wb") as f:
    f.write(result.audio)

Code Reference

Source file: src/elevenlabs/music_custom.py

Dataclasses

@dataclass
class SongMetadata:
    title: str
    description: str
    genres: typing.List[str]
    languages: typing.List[str]
    is_explicit: bool

@dataclass
class MultipartResponse:
    json: typing.Dict[str, typing.Any]  # Contains compositionPlan and songMetadata
    audio: bytes
    filename: str

MusicClient (Synchronous)

class MusicClient(AutogeneratedMusicClient):
    def compose_detailed(
        self,
        *,
        output_format: typing.Optional[AllowedOutputFormats] = None,
        prompt: typing.Optional[str] = OMIT,
        composition_plan: typing.Optional[MusicPrompt] = OMIT,
        music_length_ms: typing.Optional[int] = OMIT,
        model_id: typing.Optional[typing.Literal["music_v1"]] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> MultipartResponse: ...

    def _parse_multipart(self, stream: typing.Iterator[bytes]) -> MultipartResponse: ...

AsyncMusicClient (Asynchronous)

class AsyncMusicClient(AutogeneratedAsyncMusicClient):
    async def compose_detailed(
        self,
        *,
        output_format: typing.Optional[AllowedOutputFormats] = None,
        prompt: typing.Optional[str] = OMIT,
        composition_plan: typing.Optional[MusicPrompt] = OMIT,
        music_length_ms: typing.Optional[int] = OMIT,
        model_id: typing.Optional[typing.Literal["music_v1"]] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> MultipartResponse: ...

    async def _parse_multipart_async(self, stream: typing.AsyncIterator[bytes]) -> MultipartResponse: ...

Import statement:

from elevenlabs.music_custom import MusicClient, AsyncMusicClient, MultipartResponse, SongMetadata

I/O Contract

compose_detailed

Parameter Type Required Default Description
output_format Optional[AllowedOutputFormats] No None Audio output format for the generated music
prompt Optional[str] No OMIT Text prompt describing the desired composition
composition_plan Optional[MusicPrompt] No OMIT Structured composition plan object (alternative to prompt)
music_length_ms Optional[int] No OMIT Desired length of the generated music in milliseconds
model_id Optional[Literal["music_v1"]] No OMIT Model identifier; currently only "music_v1" is supported
request_options Optional[RequestOptions] No None Per-request configuration (timeouts, headers, etc.)

Returns:

Field Type Description
json Dict[str, Any] Parsed JSON metadata containing composition plan and song metadata
audio bytes Raw audio bytes of the generated music file
filename str Extracted filename from response headers (defaults to generated_music.mp3)

Raises:

Exception Condition
ValueError Empty response from music API
ValueError Could not find audio part boundary in multipart response
ValueError Could not parse JSON data from the response

Multipart Parsing Logic

The internal _parse_multipart / _parse_multipart_async methods perform the following steps:

  1. Collect all byte chunks from the streaming response into a single buffer.
  2. Decode the buffer to text and extract the multipart boundary string from the first line.
  3. Scan the first 10 lines for a Content-Type: application/json header and parse the subsequent JSON payload.
  4. Scan the first 20 lines for a filename="..." header to extract the output filename.
  5. Locate the second boundary marker to find where the audio data begins.
  6. Skip past the audio part headers (searching for a double newline \n\n delimiter).
  7. Return all remaining bytes as the audio content.

Usage Examples

Synchronous: Compose from a Text Prompt

from elevenlabs import ElevenLabs

client = ElevenLabs(api_key="your_api_key")
result = client.music.compose_detailed(
    prompt="An upbeat electronic track with synth leads",
    music_length_ms=60000,
    model_id="music_v1",
)

print(f"Filename: {result.filename}")
print(f"Metadata: {result.json}")
print(f"Audio size: {len(result.audio)} bytes")

# Save audio to disk
with open(result.filename, "wb") as f:
    f.write(result.audio)

Asynchronous: Compose from a Composition Plan

import asyncio
from elevenlabs import AsyncElevenLabs
from elevenlabs.types.music_prompt import MusicPrompt

async def main():
    client = AsyncElevenLabs(api_key="your_api_key")
    plan = MusicPrompt(...)  # Build a structured composition plan
    result = await client.music.compose_detailed(
        composition_plan=plan,
        output_format="mp3_44100_128",
    )

    with open(result.filename, "wb") as f:
        f.write(result.audio)

    # Access the parsed metadata
    song_metadata = result.json.get("songMetadata", {})
    print(f"Title: {song_metadata.get('title')}")

asyncio.run(main())

Handling Parsing Errors

from elevenlabs import ElevenLabs

client = ElevenLabs(api_key="your_api_key")
try:
    result = client.music.compose_detailed(prompt="Jazz quartet improvisation")
except ValueError as e:
    print(f"Failed to parse multipart response: {e}")

Related Pages

Page Connections

Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment