Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Budgets across runs

The spend limits from the beginner lessons work inside one run. They cannot stop a user who runs the agent a thousand times, two cents at a time. For that you need a cap that remembers what was spent before: per user, per customer, per goal. And it has to survive a restart, or a deploy resets everyone's budget to zero.

Troupekit calls the memory of past spend a usage ledger. This lesson keeps one in a SQLite file and caps one user with it.

A cap with a key

#![allow(unused)]
fn main() {
async fn helper(store: Arc<SqliteStore>) -> Result<BuiltAgent, KitError> {
    Agent::new("helper")
        .model(MODEL)
        .instructions("Answer in one short sentence.")
        .max_tokens(256)
        .max_turns(2)
        .limits(Limits {
            run: Some(5_000),
            user: Some(PeriodLimit {
                key: ADA.into(),
                max_usd_micros: CAP,
            }),
            ..Limits::default()
        })
        .ledger(store)
        .build()
        .await
}
}

Two new things. user: Some(PeriodLimit { .. }) adds a cap that spans runs. Its key, here "user:ada", names the total in the ledger it reads, and max_usd_micros is the cap, 300 millionths of a dollar in this example so you can watch it bite in a few runs. Your code picks the key, the same way it picked the user for memory.

.ledger(store) says where totals live. An agent's default ledger is in memory and starts at zero on every restart, which is fine for a test and wrong for a budget. SqliteStore is a ledger too: it keeps one running total per key in its file. Before every model call the run estimates the call's cost: the full max_tokens of output, and input counted as a quarter of the request's JSON bytes. It checks the ledger total plus that estimate against the cap, and pauses if the sum is over. When the call fits, the run holds its estimate under the key in the same step, so the next check counts it. After the call the run adds the actual cost under the key and lets the hold go.

Runs in one process that share this ledger take turns at that check, so two of them cannot both take the last room under the cap. The cap is still not exact. Input is an estimate, so a call can cost more than its hold. And holds live in one process: runs in separate processes, or on two ledgers opened over the same file, do not see each other's holds, so the cap is not enforced across them. Use one process per shared cap (issue #79).

Spending down a budget

#![allow(unused)]
fn main() {
for run in 1..=12 {
    let spent = store.period_total(ADA).await?;
    match agent.run_with("Name one thing a spend cap protects.").await {
}

Each turn of the loop reads ada's total from the ledger, then runs the agent once. While the estimate of the next call fits under what is left, the run answers. When it does not, the run pauses before calling the model:

#![allow(unused)]
fn main() {
Err(KitError::Paused { reason, .. }) => {
    println!(
        "run {run}: ada had spent {spent} of {CAP}; paused before the call: {reason:?}"
    );
    return Ok(());
}
}

and reason names the user layer.

Try it, twice

cargo run -p troupekit --example course_shared_budget

The first start prints a few runs, each with ada's total so far and what the run cost, and then a pause. Notice that the pause comes while there is still a little budget left: the next call's estimate no longer fits.

Now run the same command again. This time the very first run pauses. Nothing in the program remembers ada; the file does. That is the property you want from a budget, and the reason the default in-memory ledger is not one. To start over, delete course-ledger.db from your temp folder, or point COURSE_LEDGER_DB at a new file.

Sharing one ledger

Several agents can share one ledger and one key, which is how you cap a whole team of agents working for one customer. The team lesson in the applications level does exactly that. The scope layer works like user with its own key, for a cap per goal or per project, and both are checked before every call.

This is the end of the advanced level. You can now build an agent whose runs survive a crash and whose spend is capped per user across restarts. The last level puts it all together in applications.

Next: Build a support agent with knowledge.