Skip to main content

How to Get the Token Usage and Cost of a LangChain Agent Run in Python

· 10 min read
Jagdish Kumawat
Founder @ Dewiride

Every agent run costs money: the model is paid per token, and an agent calls it more than once. LangChain records the tokens of every model call and can add them up for you. This guide reads them for a small Python agent on Claude, and turns them into US dollars.

Syntax​

Syntax
from langchain_core.callbacks import get_usage_metadata_callback

with get_usage_metadata_callback() as <callback>:
<result> = <agent>.invoke(<input>)

<totals> = <callback>.usage_metadata
PartWhat it is
get_usage_metadata_callback()Records the token usage of every model call made inside the with block
<callback>.usage_metadataThe totals, in a dictionary with one entry per model name: {"<model>": {"input_tokens": …, "output_tokens": …, …}}
<message>.usage_metadataThe usage of one model call, on the AIMessage that call returned

LangChain's models guide says that you can track aggregate token counts across models in an application using either a callback or context manager. get_usage_metadata_callback() is the context manager. Its messages guide adds that an AIMessage can hold token counts and other usage metadata in its usage_metadata field.

The Example​

An agent on Claude Opus 5.5 with one tool, is_open, which says whether a bakery is open on a day of the week. The bakery is closed on Sundays. The agent is asked: Is the bakery open on Monday?

Prerequisites​

  • A Claude API key, with credit on your Anthropic account. The Claude API has no free tier. Each run of this guide's agent cost about half a US cent.
  • uv. This guide uses uv 0.13.10 with Python 3.14.10.

Step 1: Create the Project​

In a terminal, in the folder where you keep your projects, create a project, move into it and add three packages:

Terminal
uv init --python 3.14 --no-package bakery-hours
cd bakery-hours
uv add langchain langchain-anthropic python-dotenv
Output (shortened)
Initialized project `bakery-hours` at `/Users/you/source/bakery-hours`
Using CPython 3.14.10
Creating virtual environment at: .venv
Resolved 47 packages in 10ms
Installed 45 packages in 129ms
+ langchain==1.5.2
+ langchain-anthropic==1.7.13
+ python-dotenv==1.2.4

The shortened output keeps the three packages you asked for. langchain gives you create_agent, langchain-anthropic connects LangChain to Claude, and python-dotenv reads your API key from a .env file. --no-package makes a plain project with main.py at the top.

Step 2: Add Your Claude API Key​

Create a file called .env in the bakery-hours folder, with this line:

.env
ANTHROPIC_API_KEY=your-api-key

Replace your-api-key with your key. How to Get a Claude API Key shows where to create one. The key is a secret, so add a line with .env to the project's .gitignore.

Step 3: See the Usage of Each Model Call​

Replace everything in main.py with:

main.py
from dotenv import load_dotenv
from langchain.agents import create_agent

load_dotenv()


def is_open(day: str) -> bool:
"""Check whether the bakery is open on a day of the week."""
return day != "Sunday"


agent = create_agent(model="anthropic:claude-opus-5-5", tools=[is_open])

result = agent.invoke({"messages": [{"role": "user", "content": "Is the bakery open on Monday?"}]})

for message in result["messages"]:
if message.type == "ai":
print(message.usage_metadata)
  • is_open is the tool. create_agent turns the function into a tool the model can call.
  • message.type == "ai" picks the model's own messages. Each one is the reply to one call to Claude, and its usage_metadata holds that call's token counts. Your question and the tool's result are messages too, but no model wrote them, so they have no usage.

Run it:

Terminal
uv run main.py
Output
{'input_tokens': 384, 'output_tokens': 49, 'total_tokens': 433, 'input_token_details': {'cache_read': 0, 'cache_creation': 0, 'ephemeral_5m_input_tokens': 0, 'ephemeral_1h_input_tokens': 0}, 'output_token_details': {'reasoning': 0}}
{'input_tokens': 439, 'output_tokens': 17, 'total_tokens': 456, 'input_token_details': {'cache_read': 0, 'cache_creation': 0, 'ephemeral_5m_input_tokens': 0, 'ephemeral_1h_input_tokens': 0}, 'output_token_details': {'reasoning': 0}}

The terminal after uv run main.py: two usage dictionaries, the first with 384 input and 49 output tokens, the second with 439 input and 17 output tokens, every cache and reasoning count at 0.

One question took two calls to Claude:

  1. The first call read the question and asked for the tool: 384 tokens in, 49 out.
  2. The second call read the tool's result and wrote the answer: 439 tokens in, 17 out. Its input is larger because the agent sends the whole conversation again: the question, the tool call and the tool's result.

Even the first call read far more tokens than the six words of the question. The input also holds the tool's name, description and arguments, and, as Anthropic's pricing page explains, when you use tools, the API also automatically includes a special system prompt for the model that enables tool use: 286 tokens for Claude Opus 5.5.

Each dictionary has the same fields:

FieldWhat it counts
input_tokensEvery token Claude read in that call
output_tokensEvery token Claude wrote, thinking included
total_tokensThe two added up
input_token_detailsHow many of the input tokens Claude read from Anthropic's prompt cache (cache_read) and how many it wrote to it (cache_creation, split into 5-minute and 1-hour writes)
output_token_detailsHow many of the output tokens were thinking (reasoning)

Step 4: Add Up the Whole Run and Its Cost​

Replace everything in main.py with:

main.py
from dotenv import load_dotenv
from langchain.agents import create_agent
from langchain_core.callbacks import get_usage_metadata_callback

load_dotenv()

# Claude Opus 5.5 prices, in US dollars per million tokens.
INPUT_PRICE = 4.00
OUTPUT_PRICE = 20.00


