Just want to generate songs? You're in the wrong place. Back to Treblo

API documentation

v1

These guides show how to do each task with the Treblo API. The API reference lists every endpoint and parameter.

Base URL:https://api.treblo.com/v1

Quick start

Send a prompt and get back a song. The whole song takes a minute or two, but you can start listening in under 20 seconds.

  1. Create an API key and start your free trial, which gives you 3,000 credits.
  2. Start a generation with a prompt and the API will provide a task_id immediately.
  3. Check the task's status until it is SUCCESS, then fetch the song's URL.
import time
import requests
API = "https://api.treblo.com/v1"
headers = {"Authorization": "Bearer your_api_key_here"}
# 1. Start the generation
response = requests.post(
f"{API}/generations/v3",
headers=headers,
json={
"prompt": "a chill lofi beat for studying",
},
)
response.raise_for_status()
task_id = response.json()["task_id"]
# 2. Wait for it to finish, for up to 5 minutes
deadline = time.time() + 300
while True:
response = requests.get(f"{API}/generations/status/{task_id}", headers=headers)
response.raise_for_status()
status = response.json()
print(status)
if status in ("SUCCESS", "FAILURE"):
break
if time.time() > deadline:
raise SystemExit("Timed out waiting for the song")
time.sleep(5)
# 3. Get the song
song = requests.get(f"{API}/generations/{task_id}", headers=headers).json()
if status == "FAILURE":
raise SystemExit(song["error_message"])
print(song["song_paths"][0])

Listen before the song is finished

Add "enable_streaming": true to the request. When the status reaches GENERATING_STREAMING_READY, play the song from the streaming URL while we generate the rest. See Stream while generating.

html
<!-- Works once the task reaches GENERATING_STREAMING_READY -->
<audio controls autoplay>
<source src="https://api-stream.treblo.com/stream/your_task_id" type="audio/ogg" />
</audio>

Every generation request on this page returns a task_id that you poll in the same way, so the examples below show only the request.

API keys and credits

Send your API key in the Authorization header of every request:

Authorization: Bearer your_api_key_here

Each song costs 100 credits, whatever options you set, so a request for two songs costs 200. We charge only for songs that succeed. GET /credits/balance returns your balance. If you have no credits, the API rejects the request with a 402.

Generate a song

Send a prompt. We write the lyrics, pick the style, and generate the song.

import requests
response = requests.post(
"https://api.treblo.com/v1/generations/v3",
headers={"Authorization": "Bearer your_api_key_here"},
json={
"prompt": "An upbeat indie rock song about a road trip with old friends",
},
)
print(response.json()) # {"task_id": "..."}

Instrumentals

Set instrumental to true for a song with no vocals. We then use the prompt only to pick the style.

import requests
response = requests.post(
"https://api.treblo.com/v1/generations/v3",
headers={"Authorization": "Bearer your_api_key_here"},
json={
"prompt": "A chill lofi beat for studying",
"instrumental": True,
},
)
print(response.json()) # {"task_id": "..."}

Length

A song is usually two to four minutes long and never longer than 4 minutes 45 seconds. To ask for a different length, set length_range to the shortest and longest length you want, in seconds.

import requests
response = requests.post(
"https://api.treblo.com/v1/generations/v3",
headers={"Authorization": "Bearer your_api_key_here"},
json={
"prompt": "A short, punchy pop-punk song about Mondays",
"length_range": [60, 120],
},
)
print(response.json()) # {"task_id": "..."}

The range is a suggestion to the model, and the model generally follows it. A larger range gives a longer song, but some songs do not follow the range. If you send your own lyrics, the amount of lyrics you send is a strong indicator of how long the song will be.

Clips

Set clip to true for a short piece that sounds like it was cut from the middle of a song. Without this option, our model tries to generate a complete song.

import requests
response = requests.post(
"https://api.treblo.com/v1/generations/v3",
headers={"Authorization": "Bearer your_api_key_here"},
json={
"prompt": "A catchy synth-pop hook for a sneaker ad",
"clip": True,
},
)
print(response.json()) # {"task_id": "..."}

