Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 7

Managing LLM Costs: Tokens and Dollars

Recommended resources

Welcome to the final lesson in our foundational module on LLMs. In our last session, we mastered how to stream responses to create a fluid user experience. While this makes your application feel fast, it doesn't change the underlying cost. For an AI agency, managing operational costs isn't just a technical detail—it's a critical business function that determines profitability and pricing.

This lesson will equip you to answer the crucial question: "How much does this AI feature actually cost to run?" We'll move beyond the simple cost = tokens × rate formula to uncover the full picture of LLM expenses. Your goal is to be able to estimate, monitor, and control the costs of the agents you build, a non-negotiable skill for delivering production-grade services to clients.

To frame our discussion, consider the cost of an LLM call like an iceberg.

This iceberg metaphor illustrates that the simple token-based pricing formula is just the visible tip. Many complex and often "hidden" factors contribute to the true cost of using an LLM.

Today, we'll explore what lies both above and below the water line, ensuring you can navigate LLM costs with confidence and avoid any surprise bills.

The Unit of Cost: What Exactly is a Token?

Everything in the world of LLM pricing revolves around tokens. But what are they? An LLM doesn't read text as words or characters; it reads it as a sequence of tokens. A token can be a whole word, a part of a word (like ing), a punctuation mark, or even a space.

Different models use different "tokenizers" to split text, which is why the same prompt can result in a different number of tokens—and a different cost—depending on the provider. Since you're building in TypeScript, the best way to develop an intuition for this is to see it in code.

Most devs don't understand how LLM tokens work

This excellent video from Matt Pocock breaks down the concept of tokens, using TypeScript and the js-tiktoken library to make it tangible. It perfectly explains why costs can vary between providers for the exact same input.

Please watch the following segments: Cost Calculation Basics: Start from 0:35 to 2:06. This section introduces the core idea: you're billed for both input and output tokens, and often at different rates. It also demonstrates how to get usage data from the API response in TypeScript. Encoding and Decoding: Next, watch from 2:17 to 4:47. Here, you'll see the process of encoding text into a series of numbers (tokens) and decoding them back, using a practical js-tiktoken example. Tokenizer Training: Finally, watch from 4:59 to 9:47. This part explains how tokenizers are built and the trade-offs involved. It clarifies why some text is more "expensive" to process, a key insight for cost optimization. For instance, less common languages or even specialized coding languages can result in more tokens.

The video makes it clear that tokens are the fundamental unit. As a developer, you need to be aware of what kind of text is "token-heavy."

An LLM API call, in 4 GIFs - DEV Community

This article provides a concise, developer-focused summary of what makes certain types of text more expensive.

Read the section titled 3. Tokens. Pay attention to the "surprises" it lists: Code and JSON are expensive: Every bracket, comma, and space can be its own token. This is highly relevant when you start defining complex tool schemas for your agents. Non-English costs more: The training data for most tokenizers is English-heavy, so other languages are often tokenized less efficiently. The rule of thumb: For English, you can estimate ~1 token ≈ 4 characters ≈ 0.75 words. This is useful for quick, back-of-the-napkin calculations.


From Tokens to Dollars: Calculating the Cost

Now that you understand what tokens are, let's connect them to your bill. Every modern LLM provider's API response includes a usage object that tells you exactly how many tokens were processed.

The basic cost formula is:

Note that prices are almost always quoted "per million tokens" (or sometimes per 1K tokens). The most important part of this formula is the cost asymmetry: output tokens are typically 3-5 times more expensive than input tokens. This is because generating output requires significantly more computation than simply reading the input.

An LLM API call, in 4 GIFs - DEV Community

Let's return to the same article to see how this looks in a real API response and what the financial implications are.

First, quickly review the section The response to see exactly where the usage object is located. Then, read the section titled 4. The bill, which visualizes the cost asymmetry and provides the complete cost formula.

In your Node.js code, after a non-streaming API call (or after a stream is complete and you have the final response object), you would access this like so:

// Example using OpenAI's SDK
import OpenAI from 'openai';

const openai = new OpenAI();

