Give an LLM a music recognition tool
Add a recognize_song tool to Claude or an OpenAI model with function calling, without MCP: one JSON Schema for both APIs, a Python handler that calls AudD from your server and returns a small result, no-match and error results the model can act on, a second tool for long recordings with a capped limit, and when to use the MCP server instead.
In this guide, we’ll give a model a tool that answers “what’s this song?”, using the Claude or the OpenAI API and no MCP server. We wanted to make it as simple as possible: you describe the tool to the model, and when the model calls it, your server sends the URL to our API. We send back the song, and the model gets the artist, the title, and a link to the song’s page. The token stays on your server, and the model only sees a small result.
Save the tool definition as audd_tools.json:
[
{
"name": "recognize_song",
"description": "Identifies the song playing in an audio file at a URL, using the AudD music recognition API. A link to a video file sometimes works too. Use it when the user gives you a link to a short clip and asks what song it is. Only the first 12 seconds of the file are analyzed, and one song is returned. The result has the artist, title, album, release date and a song_link page, or match: false when no song matched. When there is no match, say so: never guess a song.",
"parameters": {
"type": "object",
"properties": {
"url": {
"type": "string",
"description": "An http:// or https:// link to the audio file, exactly as the user gave it. Local file paths are not accepted."
}
},
"required": ["url"],
"additionalProperties": false
}
}
]
You can send the same JSON Schema to Claude and to OpenAI models, in the input_schema and the parameters fields respectively. The model will rely on the description to determine when to call the tool, and what to do if there are no matches.
Using an MCP client? Connect our MCP server instead. The method you choose depends upon where the model runs, but if it’s an MCP client, like Claude, ChatGPT, Cursor, or VS Code, we recommend connecting our MCP server at
https://mcp.audd.ioinstead (see Connect Claude, Cursor, or another MCP client). Write your own tool when the model runs in your app, and the requests are sent from your server.
How it works
- You send the tool definition with every request to the model.
- When the user asks about a song, the model answers with a tool call: the name
recognize_songand aurl. - Your code checks the URL, sends it to AudD with your token, and makes a small result from the response.
- You send the result back, and the model writes the answer for the user.
Write the tool on your server
pip install audd anthropic openai
export AUDD_API_TOKEN=your-api-token
You only need the SDK of the model you use. Get your token at dashboard.audd.io. Save this next to the JSON file as audd_tools.py:
import json
import logging
from pathlib import Path
from urllib.parse import urlparse
from audd import (
AudD,
AudDAuthenticationError,
AudDError,
AudDInvalidAudioError,
AudDInvalidRequestError,
AudDQuotaError,
AudDSubscriptionError,
)
log = logging.getLogger("audd_tools")
audd = AudD() # reads AUDD_API_TOKEN from your server's environment
TOOL_DEFINITIONS = json.loads(Path(__file__).with_name("audd_tools.json").read_text())
def check_url(text):
"""Return (url, None) for an http(s) URL, or (None, error) for anything else."""
parsed = urlparse(str(text).strip())
if parsed.scheme not in ("http", "https") or not parsed.netloc:
return None, {
"error": "not_a_url",
"message": "Only http:// and https:// links can be recognized. "
"Ask the user for a link to the audio file.",
}
return parsed.geturl(), None
def song_fields(song):
return {
"artist": song.artist,
"title": song.title,
"album": song.album,
"release_date": song.release_date,
"song_link": song.song_link,
}
def error_result(e):
"""Turn an SDK exception into a short result the model can act on."""
log.warning("AudD request failed: %r", e) # the details are for you, not the model
code = getattr(e, "error_code", None)
if isinstance(e, (AudDAuthenticationError, AudDQuotaError, AudDSubscriptionError)):
message = "Song recognition isn't available right now. Don't retry; tell the user."
elif isinstance(e, (AudDInvalidRequestError, AudDInvalidAudioError)):
message = ("AudD couldn't download or read audio at this URL. "
"Ask the user for a direct link to an audio file.")
else:
message = "Recognition failed for a temporary reason. Tell the user to try again in a few minutes."
return {"error": "recognition_failed", "error_code": code, "message": message}
def recognize_song(url):
url, bad = check_url(url)
if bad:
return bad
try:
result = audd.recognize(url)
except AudDError as e:
return error_result(e)
if result is None:
return {
"match": False,
"message": "The audio was processed, but no song matched its first 12 seconds.",
}
return {"match": True, **song_fields(result)}
TOOLS = {"recognize_song": recognize_song}
def run_tool(name, args):
tool = TOOLS.get(name)
if tool is None:
return {"error": "unknown_tool", "message": f"There is no tool named {name}."}
try:
return tool(**args)
except TypeError:
return {"error": "bad_arguments", "message": f"Wrong arguments for {name}: {args}"}
AudD() reads the token from the AUDD_API_TOKEN environment variable, so the token is never in a prompt, a tool result, or the client. Please don’t include your API tokens in the client-side software: see Keeping your API token on the server.
The tool sends the URL in the url parameter. Our server will download the file and identify the music, so your server never downloads it. If there are matches, the response contains artist, title, album, release_date, label, timecode, and song_link fields, and the tool passes on five of them. It leaves out timecode on purpose: it’s the time in the recognized song when the fragment you sent is played, and a model could take it for a position in the user’s clip.
When the model passes something that isn’t a URL
The model will pass the tool whatever the user gave it, and it doesn’t have to be a URL. Our Python and Node.js SDKs will pick the right field for you: a string that starts with http:// or https:// is sent as a URL, and any other string is opened as a local file and uploaded. So if a user, or a web page the model has read, asks it to recognize /etc/passwd or your .env file, the SDK would send that file from your server to AudD. That’s why check_url only lets through http:// and https:// URLs, and the model gets a result that tells it to ask the user for a link.
When result is null
If the server has successfully processed the request, but there are no matches, the result field is null, and the SDK returns None. It’s a normal answer, not an error, so the tool returns match: false and doesn’t tell the model that something failed. The standard endpoint analyzes up to the first 12 seconds of audio, so in a long file the song might start later. The description tells the model not to guess a song.
When AudD returns an error
We have about 40 different error codes. In the SDK, you’ll get a typed exception instead, and error_result sorts them into three groups. Errors 900 to 905 are about your account: the token is invalid, there are no requests left, or the plan doesn’t include the feature. Please note that if you retry with the same token, you’ll get the same error. So the tool tells the model not to retry, and you’ll find the details in your log.
If it’s the audio or the URL (600, 700, 300, 500, and others), the file couldn’t be downloaded or read as audio. The model will ask the user for another link.
If it’s our server (19, 100) or the network, the model tells the user to try again later. The SDK will automatically retry the connection failures that happen before the upload is complete, so the tool doesn’t retry by itself.
The error_message in our responses is for you, not for your user: it might ask you to check the api_token parameter or the status of your account on dashboard.audd.io. So the tool logs it, and the model gets a message of its own. You can find every code, grouped by category, in the error codes reference.
Run the loop with Claude
chat_claude.py sends the question with the tool, runs every tool call Claude makes, and sends the results back. The model ID, claude-opus-5-5, is from Anthropic’s models overview; put in the model you use.
import json
import anthropic
from audd_tools import TOOL_DEFINITIONS, run_tool
client = anthropic.Anthropic() # reads ANTHROPIC_API_KEY
MODEL = "claude-opus-5-5"
TOOLS = [
{"name": t["name"], "description": t["description"], "input_schema": t["parameters"]}
for t in TOOL_DEFINITIONS
]
MAX_ROUNDS = 5 # rounds of tool calls allowed for one question
def ask(question):
messages = [{"role": "user", "content": question}]
for _ in range(MAX_ROUNDS):
response = client.messages.create(
model=MODEL, max_tokens=4096, tools=TOOLS, messages=messages
)
if response.stop_reason != "tool_use":
return "".join(b.text for b in response.content if b.type == "text")
messages.append({"role": "assistant", "content": response.content})
results = []
for block in response.content:
if block.type == "tool_use":
output = run_tool(block.name, block.input)
results.append({
"type": "tool_result",
"tool_use_id": block.id,
"content": json.dumps(output),
"is_error": "error" in output,
})
messages.append({"role": "user", "content": results})
return "I couldn't finish this with the tools I have."
if __name__ == "__main__":
print(ask("What's the song in https://audd.tech/example.mp3?"))
When Claude calls a tool, you’ll receive a response with stop_reason set to tool_use and a tool_use block for each call, with an id, the name of the tool, and its input. To send the results back, add the response’s content to the messages as it is, as an assistant message, and then a user message with the results. Please ensure that every tool_use block gets a tool_result block with the same tool_use_id, even if the tool failed. If the tool failed, set is_error to true: Claude might then call the tool again or tell the user what happened, so limit how many rounds the loop allows (MAX_ROUNDS). You can find the steps in Anthropic’s guide Handle tool calls.
Run the loop with an OpenAI model
chat_openai.py does the same with OpenAI’s Responses API. The tools get "type": "function" and "strict": true. Strict mode makes the model’s arguments follow the schema. Please note that it requires additionalProperties: false and every property in required: our schema has both. The model ID, gpt-6.2-astra, is from OpenAI’s models page.
import json
from openai import OpenAI
from audd_tools import TOOL_DEFINITIONS, run_tool
client = OpenAI() # reads OPENAI_API_KEY
MODEL = "gpt-6.2-astra"
TOOLS = [{"type": "function", "strict": True, **t} for t in TOOL_DEFINITIONS]
MAX_ROUNDS = 5 # rounds of tool calls allowed for one question
def ask(question):
input_list = [{"role": "user", "content": question}]
for _ in range(MAX_ROUNDS):
response = client.responses.create(model=MODEL, tools=TOOLS, input=input_list)
calls = [item for item in response.output if item.type == "function_call"]
if not calls:
return response.output_text
input_list += response.output
for call in calls:
output = run_tool(call.name, json.loads(call.arguments))
input_list.append({
"type": "function_call_output",
"call_id": call.call_id,
"output": json.dumps(output),
})
return "I couldn't finish this with the tools I have."
if __name__ == "__main__":
print(ask("What's the song in https://audd.tech/example.mp3?"))
When the model calls a tool, you’ll receive a function_call item in the response’s output for each call, with a call_id, the name, and the arguments as a JSON string. To send the results back, add the output to the input as it is, and then a function_call_output item for each call. Please ensure that every function_call_output has the same call_id as its call. The result is a string, so if the tool failed, the error field in it is what tells the model. You can find the steps in OpenAI’s function calling guide.
Long recordings: a second tool with a limit
recognize_song is for a short clip with one song. If the user wants every song in a DJ set, a podcast, or a video, you need the enterprise endpoint. We count requests to the enterprise endpoint as 1 request per 12 seconds of audio, so if a model is asked for every song in a 3-hour mix, one call without a limit spends 900 requests. That’s why the second tool has a required limit: the upper bound for the number of chunks the server will recognize. Your code caps it too, since the model can send any number.
Add this object to the array in audd_tools.json:
{
"name": "find_songs_in_recording",
"description": "Lists the songs in a long recording at a URL, such as a DJ set, a podcast episode, a stream recording or a video, with where each song was found in the file. Use it when the user wants every song in a recording, or when recognize_song found no match in a long file. AudD scans the file in 12-second chunks, and each chunk costs one request, so limit is the number of chunks to scan from the start of the file: 5 chunks cover the first minute, 30 cover six minutes. Use the smallest limit that covers the part the user asked about.",
"parameters": {
"type": "object",
"properties": {
"url": {
"type": "string",
"description": "An http:// or https:// link to the recording, exactly as the user gave it."
},
"limit": {
"type": "integer",
"minimum": 1,
"maximum": 30,
"description": "How many 12-second chunks to scan from the start of the file (1 to 30)."
}
},
"required": ["url", "limit"],
"additionalProperties": false
}
}
And add this to the end of audd_tools.py:
MAX_CHUNKS = 30 # the most one call can spend: 30 requests, 6 minutes of audio
def clock(seconds):
s = int(seconds)
return f"{s // 3600}:{s // 60 % 60:02d}:{s % 60:02d}" if s >= 3600 else f"{s // 60}:{s % 60:02d}"
def find_songs_in_recording(url, limit):
url, bad = check_url(url)
if bad:
return bad
if not isinstance(limit, int) or limit < 1:
return {"error": "bad_limit", "message": "limit must be a whole number from 1 to 30."}
limit = min(limit, MAX_CHUNKS)
try:
matches = audd.recognize_enterprise(url, limit=limit)
except AudDError as e:
return error_result(e)
songs = {}
for m in matches:
key = m.song_link or f"{m.artist} - {m.title}"
song = songs.setdefault(key, {**song_fields(m), "found_at": []})
if m.start_seconds is not None:
song["found_at"].append(clock(m.start_seconds))
return {
"songs": list(songs.values()),
"scanned": f"at most the first {clock(limit * 12)} of the file",
}
TOOLS["find_songs_in_recording"] = find_songs_in_recording
When you send a recording, our servers consider it to be a group of 12-second-long audio chunks, and the SDK returns the matches from all of them. start_seconds is the position, in the file you sent, of the start of the matched fragment. A song that plays longer than 12 seconds is matched in several chunks, so the tool lists each song once, with all the positions where it was found. scanned tells the model how much of the file was covered.
With MAX_CHUNKS = 30, one call can’t spend more than 30 requests, which is 6 minutes of audio. If you don’t want every one of the chunks to be recognized and counted as the requests, there are two parameters that you can use: skip and every (see Controlling enterprise endpoint cost). To scan whole recordings, raise the cap, and have the model ask the user before a large scan.
Note. Music recognition by URL on our enterprise endpoint is only available to paid users. On the free trial, you can send a file by POST instead of the file URL, but this tool only takes URLs: you’ll get error 904, and the tool tells the model that recognition isn’t available.
recognize_songworks on the free trial.
Test the tool without spending requests
You can test the tool without sending any requests to our API. Inject your own httpx client with a mock transport, and the SDK will get your recorded response instead of ours (the testing guide has recorded responses for matches, no-matches, and errors):
import os
import httpx
from audd import AudD
os.environ.setdefault("AUDD_API_TOKEN", "stub") # audd_tools makes a client on import
import audd_tools # noqa: E402
def no_match(request):
# what AudD answers when it processed the audio and nothing matched
return httpx.Response(200, json={"status": "success", "result": None})
http = httpx.Client(transport=httpx.MockTransport(no_match))
audd_tools.audd = AudD("stub", httpx_client=http)
print(audd_tools.run_tool("recognize_song", {"url": "https://audd.tech/example.mp3"}))
print(audd_tools.run_tool("recognize_song", {"url": "/etc/passwd"}))
When run, the program should print the following:
{'match': False, 'message': 'The audio was processed, but no song matched its first 12 seconds.'}
{'error': 'not_a_url', 'message': 'Only http:// and https:// links can be recognized. Ask the user for a link to the audio file.'}
When your app has no AudD account
If you want the assistant to pay for its own requests, it can register with us and buy prepaid requests: you’ll be able to use our API without an AudD account or an email. We sell the requests in packs: 1,000 requests cost $5.00, and they expire 12 months after the last purchase. Your tool then sends the same request to https://api.audd.io/agent/recognize, with the key in the Authorization: Bearer header instead of the api_token parameter. The parameters and the response are those of the standard endpoint, so the URL check and the small result stay the same. Prepaid requests are for standard recognition only, so the long-recording tool needs an AudD account. See Agent notes: prepaid requests without an AudD account and the recipe Build an assistant that pays for its own song recognition.
Other ways to give a model AudD
There are other ways to give a model access to our API, and you might not need a tool of your own. If the model runs in an MCP client, connect our MCP server at https://mcp.audd.io. It has tools for your usage, your plan and billing, the API token, payment links, and the docs, and it can also send a song to our API for you, but only by URL (see the setup guide). Our command-line tool also works as an MCP server: when your client starts audd mcp, the agent can recognize files from your computer, scan long recordings, and manage your streams. And if the agent can run shell commands, it can use the CLI itself: when its output is piped, every command prints JSON and exits with a documented code (see the AudD CLI guide for AI agents). We have written about all of them in Music recognition for AI agents.
Related
Reading this as an AI agent? The raw Markdown is at integrations/llm-tool-use.md, and the full index is /resources/llms.txt.