A clip is under 30 seconds. For a longer one, send length_range with it. If you send your own lyrics, send only the few lines the clip should sing. A clip costs the same credits as a song. clip is only valid for new generations, not extensions.

Two songs

Set num_songs to 2 and one request generates two different songs. Both songs will have the same styles and lyrics.

import requests
response = requests.post(
"https://api.treblo.com/v1/generations/v3",
headers={"Authorization": "Bearer your_api_key_here"},
json={
"prompt": "An upbeat indie rock song about a road trip with old friends",
"num_songs": 2,
},
)
print(response.json()) # {"task_ids": ["...", "..."]}

Each song is generated as a separate task, so the response includes task_ids instead of task_id:

json
{
"task_ids": [
"a598194b-d464-474c-b1e6-1c99f8f8e457",
"c41d7e02-9b3a-4f6d-8e15-2a7f0b6c93d8"
]
}
  • A request for two songs creates two tasks, and each task has a different task_id. When you request the result for each task_id with GET /generations/{task_id}, the song_paths of that task includes one URL.
  • Each task is tracked in the same way as a task for a single song. Each task has its own status and its own stream.
  • When using a webhook_url, status updates for each task are separately sent to the same URL. Each POST request still includes the task_id of the corresponding task.
  • A request for two songs costs 200 credits. If one of the songs fails, you are only charged for the song that succeeded.
  • All other parameters in the request apply to both songs.
  • num_songs is also supported when extending a song or generating from reference audio.

Parameters in this section

promptstring
A description of the song. We use it to write the tags and lyrics you do not send. Up to 14,000 characters.
instrumentalbooleanDefault: false
Set to true for a song with no vocals. You cannot send lyrics with it.
length_range[integer, integer]
The [shortest, longest] length you want for the song, in seconds. This is a suggestion to the model and it generally follows it. Both values are multiples of 30. The first is 0 to 270, the second is 30 to 300, and the first must be lower than the second. The model never generates more than 4 minutes 45 seconds in one request.
clipbooleanDefault: false
Set to true for a short piece from the middle of a song, with no intro or ending. The piece is under 30 seconds unless you set length_range.
num_songsintegerDefault: 1
The number of songs to generate, 1 or 2. Each song is generated as a separate task, and both songs have the same styles and lyrics. When set to 2, the response includes task_ids instead of task_id.

These are only the parameters this section uses. The endpoint accepts more, and the API reference lists all of them.

Use your own lyrics

Send the lyrics and a prompt that describes how the song should sound.

import requests
response = requests.post(
"https://api.treblo.com/v1/generations/v3",
headers={"Authorization": "Bearer your_api_key_here"},
json={
"prompt": "Dreamy indie pop with a big singalong chorus",
"lyrics": "[Verse]\nHeadlights on an empty road\nRadio is singing low\n\n[Chorus]\nWe are going where the map runs out\nWe are going where the map runs out",
},
)
print(response.json()) # {"task_id": "..."}

The lyrics in that request, written out:

[Verse]
Headlights on an empty road
Radio is singing low
[Chorus]
We are going where the map runs out
We are going where the map runs out
  • Label sections in square brackets, such as [Verse] and [Chorus], with each label on its own line.
  • Send lyrics with either a prompt or tags, but not both. The API rejects lyrics sent alone.
  • The amount of lyrics you send is a strong indicator of how long the song will be.
  • Lyrics can be up to 40,000 characters, but they must also fit in one song. If they do not, the API rejects the request or the task fails with "Prompt (tags + lyrics) too long".

Parameters in this section

promptstring
A description of the song. We use it to write the tags and lyrics you do not send. Up to 14,000 characters.
lyricsstring
The lyrics to sing. Send them with either prompt or tags. Up to 40,000 characters.

These are only the parameters this section uses. The endpoint accepts more, and the API reference lists all of them.

Choose the style

We normally pick a song's style tags from your prompt. Send tags to pick them yourself.

Tags are short labels such as a genre, a mood, or an instrument. They must come from our tag list. We recommend sending at least three.

import requests
response = requests.post(
"https://api.treblo.com/v1/generations/v3",
headers={"Authorization": "Bearer your_api_key_here"},
json={
"prompt": "A song about leaving your hometown",
"tags": ["indie rock", "female vocalist", "melancholic"],
},
)
print(response.json()) # {"task_id": "..."}

