Skip to content
PodSubs
ShowsPeopleGuestsJobsNewsEvents
More
BlogPodCred
Menu
ShowsPeopleGuestsJobsNewsEventsBlogPodCredNetworksSign in
Join nowSign in
  • Shows
  • People
  • Jobs
  • News
  • More
    • Guests
    • Events
    • Blog
    • PodCred
    • Networks
    Join nowSign in

The AI Practitioner Podcast

The AI Practitioner Podcast artwork

PODCAST — LLM Cost Prediction: From Single Prompts to Agentic Systems

Sep 2, 202613 minAudio
ShareXLinkedInFacebookWhatsAppEmail

Prefer reading instead? The full article is available here. The podcast is also available on Spotify and Apple Podcasts. Subscribe to keep up with the latest drops. LLM costs are easy to calculate after execution, but estimating them before a prompt or agent actually runs is a much harder problem. In this episode, the focus is on predicting LLM and agent costs before execution, from estimating output length for a single model call to reasoning about the much more variable execution paths of AI agents. You’ll learn: * What can be predicted from a prompt before execution? Exploring how token consumption, output length, and model cost can be estimated before sending a request to an LLM. * Can an agent’s cost be estimated before execution? Understanding the additional uncertainty introduced by multiple model calls, tool calls, retries, reasoning steps, and variable execution trajectories. * What Python tooling is available today? Reviewing practical libraries and approaches for estimating and calculating LLM and agent costs, including LiteLLM, genai-prices, tokencost, and tiktoken. 👉 Enjoyed this episode? Subscribe to The AI Practitioner to get future articles and podcasts delivered straight to your inbox: aipractitioner.substack.com Get full access to The AI Practitioner at aipractitioner.substack.com/subscribe

Audio and video play straight from the show's own hosting. PodSubs stores and serves no media.

Transcript

From the show. Tap a time to play from there.

[music]

SPEAKER_02Welcome back to The AI Practitioner. I'm Lina Faik, ML Engineer, Consultant and Lecturer in Advanced Machine Learning at Sorbonne University. I help companies turn their data into real outcomes with AI and this is where I share what I learn from actual projects. The deep technical write-ups live on Substack at AIPpractitioner.substack.com and these conversations are the audio companion. Today I'm joined by Priya, who spends her days building agent tooling for a mid-sized platform team

SPEAKER_02and has very strong opinions about surprise bills.

SPEAKER_01Guilty as charged. So what's on the table today?

SPEAKER_02Picture this. A few months back, I'm on a call with a client rolling out an agent for customer support. Midway through, their finance lead asks me a completely reasonable question, how much is this going to cost per ticket? And I realize I genuinely don't know. Not until it actually runs.

SPEAKER_01Ouch.

SPEAKER_02And that's the strange thing about LLM costs. Once something has run, measuring it is trivial. You know the tokens, you know the price, you multiply. Predicting it beforehand is a completely different problem.

SPEAKER_01But you already know the price per token from the provider's pricing page. Isn't this just multiplication once you know the tokens?

SPEAKER_02That's the catch. You only know half the tokens in advance. The prompt already exists, so the input side is fully known. You can tokenize it right now. The output hasn't been generated yet. Nobody knows how long the response is going to be until the model actually writes it.

SPEAKER_01Okay, I'll admit the first time I saw one of our bills, I assumed someone had added an extra zero by mistake.

SPEAKER_02It happens to everyone. And it's not just an accounting annoyance. In production, if a serving system doesn't know how long a response is going to be, short requests end up stuck waiting behind massive ones. There's a name for it, head of line blocking. So getting even a rough sense of output length in advance changes how well the whole system runs, not just the invoice at the end of the month.

SPEAKER_01Wait, so this isn't just my finance leads problem, it's an infrastructure problem too.

SPEAKER_02Exactly, it's both. The billing side is what most people think of first, but for anyone actually serving the model, the scheduling side is arguably the bigger deal.

SPEAKER_01So where do people even start guessing that?

SPEAKER_02What? There are three families of methods, and what I like about all three is they only look at the prompt, no peeking inside the model, which means they work even with closed APIs like the big hosted providers. The first is almost embarrassingly direct, you ask the model to predict the length of its own answer before it writes the answer.

SPEAKER_01Wait, that's an extra call to the model. Aren't you spending money to guess how much you're about to spend?

SPEAKER_02Exactly the catch. It's actually pretty accurate. In the best setup, off by only around 20 words on average. But the moment you separate the prediction from the generation so the model can't peek at its own upcoming answer, the error roughly quadruples. And either way, you've paid for an extra round trip before the real request has even started.

SPEAKER_01So is that even worth doing at that point?

SPEAKER_02For serving infrastructure, sometimes yes. One paper found that using these length predictions to schedule requests, put similar length ones together, prioritize the short ones, boosted inference throughput by 86%. That's a lot of extra capacity from just organizing the queue better.

SPEAKER_0186% is not a rounding error.

