Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions lib/crewai-tools/src/crewai_tools/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -320,6 +323,7 @@
"TavilyGetResearchTool",
"TavilyResearchTool",
"TavilySearchTool",
"TunovaMusicGenerationTool",
"VisionTool",
"WeaviateVectorSearchTool",
"WebsiteSearchTool",
Expand Down
4 changes: 4 additions & 0 deletions lib/crewai-tools/src/crewai_tools/tools/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -303,6 +306,7 @@
"TavilyGetResearchTool",
"TavilyResearchTool",
"TavilySearchTool",
"TunovaMusicGenerationTool",
"VisionTool",
"WeaviateVectorSearchTool",
"WebsiteSearchTool",
Expand Down
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
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}"
Comment on lines +102 to +106

Copy link
Copy Markdown

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 ValueError alongside RequestException in the submission error handler.

_submit_job raises ValueError at line 74 when the API returns a 2xx response without a job_id field. The except block here only catches requests.exceptions.RequestException, so that ValueError propagates 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

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
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}"
try:
job_id = self._submit_job(prompt, make_instrumental)
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}"
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@lib/crewai-tools/src/crewai_tools/tools/tunova_music_generation_tool/tunova_music_generation_tool.py`
around lines 102 - 106, Update the submission error handler around _submit_job
to catch ValueError alongside requests.exceptions.RequestException, preserving
the existing logging and user-friendly failure-string behavior for missing
job_id responses.


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 lib/crewai-tools/tests/tools/tunova_music_generation_tool_test.py
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")