Budget enforcement at the middleware level — has anyone explored this? #1977
Replies: 2 comments
|
Budget enforcement at the middleware level is possible and worth exploring. The most practical approach I have seen is to wrap the model client in a middleware that tracks token usage across turns and raises an exception or returns a canned "budget exceeded" response when the cumulative spend crosses a threshold. Here is a minimal sketch: from deepagents import Middleware, ModelRequest, ModelResponse
class BudgetMiddleware(Middleware):
def __init__(self, max_tokens: int):
self.max_tokens = max_tokens
self.spent = 0
async def run(self, request: ModelRequest, call_next) -> ModelResponse:
if self.spent >= self.max_tokens:
raise RuntimeError(f"Token budget of {self.max_tokens} exceeded ({self.spent} used)")
response: ModelResponse = await call_next(request)
if response.usage:
self.spent += response.usage.total_tokens
return responseA few things to think about:
Has anyone tried keying the counter by |
|
We've implements soft and hard limits of tokens per turn that resets on every turn. |
Uh oh!
There was an error while loading. Please reload this page.
The README notes: "Enforce boundaries at the tool/sandbox level, not by expecting the model to self-police."
Agreed — but there's one enforcement problem that's hard to solve at the tool level: concurrent agents sharing a budget.
Two sub-agents check the same balance, both see enough, both proceed. A per-tool check can't prevent this without atomic cross-agent coordination.
The pattern that works: reserve estimated exposure before execution, commit actual usage after, release the remainder on failure. Fits naturally into the middleware lifecycle (before_tool_call → execute → after_tool_call) but the coordination has to live outside the agent process.
Has anyone tackled this on deepagents? Curious whether the middleware system is flexible enough or whether this needs to be a separate server-side concern.
For context, I built an open protocol for this: https://runcycles.io/ — but genuinely interested in how others are approaching the coordination problem.
All reactions