-
Notifications
You must be signed in to change notification settings - Fork 7.8k
feat(tools): add tunova music generation tool #6513
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
erliona
wants to merge
1
commit into
crewAIInc:main
Choose a base branch
from
erliona:feat/tunova-music-tool
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
43 changes: 43 additions & 0 deletions
43
lib/crewai-tools/src/crewai_tools/tools/tunova_music_generation_tool/README.md
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,43 @@ | ||
| # TunovaMusicGenerationTool Documentation | ||
|
|
||
| ## Description | ||
| The TunovaMusicGenerationTool generates complete songs from text prompts using the [Tunova](https://tunova.ai) API, a hosted Suno-quality music generation service. The tool submits a generation job, waits for the render to finish, and returns the track title and audio URL. Songs are billed only on successful renders, so failed generations can be retried at no extra cost. | ||
|
|
||
| ## Features | ||
| - Full song generation from a single text prompt | ||
| - Optional instrumental-only mode (no vocals) | ||
| - Configurable maximum wait time for the render | ||
| - Billed only on successful renders — failed renders are automatically refunded | ||
| - Free tier available (no card required) | ||
|
|
||
| ## Installation | ||
| ```shell | ||
| pip install 'crewai[tools]' | ||
| ``` | ||
|
|
||
| ## Usage | ||
| ```python | ||
| from crewai_tools import TunovaMusicGenerationTool | ||
|
|
||
| # Initialize the tool | ||
| tool = TunovaMusicGenerationTool() | ||
|
|
||
| # Generate a song | ||
| result = tool.run( | ||
| prompt="an upbeat synthwave track about summer nights", | ||
| make_instrumental=False, # Optional: generate without vocals (default: False) | ||
| wait_seconds=360, # Optional: max seconds to wait for the render (default: 360) | ||
| ) | ||
| ``` | ||
|
|
||
| ## Configuration | ||
| 1. **API Key Setup**: | ||
| - Sign up for an account at [tunova.ai](https://tunova.ai) | ||
| - Obtain your API key | ||
| - Set the environment variable: `TUNOVA_API_KEY` | ||
|
|
||
| ## Response Format | ||
| The tool returns a short string result: | ||
| - On success: the track title, duration, and audio URL for each generated clip | ||
| - On failure: an explanatory error message (failed renders are automatically refunded, so retrying is free) | ||
| - On timeout: the job id and a note that only successful renders are billed |
Empty file.
133 changes: 133 additions & 0 deletions
133
...tools/src/crewai_tools/tools/tunova_music_generation_tool/tunova_music_generation_tool.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,133 @@ | ||
| import logging | ||
| import os | ||
| import time | ||
| from typing import Any | ||
|
|
||
| from crewai.tools import BaseTool, EnvVar | ||
| from pydantic import BaseModel, Field | ||
| import requests | ||
|
|
||
|
|
||
| logger = logging.getLogger(__name__) | ||
|
|
||
|
|
||
| class TunovaMusicGenerationToolSchema(BaseModel): | ||
| """Input for TunovaMusicGenerationTool.""" | ||
|
|
||
| prompt: str = Field( | ||
| ..., | ||
| description="Mandatory text prompt describing the music to generate, e.g. 'an upbeat synthwave track about summer nights'", | ||
| ) | ||
| make_instrumental: bool = Field( | ||
| False, description="Generate an instrumental track without vocals" | ||
| ) | ||
| wait_seconds: int = Field( | ||
| 360, | ||
| ge=10, | ||
| le=360, | ||
| description="Maximum number of seconds to wait for the render to finish", | ||
| ) | ||
|
|
||
|
|
||
| class TunovaMusicGenerationTool(BaseTool): | ||
| name: str = "Tunova music generation tool" | ||
| description: str = ( | ||
| "Generate a complete song from a text prompt with Tunova, a hosted " | ||
| "Suno-quality music generation API. Returns the track title and audio " | ||
| "URL. Songs are billed only on successful renders, so failed " | ||
| "generations can be retried at no extra cost." | ||
| ) | ||
| args_schema: type[BaseModel] = TunovaMusicGenerationToolSchema | ||
| base_url: str = "https://api.tunova.ai" | ||
| poll_interval: int = 10 | ||
| env_vars: list[EnvVar] = Field( | ||
| default_factory=lambda: [ | ||
| EnvVar( | ||
| name="TUNOVA_API_KEY", description="API key for Tunova", required=True | ||
| ), | ||
| ] | ||
| ) | ||
|
|
||
| def _headers(self) -> dict[str, str]: | ||
| """Build request headers with the Tunova API key.""" | ||
| api_key = os.environ.get("TUNOVA_API_KEY") | ||
| if not api_key: | ||
| raise EnvironmentError( | ||
| "TUNOVA_API_KEY environment variable is required to use this tool" | ||
| ) | ||
| return {"X-API-Key": api_key, "content-type": "application/json"} | ||
|
|
||
| def _submit_job(self, prompt: str, make_instrumental: bool) -> str: | ||
| """Submit a generation job and return its job id.""" | ||
| payload: dict[str, Any] = {"prompt": prompt} | ||
| if make_instrumental: | ||
| payload["make_instrumental"] = True | ||
| response = requests.post( | ||
| f"{self.base_url}/api/generate", | ||
| headers=self._headers(), | ||
| json=payload, | ||
| timeout=30, | ||
| ) | ||
| response.raise_for_status() | ||
| job_id = response.json().get("job_id") | ||
| if not job_id: | ||
| raise ValueError("Tunova API did not return a job_id") | ||
| return str(job_id) | ||
|
|
||
| def _get_job(self, job_id: str) -> dict[str, Any]: | ||
| """Fetch the current state of a generation job.""" | ||
| response = requests.get( | ||
| f"{self.base_url}/api/jobs/{job_id}", | ||
| headers=self._headers(), | ||
| timeout=30, | ||
| ) | ||
| response.raise_for_status() | ||
| return dict(response.json()) | ||
|
|
||
| @staticmethod | ||
| def _format_clips(clips: list[dict[str, Any]]) -> str: | ||
| """Format finished clips into a short human-readable summary.""" | ||
| lines: list[str] = [] | ||
| for clip in clips: | ||
| title = clip.get("title") or "Untitled" | ||
| duration = clip.get("duration") | ||
| duration_note = f" ({duration:.0f}s)" if duration else "" | ||
| lines.append(f"'{title}'{duration_note}: {clip.get('audio_url', '')}") | ||
| return "\n".join(lines) | ||
|
|
||
| def _run( | ||
| self, prompt: str, make_instrumental: bool = False, wait_seconds: int = 360 | ||
| ) -> str: | ||
| """Generate a song from a text prompt and wait for the render to finish.""" | ||
| try: | ||
| job_id = self._submit_job(prompt, make_instrumental) | ||
| except requests.exceptions.RequestException as e: | ||
| logger.error(f"Error submitting generation job to Tunova API: {e}") | ||
| return f"Failed to submit music generation job: {e}" | ||
|
|
||
| deadline = time.monotonic() + wait_seconds | ||
| while time.monotonic() < deadline: | ||
| time.sleep(self.poll_interval) | ||
| try: | ||
| job = self._get_job(job_id) | ||
| except requests.exceptions.RequestException as e: | ||
| logger.warning(f"Error polling Tunova job {job_id}: {e}") | ||
| continue | ||
|
|
||
| status = job.get("status") | ||
| if status == "complete": | ||
| clips = job.get("clips") or [] | ||
| if not clips: | ||
| return f"Music generation job {job_id} completed but returned no clips." | ||
| return f"Music generated successfully:\n{self._format_clips(clips)}" | ||
| if status == "failed": | ||
| return ( | ||
| f"Music generation job {job_id} failed. Failed renders are " | ||
| "automatically refunded, so it is safe to retry this tool " | ||
| "at no extra cost." | ||
| ) | ||
|
|
||
| return ( | ||
| f"Music generation job {job_id} did not finish within {wait_seconds} " | ||
| "seconds. You are only billed for successful renders." | ||
| ) | ||
114 changes: 114 additions & 0 deletions
114
lib/crewai-tools/tests/tools/tunova_music_generation_tool_test.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,114 @@ | ||
| import os | ||
| from unittest.mock import patch | ||
|
|
||
| from crewai_tools.tools.tunova_music_generation_tool.tunova_music_generation_tool import ( | ||
| TunovaMusicGenerationTool, | ||
| ) | ||
| import pytest | ||
|
|
||
|
|
||
| @pytest.fixture(autouse=True) | ||
| def mock_tunova_api_key(): | ||
| with patch.dict(os.environ, {"TUNOVA_API_KEY": "test_key"}): | ||
| yield | ||
|
|
||
|
|
||
| @pytest.fixture | ||
| def tunova_tool(): | ||
| return TunovaMusicGenerationTool(poll_interval=0) | ||
|
|
||
|
|
||
| def test_tunova_tool_initialization(): | ||
| tool = TunovaMusicGenerationTool() | ||
| assert tool.base_url == "https://api.tunova.ai" | ||
| assert tool.poll_interval == 10 | ||
|
|
||
|
|
||
| @patch("requests.get") | ||
| @patch("requests.post") | ||
| def test_tunova_tool_successful_generation(mock_post, mock_get, tunova_tool): | ||
| mock_post.return_value.status_code = 202 | ||
| mock_post.return_value.json.return_value = {"job_id": "job_123"} | ||
| mock_get.return_value.status_code = 200 | ||
| mock_get.return_value.json.return_value = { | ||
| "status": "complete", | ||
| "clips": [ | ||
| { | ||
| "audio_url": "https://cdn.tunova.ai/clips/abc.mp3", | ||
| "title": "Summer Nights", | ||
| "duration": 120.0, | ||
| } | ||
| ], | ||
| } | ||
|
|
||
| result = tunova_tool.run(prompt="an upbeat synthwave track about summer nights") | ||
|
|
||
| assert "Summer Nights" in result | ||
| assert "https://cdn.tunova.ai/clips/abc.mp3" in result | ||
| called_payload = mock_post.call_args.kwargs["json"] | ||
| assert called_payload == {"prompt": "an upbeat synthwave track about summer nights"} | ||
| called_headers = mock_post.call_args.kwargs["headers"] | ||
| assert called_headers["X-API-Key"] == "test_key" | ||
|
|
||
|
|
||
| @patch("requests.get") | ||
| @patch("requests.post") | ||
| def test_tunova_tool_instrumental_payload(mock_post, mock_get, tunova_tool): | ||
| mock_post.return_value.status_code = 202 | ||
| mock_post.return_value.json.return_value = {"job_id": "job_123"} | ||
| mock_get.return_value.status_code = 200 | ||
| mock_get.return_value.json.return_value = { | ||
| "status": "complete", | ||
| "clips": [ | ||
| { | ||
| "audio_url": "https://cdn.tunova.ai/clips/abc.mp3", | ||
| "title": "Instrumental", | ||
| "duration": 90.0, | ||
| } | ||
| ], | ||
| } | ||
|
|
||
| tunova_tool.run(prompt="a calm piano piece", make_instrumental=True) | ||
|
|
||
| called_payload = mock_post.call_args.kwargs["json"] | ||
| assert called_payload["make_instrumental"] is True | ||
|
|
||
|
|
||
| @patch("requests.get") | ||
| @patch("requests.post") | ||
| def test_tunova_tool_failed_generation_mentions_refund( | ||
| mock_post, mock_get, tunova_tool | ||
| ): | ||
| mock_post.return_value.status_code = 202 | ||
| mock_post.return_value.json.return_value = {"job_id": "job_123"} | ||
| mock_get.return_value.status_code = 200 | ||
| mock_get.return_value.json.return_value = {"status": "failed", "clips": []} | ||
|
|
||
| result = tunova_tool.run(prompt="a song that fails") | ||
|
|
||
| assert "failed" in result | ||
| assert "refunded" in result | ||
|
|
||
|
|
||
| @patch( | ||
| "crewai_tools.tools.tunova_music_generation_tool.tunova_music_generation_tool.time" | ||
| ) | ||
| @patch("requests.get") | ||
| @patch("requests.post") | ||
| def test_tunova_tool_timeout(mock_post, mock_get, mock_time, tunova_tool): | ||
| mock_post.return_value.status_code = 202 | ||
| mock_post.return_value.json.return_value = {"job_id": "job_123"} | ||
| mock_get.return_value.status_code = 200 | ||
| mock_get.return_value.json.return_value = {"status": "processing", "clips": []} | ||
| mock_time.monotonic.side_effect = [0, 5, 15] | ||
|
|
||
| result = tunova_tool.run(prompt="a slow render", wait_seconds=10) | ||
|
|
||
| assert "did not finish" in result | ||
| assert "job_123" in result | ||
|
|
||
|
|
||
| def test_tunova_tool_missing_api_key(tunova_tool): | ||
| with patch.dict(os.environ, {}, clear=True): | ||
| with pytest.raises(EnvironmentError): | ||
| tunova_tool.run(prompt="a song without credentials") |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
Catch
ValueErroralongsideRequestExceptionin the submission error handler._submit_jobraisesValueErrorat line 74 when the API returns a 2xx response without ajob_idfield. Theexceptblock here only catchesrequests.exceptions.RequestException, so thatValueErrorpropagates unhandled and crashes the tool instead of returning a user-friendly error string — breaking the agent's workflow.🐛 Proposed fix
try: job_id = self._submit_job(prompt, make_instrumental) - except requests.exceptions.RequestException as e: + except (requests.exceptions.RequestException, ValueError) as e: logger.error(f"Error submitting generation job to Tunova API: {e}") return f"Failed to submit music generation job: {e}"📝 Committable suggestion
🤖 Prompt for AI Agents