Measuring and Interpreting Token Usage in LLMs
Introduction: Why Token Usage Matters
Welcome to the first lesson of the course, where we begin our journey into behavioral benchmarking of large language models (LLMs). In this course, you will learn how to evaluate LLMs beyond just accuracy, focusing on how they use resources, how their outputs change with different settings, and how to spot unusual or incorrect responses.
In this lesson, we focus on token usage. Tokens are the basic units of text that LLMs process — think of them as pieces of words or characters. Every time you send a prompt to an LLM, it counts the number of tokens in your input and its output.
In benchmarking, efficiency matters as much as accuracy. Tracking token usage helps you understand not only how "smart" a model is, but how resource-hungry it is — something crucial for real-world applications and cost management.
By the end of this lesson, you will know how to measure token usage for different prompts and interpret what those numbers mean.
The Role of the Context Window
When working with LLMs, it’s important to understand the concept of a context window. The context window is the maximum number of tokens (including both your input prompt and the model’s output) that the model can process in a single request. Context windows differ between models: early chat models had around 4,000 tokens, while many current models handle 100,000 tokens or more.
The context window determines how much information the model can "see" at once. If your prompt and the expected completion together exceed this limit, the model will either truncate the input or cut off the output. This can affect the quality and completeness of the responses.
When benchmarking or designing prompts, always keep the context window in mind:
- If your prompt is very long, you may need to shorten it to leave enough room for the model’s response.
- If you expect a long answer, make sure your prompt is concise enough to fit within the context window.
- Exceeding the context window can lead to incomplete outputs or errors.
Monitoring token usage helps you stay within the context window and ensures that your prompts and completions are processed as intended.
Getting Started With the OpenAI Python Client
To measure token usage, we will use the OpenAI Python client library. This library allows you to send prompts to language models using Python code. If you are working on your own computer, you would usually install the library using a command like pip install openai. However, on CodeSignal, the OpenAI library is already installed for you, so you can start coding right away.
The OpenAI client lets you send prompts to a model and receive responses. It also provides useful information about each request, including how many tokens were used for the prompt, the completion (the model’s response), and the total. In the next section, we will look at a practical example of how to use this client to measure token usage.