In that request we use the prompt only to write the lyrics. To set both the style and the lyrics yourself, send tags and lyrics with no prompt:

import requests
response = requests.post(
"https://api.treblo.com/v1/generations/v3",
headers={"Authorization": "Bearer your_api_key_here"},
json={
"tags": ["indie rock", "female vocalist", "melancholic"],
"lyrics": "[Verse]\nHeadlights on an empty road\nRadio is singing low\n\n[Chorus]\nWe are going where the map runs out\nWe are going where the map runs out",
},
)
print(response.json()) # {"task_id": "..."}

What you send and what we write

You sendWe write
promptTags and lyrics
prompt + lyricsTags
prompt + tagsLyrics
tags + lyricsNothing
tags + instrumentalNothing
prompt + instrumentalTags

The API rejects any other combination, such as prompt, tags, and lyrics together, lyrics alone, or tags alone without instrumental. To send tags and let us decide what the lyrics are about, add "prompt": "".

Avoid a style

List the tags you want the song to avoid in negative_tags. A higher negative_tags_strength makes the model avoid them more.

import requests
response = requests.post(
"https://api.treblo.com/v1/generations/v3",
headers={"Authorization": "Bearer your_api_key_here"},
json={
"prompt": "A slow acoustic song about leaving your hometown",
"negative_tags": ["electronic", "drum machine"],
"negative_tags_strength": 2,
},
)
print(response.json()) # {"task_id": "..."}

How closely the song follows the style

Higher values of style_scale and prompt_strength make the song follow your tags and lyrics more closely but sound less natural. We tuned the defaults, so change them only if songs ignore what you asked for. Only one of the two can be above 1.0. We strongly discourage setting either above 3.0, or negative_tags_strength above 5.0. Higher values will likely give lower quality results.

Parameters in this section

tagsarray of strings
Style tags from our tag list. Up to 64 tags. The API rejects a tag that is not on the list. The array needs at least 1 tag. Leave the field out and we pick the tags.
negative_tagsarray of strings
Tags for the song to avoid, from the same tag list. Up to 64 tags.
negative_tags_strengthfloatDefault: 1.0
How strongly the model avoids negative_tags. 1.0 to 10.0. We strongly discourage values above 5.0, which will likely give lower quality results. You can change it only if you send negative_tags.
style_scalefloatDefault: 2.3
How closely the song follows its tags. A higher value follows them more closely but sounds less natural. 1.0 to 12.0. We strongly discourage values above 3.0, which will likely give lower quality results.
prompt_strengthfloatDefault: 1.0
How closely the song follows its tags and lyrics together. A higher value follows them more closely but sounds less natural. 1.0 to 12.0. We strongly discourage values above 3.0, which will likely give lower quality results. Exactly one of prompt_strength and style_scale must be above 1.0, so set style_scale to 1.0 before you raise this.

These are only the parameters this section uses. The endpoint accepts more, and the API reference lists all of them.

Use a model variant

Beta

A variant is a version of the model with its own sound.

List the variant you want in variants. Without the field, we use the standard model.

VariantSound
s-punchyHarder-hitting, more dance/pop-oriented sound
s-smoothCatchy and mellow pop-oriented sound
s-squishySquishy drums, a bouncy groove, and happy accidents
import requests
response = requests.post(
"https://api.treblo.com/v1/generations/v3",
headers={"Authorization": "Bearer your_api_key_here"},
json={
"prompt": "An upbeat synth-pop song about a road trip",
"variants": ["s-punchy"],
},
)
print(response.json()) # {"task_id": "..."}
  • Variants are in beta. We may add or remove a variant at any time.
  • variants works on every v3 request: generating, extending, covering, using a voice, and transferring a style.
  • A variant changes only the sound. It takes the same tags and costs the same credits.
  • The field is a list, so you can combine variants by sending more than one.
  • An extend does not reuse the variants of the song it continues. To keep the same sound, send variants again.
  • GET /generations/{task_id} returns the variants a task used in v3_params.variants.

Parameters in this section

