← All posts

How an AI agent funds and pays for its own API calls

NemanjaFounder @ ApexApi7 min read
How an AI agent funds and pays for its own API calls

An agent that runs out of balance at 3am stops working until somebody wakes up and fills in a payment form. That is the actual failure, and it is not a limitation of agents. It is a limitation of providers who expose funding as a web page rather than as an API call.

Three HTTP calls remove the human from that loop: get a credential, read the balance, top up. This article is the flow, the bounds that make it safe, and the honest list of what still needs a person.

The three calls

Get a credential

curl -s -X POST https://api.apexapi.dev/agent/register \
  -H 'Content-Type: application/json' \
  -d '{"type":"anonymous"}'

No dashboard, no email confirmation, no card. The 201 response contains a working ak- key, a claim token, and a funding URL:

{
  "account_id": "...",
  "api_key": "ak-...",
  "claim_token": "act_...",
  "fund_url": "https://apexapi.dev/fund/aft_...",
  "expires_unless_funded_at": "..."
}

Two things about that response deserve more attention than they usually get.

Store the claim token as durably as the key. It is the only recovery path if the key is lost. An agent that keeps its key in memory and its claim token nowhere has one process restart between working and starting over.

Registration is rate limited to ten per IP per day. That is not a throttle you should be hitting. If your architecture registers a fresh account per task, it is the wrong architecture. One durable account per agent, funded and claimed, is the shape this is built for.

Read the balance

curl -s https://api.apexapi.dev/agent/account \
  -H "Authorization: Bearer $APEXAPI_KEY"

Returns balance_usd, whether the account has been claimed, the funding URL and the expiry. This is the call your top-up loop polls.

An agent already connected over MCP can skip the REST call entirely and use the get_balance tool, since it is talking to the gateway anyway. The MCP reference has the full tool list.

Top up

curl -s -X POST https://api.apexapi.dev/agent/fund \
  -H "Authorization: Bearer $APEXAPI_KEY" \
  -H 'Content-Type: application/json' \
  -d '{"amount_usd": 50}'

The response is a USDC deposit address on Base:

{
  "payment_intent": "pi_...",
  "network": "base",
  "deposit_address": "0x...",
  "token": "usdc",
  "amount_usdc": "50.00"
}

The agent sends the USDC from its own wallet. When the deposit settles on chain the balance is credited, and the agent confirms by polling GET /agent/account until the number moves.

Amounts are whole dollars, with a minimum of $5. Crypto is the rail here for a specific reason rather than as a novelty: a card payment needs a card, a billing address and a form, and it can be reversed months later. An on-chain settlement needs a wallet and a network, both of which a program can have.

The loop, and the race that breaks it

Putting those together is a threshold check and a top-up. The design has three decisions and one bug that everyone writes at least once.

What triggers the check. Elapsed time, request count, or a balance threshold. Threshold-based is usually right, and it costs nothing extra if you read the balance from a response header rather than polling. Every response carries its exact USD cost in the X-ApexApi-Cost header to eight decimal places, so an agent can maintain a running total locally and only call GET /agent/account when its own arithmetic says it is close.

What the increment is. Large enough that you are not topping up constantly, small enough that a compromised agent cannot drain the wallet in one call.

What happens when two threads notice at once. This is the bug. Threads A and B both read a low balance, both fire a top-up, and the account is funded twice. The fix is a distributed lock or an atomic database update, plus an idempotency key on the request so that even if both arrive, one operation is processed.

We enforce a bound on the server side too. Fund intent creation is capped per user per hour, currently twenty. That is not the primary protection, since crediting still requires real USDC to settle, but it stops a loop from opening thousands of live payment intents while you debug the client-side lock.

The bounds that make this safe

Autonomous spending is safe when it is bounded and observable, and reckless when it is neither. Four layers, and they are independent on purpose.

Per-transaction bounds. A single top-up is a whole-dollar amount inside fixed limits. A fat-fingered or hallucinated amount cannot become a five-figure transfer.

Unclaimed account ceilings. An account that has not been linked to a human owner carries lower limits, currently $250 per payment and $500 in total. Claiming removes them. This is deliberate: an anonymous account is one that nobody has vouched for, so it is trusted with less until somebody does.

Per-key spend limits. Separately from funding, the key itself can carry a daily spend limit, a monthly spend limit, a model allowlist and an expiry date. Funding controls how much money enters the account. These control how fast it can leave. Both matter, and a well-configured agent has both. The fields are in the authentication docs.

