Skip to main content

Controlling cost

Every model call is billed by the token. Freyja reports what each run spent, stops a run or a whole request at a limit you set, and prices the spend in dollars from your price list. Two features lower the bill itself: prompt caching and batches.

Run usage​

Every Run has usage, the sum across every model call the run made, and turns, the number of requests. A provider that reports no usage counts as zero. Tokens that tools spend on models of their own are included, as covered below.

use freyja::{Agent, Client, EndpointPreset};

// Connects to Anthropic with the key in ANTHROPIC_API_KEY.
let agent = Agent::new(Client::from_env(EndpointPreset::Anthropic)?);

let run = agent.ask("What is 20 + 22?").await?;
println!("{} in, {} out", run.usage.input_tokens, run.usage.output_tokens);

Token budget​

Agent::token_budget(n) bounds what one run spends. After each model call the agent adds that call's total_tokens to the run's sum, and once the sum reaches n the run ends with StopReason::OverBudget before any requested tool runs. The answer is that last call's text. Each run starts from zero, so a conversation's second message has the whole budget again.

let run = agent.token_budget(20_000).ask("Summarise the repo").await?;
if run.stop == StopReason::OverBudget {
println!("spent {} tokens, stopped early", run.usage.total_tokens);
}

The budget is checked again after a turn's tools. When tools take the run over, they have already run and no further model call is made.

A budget for a whole request​

token_budget bounds one agent's run. A Budget bounds everything a request spends. Make one with Budget::tokens(n), put a clone in the Context and send with .context(&cx). Clones share one count, so the agent, every helper made with into_tool, every team member and every resumed run charge the same budget.

use freyja::{Budget, Context, StopReason};

let budget = Budget::tokens(50_000);
let mut cx = Context::new();
cx.insert(budget.clone());

let run = chat.send("Summarise the repo").context(&cx).await?;
if run.stop == StopReason::OverBudget {
println!("spent {} of {} tokens", budget.spent(), budget.limit());
}

It differs from token_budget in three ways. It is shared, where token_budget belongs to one agent and each run starts from zero. It is checked before every model call, so a run that starts with the budget already spent makes no call and returns OverBudget with zero turns. And when both are set, the smaller one stops the run.

The limit applies to calls that have not started. A call already in flight finishes and is charged, so the total can pass the limit by what those calls spend, but never by a new call.

Reuse one Budget across requests and it becomes a running cap, such as a daily limit per user. It counts total_tokens, lives in this process and is not saved to storage. spent, remaining, limit and is_spent read the count.

Helpers and members charge themselves. A tool that calls a model itself charges its usage with Budget::charge, read from the context:

if let Some(budget) = cx.get::<Budget>() {
budget.charge(&usage);
}

Tool tokens​

A tool that calls a model of its own spends tokens the agent would not otherwise see. Tool::call_metered is the method the agent calls, and it returns a MeteredFuture, a boxed future of the result and an Option<Usage>. The default runs call and reports nothing. A tool that spends tokens overrides it and returns the usage:

fn call_metered<'a>(&'a self, arguments: &'a str, cx: &'a Context) -> MeteredFuture<'a> {
Box::pin(async move {
let (text, usage) = self.ask_inner_model(arguments).await;
(Ok(text), Some(usage))
})
}

ask_inner_model stands for your own code. The agent adds the reported usage to run.usage and counts it against token_budget. A wrapper around another tool must forward call_metered as well as call, or the wrapped tool's tokens go uncounted. Agent::into_tool reports its inner run this way. See Reporting tokens.

Computing cost​

Freyja knows no prices, because they change and differ by provider. A Cost takes yours and totals what a request spends in dollars. Give it a default price per million input and output tokens, and an override for each model you use:

use freyja::{Context, Cost, StopReason};

let cost = Cost::per_million(2.00, 8.00)
.model("gpt-5-nano", 0.05, 0.40)
.model("claude-haiku-4-5", 1.00, 5.00)
.limit(0.50);
let mut cx = Context::new();
cx.insert(cost.clone());

let run = agent.ask("Summarise the repo").context(&cx).await?;
println!("${:.4}", cost.spent());
if run.stop == StopReason::OverBudget {
eprintln!("hit the $0.50 limit");
}

The rates above are placeholders. Use your provider's current price list.

Each model call is priced by the model id the response reports. An override applies to every id that starts with it, so gpt-5-nano also prices gpt-5-nano-2025-08-07, and when several match, the longest wins. Anything unmatched gets the default price. A helper or a team member on a different model is priced at its own rate.

Like a Budget, clones share one total, so the agent, its helpers, team members and resumed runs all add to it. limit is optional. Without it, a Cost only counts. With it, a run stops with StopReason::OverBudget before its next model call once the limit is reached, and a call already in flight finishes and is charged. spent and remaining read the total, and is_spent says whether the limit was reached.

The total is an estimate. Input read from the provider's prompt cache is priced at a tenth of the input rate, and input written to it at a quarter more, which are Anthropic's rates. Reads cost about a tenth on OpenAI and Gemini too, though it varies by model. Gemini reports no writes, and OpenAI does, so if your OpenAI price list charges writes as plain input, use .cache_rates(0.1, 1.0). Both are fractions of the input price. A tool that calls a model itself adds its usage with cost.charge(model, &usage), read from the context.

Reuse one Cost across requests and it becomes a running spend per user or per day. It lives in this process and is not saved to storage.

Paying less​

Prompt caching reads a prompt the provider has seen recently at about a tenth of the input price. Freyja asks Anthropic to cache every request, and OpenAI and Gemini cache on their own, so a conversation's earlier turns and a long system prompt are already cheaper from the second request on. run.usage.cached_input_tokens shows how much was read from cache. See Prompt caching.

Batches run requests that can wait up to a day at half price on OpenAI and Anthropic. Cost tracking charges full price for them, so halve the total.