Tracing and budgets
An agent that answers wrongly, or spends more than you expected, is hard to debug from its final answer alone. A trace records what happened on the way: each model call, tool call, search and graph step, as spans in a JSONL file you can read in the terminal or open as an HTML page. Budgets are the other half of keeping a run under control: they stop a run before it spends more than you allow.
Turn tracing on
Tracing is off by default. Call .tracing(true) on an agent or a graph, and build and every run write spans for every category to ./traces/<name>-<trace id>.jsonl. Set $TROUPEKIT_TRACE_DIR to write them somewhere else.
| Method | Meaning | Default |
|---|---|---|
tracing(on) | every category, or off | off |
trace(categories) | only the listed categories; an empty list turns tracing off | off |
trace_content(on) | keep prompt, reply, tool argument, query and document text in spans | off: spans hold only byte counts |
trace_to(sink) | send records to a TraceSink instead of a file | none |
trace_file(path) | write records to the new file path; an existing file is refused at build | none |
By default a span records sizes, not text, so a trace does not write your users' prompts to disk unless you ask for it. Turn on trace_content when you need the text itself. The model's API key is scrubbed either way when .api_key(..), .api_key_env(..) or the vendor's environment variable supplies it. A key that only a custom .model_client(..) holds is not scrubbed, and no other secret in the text is either: with trace_content on, a password a user types into a message is written to the trace as is. Treat a content trace as sensitive data.
There are eleven categories: Agents, Models, Tools, Memory, Knowledge, Graphs, Laws, Evals, Budget, Store and Routing. Pick a few with trace(..) when the full trace is more than you need.
Tracing from the macro
The #[agent] macro takes trace and trace_content as keys; trace_to and trace_file have no macro key. The first agent here traces two categories; the second traces everything:
#![allow(unused)]
fn main() {
/// Echo the user.
#[agent(
model = "fake/m",
trace = [Agents, troupekit::prelude::Trace::Models],
trace_content = false,
private = false,
route = office(),
tier = "large",
)]
fn routed_echo() {}
/// Echo the user.
#[agent(model = "fake/m", trace = all)]
fn traced_echo() {}
}
Persona and workflow TOML files take the same three keys. trace is a list of lowercase category names, such as ['graphs', 'tools'], and trace_content and trace_file work as on the builder.
Read a trace
usage: troupekit trace <file> [--html [OUT]] [--only CATS] [--no-color]
troupekit trace prints the span tree in the terminal, or writes one HTML page with --html. A damaged trace file still opens. When the reader meets a line that is malformed, longer than 1 MiB or nested more than 32 levels deep, it skips the line, counts it and keeps going. It reads at most 1 000 000 records.
Spend limits
A run checks the spend limits you set before every model call, on an estimate of that call's cost: the full max_tokens of output, input counted as a quarter of the request's JSON bytes, and the fee of every hosted web search the call allows. It pauses or fails instead of making a call the estimate says would cross a limit. The input count is approximate, so a token-dense input can cost more than estimated. Limits holds four layers of them. Amounts are in millionths of a US dollar, and None means no limit.
| Field | Limits |
|---|---|
call | one model call |
run | the whole run |
scope | a PeriodLimit for a scope's period, such as a goal's month |
user | a PeriodLimit for the user's period |
The two period limits count spend across runs, which needs a record of what was spent before. That record is the usage ledger. A PeriodLimit names the ledger total it reads with key, such as goal:42, and the cap with max_usd_micros; the ledger decides how long the period is.
In this test, the ledger already holds spend for user-1. We cap that user below it and run a graph, and the run pauses or fails without making the call:
#![allow(unused)]
fn main() {
let capped = troupekit_agent::Limits {
user: Some(troupekit_agent::PeriodLimit {
key: "user-1".into(),
max_usd_micros: 10,
}),
..Default::default()
};
let result = Graph::new("g")
.agent("draft", drafter())
.limits(capped)
.ledger(ledger.clone())
.run("hi")
.await;
assert!(
matches!(
result,
Err(KitError::Paused { .. } | KitError::Failed { .. })
),
"{result:?}"
);
}
Warning
An agent's default ledger lives in memory and is lost on restart. If several agents share a cap, or the cap must hold across restarts, pass them one durable ledger, such as the SQLite store's.
Before each call a run holds the call's estimate under the scope and user keys until the call's cost is recorded, and admissions on one ledger take turns, so runs in one process that share a ledger cannot both take the last room under a cap. A call can still cost more than its estimate. Runs in separate processes, or on two ledgers opened over the same store, do not see each other's holds, so the cap is not enforced across them. Use one process per shared cap (issue #79).
Limits can also come from other places. A persona's budget = { call_usd = 0.05, run_usd = 0.5 } is combined with the limits set in code, and for call and run the stricter of the two wins. A route policy's [budget] cloud_usd_per_day caps remote spend per day: once it is reached, the policy skips the remote targets and stays local. And a hosted graph run that paused on its budget continues once you call Runner::raise_budget(run_id, limits).