relayted blog

For agents

Pay-per-request APIs for AI agents: one prepaid balance instead of sign-up forms

apiPublished Updated 3 min read
Pay-per-request APIs for AI agents: one prepaid balance instead of sign-up forms

Short answer

With the relayted API an agent uses one key and one prepaid balance for three services: web pages as Markdown, text, HTML or PDF (websitepro), screenshots in real browsers (shots) and Nostr relay tests (labs). Prices are fixed per delivered item in Payloads (10,000 Payloads = 1 EUR), a free quote shows the cost before anything is charged, undelivered items are refunded automatically, and the balance is topped up from 0.25 EUR via Lightning.

The problem with sign-up forms

Most APIs expect a person to register, confirm an e-mail address, choose a plan and store a credit card before the first request. An agent cannot do any of that, and a monthly plan is a poor fit for work that comes in bursts. What an agent needs is simpler: a key, a balance, a price it can check before it buys, and an error it can act on when the money runs out.

How the relayted API works

Every service follows the same three steps: optional free quote, create the job, download the results.

ServiceEndpointWhat the agent gets
websiteproPOST /v1/websitepro/jobsA web page as Markdown, text, sanitised HTML, metadata JSON or PDF
shotsPOST /v1/shots/jobsScreenshots in real desktop browsers and mobile profiles
labsPOST /v1/labs/jobsA JSON report on a Nostr relay (Quick Check or NIP-01 conformance)

Check the price before buying

POST /v1/<service>/quote takes exactly the body of the job and costs nothing. It returns cost, the items with their prices, the current balance and sufficient (true or false). An agent can use it as a budget guard: quote first, compare with its own limit, then buy.

Running out of balance

If the balance is too low, the job request answers 402 with the error code insufficient_funds, and nothing is created or charged. Every error has the same shape, {"error":{"code":"...","message":"..."}}, so the agent branches on code, not on text. 429 rate_limited and 503 busy mean: wait and try again.

Safe retries with Idempotency-Key

Networks drop responses. If an agent repeats a purchase after a timeout, it must not pay twice. Send your own unique Idempotency-Key header with POST /v1/<service>/jobs (and POST /v1/topups). Repeating the identical request with the same key returns the first job, with the header Idempotent-Replayed: true, instead of creating a new one. Keys are kept for 24 hours; use a new key for every new purchase.

A tool function for an agent

This Python function, standard library only, wraps the pattern: quote, check a budget, buy with an idempotency key, wait for the result. An agent framework can expose it as a tool.

import json, os, time, uuid, urllib.request, urllib.error

API = "https://api.relayted.de/v1"
KEY = os.environ["RELAYTED_KEY"]

def _call(method, path, body=None, headers=None):
    h = {"Authorization": "Bearer " + KEY, "Content-Type": "application/json"}
    h.update(headers or {})
    req = urllib.request.Request(API + path, method=method, headers=h,
        data=json.dumps(body).encode() if body is not None else None)
    try:
        with urllib.request.urlopen(req, timeout=60) as r:
            return r.status, json.loads(r.read() or b"{}")
    except urllib.error.HTTPError as e:
        return e.code, json.loads(e.read() or b"{}")

def buy(service, body, max_payloads=1000):
    """Run one relayted job. Returns the finished job or an error dict."""
    status, quote = _call("POST", "/%s/quote" % service, body)
    if status != 200:
        return {"error": quote.get("error", {}).get("code", status)}
    if quote["cost"] > max_payloads:
        return {"error": "over_budget", "cost": quote["cost"]}
    if not quote["sufficient"]:
        return {"error": "insufficient_funds", "cost": quote["cost"], "balance": quote["balance"]}
    idem = {"Idempotency-Key": str(uuid.uuid4())}
    for attempt in range(3):                      # same key on every retry
        status, res = _call("POST", "/%s/jobs?wait=20" % service, body, idem)
        if status in (409, 429, 503) or status >= 500:
            time.sleep(5)
            continue
        break
    if "job" not in res:
        return {"error": res.get("error", {}).get("code", status)}
    job = res["job"]
    while job["status"] in ("queued", "processing"):
        job = _call("GET", "/jobs/%s?wait=20" % job["id"])[1]["job"]
    return job

# Example: read a page as Markdown, at most 100 Payloads
job = buy("websitepro", {"url": "https://example.com", "outputs": ["markdown"]}, 100)

The finished job lists its results; each delivered result has a download url that is fetched with the same Authorization header. The job also reports cost, refunded and charged, so the agent can keep its own ledger. Balance, job status, price list and quotes are free; GET /v1/transactions returns the ledger, newest first.

Machine-readable entry points

Topping up

The balance is topped up with Bitcoin Lightning from 0.25 EUR, on the account page or by the program itself with POST /v1/topups (it returns a Lightning invoice; the balance is credited once it is paid). Businesses that need an invoice top up by PayPal or bank transfer on the business page. Limits: 600 jobs per hour and key, request bodies up to 64 KB, only public targets.

FAQ

Can an agent create its own API key?

No. A person creates the key once in a browser at https://api.relayted.de/account. There is no API call that creates, lists or returns keys. The agent then only needs the key and the balance.

How does the agent know what a request will cost?

POST /v1/<service>/quote with the same body as the job. It is free and returns cost, the price of every item, the current balance and whether it is sufficient.

What happens when the balance is too low?

The job request answers 402 insufficient_funds and nothing is created or charged. After a top-up the agent can send the same request again.

How do retries work without paying twice?

Send an Idempotency-Key header with POST /v1/<service>/jobs and POST /v1/topups. Repeating the identical request with the same key within 24 hours returns the first job or top-up instead of creating a new one.

Is there a machine-readable description of the API?

Yes: https://api.relayted.de/llms.txt (plain-text instructions for LLMs and agents), https://api.relayted.de/openapi.json and the price list https://api.relayted.de/v1/pricing.