def is_open(day: str) -> bool:
"""Check whether the bakery is open on a day of the week."""
return day != "Sunday"


agent = create_agent(model="anthropic:claude-opus-5-5", tools=[is_open])

with get_usage_metadata_callback() as callback:
result = agent.invoke({"messages": [{"role": "user", "content": "Is the bakery open on Monday?"}]})

print(result["messages"][-1].text)
print(callback.usage_metadata)

for model_name, usage in callback.usage_metadata.items():
cost = (usage["input_tokens"] * INPUT_PRICE + usage["output_tokens"] * OUTPUT_PRICE) / 1_000_000
print(f"{model_name}: {usage['input_tokens']} input tokens, {usage['output_tokens']} output tokens, ${cost:.6f}")
  • INPUT_PRICE and OUTPUT_PRICE are Claude Opus 5.5's prices from Anthropic's pricing page: $4 per million input tokens and $20 per million output tokens.
  • The with block runs the agent while get_usage_metadata_callback() records every model call.
  • The loop goes through the totals, one entry per model, and turns each into dollars. The prices are per million tokens, hence the division by 1_000_000.

Run it:

Terminal
uv run main.py
Output
Yes, the bakery is open on Monday.
{'claude-opus-5-5': {'output_tokens': 66, 'input_token_details': {'ephemeral_5m_input_tokens': 0, 'cache_creation': 0, 'ephemeral_1h_input_tokens': 0, 'cache_read': 0}, 'output_token_details': {'reasoning': 0}, 'total_tokens': 889, 'input_tokens': 823}}
claude-opus-5-5: 823 input tokens, 66 output tokens, $0.004612

The terminal after uv run main.py: the answer Yes, the bakery is open on Monday, the totals dictionary for claude-opus-5-5 with 823 input and 66 output tokens, and the line claude-opus-5-5: 823 input tokens, 66 output tokens, $0.004612.

The callback added up both calls: 823 input tokens (384 + 439) and 66 output tokens (49 + 17), under the model's name. The cost is 823 × $4 / 1,000,000 + 66 × $20 / 1,000,000 = $0.003292 + $0.001320 = $0.004612: about half a cent for one question. An agent that answers a thousand such questions a day would spend about $4.61.

The Complete File​

main.py
from dotenv import load_dotenv
from langchain.agents import create_agent
from langchain_core.callbacks import get_usage_metadata_callback

load_dotenv()

# Claude Opus 5.5 prices, in US dollars per million tokens.
INPUT_PRICE = 4.00
OUTPUT_PRICE = 20.00


def is_open(day: str) -> bool:
"""Check whether the bakery is open on a day of the week."""
return day != "Sunday"


agent = create_agent(model="anthropic:claude-opus-5-5", tools=[is_open])

with get_usage_metadata_callback() as callback:
result = agent.invoke({"messages": [{"role": "user", "content": "Is the bakery open on Monday?"}]})

print(result["messages"][-1].text)
print(callback.usage_metadata)

for model_name, usage in callback.usage_metadata.items():
cost = (usage["input_tokens"] * INPUT_PRICE + usage["output_tokens"] * OUTPUT_PRICE) / 1_000_000
print(f"{model_name}: {usage['input_tokens']} input tokens, {usage['output_tokens']} output tokens, ${cost:.6f}")

The complete main.py in a macOS-style code window: Claude Opus 5.5's input and output prices, the is_open tool, an agent run inside get_usage_metadata_callback(), and a loop that prints each model's tokens and cost in dollars.

When the Simple Formula Isn't Enough​

The formula multiplies every input token by the base price. That was exact here, because every cache count was 0. Two things change the bill:

  • Prompt caching. LangChain's input_tokens already includes the cached tokens: langchain-anthropic's source notes that Anthropic's input_tokens excludes cached tokens, so we manually add cache_read and cache_creation tokens to get the true total. Cached tokens have their own prices. For Claude Opus 5.5, Anthropic's pricing page lists $0.20 per million tokens for cache hits, $5 for 5-minute cache writes and $8 for 1-hour cache writes. When your counts aren't 0, price those parts separately and charge only the rest at $4.
  • Thinking. It's already in the formula. output_tokens includes the thinking tokens, and Anthropic's thinking guide says the tokens Claude spends reasoning are billed as output tokens, even when the thinking text isn't returned to you. This run had none, but in a run of another agent, 29 of an answer's 80 output tokens were thinking.

Anthropic's pricing page also lists options that change the price per token, such as the Batch API's discount and the surcharge for US-only inference.

Common Mistakes​

MistakeWhat happensDo this instead
Reading only the last message's usage_metadataYou get one model call, not the run: 439 input and 17 output tokens here, out of 823 and 66Use get_usage_metadata_callback(), or add up every AIMessage
Calling invoke outside the with blockNothing is recorded: a callback with no model call inside its block held {}Put the invoke inside the block
Charging cache reads at the base input priceCache hits cost $0.20 per million tokens on Claude Opus 5.5, not $4, so the cost comes out up to 20 times too high for themPrice cache_read and cache writes separately

FAQ​

Does the cost include the tool's own work?​

No. The tool runs on your computer, inside your Python program. Only the calls to Claude are billed, and they include the tool's result, which Claude reads in the second call.

Does it work with models from other providers?​

When the provider reports usage, yes. LangChain's models guide says that a number of model providers return token usage information as part of the invocation response and that LangChain puts it on the AIMessage objects. The totals dictionary has one entry per model name, so an app that uses several models gets one entry for each.

Conclusion​

Each AIMessage holds the tokens of one model call in usage_metadata, and get_usage_metadata_callback() adds up every call made inside its with block. This agent's one question took two calls to Claude: 823 input and 66 output tokens, which at Claude Opus 5.5's prices came to $0.004612.

Additional Resources​