---
title: "Build an assistant that pays for its own song recognition"
description: "A small Python program that registers with AudD's agent API, gives its user a checkout link when the prepaid balance is 0, waits for the purchase, then recognizes a clip and reports the requests left. No AudD account, no subscription."
slug: "/resources/recipes/assistant-with-prepaid-recognition"
section: "recipes"
keywords: [audd, ai assistant, agent, prepaid requests, checkout link, pay per request, music recognition, python, requests, no subscription]
---

# Build an assistant that pays for its own song recognition

In this recipe, we'll build the AudD side of an assistant that names the song playing, like an Android assistant that a user asks "what's this song?". You'll be able to use our API without an AudD account or an email: the assistant registers by itself and pays for prepaid requests. When it runs out of requests, it gives its user a checkout link and waits for the payment. Here you'll build up a small Python program that does all of this, step by step.

The agent API is described in [audd.io/auth.md](https://audd.io/auth.md), and the [agent notes on prepaid requests](/resources/agents/pay-per-request) list every field, state and error code. You can use them for reference.

## What you'll build

`song_assistant.py`, which does five things:

1. Registers once and saves the key and the refresh token in a file only you can read.
2. Checks the balance it saw last: a new registration starts at 0.
3. When the balance is 0, asks AudD for a checkout link and prints the sentence for the user.
4. Polls the purchase until it's `fulfilled`, with a deadline, and stops on `expired` or `failed`.
5. Recognizes a clip and prints the song and the requests left, from the `AudD-Credits-Remaining` header.

### When an AudD account is the better choice

If you want to pay for all your users' recognitions yourself, you don't need any of this: get a token from the [Dashboard](https://dashboard.audd.io), keep it on your server, and pick a monthly plan. New accounts get a free trial of 300 requests where available, usable for 14 days; an agent registration gets no free requests. You'll also need an account to recognize long files or to monitor live streams, since agent keys work only for standard recognition. The plans are on the [pricing page](https://audd.io/pricing/).

## Prerequisites

- Python 3 with the `requests` library: `pip install requests`
- Nothing from AudD: the program registers on its first run
- Someone who can pay a $5.00 checkout link for 1,000 requests (the price is in the [service document](https://dashboard-api.audd.io/agent/))

Save the five code blocks below, in order, in one file called `song_assistant.py`.

## Walkthrough

### Step 1: Register once and keep the key

```python
import json
import os
import sys
import time
import uuid
from pathlib import Path

import requests

AGENT_API = "https://dashboard-api.audd.io/agent"
RECOGNIZE_URL = "https://api.audd.io/agent/recognize"
STATE_FILE = Path.home() / ".config" / "song-assistant" / "audd-agent.json"
PACKS = 1  # one pack is 1,000 requests


class AgentError(Exception):
    """An error answer from the agent API (application/problem+json)."""

    def __init__(self, response):
        try:
            body = response.json()
        except ValueError:
            body = {}
        audd = body.get("audd") or {}
        self.status = response.status_code
        self.code = audd.get("code")
        self.charged = audd.get("charged")
        super().__init__(f"HTTP {self.status} {self.code}: {body.get('detail', response.text[:200])}")


def load_state():
    try:
        return json.loads(STATE_FILE.read_text())
    except FileNotFoundError:
        return None


def save_state(state):
    STATE_FILE.parent.mkdir(parents=True, exist_ok=True)
    tmp = STATE_FILE.with_suffix(".tmp")
    fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
    with os.fdopen(fd, "w") as f:
        json.dump(state, f)
    os.replace(tmp, STATE_FILE)


def auth(state):
    return {"Authorization": f"Bearer {state['api_key']}"}


def register():
    r = requests.post(f"{AGENT_API}/identity",
                      json={"type": "anonymous", "client_name": "song-assistant"},
                      timeout=30)
    if not r.ok:
        raise AgentError(r)
    body = r.json()
    state = {
        "api_key": body["audd"]["api_key"],      # agt_..., shown only once
        "refresh_token": body["refresh_token"],  # audd_art_...
        "balance": 0,                            # no free requests at sign-up
    }
    save_state(state)
    return state
```

When the program starts, it reads the file with its key. If the file doesn't exist, the program registers and saves the key and the refresh token to it, with mode `600`, so only your user account can read it. Store the key somewhere safe: you won't be able to see it again. You'll need the refresh token if you lose the key. If you're building a phone app, keep the key and the refresh token in the platform's secret store, and never write the key to a log.

Please note that all the agent API requests require the key to be sent in the `Authorization` header. A key in a URL or in an `api_token` field is refused; if that happens, replace the key, since it may be in logs.

### Step 2: Ask for a checkout link

```python
def create_checkout_link(state, packs=PACKS):
    # Keep the key until this purchase is over: a retry, or a restart of
    # the program, then gets the same link back instead of a second one.
    if "checkout_key" not in state:
        state["checkout_key"] = str(uuid.uuid4())
        save_state(state)
    r = requests.post(f"{AGENT_API}/checkout",
                      headers={**auth(state), "Idempotency-Key": state["checkout_key"]},
                      json={"packs": packs}, timeout=30)
    if not r.ok:
        raise AgentError(r)
    return r.json()
```

The answer contains the link in `checkout_url`, a ready sentence in `user_message`, and the `status_url` of the purchase. The checkout link opens a Stripe payment page, where your user can pay by card or any other payment method Stripe offers in their country. They don't have to have an AudD account in order to pay. When your user pays, we'll add the requests to your registration automatically, whoever paid. If nobody pays the link, nothing is charged.

The program saves the `Idempotency-Key` to its file before it sends the request. You can send the same request again with the same key, and you'll get the same link and its current state. If the program is restarted while the user is still paying, it gets the same link back instead of a second one.

> **Please ask before you buy.** Buying spends real money. Pay only with a payment method, and up to an amount, that your user has authorized. Please don't buy more than your user agreed to: the program buys one pack, and if you change `PACKS`, ask your user first.

### Step 3: Wait for the purchase, with a deadline

```python
def wait_for_purchase(state, purchase, max_wait=15 * 60):
    deadline = time.monotonic() + max_wait
    while time.monotonic() < deadline:
        r = requests.get(purchase["status_url"], headers=auth(state), timeout=30)
        if r.status_code in (429, 503):
            time.sleep(int(r.headers.get("Retry-After", "10")))
            continue
        if not r.ok:
            raise AgentError(r)
        current = r.json().get("state")
        if current in ("fulfilled", "expired", "failed"):
            return current
        time.sleep(5)  # awaiting_payment or processing
    return "waiting"


def top_up(state, packs=PACKS):
    purchase = create_checkout_link(state, packs)
    if purchase["state"] == "awaiting_payment":
        print(purchase.get("user_message") or purchase["checkout_url"])
    outcome = purchase["state"]
    if outcome != "fulfilled":
        outcome = wait_for_purchase(state, purchase)
    if outcome == "waiting":
        sys.exit("No payment yet. Run the program again to keep waiting; "
                 f"the link works until {purchase['expires_at']}.")
    del state["checkout_key"]  # the next purchase needs a new key
    if outcome != "fulfilled":
        save_state(state)
        sys.exit(f"The purchase ended as {outcome}. Run the program again for a new link.")
    state["balance"] = None  # known again after the next recognition
    save_state(state)
```

`top_up` prints the `user_message` and polls `status_url` every 5 seconds. The state of the purchase moves from `awaiting_payment` to `fulfilled` when the requests are on the balance. `processing` means the user paid with a method that the bank confirms later, so the program keeps waiting. When AudD answers `429` or `503`, the program waits for the number of seconds in `Retry-After`.

By default, the program waits for 15 minutes. The link works for about 24 hours, so your user can still pay it later. If you run the program again, it gets the same link back and keeps waiting.

#### When the link expires or the purchase fails

If nobody pays, the link stops working after about 24 hours, and nothing is charged. When the purchase is `expired` or `failed`, the program forgets the `Idempotency-Key`, so the next run asks for a new link.

### Step 4: Recognize the clip and read the balance

```python
def recognize(state, url=None, path=None):
    """Send a link (url) or a file your own code chose (path).
    Returns the song, or None if nothing matched."""
    if isinstance(url, str) and url.startswith(("https://", "http://")):
        r = requests.post(RECOGNIZE_URL, headers=auth(state),
                          files={"url": (None, url)}, timeout=60)
    elif url is None and path:
        with open(path, "rb") as f:
            r = requests.post(RECOGNIZE_URL, headers=auth(state),
                              files={"file": f}, timeout=60)
    else:
        raise ValueError("url must be an http:// or https:// link")
    remaining = r.headers.get("AudD-Credits-Remaining")
    if remaining is not None:
        state["balance"] = int(remaining)
        save_state(state)
    if not r.ok:
        raise AgentError(r)
    body = r.json()
    if body.get("status") == "error":
        error = body.get("error") or {}
        raise RuntimeError(f"AudD error {error.get('error_code')}: {error.get('error_message')}")
    return body.get("result")
```

The recognition endpoint takes the same parameters as our [standard endpoint](/resources/agents/standard-recognition): a `url`, or the clip itself as a multipart `file`. The program sends both as `multipart/form-data`. Text from your user or the model should only be sent as `url`, since a `path` would let them send any file from your server. The endpoint analyzes up to the first 12 seconds of audio, so send the part with the music. The file can be up to 15 MB.

All the answers to requests with a valid key contain the `AudD-Credits-Remaining` header with your balance. The program saves it, so on the next run it knows the balance without asking us. `status: "success"` with `result: null` means the clip was processed and no song matched. Please note that a no-match uses a credit too. If we couldn't process the audio, the answer has `status: "error"` and an `error_code`.

### Step 5: Put it together

```python
def main(audio):
    state = load_state() or register()
    # The command line is yours, so a name that isn't a link is a file you chose.
    # Text from your user or the model goes to recognize() only as url=.
    source = {"url": audio} if audio.startswith(("https://", "http://")) else {"path": audio}
    if state.get("balance") == 0:
        top_up(state)
    try:
        song = recognize(state, **source)
    except AgentError as e:
        if e.code not in ("no_prepaid_requests", "credits_expired"):
            raise
        top_up(state)  # the balance ran out, or the credits expired
        song = recognize(state, **source)
    if song:
        print(f"{song.get('artist')} - {song.get('title')} {song.get('song_link')}")
    else:
        print("No song matched this clip.")
    print(f"Requests left: {state.get('balance')}")


if __name__ == "__main__":
    main(sys.argv[1] if len(sys.argv) > 1 else "https://audd.tech/example.mp3")
```

The program checks the balance it saw last, and a new registration starts at 0. The credits expire 12 months after the last purchase, so the saved balance can be wrong. If there are no requests left, the recognition endpoint answers `402` with `no_prepaid_requests` or `credits_expired`, and nothing is charged. The program then buys and sends the same request again.

Now you can run the program:

```bash
python3 song_assistant.py
python3 song_assistant.py clip.mp3
```

## What you get back

When run, the program should print something like the following:

```text
To add 1,000 music recognition requests to my AudD balance, please pay $5.00 to AudD, LLC here, by card or any other payment method Stripe offers in your country: https://checkout.stripe.com/... (the link works until 2026-11-19 20:08 UTC).
Tears For Fears - Everybody Wants To Rule The World https://lis.tn/NbkVb
Requests left: 999
```

The first line is the sentence for your user, from the `user_message` field. When your user pays, the program prints the song and the requests left.

If there are matches, `song` always contains `artist`, `title`, `album`, `release_date`, `label`, `timecode`, and `song_link`. If you add the `return` parameter to the request, it also has the data you asked for, like Apple Music or Spotify links; see the [result fields reference](/resources/reference/result-fields).

## Paying with a machine payment instead

If the assistant has a wallet that can pay the Machine Payments Protocol (MPP) with the `stripe` method, it can buy without a link. `POST /agent/credits` with `{"packs": N}` answers `402` with a payment challenge; pay it with an MPP client and repeat the request with the `Payment-Authorization` header. The recognition endpoint also answers `402` with a challenge for one pack when the balance is 0. The steps are in [auth.md](https://audd.io/auth.md) and in the [agent notes](/resources/agents/pay-per-request#5-pay-a-402-challenge-yourself). The same rule applies: pay only with a payment method, and up to an amount, that your user has authorized.

## Handling errors

If something goes wrong, the agent API answers with `application/problem+json`, and `AgentError` keeps the `audd.code` and `audd.charged` from the body. The [agent notes](/resources/agents/pay-per-request#9-errors-come-as-applicationproblemjson) group the codes by what to do. These are the ones to plan for:

- **`invalid_token` (`401`)**: the key is unknown, revoked or expired. Mint a new key with the refresh token (see the next section).
- **`no_prepaid_requests`, `credits_expired` (`402`)**: handled in `main`. Nothing was charged.
- **`rate_limited`, `too_many_failed_inputs` (`429`) and the `503` codes**: wait for `Retry-After`. For `too_many_failed_inputs`, fix the input first.
- **`timeout` (`504`)**: recognition didn't finish in time, and it wasn't charged. You can send the request again.
- **`status: "error"`** in a `200` answer: AudD couldn't process the audio. Errors 300 and 19 use a credit; the others are free.

If the request times out on your side, we may have processed it anyway: a cancelled request might still consume requests. So please don't resend it in a loop.

### When the key is lost

Send the refresh token to `/agent/identity` with `{"type": "refresh", "refresh_token": "audd_art_...", "new_api_key": true}`. Every time you use the refresh token, you get a new refresh token, so save the new one before you do anything else. If an old refresh token is used again more than 60 seconds later, every credential of the registration is revoked. The request is in the [agent notes](/resources/agents/pay-per-request#10-manage-the-registration-with-your-key).

## Going further

- **On Android or iOS.** These are plain HTTPS requests, so you can send them from any HTTP client. Show the `user_message` in the chat, and let the user open the link.
- **Show the balance.** `GET https://dashboard-api.audd.io/agent/balance` with the key returns the current balance; check it before a long job. `GET https://dashboard-api.audd.io/agent/usage?from=YYYY-MM-DD&to=YYYY-MM-DD` gives the usage per day.
- **Warn early.** Answers carry `AudD-Credits-Low: 1` when the balance runs low, so the assistant can ask for a new link before it reaches 0.

---

**Related**

- [Agent notes: prepaid requests without an AudD account](/resources/agents/pay-per-request)
- [Agent notes: the standard recognition endpoint](/resources/agents/standard-recognition)
- [Keeping your API token on the server](/resources/concepts/keeping-your-token-server-side)
- [Build a Shazam-style music identification app](/resources/recipes/shazam-clone)
- [auth.md: AudD for agents without an account](https://audd.io/auth.md)

## Sitemap

See the [resources sitemap](https://audd.io/resources/sitemap.md) for every guide and the [glossary](https://audd.io/resources/reference/glossary.md) for AudD terms.