async function main() {
  const completion = await openai.chat.completions.create({
    messages: [{ role: 'user', content: 'Tell me a short story.' }],
    model: 'gpt-4o',
  });

  // Extract usage data
  const usage = completion.usage;
  if (usage) {
    console.log(`Input tokens: ${usage.prompt_tokens}`);
    console.log(`Output tokens: ${usage.completion_tokens}`);
    console.log(`Total tokens: ${usage.total_tokens}`);

    // Example cost calculation (prices are for illustration)
    const inputPricePerMillion = 3.00; // $ per 1M tokens
    const outputPricePerMillion = 15.00; // $ per 1M tokens

    const inputCost = (usage.prompt_tokens / 1000000) * inputPricePerMillion;
    const outputCost = (usage.completion_tokens / 1000000) * outputPricePerMillion;
    const totalCost = inputCost + outputCost;

    console.log(`Total cost: $${totalCost.toFixed(6)}`);
  }
}

main();

Below the Water Line: Hidden Costs

The simple calculation above is the "tip of the iceberg." To truly control costs for production agents, you must understand the factors lurking below the surface.

A comprehensive article from "Oh That Data Girl" dives deep into these nuances. While the code is in Python, the concepts are universal and directly applicable to the APIs you're using.

Know your tokens. Own your costs.

This article is a masterclass in the practical economics of LLMs. It explains concepts that separate hobbyist developers from professional agent builders.

Please read the following sections, focusing on the concepts rather than the Python syntax: Same text, different bill: Read this section to understand why you can't use one provider's tokenizer (like tiktoken) to estimate costs for another (like Claude or Gemini). Each has its own tokenizer, resulting in different counts. It also shows how providers offer API endpoints to count tokens before you make the full request. For your work in TS, you would use js-tiktoken for OpenAI models and look for similar utilities or API endpoints from Anthropic and Google. What comes back: tokens in API responses: This section reinforces what we've covered, showing how the usage object appears in the responses from Claude, OpenAI, and Gemini. Notice the different field names (prompt_tokens vs. input_tokens). The hidden tokens: This is crucial. Read this section carefully to understand reasoning/thinking tokens. These are tokens a model generates internally to "think through" a complex problem before producing the final answer. You are billed for them (usually at the output rate), but they don't appear in the response text. The iceberg image calls these "Thinking tokens." Cached tokens: Read this section to learn about prompt caching. When you send repeated requests with a shared prefix (like a long system prompt in a chat), some providers can cache the processed tokens, charging you a fraction of the cost on subsequent calls. This is a massive cost-saving opportunity for agentic workflows.


Putting It All Together: Practical Monitoring

Understanding cost is one thing; tracking it is another. For any production service, you need a system to log every API call and its associated cost. This allows you to monitor expenses, identify costly workflows, and bill clients accurately.

Your experience with n8n is a huge advantage here. You can build a robust monitoring system with tools you already know.

How I Auto Track AI Agent Actions and Token Usage (n8n tutorial)

This video by Nate Herk is a perfect practical demonstration of how to build an agent monitoring log using n8n and Google Sheets. It's a fantastic starting point for your own agency's operational dashboard.

Watch the full video, paying attention to these key steps: The final result: See how each agent run is logged with its input, output, actions taken, token usage, and total cost. Capturing the data: The key is enabling the "Return Intermediate Steps" option in the n8n AI Agent node. This exposes the usage data for each step of the agent's thought process. Processing the data: A simple code node is used to parse the complex JSON output, extract the relevant token counts, and sum up the total cost. This is a great example of combining no-code with small, targeted scripts. Logging to Google Sheets: The cleaned-up data is then appended to a Google Sheet, creating a simple but effective monitoring dashboard.

This n8n workflow is a powerful and immediately usable pattern. You can adapt it to log data to a PostgreSQL database or any other system as your needs grow. The principle is the same: log every call, capture the usage data, and calculate the cost.


Conclusion

This lesson concludes our foundational module. You now have a comprehensive understanding of the core mechanics of LLMs, from token generation and streaming to the critical economics of their operation.

Here are the key takeaways on cost management:

  • Tokens are the currency: All costs are derived from the number of input and output tokens.
  • Cost is asymmetrical: Output tokens are significantly more expensive than input tokens.
  • Look below the surface: The true cost is influenced by hidden factors like different tokenizers, "thinking" tokens, and caching.
  • Monitoring is non-negotiable: You cannot control what you cannot measure. Setting up a logging system from day one is essential for any commercial AI application.

You've built a solid foundation. You know how LLMs work, how to compare them, how to control their output, how to stream it efficiently, and how to manage the cost.

Now, we are ready to move from mechanics to artistry. In the next module, Advanced Prompt Engineering for Agents, we'll begin to explore how to craft the instructions that make an LLM a capable and reliable agent. Our first lesson will focus on the most important prompt of all: the system prompt, which defines your agent's role, capabilities, and personality.