DEV Community

Adebowale Jolaosho
Adebowale Jolaosho

Posted on

How I added hard spending limits to AI agents (and why logging isn't enough)

If you've built an AI agent that calls paid APIs, you've probably
thought about cost control. Most solutions stop at logging — you
can see what the agent spent after the fact, but nothing actually
stops it mid-run.

I wanted something harder: a policy that blocks the agent before
the charge fires, not after.

The problem with callbacks and middleware

LangChain callbacks, OpenAI traces, CrewAI logs — they're all
observability tools. If an agent loops 200 times overnight, the
log shows 200 entries in the morning. The money is already gone.

Even interrupt-based approaches like HumanInTheLoopMiddleware
require you to know upfront which tools are risky. In practice,
agents acquire new tools over time and the interrupt list drifts.

The pattern that actually works

Treat budget as a tool the agent calls before any paid operation:


python
@function_tool
def check_spend(amount: float, category: str = None) -> str:
    """
    Check whether a planned spend is within budget.
    Returns 'approved' or 'denied: <reason>'.
    Never proceed after 'denied'.
    """
    # call your policy engine here
    ...
Enter fullscreen mode Exit fullscreen mode

Top comments (0)