Code Monkey home page Code Monkey logo

suno-api's Introduction

Suno AI API

Use API to call the music generation AI of Suno.ai and easily integrate it into agents like GPTs.

👉 We update quickly, please star.

English | 简体中文 | Demo | Docs | Deploy with Vercel

gcui-art/suno-api:Open-source SunoAI API - Use API to call the music generation AI of suno.ai. | Product Hunt

suno-api banner

Introduction

Suno.ai v3 is an amazing AI music service. Although the official API is not yet available, we couldn't wait to integrate its capabilities somewhere.

We discovered that some users have similar needs, so we decided to open-source this project, hoping you'll like it.

Demo

We have deployed an example bound to a free Suno account, so it has daily usage limits, but you can see how it runs: suno.gcui.ai

Features

  • Perfectly implements the creation API from app.suno.ai
  • Automatically keep the account active.
  • Compatible with the format of OpenAI’s /v1/chat/completions API.
  • Supports Custom Mode
  • One-click deployment to Vercel
  • In addition to the standard API, it also adapts to the API Schema of Agent platforms like GPTs and Coze, so you can use it as a tool/plugin/Action for LLMs and integrate it into any AI Agent.
  • Permissive open-source license, allowing you to freely integrate and modify.

Getting Started

1. Obtain the cookie of your app.suno.ai account

  1. Head over to app.suno.ai using your browser.
  2. Open up the browser console: hit F12 or access the Developer Tools.
  3. Navigate to the Network tab.
  4. Give the page a quick refresh.
  5. Identify the request that includes the keyword client?_clerk_js_version.
  6. Click on it and switch over to the Header tab.
  7. Locate the Cookie section, hover your mouse over it, and copy the value of the Cookie.

get cookie

2. Clone and deploy this project

You can choose your preferred deployment method:

Deploy to Vercel

Deploy with Vercel

Run locally

git clone https://github.com/gcui-art/suno-api.git
cd suno-api
npm install

Alternatively, you can use Docker Compose

docker compose build && docker compose up

3. Configure suno-api

  • If deployed to Vercel, please add an environment variable SUNO_COOKIE in the Vercel dashboard, with the value of the cookie obtained in the first step.

  • If you’re running this locally, be sure to add the following to your .env file:

SUNO_COOKIE=<your-cookie>

4. Run suno api

  • If you’ve deployed to Vercel:
    • Please click on Deploy in the Vercel dashboard and wait for the deployment to be successful.
    • Visit the https://<vercel-assigned-domain>/api/get_limit API for testing.
  • If running locally:
    • Run npm run dev.
    • Visit the http://localhost:3000/api/get_limit API for testing.
  • If the following result is returned:
{
  "credits_left": 50,
  "period": "day",
  "monthly_limit": 50,
  "monthly_usage": 50
}

it means the program is running normally.

5. Use Suno API

You can check out the detailed API documentation at : suno.gcui.ai/docs

API Reference

Suno API currently mainly implements the following APIs:

- `/api/generate`: Generate music
- `/v1/chat/completions`: Generate music - Call the generate API in a format that works with OpenAI’s API.
- `/api/custom_generate`: Generate music (Custom Mode, support setting lyrics, music style, title, etc.)
- `/api/generate_lyrics`: Generate lyrics based on prompt
- `/api/get`: Get music information based on the id. Use “,” to separate multiple ids.
    If no IDs are provided, all music will be returned.
- `/api/get_limit`: Get quota Info
- `/api/extend_audio`: Extend audio length
- `/api/clip`: Get clip information based on ID passed as query parameter `id`
- `/api/concat`: Generate the whole song from extensions

For more detailed documentation, please check out the demo site: suno.gcui.ai/docs

API Integration Code Example

Python

import time
import requests

# replace your vercel domain
base_url = 'http://localhost:3000'


def custom_generate_audio(payload):
    url = f"{base_url}/api/custom_generate"
    response = requests.post(url, json=payload, headers={'Content-Type': 'application/json'})
    return response.json()


def extend_audio(payload):
    url = f"{base_url}/api/extend_audio"
    response = requests.post(url, json=payload, headers={'Content-Type': 'application/json'})
    return response.json()

def generate_audio_by_prompt(payload):
    url = f"{base_url}/api/generate"
    response = requests.post(url, json=payload, headers={'Content-Type': 'application/json'})
    return response.json()


def get_audio_information(audio_ids):
    url = f"{base_url}/api/get?ids={audio_ids}"
    response = requests.get(url)
    return response.json()


def get_quota_information():
    url = f"{base_url}/api/get_limit"
    response = requests.get(url)
    return response.json()