variantsarray of strings
The variants of the model to generate with. Any of s-punchy, s-smooth, and s-squishy, each at most once. Leave the field out to use the standard model.

These are only the parameters this section uses. The endpoint accepts more, and the API reference lists all of them.

Upload audio

To extend a song, cover a song, use a voice, or transfer a style, you send us audio. There are three ways to send it.

audio_urlstring (URL)
A public URL of the audio. For a song the API generated, pass its URL from song_paths.
audio_upload_idstring (UUID)
The id that POST /uploads returns. It expires after about 24 hours.
audio_base64string
The bytes of the file, encoded as base64. Up to 40MB. We recommend an upload instead.

Send exactly one of the three.

Uploading a file

If the audio is not at a public URL, upload it and pass the id from the response. We accept mp3, m4a, ogg, flac, wav, amr, aac, and aiff files of up to 40MB.

import requests
# 1. Upload the file
with open("my-song.mp3", "rb") as f:
upload = requests.post(
"https://api.treblo.com/v1/uploads",
headers={"Authorization": "Bearer your_api_key_here"},
files={"file": f},
)
audio_upload_id = upload.json()["audio_upload_id"]
# 2. Use it
response = requests.post(
"https://api.treblo.com/v1/generations/v3/extend",
headers={"Authorization": "Bearer your_api_key_here"},
json={
"audio_upload_id": audio_upload_id,
"prompt": "Add a guitar solo, then one last chorus",
},
)
print(response.json()) # {"task_id": "..."}
  • You can use an upload in any number of requests until it expires, about 24 hours after you upload it.
  • Keep the id private, because anyone who has it can use the upload.

Extend a song

Continue a song from where it ends. The result is the whole song, with the new part after the original.

import requests
response = requests.post(
"https://api.treblo.com/v1/generations/v3/extend",
headers={"Authorization": "Bearer your_api_key_here"},
json={
"audio_url": "https://cdn.treblo.com/pubapi/generations3/audio_a598194b-d464-474c-b1e6-1c99f8f8e457_0.ogg",
"prompt": "Add a guitar solo, then one last chorus",
},
)
print(response.json()) # {"task_id": "..."}

The prompt describes what happens next. As with a new song, you can also send lyrics for the new part or set the tags.

Continue from before the ending

A finished song usually has an outro. Set crop_duration to cut that many seconds from the end before the model continues the song:

import requests
response = requests.post(
"https://api.treblo.com/v1/generations/v3/extend",
headers={"Authorization": "Bearer your_api_key_here"},
json={
"audio_url": "https://cdn.treblo.com/pubapi/generations3/audio_a598194b-d464-474c-b1e6-1c99f8f8e457_0.ogg",
"prompt": "Replace the fade-out with a bridge and a final chorus",
"crop_duration": 12,
},
)
print(response.json()) # {"task_id": "..."}

Make room for a longer new part

Before it continues, the model listens to the end of your song, up to 150 seconds by default. That context and the new audio together cannot be longer than 4 minutes 45 seconds, so the default leaves up to 2 minutes 15 seconds for the new part. To get a longer new part, lower context_seconds. Less context leaves more room for new audio but keeps the new part less close to the original.

import requests
response = requests.post(
"https://api.treblo.com/v1/generations/v3/extend",
headers={"Authorization": "Bearer your_api_key_here"},
json={
"audio_url": "https://cdn.treblo.com/pubapi/generations3/audio_a598194b-d464-474c-b1e6-1c99f8f8e457_0.ogg",
"prompt": "Add two more verses and a long outro",
"context_seconds": 60,
},
)
print(response.json()) # {"task_id": "..."}

Parameters in this section

context_secondsfloatDefault: 150
The number of seconds at the end of your song that the model listens to before it continues. If your song is shorter, the model listens to all of it. More than 0 and at most 284.
crop_durationfloatDefault: 0
The number of seconds to cut from the end of your song before the model continues it. Use it to remove an outro. It must be shorter than the song.

These are only the parameters this section uses. The endpoint accepts more, and the API reference lists all of them.

Cover a song

Make a new version of a song that keeps its melody, for example in another genre or with other lyrics.

A cover is a request to /generations/v3/reference with reference_mode: "cover".

