Implementation:Elevenlabs Elevenlabs python MusicCustomClient
| 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:
- Collect all byte chunks from the streaming response into a single buffer.
- Decode the buffer to text and extract the multipart boundary string from the first line.
- Scan the first 10 lines for a
Content-Type: application/jsonheader and parse the subsequent JSON payload. - Scan the first 20 lines for a
filename="..."header to extract the output filename. - Locate the second boundary marker to find where the audio data begins.
- Skip past the audio part headers (searching for a double newline
\n\ndelimiter). - 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
- Elevenlabs_Elevenlabs_python_Package_Exports - Package-level exports including the music submodule
- Elevenlabs_Elevenlabs_python_RawBaseClient - Low-level raw HTTP client used by the SDK
- Elevenlabs_Elevenlabs_python_WebhookSignatureVerification - Webhook signature verification utilities