AI Hints
Home›LangChain Tutorial›Tokens and Providers
LangChain · Lesson 10 of 120

Tokens and Usage

Counting the cost.

⏱ 2 min read▶ Video at 9:35🎓 Free
Watch this lesson in the LangChain courseWatch on YouTube ↗Full LangChain course

Models don't read words. They read tokens, small pieces of text, often part of a word. Providers charge by the token, for both what you send, and what the model writes.

Tokens and Usage
From the video: Tokens and Usage
  • Models read tokens
  • Pieces of words
  • You pay per token

Reading the usage

Every reply has usage metadata, with the input tokens, the output tokens, and the total. Here we compare a short prompt with a long one. Run it. The longer prompt uses many more input tokens. Long histories and big documents are what make calls expensive.

usage.pypython
from langchain.chat_models import init_chat_model

model = init_chat_model("google_genai:gemini-flash-lite-latest", temperature=0)

short = "Name one fruit."
long = "Here is some background. " * 50 + "Name one fruit."

for name, prompt in [("short", short), ("long", long)]:
    usage = model.invoke(prompt).usage_metadata
    print(f"{name}: {usage['input_tokens']} in, {usage['output_tokens']} out")
Output
short: 5 in, 2 out
long: 255 in, 2 out

Rules of thumb

Some rules of thumb. In English, a token is about three quarters of a word, so a thousand tokens is roughly seven hundred and fifty words. Output tokens usually cost more than input tokens. And every message in the history is sent again, and paid for again, on every call.

keyvalue
1 token≈ ¾ of a word
1,000 tokens≈ 750 words
Outputusually costs more
Historypaid for every call

Summary

Tokens are pieces of text, and you pay for them in and out. Usage metadata tells you exactly how many each call used. Next, switching to a different model provider.

Key takeaways
  • Tokens, not words
  • usage_metadata
  • History costs every time
Next up: Switching Providers — one interface