GitHub

AI budgets

Cap the tokens, requests, tool calls and cost of a whole agent run, sub-agents and parallel tool calls included.

pyfect.ai.budget limits what everything under an effect may spend: input, output and total tokens, model requests, tool calls, and cost through a price function you give. effect.pipe(budget.limit(budget.Limits(...))) gives the effect a new budget each time it runs; budget.make(limits) and budget.provide(shared) share one you can read with spent() and held(). The effect can then fail with BudgetExceeded, which fx.catch_tag recovers from. For a time limit, use fx.timeout.

One budget for the whole run

The budget lives in the fiber's context. Forked fibers, concurrent tool calls and an agent run inside a tool's handler all draw from it, whatever LanguageModel they use, so a sub-agent can't slip past its parent's limit. A nested limit or provide draws from its own budget and from every one around it.

A tool call is counted before its handler runs. Here a lead agent delegates eight tasks at once and each sub-agent searches once: sixteen calls, with room for nine. The ninth is the last to be counted, the tenth fails with BudgetExceeded, and that failure interrupts the calls still running, whose finalizers run as with any interrupted fiber:

budget.py
from typing import TypedDict

import pyfect as fx
from pyfect import schema as S
from pyfect import stream
from pyfect.ai import budget, language_model, tool, toolkit
from pyfect.ai.language_model import LanguageModel, ProviderOptions


class Task(TypedDict):
    task: str


# Delegate's handler runs a sub-agent, so it needs a LanguageModel.
Delegate = tool.make("Delegate", parameters=S.Struct(Task), success=S.String).add_dependency(
    LanguageModel
)
Search = tool.make("Search", parameters=S.Struct(Task), success=S.String)
Lead = toolkit.make(Delegate)
Researcher = toolkit.make(Search)

searches: list[str] = []


def search(params: Task, _: object):
    return fx.sync(lambda: searches.append(params["task"])).as_("found it")


ResearchTools = Researcher.to_layer(Search.handler(search))


def delegate(params: Task, _: object):
    # A sub-agent: its requests and tool calls draw from the same budget.
    sub_agent = language_model.generate_text(params["task"], toolkit=Researcher)
    return sub_agent.map(lambda reply: reply.text).pipe(fx.provide(ResearchTools))


LeadTools = Lead.to_layer(Delegate.handler(delegate))


# A scripted model: the lead delegates eight tasks at once, each researcher searches once.
def answer(options: ProviderOptions):
    usage = {"inputTokens": {"total": 9}, "outputTokens": {"total": 4}}
    if any(message.role == "tool" for message in options.prompt.content):
        return fx.succeed([{"type": "finish", "reason": "stop", "usage": usage}])
    name = "Delegate" if options.tools[0].name == "Delegate" else "Search"
    calls = [
        {"type": "tool-call", "id": f"c{i}", "name": name, "params": {"task": f"topic {i}"}}
        for i in range(8 if name == "Delegate" else 1)
    ]
    return fx.succeed([*calls, {"type": "finish", "reason": "tool-calls", "usage": usage}])


Scripted = fx.layer.effect(
    LanguageModel, language_model.make(generate_text=answer, stream_text=lambda _: stream.empty)
)


@fx.gen
def main():
    shared = yield from budget.make(budget.Limits(tool_calls=9))
    outcome = yield from (
        language_model.generate_text("Research these eight topics", toolkit=Lead)
        .map(lambda reply: reply.text)
        .pipe(budget.provide(shared))
        .pipe(fx.catch_tag(budget.BudgetExceeded, lambda error: fx.succeed(str(error))))
    )
    spent = yield from shared.spent()
    print(outcome)
    print("tool calls counted:", spent.tool_calls, "of 16 asked for")
    # The ninth call was counted; the failure interrupted it with the other agents.
    assert spent.tool_calls == 9 and len(searches) <= 1


fx.run_main(main.pipe(fx.provide(LeadTools)).pipe(fx.provide(Scripted)))

Reservations

Calls running in parallel can't overshoot a token or cost limit, because each request reserves its worst case before it is sent. The worst case is an estimate of the prompt's input tokens plus max_output_tokens, which you set to the max_tokens your provider is configured with (a limit on output tokens, total tokens or cost needs it). If the reservation doesn't fit beside what is spent and held, the request fails before the provider is called. When the response arrives, its usage settles the reservation, and what it didn't use goes back.

A request that fails or is interrupted gives its tokens and cost back but still counts as a request. A response without usage spends the whole reservation. The default estimate counts a token per four characters of the prompt, so pass estimate_input_tokens (a function of the ProviderOptions) to count with your provider's tokenizer. Overshoot is possible only when the response uses more than its reservation: more input tokens than estimated, or more output than max_output_tokens.

budget_tokens.py
from decimal import Decimal

import pyfect as fx
from pyfect import stream
from pyfect.ai import budget, language_model
from pyfect.ai.language_model import LanguageModel, ProviderOptions


def price(tokens: budget.Tokens) -> Decimal:
    return tokens.input * Decimal("0.000003") + tokens.output * Decimal("0.000015")


limits = budget.Limits(
    total_tokens=5_000,
    cost=budget.Cost(Decimal("0.05"), price),
    max_output_tokens=1_000,  # the provider's max_tokens: each request reserves it
)
shared = budget.Budget(limits)


def answer(options: ProviderOptions):
    # While the request runs, the budget holds its worst case.
    held = shared.held().map(lambda held: print("held during the call:", held.total_tokens))
    usage = {"inputTokens": {"total": 40}, "outputTokens": {"total": 120}}
    reply = [{"type": "text", "text": "Hi!"}, {"type": "finish", "reason": "stop", "usage": usage}]
    return held.as_(reply)


Scripted = fx.layer.effect(
    LanguageModel, language_model.make(generate_text=answer, stream_text=lambda _: stream.empty)
)


@fx.gen
def main():
    yield from language_model.generate_text("Say hi").pipe(budget.provide(shared))
    spent = yield from shared.spent()
    print("spent:", spent.total_tokens, "tokens,", spent.cost)
    print("still held:", (yield from shared.held()).total_tokens)
    # A long prompt's worst case (5,000 estimated input tokens plus 1,000 output) does
    # not fit what is left, so it fails before the provider is called.
    error = yield from (
        language_model.generate_text("x" * 20_000).pipe(budget.provide(shared)).flip()
    )
    print(error)
    assert (yield from shared.spent()).requests == 1


fx.run_main(main.pipe(fx.provide(Scripted)))

stream_text reserves the same way when its stream starts. It settles from the stream's finish part when the stream ends, fails or is interrupted.

Reference: budget, language_model.