From eaefaa43de34f82b3f35c040dbce44432bbaea5c Mon Sep 17 00:00:00 2001 From: erliona Date: Fri, 10 Jul 2026 18:10:08 +0300 Subject: [PATCH] feat(tools): add tunova music generation tool Adds TunovaMusicGenerationTool, which generates complete songs from text prompts via the Tunova API (hosted Suno-quality music generation, billed only on successful renders). Submits a generation job, polls until the render completes or times out, and returns the track title and audio URL. Co-Authored-By: Claude Fable 5 --- lib/crewai-tools/src/crewai_tools/__init__.py | 4 + .../src/crewai_tools/tools/__init__.py | 4 + .../tunova_music_generation_tool/README.md | 43 ++++++ .../tunova_music_generation_tool/__init__.py | 0 .../tunova_music_generation_tool.py | 133 ++++++++++++++++++ .../tunova_music_generation_tool_test.py | 114 +++++++++++++++ 6 files changed, 298 insertions(+) create mode 100644 lib/crewai-tools/src/crewai_tools/tools/tunova_music_generation_tool/README.md create mode 100644 lib/crewai-tools/src/crewai_tools/tools/tunova_music_generation_tool/__init__.py create mode 100644 lib/crewai-tools/src/crewai_tools/tools/tunova_music_generation_tool/tunova_music_generation_tool.py create mode 100644 lib/crewai-tools/tests/tools/tunova_music_generation_tool_test.py diff --git a/lib/crewai-tools/src/crewai_tools/__init__.py b/lib/crewai-tools/src/crewai_tools/__init__.py index a7c7ba9678..249ecdb314 100644 --- a/lib/crewai-tools/src/crewai_tools/__init__.py +++ b/lib/crewai-tools/src/crewai_tools/__init__.py @@ -204,6 +204,9 @@ TavilyResearchTool, ) from crewai_tools.tools.tavily_search_tool.tavily_search_tool import TavilySearchTool +from crewai_tools.tools.tunova_music_generation_tool.tunova_music_generation_tool import ( + TunovaMusicGenerationTool, +) from crewai_tools.tools.txt_search_tool.txt_search_tool import TXTSearchTool from crewai_tools.tools.vision_tool.vision_tool import VisionTool from crewai_tools.tools.weaviate_tool.vector_search import WeaviateVectorSearchTool @@ -320,6 +323,7 @@ "TavilyGetResearchTool", "TavilyResearchTool", "TavilySearchTool", + "TunovaMusicGenerationTool", "VisionTool", "WeaviateVectorSearchTool", "WebsiteSearchTool", diff --git a/lib/crewai-tools/src/crewai_tools/tools/__init__.py b/lib/crewai-tools/src/crewai_tools/tools/__init__.py index 18bf4e5638..60d9b94b5e 100644 --- a/lib/crewai-tools/src/crewai_tools/tools/__init__.py +++ b/lib/crewai-tools/src/crewai_tools/tools/__init__.py @@ -191,6 +191,9 @@ TavilyResearchTool, ) from crewai_tools.tools.tavily_search_tool.tavily_search_tool import TavilySearchTool +from crewai_tools.tools.tunova_music_generation_tool.tunova_music_generation_tool import ( + TunovaMusicGenerationTool, +) from crewai_tools.tools.txt_search_tool.txt_search_tool import TXTSearchTool from crewai_tools.tools.vision_tool.vision_tool import VisionTool from crewai_tools.tools.weaviate_tool.vector_search import WeaviateVectorSearchTool @@ -303,6 +306,7 @@ "TavilyGetResearchTool", "TavilyResearchTool", "TavilySearchTool", + "TunovaMusicGenerationTool", "VisionTool", "WeaviateVectorSearchTool", "WebsiteSearchTool", diff --git a/lib/crewai-tools/src/crewai_tools/tools/tunova_music_generation_tool/README.md b/lib/crewai-tools/src/crewai_tools/tools/tunova_music_generation_tool/README.md new file mode 100644 index 0000000000..12cabed63b --- /dev/null +++ b/lib/crewai-tools/src/crewai_tools/tools/tunova_music_generation_tool/README.md @@ -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 diff --git a/lib/crewai-tools/src/crewai_tools/tools/tunova_music_generation_tool/__init__.py b/lib/crewai-tools/src/crewai_tools/tools/tunova_music_generation_tool/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/lib/crewai-tools/src/crewai_tools/tools/tunova_music_generation_tool/tunova_music_generation_tool.py b/lib/crewai-tools/src/crewai_tools/tools/tunova_music_generation_tool/tunova_music_generation_tool.py new file mode 100644 index 0000000000..256ac5d88d --- /dev/null +++ b/lib/crewai-tools/src/crewai_tools/tools/tunova_music_generation_tool/tunova_music_generation_tool.py @@ -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." + ) diff --git a/lib/crewai-tools/tests/tools/tunova_music_generation_tool_test.py b/lib/crewai-tools/tests/tools/tunova_music_generation_tool_test.py new file mode 100644 index 0000000000..a1e910c938 --- /dev/null +++ b/lib/crewai-tools/tests/tools/tunova_music_generation_tool_test.py @@ -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")