n8n AI Agent Token Usage: How to Get Prompt and Completion Tokens (and Cost) per Execution
You open the chat model under your AI Agent and the token counts are right there, but nothing after the agent can read them. An expression like {{ $json.tokenUsage }} comes back empty, and the agent's output only has the answer. This is one of the most asked n8n AI questions, and as of October 2026 there's still no switch for it. There are two workable routes. Which one fits depends on whether you need the agent's tool loop.
Quick reference
| Route | Keeps the AI Agent node? | What you get | Effort |
|---|---|---|---|
| Call the model with an HTTP Request node | No (you write the prompt call yourself) | The provider's own usage object, per call, inline |
Low |
| Read the finished execution with the n8n node | Yes | The token counts the chat model sub-node recorded, per model call | Medium |
☐ 1. Know where the numbers actually live
The provider sends token counts with each model response. In an agent setup, only the chat model sub-node sees that raw response. The AI Agent node outputs the final answer (and intermediate steps, if you turn that option on), not the usage.
Note: the details here come from n8n community answers, not from n8n's documentation. The chat model sub-node records tokenUsage with promptTokens, completionTokens and totalTokens for each of its runs, or tokenUsageEstimate when the provider returned no usage. A tools agent makes one model call per tool round trip, so one execution can contain several model runs. Check this against one of your own executions before you build on it.
☐ 2. Route A: call the model with an HTTP Request node
If a single prompt-and-answer call is enough (classification, extraction, drafting a reply), skip the agent and call the provider's Chat Completions endpoint directly with an HTTP Request node: POST {base URL}/chat/completions. Keep the full response, not a simplified one.
OpenAI's API reference documents the usage object on every chat completion:
prompt_tokens: "Number of tokens in the prompt."completion_tokens: "Number of tokens in the generated completion."total_tokens: prompt plus completion.completion_tokens_details.reasoning_tokens: tokens the model spent on reasoning. These count toward completion tokens for billing.prompt_tokens_details.cached_tokens: cached prompt tokens, which many providers price lower.
A Set node right after the request can work out the cost. Replace 0.15 and 0.60 with your model's input and output price per 1M tokens:
{{ ((($json.usage || {}).prompt_tokens || 0) * 0.15 + (($json.usage || {}).completion_tokens || 0) * 0.60) / 1000000 }}
- If you stream, ask for usage explicitly. With
stream_options: { include_usage: true }, OpenAI sends one extra chunk with the totals before[DONE]. If the stream is interrupted you may not receive it. - Note: some OpenAI-compatible providers or proxies don't return
usage. Look at one raw response before you trust a cost of 0. - Note: according to community answers, the regular OpenAI node returns usage only with Simplify Output turned off.
☐ 3. Route B: keep the AI Agent, read the execution afterwards
If you need the agent's tools and memory, read the token counts from the execution data. The built-in n8n node can do this. Its Execution → Get operation takes an Execution ID and has an Include Execution Details option for the detailed execution data. Pass {{ $execution.id }}, "the unique ID of the current workflow execution".
The catch: the execution you're reading has to be finished, or at least saved. Two setups are reported to work:
- Separate logger workflow. At the end of the main workflow, call a small logging workflow with Execute Workflow and pass the execution ID. Don't wait for it to finish. In the logger, wait a few seconds, then run Execution → Get.
- Same workflow, saved progress. Turn on Save execution progress in the workflow settings, which saves "execution data for each node". It "may increase latency".
Note: both setups come from community answers. Also check that the workflow saves successful production executions, or there will be nothing to read later.
The n8n node uses the n8n API, so it needs an n8n API credential. n8n's docs note that it "doesn't support SSL". If your server requires an SSL connection, call the n8n API with an HTTP Request node instead.
A Code node after the Get can collect every token count, wherever it sits. It walks the execution data and returns one item per model run:
const exec = $input.first().json;
const runData = (exec.data && exec.data.resultData && exec.data.resultData.runData) || {};
const rows = [];
function collect(node, value) {
if (!value || typeof value !== 'object') return;
for (const [key, v] of Object.entries(value)) {
if ((key === 'tokenUsage' || key === 'tokenUsageEstimate') && v && typeof v === 'object') {
rows.push({
node,
estimated: key === 'tokenUsageEstimate',
promptTokens: v.promptTokens || 0,
completionTokens: v.completionTokens || 0,
totalTokens: v.totalTokens || 0,
});
} else {
collect(node, v);
}
}
}
for (const [nodeName, runs] of Object.entries(runData)) collect(nodeName, runs);
return rows.map(r => ({ json: { executionId: exec.id, ...r } }));
Note: the data.resultData.runData path is the structure community answers describe for Get with Include Execution Details. If your version nests it differently, the walker still finds the token fields but the node names may be off.
☐ 4. Log one row per model call, not per workflow
Whichever route you pick, write one row for each model call:
| Field | Where it comes from |
|---|---|
| Execution ID | $execution.id |
| Workflow ID | $workflow.id |
| Model | Your request body or the response's model |
| Prompt / completion / cached tokens | Provider usage, or the sub-node's token counts |
| Estimated? | tokenUsageEstimate vs tokenUsage |
| Attempt | 1 for the first call, 2+ for retries |
| Cost | Your price formula |
Retries are separate, billed calls. If a node has Retry On Fail on, or you send a corrective retry after invalid JSON, log each attempt. A tools agent's extra round trips are billed too.
☐ 5. Get the price math right
- Prices are usually quoted per 1M tokens, separately for input and output.
- Reasoning tokens are billed as completion tokens even though you don't see them in the answer.
- Cached input tokens often have their own lower price.
- OpenAI notes that with
ngreater than 1 "you will be charged based on the number of generated tokens across all of the choices." - Once a month, compare your log with the provider's usage dashboard. That's the number you pay.
Symptom table
| Symptom | Likely cause | Check |
|---|---|---|
{{ $json.tokenUsage }} empty after the AI Agent |
The agent doesn't pass usage on | Check 3 (or 2) |
| Cost always 0 | Provider didn't return usage, or output was simplified |
Check 2 |
| Logged tokens lower than the bill | Retries, tool round trips or streamed calls not counted | Checks 4, 2 |
| Execution → Get has no token data | Execution not finished or not saved | Check 3 |
| Numbers flagged as estimates | tokenUsageEstimate instead of provider usage |
Check 1 |
If you'd rather start from workflows that already report it
The Store Support Agent Pack for n8n is a pack of 8 n8n workflow JSON files for online stores (order status replies, ticket triage, FAQ answers, review replies, refund triage). You import them into your own n8n and run them with your own model API key. According to its product page, it works with any OpenAI-compatible model, and every run reports its own token usage and estimated cost, plus there's a cost estimate table you fill in with your model's prices. A single scenario is $39 and the full pack is $79. Its listed limits: the Shopify adapter is unit-tested against simulated Shopify responses, not yet a live store, and it was workflow-tested on n8n 1.123.84.
Sources
- OpenAI API reference, Chat Completions (
usage,stream_options.include_usage,n): https://platform.openai.com/docs/api-reference/chat/object - n8n docs, n8n node (Execution → Get, Include Execution Details, SSL note): https://docs.n8n.io/integrations/builtin/core-nodes/n8n-nodes-base.n8n/
- n8n docs, Workflow settings (Save execution progress): https://docs.n8n.io/workflows/settings/
- n8n docs, n8n metadata (
$execution.id,$workflow.id): https://docs.n8n.io/code/builtin/n8n-metadata/ - n8n community, How to get AI token usage information from AI Agent?: https://community.n8n.io/t/how-to-get-ai-token-usage-information-from-ai-agent/94671
- n8n community, Retrieve LLM Token Usage in AI Agents: https://community.n8n.io/t/retrieve-llm-token-usage-in-ai-agents/68714