Wallet exposure. The most important one and the one that is not our feature. The agent's wallet should hold what you are willing to lose, not your treasury. Every other control is software and can have a bug. The wallet balance is the ceiling that holds regardless.

What still needs a human

Being straight about the boundaries, since the interesting part of autonomy is where it stops.

Claiming the account. Linking an agent account to a human owner is a short ceremony involving a code and a person, deliberately. It is what lifts the unclaimed ceilings, and an unclaimed account that goes unfunded is deleted after about thirty days. A funded account does not expire.

Funding the wallet. The agent can move USDC it holds. It cannot decide to acquire more. Somewhere upstream a person decides how much capital this process is allowed to consume, and that is the correct place for that decision.

Anomaly detection. We do not detect unusual agent behavior on your behalf. If you want a spend spike or a request-rate anomaly to trigger something, that logic is yours to write. What we provide is the raw material, per-call cost on every response and per-key limits that fail closed.

Revoking a key programmatically. Revocation is instant but it is a dashboard action rather than a public API call today. If your incident plan assumes an agent can revoke its own credential in response to its own signal, that gap is currently yours to fill. The nearest available substitute is a short expiry on the key so that credentials rotate by aging out.

Audit records worth keeping

Removing the human from the approval loop is not the same as removing them from the visibility loop, and the difference is entirely whether you can answer questions afterwards.

For every autonomous credential or funding operation, record the agent identifier, the triggering condition, the session, a reference to the credential rather than the credential itself, the amount, and the resulting balance. A security or finance person needs to answer four things from those records: what triggered it, which agent executed it, how much moved, and whether it stayed inside policy.

Write them where a person will actually look. An audit trail that lives only in the agent's own log file is not an audit trail, because the first thing a misbehaving agent affects is its own logs.

Is this worth building?

Honestly, not always, and it is worth saying so.

If your agent runs during business hours against a balance somebody tops up monthly, autonomous funding solves a problem you do not have. The setup cost, a funded wallet and a policy, exceeds the cost of occasionally filling in a form.

It earns its place in three situations. Long-running unattended agents where a stall is expensive and nobody is watching. Agents you deploy on behalf of someone else, where you do not want to be in their payment path. And spiky workloads where consumption is unpredictable enough that pre-funding for the peak means leaving a lot of capital idle.

If none of those describe you, prepay a balance and set an alert. The interesting thing about this capability is not that every agent should use it, it is that the option exists at all, and that the constraint was never the agent.

For the credential side of the same problem, how to build an AI agent that manages its own API keys covers generation, rotation and storage. The quickstart covers ordinary key creation if you would rather start there.

Frequently asked questions

Can an AI agent pay for its own API usage?
Only if the provider exposes funding as an API call rather than a checkout page. Most do not, which is the actual blocker rather than anything about the agent. On ApexApi an agent calls POST /agent/fund with a whole-dollar amount, receives a USDC deposit address on Base, and sends the funds from its own wallet. The balance is credited when the deposit settles on chain.
How does an agent get an API key without a human?
POST /agent/register with a body of {"type": "anonymous"} returns a working ak- key and a claim token, with no dashboard, no email and no card. Registrations are capped at ten per IP per day. The claim token is the only recovery path if the key is lost, so it has to be stored as durably as the key itself.
What stops an autonomous agent from spending without limit?
Several bounds, and they should be layered rather than relied on individually. A single top-up is a whole-dollar amount within fixed bounds. Fund intent creation is capped per user per hour. Accounts that have not been claimed by a human carry lower ceilings, currently $250 per payment and $500 in total. On top of that, the agent's own key can carry a daily and monthly spend limit and a model allowlist.
What happens to an agent account nobody ever claims?
An account that stays unfunded and unclaimed is deleted after about thirty days. A funded account does not expire. Claiming an account links it to a human owner through a short ceremony and removes the unclaimed funding ceilings, which is the intended path once an agent is doing real work.
Is autonomous funding safe to turn on?
It is safe when it is bounded and observable, and reckless when it is neither. The goal is removing a human from the approval loop for routine refills, not removing visibility. That means a funded wallet holding only what you are willing to lose, a hard ceiling per top-up, a maximum frequency, and audit records a person can review afterwards.
guidesagentspayments

Recommended

More posts

One API key for every AI model

Start free