import requests
# 1. Upload the file
with open("original.mp3", "rb") as f:
upload = requests.post(
"https://api.treblo.com/v1/uploads",
headers={"Authorization": "Bearer your_api_key_here"},
files={"file": f},
)
audio_upload_id = upload.json()["audio_upload_id"]
# 2. Use it
response = requests.post(
"https://api.treblo.com/v1/generations/v3/reference",
headers={"Authorization": "Bearer your_api_key_here"},
json={
"audio_upload_id": audio_upload_id,
"reference_mode": "cover",
"prompt": "A slow acoustic version with fingerpicked guitar",
},
)
print(response.json()) # {"task_id": "..."}
  • The prompt describes the new version. Send an empty string to let us decide.
  • If you send no lyrics, we transcribe the original and write new lyrics in its style. To keep the original lyrics, send them as lyrics.
  • Set instrumental to true for a version with no vocals.
  • reference_scale has a large effect. If the cover does not follow the original closely enough, raise it.

Choose the part to cover

By default the model listens to the first 90 seconds of the audio. Choose another part with reference_crop_start and reference_crop_end. For a cover, the reference audio must be 12 to 284.7 seconds long (about 4 minutes 45 seconds). The new song can also be up to 4 minutes 45 seconds long.

import requests
response = requests.post(
"https://api.treblo.com/v1/generations/v3/reference",
headers={"Authorization": "Bearer your_api_key_here"},
json={
"audio_url": "https://cdn.treblo.com/pubapi/generations3/audio_a598194b-d464-474c-b1e6-1c99f8f8e457_0.ogg",
"reference_mode": "cover",
"prompt": "A slow acoustic version with fingerpicked guitar",
"reference_crop_start": 30,
"reference_crop_end": 120,
"reference_scale": 2,
},
)
print(response.json()) # {"task_id": "..."}

Parameters in this section

reference_crop_startfloat
The start, in seconds, of the part of the audio that the model listens to. Set it together with reference_crop_end.
reference_crop_endfloat
The end of that part, in seconds. The part must be 12 to 284.7 seconds long for a cover or a style, and 10 to 75 for a voice. It must lie inside the audio. Leave both out to use the first 90 seconds, or the first 75 for a voice, or all of the audio if it is shorter.
reference_scalefloatDefault: 1.0, or 4.0 for a voice
How closely the song follows the audio. 1.0 to 5.0, or up to 7.0 for a voice.

These are only the parameters this section uses. The endpoint accepts more, and the API reference lists all of them.

Use a voice

Generate a new song sung in the voice from a recording.

Send a recording of the singer to /generations/v3/reference with reference_mode: "voice". Your prompt, lyrics, and tags decide the rest of the song, as in any other request.

import requests
# 1. Upload the file
with open("my-voice.wav", "rb") as f:
upload = requests.post(
"https://api.treblo.com/v1/uploads",
headers={"Authorization": "Bearer your_api_key_here"},
files={"file": f},
)
audio_upload_id = upload.json()["audio_upload_id"]
# 2. Use it
response = requests.post(
"https://api.treblo.com/v1/generations/v3/reference",
headers={"Authorization": "Bearer your_api_key_here"},
json={
"audio_upload_id": audio_upload_id,
"reference_mode": "voice",
"prompt": "A soulful ballad about coming home",
},
)
print(response.json()) # {"task_id": "..."}

When the recording is a full song

If the audio has instruments as well as the singer, set voice_from_song to true and we separate the vocals first. We always do this for a song that this API generated.

import requests
# 1. Upload the file
with open("my-song.mp3", "rb") as f:
upload = requests.post(
"https://api.treblo.com/v1/uploads",
headers={"Authorization": "Bearer your_api_key_here"},
files={"file": f},
)
audio_upload_id = upload.json()["audio_upload_id"]
# 2. Use it
response = requests.post(
"https://api.treblo.com/v1/generations/v3/reference",
headers={"Authorization": "Bearer your_api_key_here"},
json={
"audio_upload_id": audio_upload_id,
"reference_mode": "voice",
"voice_from_song": True,
"reference_crop_start": 45,
"reference_crop_end": 105,
"prompt": "A soulful ballad about coming home",
},
)
print(response.json()) # {"task_id": "..."}
  • We use the singing in the first 75 seconds, unless you choose a part with reference_crop_start and reference_crop_end. The part must be 10 to 75 seconds long and contain singing.
  • reference_scale has a large effect. If the new song does not keep enough of the voice, raise it. For a voice it defaults to 4.0 and can be up to 7.0.
  • To use a voice again, upload the recording once and reuse its audio_upload_id. Later requests with the same upload and the same part of it can skip the step that prepares the voice.