def get_clip(clip_id):
    url = f"{base_url}/api/clip?id={clip_id}"
    response = requests.get(url)
    return response.json()

def generate_whole_song(clip_id):
    payloyd = {"clip_id": clip_id}
    url = f"{base_url}/api/concat"
    response = requests.post(url, json=payload)
    return response.json()


if __name__ == '__main__':
    data = generate_audio_by_prompt({
        "prompt": "A popular heavy metal song about war, sung by a deep-voiced male singer, slowly and melodiously. The lyrics depict the sorrow of people after the war.",
        "make_instrumental": False,
        "wait_audio": False
    })

    ids = f"{data[0]['id']},{data[1]['id']}"
    print(f"ids: {ids}")

    for _ in range(60):
        data = get_audio_information(ids)
        if data[0]["status"] == 'streaming':
            print(f"{data[0]['id']} ==> {data[0]['audio_url']}")
            print(f"{data[1]['id']} ==> {data[1]['audio_url']}")
            break
        # sleep 5s
        time.sleep(5)

Js

const axios = require("axios");

// replace your vercel domain
const baseUrl = "http://localhost:3000";

async function customGenerateAudio(payload) {
  const url = `${baseUrl}/api/custom_generate`;
  const response = await axios.post(url, payload, {
    headers: { "Content-Type": "application/json" },
  });
  return response.data;
}

async function generateAudioByPrompt(payload) {
  const url = `${baseUrl}/api/generate`;
  const response = await axios.post(url, payload, {
    headers: { "Content-Type": "application/json" },
  });
  return response.data;
}

async function extendAudio(payload) {
  const url = `${baseUrl}/api/extend_audio`;
  const response = await axios.post(url, payload, {
    headers: { "Content-Type": "application/json" },
  });
  return response.data;
}

async function getAudioInformation(audioIds) {
  const url = `${baseUrl}/api/get?ids=${audioIds}`;
  const response = await axios.get(url);
  return response.data;
}

async function getQuotaInformation() {
  const url = `${baseUrl}/api/get_limit`;
  const response = await axios.get(url);
  return response.data;
}

async function getClipInformation(clipId) {
  const url = `${baseUrl}/api/clip?id=${clipId}`;
  const response = await axios.get(url);
  return response.data;
}

async function main() {
  const data = await generateAudioByPrompt({
    prompt:
      "A popular heavy metal song about war, sung by a deep-voiced male singer, slowly and melodiously. The lyrics depict the sorrow of people after the war.",
    make_instrumental: false,
    wait_audio: false,
  });

  const ids = `${data[0].id},${data[1].id}`;
  console.log(`ids: ${ids}`);

  for (let i = 0; i < 60; i++) {
    const data = await getAudioInformation(ids);
    if (data[0].status === "streaming") {
      console.log(`${data[0].id} ==> ${data[0].audio_url}`);
      console.log(`${data[1].id} ==> ${data[1].audio_url}`);
      break;
    }
    // sleep 5s
    await new Promise((resolve) => setTimeout(resolve, 5000));
  }
}

main();

Integration with Custom Agents

You can integrate Suno AI as a tool/plugin/action into your AI agent.

Integration with GPTs

[coming soon...]

Integration with Coze

[coming soon...]

Integration with LangChain

[coming soon...]

Contributing

There are four ways you can support this project:

  1. Fork and Submit Pull Requests: We welcome any PRs that enhance the component or editor.
  2. Open Issues: We appreciate reasonable suggestions and bug reports.
  3. Donate: If this project has helped you, consider buying us a coffee using the Sponsor button at the top of the project. Cheers! ☕
  4. Spread the Word: Recommend this project to others, star the repo, or add a backlink after using the project.

Questions, Suggestions, Issues, or Bugs?

We use GitHub Issues to manage feedback. Feel free to open an issue, and we'll address it promptly.

License

LGPL-3.0 or later

Related Links

Statement

suno-api is an unofficial open source project, intended for learning and research purposes only.

suno-api's People

Contributors

6bangs avatar alifhughes avatar andy-fang-piccollage avatar blueeon avatar gitpusher99 avatar jonico avatar karldivad avatar laxidou avatar linkly-ai avatar lordskare avatar newt0n avatar nkbud avatar swumagic avatar wengchaoxi avatar wheest avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

suno-api's Issues

Cors issue