SPEAKER_02Not at all. So that's why the other two approaches exist. They try to get something similarly useful without paying for a whole extra model call. The second approach trains a small, cheap classifier, something like Distalbert, On historical prompts paired with how long their responses actually turned out to be. Instead of predicting an exact number, it sorts the new prompt into one of several length buckets. The third does something similar but predicts the number directly instead of a bucket using a regression model.

SPEAKER_01And how good are those realistically?

SPEAKER_02It depends enormously on how similar your prompts are to each other. On Alpaca, a well-known set of instruction-following examples that all look fairly alike, the classifier gets it right well over 90% of the time. Move to a much broader, more varied corpus, something like a huge grab bag of web pages, books, and code, and accuracy drops to somewhere around two-thirds. Response length is easy to guess when your traffic looks alike, and hard when it doesn't.

SPEAKER_01Makes sense. If everyone's asking roughly the same kind of question, the shape of the answer is roughly the same, too.

SPEAKER_02Exactly that intuition. The regression version does a bit better on realistic, diverse conversation data pulled from real usage logs, but even the strongest variant is right maybe six times out of ten, once you map it back onto length categories. I won't get into the different loss functions each variant uses, that comparison's in the article.

SPEAKER_0160% doesn't sound like much to build a business decision on.

SPEAKER_02It isn't on its own. But compare it to guessing blind. With five roughly equal buckets, that's one right answer in five. Six in ten is a real signal. Just not something you'd want to bet an exact client invoice on.

SPEAKER_01Okay, so all of this so far is guessing from the outside. Just reading the prompt like anyone else would.

SPEAKER_02Yeah, and that's actually the boundary to the next set of methods. If you have real access to the model, meaning you're running your own serving infrastructure rather than calling someone else's API, there's another signal available. What's happening inside the model as it reads your prompt? Its hidden states.

SPEAKER_01Hold on, that's not most people's situation, though. If I'm calling a hosted API, I don't get any of that.

SPEAKER_02Fair, this branch is really for teams running their own models, but there are plenty of those, especially anyone doing high volume serving, and it's a meaningfully bigger jump in accuracy. One method updates its length estimate after every single generated token, essentially watching the model's internal state evolve in real time and refining the guess as it goes. Compared to a prompt-only guesser, that cuts the error by more than half.

SPEAKER_01So it gets more confident the further into the answer it gets, kind of like finishing someone's sentence.

SPEAKER_02That's a good way to picture it. A newer method pushes the prediction even earlier, before a single output token has been written, by looking at how uncertain the model is at each position while it's still just reading the prompt. Positions where the model is torn between a lot of possible continuations turn out to carry more information about how long the eventual answer will be.

SPEAKER_01That's kind of elegant, using the model's own confusion as the signal.

SPEAKER_02True, and then the newest twist on that argues uncertainty alone isn't the whole story. Some words are predictable, but still hugely important, like tests in give me a complete implementation with tests. So it adds a second signal, roughly how much attention other tokens pay to a given word, and combines the two. That pushes the error down further still, on the order of another 15 to 20% lower error than the entropy-only version.

SPEAKER_01So it's not just where the model is confused, it's where the model is confused about something that actually matters.

SPEAKER_02Exactly. And I won't walk through the pooling math on air. It's laid out step by step with diagrams in the article.

SPEAKER_01Okay, this is all still single call stuff though. What about the actual agent problem from your story at the top?

SPEAKER_02Yeah, this is where it gets genuinely hard. A coding agent doesn't make one call. It plans, calls tools, reads the results back into its own contexts, sometimes retries a failed step. So now two things are uncertain at once, how many steps it'll take, and how expensive each step becomes as the context keeps growing.

SPEAKER_01How uncertain are we talking, concretely?

SPEAKER_02There's a study that ran the same task through the same coding agent four separate times, on 500 real, verified GitHub issues across eight different frontier models. Same task, same model, same setup. Token consumption varied by up to 30 times between runs, and overall, agentic coding tasks like these use roughly a thousand times more tokens than a simple one-off coding request.

SPEAKER_01A thousand times more just from letting it loop.

SPEAKER_02Right. And here's the part that really surprised me. Spending more tokens on a task didn't reliably mean a better outcome. And how hard a human would rate the task barely correlated with how many tokens it actually burned.

SPEAKER_0130 times? For the identical task?

SPEAKER_02Yeah. Most of that comes from the input side too, repository content, prior messages, and tool results all get folded back into the context and reread on every step. And when they asked the model to predict its own future token usage before it even started working, the correlation between predicted and actual was weak, around 0.4. Models mostly underestimated how much they'd end up using too.

SPEAKER_01So if it's basically that unpredictable, why bother trying to estimate it at all?

SPEAKER_02That's the right question, and there's a paper that reframes it in a way I really like. Instead of asking what will this whole task cost up front, ask a narrower question partway through the run. Given how far the agent has gotten, does finishing still look feasible?

SPEAKER_01Like a sunk cost check mid-flight.

SPEAKER_02Exactly that. And it turns out that question is much easier to answer than an exact number. They compared two things, predicting whether the agent can still succeed within budget versus predicting the precise remaining budget it'll need. The feasibility question jumped from around a quarter correct to roughly 90% correct after training. The precise budget number stayed hard, under 50% coverage even with all that extra work.

