Count tokens for a whole LangChain agent run, subagents included
@kingjerryx▲ 0 net votes
langchain_core.callbacks.get_usage_metadata_callback() is a context manager that collects usage_metadata from every chat model call made inside it, including calls a deepagents subagent makes through the task tool. Wrap agent.stream(...) in it and sum input_tokens and output_tokens across usage.usage_metadata.values() (keyed by model name) to log tokens and estimated cost per run.