const handleSubmit = () => {
        const options = {
            method: 'POST',
            credentials: 'include',
            headers: {
            'Content-Type': 'application/json', 
            },
            body: JSON.stringify(selections),
        };
    fetch('http://localhost:3030/api/generate', options)
        .then(response => {
        if (!response.ok) {
            throw new Error('Network response was not ok');
        }
        return response.json();
        })
        .then(data => {
        console.log('Success:', data); 
        })
        .catch((error) => {
        console.error('Error:', error); 
        });
    };
Im trying to use api/generate endpoint. 
But there is Cors Error. 

Access to fetch at 'http://localhost:3030/api/generate' from origin 'https://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.


So i add "Access-Control-Allow-Origin": "*"  this in src/app/api/generate/route.ts  

like this 
export async function POST(req: NextRequest) {
 if (req.method === 'OPTIONS') {
  
   return new Response(null, {
     headers: {
       "Access-Control-Allow-Origin": "*", 
       "Access-Control-Allow-Methods": "POST, OPTIONS",
       "Access-Control-Allow-Headers": "Content-Type, Authorization",
     },
   });
 }

 if (req.method === 'POST') {
   try {
     const body = await req.json();
     const { prompt, make_instrumental, wait_audio } = body;

     if (!prompt) {
       return new NextResponse(JSON.stringify({ error: 'Prompt is required' }), {
         status: 400,
         headers: { 'Content-Type': 'application/json' }
       });
     }

     const audioInfo = await (await sunoApi).generate(prompt, make_instrumental == true, wait_audio == true);
     logger.info("check audio Info" , audioInfo);
     return new NextResponse(JSON.stringify(audioInfo), {
       status: 200,
       headers: { 'Content-Type': 'application/json',"Access-Control-Allow-Origin": "*" }
     });
   }
   But still there is cors error. 
-------------------------------------------------------------------------------------

image
This photo is from Network Headers In General

In custom mode, promt is not required

Now the API responds:

ERROR - Request error: 400, Response body: {"error":"Prompt, tags, and title are required"}

Although in fact in Suno you don’t have to use promt in custom mode. Therefore, the API check for this parameter in custom mode should be turned off

failed

{"error":"Internal server error. Error: Failed to get session id, you may need to update the SUNO_COOKIE"}%
image

👋 Before you submit an issue, please read our issue guidelines.

To facilitate clear and effective communication, all issue, comments, and pull requests in this project should be conducted in English. This ensures that all contributors can participate and collaborate effectively. And please submit the issue using the template.

为了促进清晰有效的沟通,本项目中的所有issue、评论和pull requests,都应以英语进行。这确保了所有贡献者都能有效地参与和协作。并且请使用模板提交issue。

Getting an error when running the test code

I write because I'm having trouble implementing it into my code. As context, I have the Suno pro version and https:///api/get_limit works well.

First I was getting an error in the return response.json() line ( error: "JSONDecodeError: Expecting value: line 1 column 1 (char 0)")

And now im getting this: https://drive.google.com/file/d/1R4EvkilCZ9Y8F0O6KV9uMiVUoxmW_tF1/view?usp=drivesdk

I would appreciate if you could let me know how to solve this issue, or if this is some kind of block from Suno (I don't think so as https:///api/get_limit is working but just checking)

Download mp3 to filesystem?

I am browsing through the code and I am wondering how to go about downloading the mp3 to the filesystem after generation is complete. (wait_audio is enabled)
There appears to be no method in SunoApi.ts to do so.

/extend_audio endpoint is returning 500s, Internal Error 'Unauthorized'

/extend_audio endpoint is returning 500s, Internal Error 'Unauthorized'

All the other endpoints work. I'm consistently running up against these 500s though. I tried with the swagger docs as well as pinging from my own script - I am supplying the body correctly

Is this endpoint /extend_audio functional?

There is no Environment variable at start of the app localy

Hi,
When trying to launch app by "npm run dev" noticed that I have no environment variable (which I should see?).

Reproduction

  1. Go to Powershell and entering cd path
  2. Running "npm run dev"
  3. Getting output:
    image

Expected behavior
Getting output (got it from another bug report):
image

Desktop:

  • OS: Windows 11
  • Browser: Chrome
  • Version: 124.0.6367.92

Additional context
Also catching traceback about updating SUNO_COOKIE.
Binding it with the absence of environmental variable.
Also tried to past cookie by methods from closed bug reports.
Tried to reinstall suno-api - didn't help.

Suno API + VoiceFlow

I'm trying to implement this API in a chatbot I made with voiceflow. The idea is that after the user provides information about him, a prompt is sent to the suno API to create a song with this information, specific to each user. My problem is being in the answer, how to get the url of the user-generated song to be placed directly as a chatbot response to the user - i think i'm having parameters problem here, but i really can't understand what - bc it isn't showing any error, but the response is always "0" when it was to be the url for the music.

Captura de tela_15-4-2024_123939_creator voiceflow com

Captura de tela_15-4-2024_124045_creator voiceflow com

PS: And i'm having error when setting true "waiting_audio" :

"error": {
"code": "504",
"message": "An error occurred with your deployment"
}
}
Response headers
cache-control: public,max-age=0,must-revalidate
content-length: 79
content-type: application/json
date: Mon,15 Apr 2024 14:39:30 GMT
server: Vercel
strict-transport-security: max-age=63072000; includeSubDomains; preload
x-matched-path: /api/generate
x-vercel-error: FUNCTION_INVOCATION_TIMEOUT
x-vercel-id: gru1::5qh7t-1713191959378-e60f698c9961 "

CORS error

When deployed to Vercel, all GET requests work as intended when calling them from another webApp.

When calling a POST request like custom_generate the API returns with an CORS error, not allowing the other webApp to perform this API call.

Any idea if this is intended behaviour or a bug or a missing feature? If possible: How can domains be allowed to request the API... maybe via setting an CORS request header?

Making his work with udio.com

This is Not a Problem but a request.

I've been working trying to get this to work with UDIO with limited Succcess.

Solution:
Udio Has a Custom Text Input (Write your Own Lyrics)
I want to be able to provide a certain text here and get the response.

Currently working my own hacky way to make this work with limited success.

Any additional suggestions welcome.

Goal is to (Grab a Text such as someone's github comment and convert that part into a song with the exact words)

Thanks!

Add "Continue API" for songs in Suno AI API

Hello,

We are working on implementing your Suno AI API into one of the largest neural bots in Telegram, but we have just found that there is no option to "Continue" the song. Is it possible for you to implement this feature? If it's a paid service, we can pay you for this work.

Look forward to hearing from you soon. 

Best Regards, 
Vladimir

API works only on first run

Describe the bug
When I start the api with npm run dev, it will only work once, even if i restart it

To Reproduce
Steps to reproduce the behavior:

  1. Clone Repo
  2. Install Node.js (on arch use pacman)
  3. run npm install and npm run dev
  4. add cookie to .env
  5. use the demo python code - first time should work
  6. run the demo code again - hangs

Expected behavior
It should have worked both times

Screenshots
If applicable, add screenshots to help explain your problem.
image
it just continues with this until it stops, producing nothing
Desktop (please complete the following information):

  • OS: Win11, also tried on Arch Linux
  • Browser: Firefox

Critical dependency: require function is used in a way in which dependencies cannot be statically extracted

Describe the bug

./node_modules/http-cookie-agent/dist/utils/validate_cookie_options.js
Critical dependency: require function is used in a way in which dependencies cannot be statically extracted

Import trace for requested module:
./node_modules/http-cookie-agent/dist/utils/validate_cookie_options.js
./node_modules/http-cookie-agent/dist/http/create_cookie_agent.js
./node_modules/http-cookie-agent/dist/http/index.js
./node_modules/http-cookie-agent/http/index.js
./node_modules/axios-cookiejar-support/dist/index.js
./src/lib/SunoApi.ts
./src/app/api/generate_lyrics/[id]/route.ts
 ○ Compiling /api/generate_lyrics/[id] ...
{"level":30,"time":1714525558430,"pid":33656,"hostname":"vee","msg":"KeepAlive...\n"}
newToken:===

To Reproduce
Only happens occasionally; sometimes restarting or re-authenticating helps, sometimes not. Any help would be greatly appreciated.

Desktop (please complete the following information):

  • Browser [Firefox]

Result
400 Bad Request

Example Code Error

Describe the bug
After running the Example code on local installation I receive following error:

Traceback (most recent call last):
  File "C:\Users\mento\Documents\PyCharm\venv\lib\site-packages\requests\models.py", line 971, in json
    return complexjson.loads(self.text, **kwargs)
  File "C:\Users\mento\AppData\Local\Programs\Python\Python310\lib\json\__init__.py", line 346, in loads
    return _default_decoder.decode(s)
  File "C:\Users\mento\AppData\Local\Programs\Python\Python310\lib\json\decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "C:\Users\mento\AppData\Local\Programs\Python\Python310\lib\json\decoder.py", line 355, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\mento\Documents\PyCharm\suno_wrapper\test.py", line 38, in <module>
    data = generate_audio_by_prompt({
  File "C:\Users\mento\Documents\PyCharm\suno_wrapper\test.py", line 22, in generate_audio_by_prompt
    return response.json()
  File "C:\Users\mento\Documents\PyCharm\venv\lib\site-packages\requests\models.py", line 975, in json
    raise RequestsJSONDecodeError(e.msg, e.doc, e.pos)
requests.exceptions.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

To Reproduce
Steps to reproduce the behavior:

  1. Go to 'Clone Repository '
  2. Install packages in repo direcotry 'npm install'
  3. Copy Suno.ai cookie from header after visiting suno ai logged in.
  4. Start the server via npm run dev
  5. Run the Example Code [provided at the bottom]

Checking Suno Limit via firefox:

After fresh installation, when I visist 'http://localhost:3000/api/get_limit'.

I receive following error:

error | 'Internal server error. TypeError [ERR_INVALID_CHAR]: Invalid character in header content ["Cookie"]'

I already got it running once, but not anymore. I checked the cookie various times.

Desktop (please complete the following information):

  • OS: Win10
  • Browser [Firefox]

Additional context

Server error:

> [email protected] dev
> next dev

   ▲ Next.js 14.1.4
   - Local:        http://localhost:3000
   - Environments: .env

Der Befehl "pnpm" ist entweder falsch geschrieben oder
konnte nicht gefunden werden.
 ✓ Ready in 1809ms
 ○ Compiling /api/generate ...
 ✓ Compiled /api/generate in 997ms (211 modules)
(node:10560) [DEP0040] DeprecationWarning: The `punycode` module is deprecated. Please use a userland alternative instead.
(Use `node --trace-deprecation ...` to show where the warning was created)
 ⨯ TypeError: Cannot read properties of undefined (reading 'data')
    at POST (webpack-internal:///(rsc)/./src/app/api/generate/route.ts:39:91)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async C:\Users\mento\Documents\PyCharm\suno_wrapper\suno-api-main\node_modules\next\dist\compiled\next-server\app-route.runtime.dev.js:6:63809
    at async eU.execute (C:\Users\mento\Documents\PyCharm\suno_wrapper\suno-api-main\node_modules\next\dist\compiled\next-server\app-route.runtime.dev.js:6:53964)
    at async eU.handle (C:\Users\mento\Documents\PyCharm\suno_wrapper\suno-api-main\node_modules\next\dist\compiled\next-server\app-route.runtime.dev.js:6:65062)
    at async doRender (C:\Users\mento\Documents\PyCharm\suno_wrapper\suno-api-main\node_modules\next\dist\server\base-server.js:1317:42)
    at async cacheEntry.responseCache.get.routeKind (C:\Users\mento\Documents\PyCharm\suno_wrapper\suno-api-main\node_modules\next\dist\server\base-server.js:1539:28)
    at async DevServer.renderToResponseWithComponentsImpl (C:\Users\mento\Documents\PyCharm\suno_wrapper\suno-api-main\node_modules\next\dist\server\base-server.js:1447:28)
    at async DevServer.renderPageComponent (C:\Users\mento\Documents\PyCharm\suno_wrapper\suno-api-main\node_modules\next\dist\server\base-server.js:1844:24)
    at async DevServer.renderToResponseImpl (C:\Users\mento\Documents\PyCharm\suno_wrapper\suno-api-main\node_modules\next\dist\server\base-server.js:1882:32)
    at async DevServer.pipeImpl (C:\Users\mento\Documents\PyCharm\suno_wrapper\suno-api-main\node_modules\next\dist\server\base-server.js:895:25)
    at async NextNodeServer.handleCatchallRenderRequest (C:\Users\mento\Documents\PyCharm\suno_wrapper\suno-api-main\node_modules\next\dist\server\next-server.js:269:17)
    at async DevServer.handleRequestImpl (C:\Users\mento\Documents\PyCharm\suno_wrapper\suno-api-main\node_modules\next\dist\server\base-server.js:791:17)
    at async C:\Users\mento\Documents\PyCharm\suno_wrapper\suno-api-main\node_modules\next\dist\server\dev\next-dev-server.js:331:20
    at async Span.traceAsyncFn (C:\Users\mento\Documents\PyCharm\suno_wrapper\suno-api-main\node_modules\next\dist\trace\trace.js:151:20)
    at async DevServer.handleRequest (C:\Users\mento\Documents\PyCharm\suno_wrapper\suno-api-main\node_modules\next\dist\server\dev\next-dev-server.js:328:24)
    at async invokeRender (C:\Users\mento\Documents\PyCharm\suno_wrapper\suno-api-main\node_modules\next\dist\server\lib\router-server.js:174:21)
    at async handleRequest (C:\Users\mento\Documents\PyCharm\suno_wrapper\suno-api-main\node_modules\next\dist\server\lib\router-server.js:353:24)
    at async requestHandlerImpl (C:\Users\mento\Documents\PyCharm\suno_wrapper\suno-api-main\node_modules\next\dist\server\lib\router-server.js:377:13)
    at async Server.requestListener (C:\Users\mento\Documents\PyCharm\suno_wrapper\suno-api-main\node_modules\next\dist\server\lib\start-server.js:140:13)

Example Code:

import time
import requests

# replace your vercel domain
base_url = 'http://localhost:3000'


def custom_generate_audio(payload):
    url = f"{base_url}/api/custom_generate"
    response = requests.post(url, json=payload, headers={'Content-Type': 'application/json'})
    return response.json()


def extend_audio(payload):
    url = f"{base_url}/api/extend_audio"
    response = requests.post(url, json=payload, headers={'Content-Type': 'application/json'})
    return response.json()

def generate_audio_by_prompt(payload):
    url = f"{base_url}/api/generate"
    response = requests.post(url, json=payload, headers={'Content-Type': 'application/json'})
    return response.json()


def get_audio_information(audio_ids):
    url = f"{base_url}/api/get?ids={audio_ids}"
    response = requests.get(url)
    return response.json()


def get_quota_information():
    url = f"{base_url}/api/get_limit"
    response = requests.get(url)
    return response.json()


if __name__ == '__main__':
    data = generate_audio_by_prompt({
        "prompt": "A popular heavy metal song about war, sung by a deep-voiced male singer, slowly and melodiously. The lyrics depict the sorrow of people after the war.",
        "make_instrumental": False,
        "wait_audio": False
    })

    ids = f"{data[0]['id']},{data[1]['id']}"
    print(f"ids: {ids}")

    for _ in range(60):
        data = get_audio_information(ids)
        if data[0]["status"] == 'streaming':
            print(f"{data[0]['id']} ==> {data[0]['audio_url']}")
            print(f"{data[1]['id']} ==> {data[1]['audio_url']}")
            break
        # sleep 5s
        time.sleep(5)

Additional Info:

NPM-Version: 10.5.0
Node-Version: v21.7.3

{"error":"Internal server error. Error: Failed to get session id, you may need to update the SUNO_COOKIE"}

Describe the bug

Error fetching limit: Error: Failed to get session id, you may need to update the SUNO_COOKIE
    at c.getAuthToken (/app/.next/server/app/api/get_limit/route.js:1:3454)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async c.init (/app/.next/server/app/api/get_limit/route.js:1:3237)
    at async /app/.next/server/app/api/get_limit/route.js:1:6780
    at async d (/app/.next/server/app/api/get_limit/route.js:1:1794)
    at async /app/node_modules/next/dist/compiled/next-server/app-route.runtime.prod.js:6:42484
    at async eI.execute (/app/node_modules/next/dist/compiled/next-server/app-route.runtime.prod.js:6:32486)
    at async eI.handle (/app/node_modules/next/dist/compiled/next-server/app-route.runtime.prod.js:6:43737)
    at async doRender (/app/node_modules/next/dist/server/base-server.js:1317:42)
    at async cacheEntry.responseCache.get.routeKind (/app/node_modules/next/dist/server/base-server.js:1539:28)

To Reproduce
1. create.env
image

2. build Dockerfile

docker build -t suno-api:1.0 .
docker run -d --name suno-api -p 3000:3000 \
  --restart=on-failure suno-api:1.0

3. request http://localhost:3000/api/get_limit

{"error":"Internal server error. Error: Failed to get session id, you may need to update the SUNO_COOKIE"}

My cookie is already up to date; I re-logged in to obtain the freshest cookie, so there is no issue of cookie expiration.
image
image

[Question] Is this a real keep-alive service?

Hello guys, thanks for your amazing work.
But I have to ask, is this a service which could keep running?
Cause I noticed this project used cookie which expires in 7 days.

curl -H "cookie: ..." https://clerk.suno.ai/v1/client\?_clerk_js_version\=4.70.5 | jq .

{
  "response": {
    "sessions": [
      {
        "expire_at": 1712040580998,
        "abandon_at": 1714027780998,
        "last_active_at": 1711454082099,
  ...
}

So could we use a discord bot like this project https://github.com/erictik/midjourney-api

Many thanks!

Adding multiple accounts

I would like you guys to add a feature where i can add multiple accounts cookies inside a json file and it will use next cookie if the previous one runs out

Add CookieCloud support

Is your feature request related to a problem? Please describe.

Manually copying Cookie is too cumbersome.

Describe the solution you'd like

The browser Cookie synchronization and maintenance plugin CookieCloud provides an API interface that can automatically retrieve Cookie and keep them active.

https://github.com/easychen/cookiecloud

Get Full Song implementation

Now that we've got access to the extend_audio api, we need a way to perform the equivalent of the get full song option to combine the old clip with the continued clip..

Demonstration Use Case

Hello, I recently came across this repo while looking for Suno API access and was very happy to find this. I wanted to use Suno to have my robots generate songs based off a prompt you speak to them. I wanted to share the process here to show some of the possibilities that this has been used for. I posted a video outlining the process here: https://youtu.be/hBqjj34e9x0

Thanks for the excellent work!

make it clear

idont know how to use it i even deploy vercel but after running i dont know whats next where do i generate songs?

使用docker-composer构建启动项目会将服务器卡死

Describe the bug
image
使用两个服务器尝试都会在这里卡住,好奇怪,最离谱的是,阿里云强制关机都不行

To Reproduce
Steps to reproduce the behavior:

  1. Go to '...'
  2. Click on '....'
  3. Scroll down to '....'
  4. See error

Expected behavior
A clear and concise description of what you expected to happen.

Screenshots
If applicable, add screenshots to help explain your problem.

Desktop (please complete the following information):

  • OS: [e.g. iOS]
  • Browser [e.g. chrome, safari]
  • Version [e.g. 22]

Additional context
Add any other context about the problem here.

Internal server error. Error: Failed to get session id, you may need to update the SUNO_COOKIE"

Hi. I am using your suno api. Thanks for this great work. But i have this error "Internal server error. Error: Failed to get session id, you may need to update the SUNO_COOKIE". You know how can fix it? I am using Vercel. If I switch to another Suno account's cookie and redeploy in Vercel, it works again, but after a while, this error appears again."

Image https://drive.google.com/file/d/1JK8j7kCf_QnrWfIBPGQHFa4JG-VnNKmf/view?usp=drive_link

Considering adding a new API: a lyrics generation API based on prompt

Is your feature request related to a problem? Please describe.
This is an official feature of suno. it can be used to address the need for lyrics generation independently, without relying on other LLMs.

Describe the solution you'd like
Reverse engineer suno’s official API.

Additional context
Is there a demand from others?

Change in the cookie format

Cookie format change:
As per the instructions I was able to earlier grab cookie that started with __client, however the cookie now starts with __stripe_mid

To Reproduce
Steps to reproduce the behavior:

  1. Go to suno.com/create
  2. Click on F12, F5 > Headers> Request Headers

Expected behavior
api/get_limit to show credits

image
Insights much appreciated.

Internal Server Error

Describe the bug
The endpoint is currently returning an internal server error
I changed my cookie but still experiencing the same thing

To Reproduce
Steps to reproduce the behavior:
Run a request on any of the endpoints

Expected behavior
Its supposed to return a response successfully

Screenshots
image

Failed to get session id

Describe the bug
After running stably for two days, today it started to report an error: Failed to get session id.

{"error":"Internal server error. Error: Failed to get session id, you may need to update the SUNO_COOKIE"}

[GenerateAndDownload]

`# Fonction pour envoyer les paroles de chansons à l'API pour la génération
def send_lyrics_to_api(song):
url = 'https://api.sunoaiapi.com/api/v1/gateway/generate/music'
headers = {'Content-Type': 'application/json', 'api-key': API_KEY}
payload = {
"title": song[0],
"tags": song[1],
"prompt": song[2],
"mv": "chirp-v3" # Ajustez si nécessaire
}
print(f"Sending song to API: {payload}") # Journalisation des détails d'envoi
response = requests.post(url, json=payload, headers=headers)
if response.status_code == 200:
song_id = response.json()['data'][0]['song_id']
print(f"Successfully submitted: {song[0]}, ID: {song_id}")
return song_id
else:
print(f"Failed to submit {song[0]} with status: {response.status_code}, Response: {response.text}")
return None

# Fonction pour interroger l'état de génération d'une chanson
def query_generation_status(song_ids):
url = f"https://api.sunoaiapi.com/api/v1/gateway/query?ids={','.join(song_ids)}"
headers = {'Content-Type': 'application/json', 'api-key': API_KEY}
print(f"Querying generation status for: {song_ids}") # Journalisation des détails de requête
response = requests.get(url, headers=headers)
if response.status_code == 200:
return response.json()
else:
print(f"Failed to query generation status with status: {response.status_code}, Response: {response.text}")
return None
`
Thoses functions didn't manage any sucessful generation. Lyrics sent nevertheless.

IF needed, full code there :
if name == "main":
songs = get_lyrics_from_sheet(SPREADSHEET_ID, RANGE_NAME)
if songs:
for idx in range(0, len(songs), 2):
if idx + 1 >= len(songs):
continue

        song_v1 = songs[idx]
        song_v2 = songs[idx + 1]

        if not song_v1 or not song_v2 or len(song_v1) < 3 or len(song_v2) < 3:
            print(f"Skipping incomplete song entry at index {idx}")
            continue

        title_v1 = song_v1[0]
        title_v2 = song_v2[0]

        if title_v1 != title_v2:
            print(f"Titles do not match for V1 and V2: {title_v1} != {title_v2}")
            continue

        # Envoyer les chansons V1 et V2 à l'API
        v1_id = send_lyrics_to_api(song_v1)
        if not v1_id:
            print(f"Failed to send V1 for song: {title_v1}")
            continue

        v2_id = send_lyrics_to_api(song_v2)
        if not v2_id:
            print(f"Failed to send V2 for song: {title_v2}")
            continue

        # Attendre que les deux versions soient générées
        v1_complete = False
        v2_complete = False

        while not (v1_complete and v2_complete):
            if not v1_complete:
                v1_result = query_generation_status([v1_id])
                if v1_result and v1_result[0]['status'] == 'complete':
                    v1_complete = True
                    print(f"V1 generation complete for song: {title_v1}")
                else:
                    print(f"V1 generation not complete for song: {title_v1}, retrying in 30 seconds...")
                    time.sleep(30)

            if not v2_complete:
                v2_result = query_generation_status([v2_id])
                if v2_result and v2_result[0]['status'] == 'complete':
                    v2_complete = True
                    print(f"V2 generation complete for song: {title_v2}")
                else:
                    print(f"V2 generation not complete for song: {title_v2}, retrying in 30 seconds...")
                    time.sleep(30)

        # Concaténer les chansons V1 et V2
        concat_id = concatenate_songs(v1_id, v2_id)
        if not concat_id:
            print(f"Failed to concatenate songs for: {title_v1}")
            continue

        # Interroger l'état de la chanson concaténée
        while True:
            concat_result = query_generation_status([concat_id])
            if concat_result:
                status = concat_result[0]['status']
                if status == 'complete':
                    audio_url = concat_result[0]['audio_url']
                    output_filename = f"{title_v1}_complete.mp3"
                    download_audio(audio_url, output_filename)
                    print(f"Successfully downloaded concatenated song: {output_filename}")

                    # Ajouter le texte de la chanson générée à la liste pour mise à jour de la feuille
                    song_text = concat_result[0]['meta_data']['prompt']
                    update_sheet_with_text(SPREADSHEET_ID, [[song_text]])
                    break
                elif status == 'error':
                    error_message = concat_result[0]['meta_data'].get('error_message', 'Unknown error')
                    print(f"Failed to concatenate song {title_v1}: {error_message}")
                    update_sheet_with_text(SPREADSHEET_ID, [["Error in concatenation: " + error_message]])
                    break
                else:
                    print(f"Concatenated song {title_v1} is in status: {status}. Retrying in 30 seconds...")
                    time.sleep(30)
            else:
                print(f"Failed to get generation status for concatenated song: {concat_id}")
                time.sleep(30)
else:
    print("No songs found or an error occurred while fetching songs.")

Thanks in advance.
sKunZel

Module not found: Can't resolve 'agent-base'

Describe the bug
I get the following error:

Import trace for requested module:
./node_modules/http-cookie-agent/dist/http/index.js
./node_modules/http-cookie-agent/http/index.js
./node_modules/axios-cookiejar-support/dist/index.js
./src/lib/SunoApi.ts
./src/app/api/get_limit/route.ts
 ⨯ ./node_modules/http-cookie-agent/dist/http/mixed_cookie_agent.js:7:0
Module not found: Can't resolve 'agent-base'

To Reproduce
Steps to reproduce the behavior:
Install the api using npm install

Expected behavior
The tool to work

Screenshots
error

Desktop (please complete the following information):

  • OS: Windows
  • Browser: Firefox

Need an improved UI panel for debugging APIs.

Is your feature request related to a problem? Please describe.
An intuitive interface for effortless usage and debugging of Suno, without getting bogged down in technical details.

Describe the solution you'd like
OpenAI’s Playground.

However, I’m not certain if this is a widespread need.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.