Parameters in this section

voice_from_songbooleanDefault: false
Only for reference_mode: "voice". Set to true when the audio is a full song and not a recording of only the singer.

These are only the parameters this section uses. The endpoint accepts more, and the API reference lists all of them.

Transfer a style

Generate a new song with the vocals and instruments of a reference but a new melody and new lyrics.

Send the reference to /generations/v3/reference with reference_mode: "style".

import requests
# 1. Upload the file
with open("reference.mp3", "rb") as f:
upload = requests.post(
"https://api.treblo.com/v1/uploads",
headers={"Authorization": "Bearer your_api_key_here"},
files={"file": f},
)
audio_upload_id = upload.json()["audio_upload_id"]
# 2. Use it
response = requests.post(
"https://api.treblo.com/v1/generations/v3/reference",
headers={"Authorization": "Bearer your_api_key_here"},
json={
"audio_upload_id": audio_upload_id,
"reference_mode": "style",
"prompt": "A song about a rainy day in the city",
},
)
print(response.json()) # {"task_id": "..."}
  • Unlike a cover, the new song does not follow the reference's melody or lyrics. We write the lyrics from your prompt unless you send lyrics.
  • The model listens to the first 90 seconds, unless you choose a part with reference_crop_start and reference_crop_end. For a style, the reference audio can be 12 to 284.7 seconds long (about 4 minutes 45 seconds). The new song can also be up to 4 minutes 45 seconds long.
  • reference_scale has a large effect. If the song does not sound enough like the reference, raise it.

Replace a section

Regenerate one part of a song and keep the rest.

import requests
response = requests.post(
"https://api.treblo.com/v1/generations/v2/inpaint",
headers={"Authorization": "Bearer your_api_key_here"},
json={
"audio_url": "https://cdn.treblo.com/pubapi/generations3/audio_a598194b-d464-474c-b1e6-1c99f8f8e457_0.ogg",
"tags": ["rock", "energetic"],
"sections": [[20, 35]],
"lyrics": "The new words for these fifteen seconds",
},
)
print(response.json()) # {"task_id": "..."}
  • sections holds the start and end, in seconds, of the part to replace.
  • lyrics are the lyrics for the new part. For a part with no vocals, leave them out and set instrumental to true.
  • tags are required, and this endpoint does not accept a prompt.
  • Set num_songs to 2 to get two versions. On v2, both versions are generated by a single task, and the song_paths of that task includes two URLs, one for each version.

Parameters in this section

sections[[float, float]]required
The [start, end] of the part to replace, in seconds. The part must be at least 0.1 seconds long. Send exactly 1 section.
selection_cropbooleanDefault: false
Set to true to get only the new part instead of the whole song.
lyricsstring
The lyrics for the new part. For a part with no vocals, leave them out and set instrumental to true. Up to 40,000 characters.
tagsarray of stringsrequired
Style tags from our tag list. Up to 64 tags. The API rejects a tag that is not on the list.

These are only the parameters this section uses. The endpoint accepts more, and the API reference lists all of them.

Track progress

Each generation is a task with a status. Poll the status, or give us a webhook URL and we send each change to you.

We recommend webhooks over polling because they are more efficient.

Polling

GET /generations/status/{task_id} returns the current status as a JSON string, as in the quick start. Once it is SUCCESS, GET /generations/{task_id} returns the song's URLs in song_paths with the lyrics and tags the song was generated with.

Statuses

These are the statuses a task can have, in the order they happen. A task skips the ones that do not apply to it, so wait for SUCCESS or FAILURE.

