How to Get the Token Usage and Cost of a LangChain Agent Run in Python
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
from langchain_core.callbacks import get_usage_metadata_callback
with get_usage_metadata_callback() as <callback>:
<result> = <agent>.invoke(<input>)
<totals> = <callback>.usage_metadata
| Part | What it is |
|---|---|
get_usage_metadata_callback() | Records the token usage of every model call made inside the with block |
<callback>.usage_metadata | The totals, in a dictionary with one entry per model name: {"<model>": {"input_tokens": …, "output_tokens": …, …}} |
<message>.usage_metadata | The 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:
uv init --python 3.14 --no-package bakery-hours
cd bakery-hours
uv add langchain langchain-anthropic python-dotenv
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:
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:
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_openis the tool.create_agentturns 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 itsusage_metadataholds 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:
uv run main.py
{'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}}

One question took two calls to Claude:
- The first call read the question and asked for the tool: 384 tokens in, 49 out.
- 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:
| Field | What it counts |
|---|---|
input_tokens | Every token Claude read in that call |
output_tokens | Every token Claude wrote, thinking included |
total_tokens | The two added up |
input_token_details | How 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_details | How many of the output tokens were thinking (reasoning) |
Step 4: Add Up the Whole Run and Its Cost
Replace everything in main.py with:
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_PRICEandOUTPUT_PRICEare Claude Opus 5.5's prices from Anthropic's pricing page: $4 per million input tokens and $20 per million output tokens.- The
withblock runs the agent whileget_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:
uv run main.py
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 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
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}")

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_tokensalready includes the cached tokens: langchain-anthropic's source notes that Anthropic'sinput_tokensexcludes cached tokens, so we manually addcache_readandcache_creationtokens 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_tokensincludes 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
| Mistake | What happens | Do this instead |
|---|---|---|
Reading only the last message's usage_metadata | You get one model call, not the run: 439 input and 17 output tokens here, out of 823 and 66 | Use get_usage_metadata_callback(), or add up every AIMessage |
Calling invoke outside the with block | Nothing 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 price | Cache 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 them | Price 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
- Token usage — LangChain's guide to usage metadata and the usage callbacks.
- get_usage_metadata_callback — the context manager's reference.
- UsageMetadata — every field of the usage dictionary.
- Claude pricing — prices per model, caching, thinking and tool use.