SPEAKER_01So we're probably not going to make it is a much easier thing to know than we're going to run out in exactly 4,000 tokens.

SPEAKER_02Exactly. And the payoff of tracking that easier signal is real. If you cut a trajectory off the moment it looks infeasible, you save well over half the tokens you'd have burned on runs that were doomed anyway, while barely denting your overall success rate. A few percentage points, not a collapse.

SPEAKER_01That's a big deal for anyone running agents at scale.

SPEAKER_02It is, especially once you're running thousands of these a day, and a chunk of them are quietly burning budget on tasks that we're never going to finish.

SPEAKER_01So the answer isn't predict the invoice in advance, it's build a kill switch.

SPEAKER_02That's a great way to put it, yeah. Cost prediction for agents turns out to be more useful as something that runs during execution than as a number you quote before you start.

SPEAKER_01Okay, with all this research, I have to assume there's a Python library that just does this for me by now.

SPEAKER_02Ha, no, not really. And that gap is kind of the point of the last part of the article. What's out there today is genuinely good at a different job, counting tokens you already have and turning known usage into a dollar figure, not forecasting what hasn't happened yet.

SPEAKER_01What's actually out there, concretely?

SPEAKER_02A handful of libraries, each solving a slice of it. One just counts tokens for a specific provider's only encodings. Another layers cost calculation on top of token counts across several providers. A broader one normalizes usage across many providers at once, handling things like cash tokens, reasoning tokens, tool schemas. And a newer one focuses purely on being a structured pricing engine that maps usage records to pricing rules. There's a full side-by-side comparison of what each one does and doesn't handle in the article.

SPEAKER_02I won't read out a table on air.

SPEAKER_01That's a lot of overlapping options for one job.

SPEAKER_02It is, and most teams end up combining two or three of them depending on which providers they're mixing. There are also provider-native token counters now, APIs the vendors themselves expose to count input tokens before you call the model at all, which handle tool schemas and message formatting more accurately than a generic tokenizer.

SPEAKER_01So even the tooling agrees with the research. We're good at accounting for what happened, bad at forecasting what hasn't.

SPEAKER_02That gap is exactly what makes this space interesting to watch right now.

SPEAKER_01So if I'm sitting at my desk Monday morning and I actually want to get a handle on my own agent's costs, where do I start?

SPEAKER_02For a single call, start with the token counting your provider already gives you on the input side, that part is fully solved today. For the output side, don't expect precision, expect a rough envelope, especially if your prompts are varied. And for agents, stop chasing one upfront number entirely. Put a check partway through the run that asks whether finishing still looks worth it, and treat that as your real cost control.

SPEAKER_01That's a pretty different mental model from just quote me a price.

SPEAKER_02It is. All the papers, the code, the exact numbers behind everything we covered, that's all up on Substack at AIPPractitioner.substack.com, links in the caption. And if there's one thing I'd want to leave people with, it's this. Right now, the honest answer to what will this cost is often, I don't know exactly, but I'll know quickly whether it's still worth continuing. For a lot of production systems, that turns out to be the more useful answer anyway.

Open the transcript file

Hosts and Guests

Nobody is credited on this episode yet.

Credit the people on this episode

Be the first to rate this episode

More episodes

All episodes
  1. PODCAST — Beyond Static Prompts: Building Self-Improving LLM Agents with ACE

    Nov 19, 202611 minAudio

    Prefer reading instead? The full article is available here. The podcast is also available on Spotify and Apple Podcasts. Subscribe to keep up with the latest drops. What if AI agents could learn from every interaction...

    Credit the people on this episode

  2. PODCAST — Inside GEPA: Evolving LLM Agent Prompts with Reflective Feedback

    Nov 11, 202611 minAudio

    Prefer reading instead? The full article is available here. The podcast is also available on Spotify and Apple Podcasts. Subscribe to keep up with the latest drops. What if AI agents could continuously improve their...

    Credit the people on this episode

  3. PODCAST — TextGrad in Practice: Optimizing LLM Agent Prompts with Textual Gradients

    Nov 3, 202615 minAudio

    Prefer reading instead? The full article is available here. The podcast is also available on Spotify and Apple Podcasts. Subscribe to keep up with the latest drops. What if AI agents could improve their own prompts...

    Credit the people on this episode

  4. PODCAST — Continuously Optimizing AI Agent Prompts in Production

    Oct 28, 202615 minAudio

    Prefer reading instead? The full article is available here. The podcast is also available on Spotify and Apple Podcasts. Subscribe to keep up with the latest drops. What if the key to better AI agents isn’t writing...

    Credit the people on this episode

  5. PODCAST — From Prompt Engineering to Harness Engineering: Where the Real Leverage Moved

    Oct 16, 202613 minAudio

    Prefer reading instead? The full article is available here. The podcast is also available on Spotify and Apple Podcasts. Subscribe to keep up with the latest drops. What if improving an AI agent’s performance had less...

    Credit the people on this episode