RECEIVED
We accepted the request.
TRANSCRIBE_TASK_STARTEDrequests with audio
We are transcribing the lyrics in your audio. TRANSCRIBE_STAGE_1, TRANSCRIBE_STAGE_2, TRANSCRIBE_STAGE_3, and TRANSCRIBE_DONE follow.
PROMPT
We are writing the tags or lyrics you did not send.
TASK_SENT
The task is waiting to start.
GENERATE_TASK_STARTED
The task has started.
LOADING_SOURCEv2 extend and replace
We are loading your audio.
BEGINNING_GENERATION
Generation is about to start.
GENERATING
We are generating the song.
GENERATING_STREAMING_READYv3
You can start listening on the streaming endpoint.
DECOMPRESSING
We are decoding the song into audio.
SAVING
We are uploading the file.
SUCCESS
The song is finished and its URL is in song_paths.
FAILURE
The task failed and we did not charge any credits. error_message may say why.

Receive webhooks

Give us a URL and we POST each status change of the task to it.

Add a webhook_url to any request. Each POST is JSON with the task_id and the new status. The POST for SUCCESS contains the song. A POST about lyrics alignment has alignment_status in place of status.

import requests
response = requests.post(
"https://api.treblo.com/v1/generations/v3",
headers={"Authorization": "Bearer your_api_key_here"},
json={
"prompt": "A chill lofi beat for studying",
"webhook_url": "https://example.com/treblo-webhook",
},
)
print(response.json()) # {"task_id": "..."}
json
{
"task_id": "a598194b-d464-474c-b1e6-1c99f8f8e457",
"status": "SUCCESS",
"song_paths": [
"https://cdn.treblo.com/pubapi/generations3/audio_a598194b-d464-474c-b1e6-1c99f8f8e457_0.ogg"
]
}

Answer each POST with a 2xx status within 10 seconds. We count any other answer, or no answer, as a failed delivery.

Check that a webhook is from us

We sign every webhook with your account's signing secret. The secret is on the API Keys page of your account. Each webhook has three headers:

webhook-id
An id for the webhook. A retry has the same id as the first delivery.
webhook-timestamp
When we sent this delivery, in Unix seconds.
webhook-signature
The signature in base64, after the prefix v1 and a comma.

The headers follow the Standard Webhooks format, so a Standard Webhooks library can check them:

python
# pip install standardwebhooks
from standardwebhooks import Webhook, WebhookVerificationError
webhook = Webhook("whsec_your_signing_secret")
def handle_webhook(body: bytes, headers: dict) -> int:
"""Takes the raw request body and the request headers. Returns the status to answer with."""
try:
update = webhook.verify(body, headers)
except WebhookVerificationError:
return 400 # We did not send this
print(update["task_id"], update.get("status"))
return 204
  • Check the raw request body. If you parse the JSON and write it out again, the bytes change and the check fails.
  • The libraries reject a webhook whose timestamp is more than 5 minutes from the current time.
  • To check a webhook without a library, compute the HMAC-SHA256 of {webhook-id}.{webhook-timestamp}.{body}. The key is the part of the secret after whsec_, decoded from base64. The signature is that HMAC in base64.
  • If you rotate the secret on the API Keys page, the old secret stops working right away.

Retries

When a webhook delivery fails (non-2xx status code or timeout), we try to send the webhook again only for SUCCESS, FAILURE, and GENERATING_STREAMING_READY status updates (includes lyrics alignment). All other statuses are not retried since they are ephemeral.

  • For SUCCESS and FAILURE, we retry up to 5 times. The wait times before the retries are 30 seconds, 2 minutes, 10 minutes, 1 hour, and 3 hours.
  • We retry GENERATING_STREAMING_READY at most 2 times, and only while the song is still generating.
  • A retry has the same webhook-id as the first delivery. Use the id to skip a webhook you have already handled.
  • A retry can arrive after the webhook for a later status. Once a task is SUCCESS or FAILURE, ignore a webhook that reports any other status for it.
  • If the last retry fails, we stop. Poll for a status you did not receive.

Stream while generating

Play a song while we are still generating it.

  1. Set enable_streaming to true on a v3 request.
  2. Wait for the status GENERATING_STREAMING_READY.
  3. Play https://api-stream.treblo.com/stream/{task_id}. The URL needs no API key, so you can use it as the source of an audio element.
import requests
response = requests.post(
"https://api.treblo.com/v1/generations/v3",
headers={"Authorization": "Bearer your_api_key_here"},
json={
"prompt": "A chill lofi beat for studying",
"enable_streaming": True,
},
)
print(response.json()) # {"task_id": "..."}
markup
<!-- Works once the task reaches GENERATING_STREAMING_READY -->
<audio controls autoplay>
<source src="https://api-stream.treblo.com/stream/your_task_id" type="audio/ogg" />
</audio>
  • If you connect late, you first receive the audio generated so far and then the rest as we generate it.
  • The stream is Opus in an ogg container unless you set stream_format to mp3. Extend requests always stream ogg.
  • The stream ends a few seconds after the song is finished. You can still open it for 150 seconds after that. Past that point, use the file in song_paths.
  • For a request with two songs, each task has its own stream.
  • Streaming does not change what a request costs.

Align the lyrics

Get the start and end time of every word, for example to show lyrics in time with the song.

Set align_lyrics to true on any request. After the song is finished, we align its lyrics to the audio in a second step that has its own status.

import requests
response = requests.post(
"https://api.treblo.com/v1/generations/v3",
headers={"Authorization": "Bearer your_api_key_here"},
json={
"prompt": "An upbeat indie rock song about a road trip with old friends",
"align_lyrics": True,
},
)
print(response.json()) # {"task_id": "..."}
  1. Wait for the song to finish, then poll /generations/status/{task_id}?include_alignment=true until alignment_status is SUCCESS. Stop if it becomes FAILURE. Webhook updates also include alignment_status.
  2. Fetch the task. The timings are in word_aligned_lyrics (null if the lyrics could not be aligned):
json
[
{
"word": "Headlights",
"start": 12.48,
"end": 13.02
},
{
"word": "on",
"start": 13.02,
"end": 13.2
}
]
  • We ignore align_lyrics for instrumentals, which have no lyrics to align.
  • If the song fails, alignment_status stays REQUESTED, so check status first.
  • If the song succeeds but the alignment fails, we still charge for the song.

Files and formats

Songs are Opus files in an ogg container unless you set output_format.

import requests
response = requests.post(
"https://api.treblo.com/v1/generations/v3",
headers={"Authorization": "Bearer your_api_key_here"},
json={
"prompt": "A chill lofi beat for studying",
"output_format": "mp3",
"output_bit_rate": 320,
},
)
print(response.json()) # {"task_id": "..."}

Parameters in this section

output_formatstringDefault: ogg
The audio file format. One of ogg, mp3, flac, wav, m4a. An ogg file contains Opus audio and an m4a file contains AAC.
output_bit_rateinteger
The bit rate in kbps. One of 128, 192, 256, 320. Only for mp3 and m4a.

These are only the parameters this section uses. The endpoint accepts more, and the API reference lists all of them.

Retry a request safely

Send an Idempotency-Key header, and a repeat of the request returns the first task. It does not create a second song.

import requests
response = requests.post(
"https://api.treblo.com/v1/generations/v3",
headers={
"Authorization": "Bearer your_api_key_here",
"Idempotency-Key": "6f1c9a4e-2d0b-4f3a-9c1e-8a7b5d3e2f10",
},
json={
"prompt": "A chill lofi beat for studying",
},
)
print(response.json()) # {"task_id": "..."}

Choose a new key for each request, such as a UUID, and send the same key every time you repeat that request. A key is 1 to 255 characters. Every endpoint that starts a generation accepts the header.

  • The first request with a key creates the task. A later request from your account with the same key returns the same task_id, and we charge you once. If the request was for two songs, repeating the request returns the same two task_ids.
  • Repeat a request with its key when it times out, the connection drops, or the API answers with a 5xx status.
  • A key keeps returning the task it created and does not expire. If that task ends in FAILURE, send a new key to try the song again.
  • A request that the API rejects creates no task, so you can correct it and send it again with the same key.
  • A repeat must go to the same endpoint with the same body, byte for byte. A body with its fields in another order counts as a different request. If you use the same idempotency key with a different request, the API will respond with a 422.