How can I access the token usage metadata returned by an LLM for a specific request and pass it to subsequent nodes in n8n for further processing, such as tracking token consumption, calculating costs, and maintaining usage logs?

Describe the problem/error/question

How can I access the token usage metadata returned by an LLM for a specific request and pass it to subsequent nodes in n8n for further processing, such as tracking token consumption, calculating costs, and maintaining usage logs?

What is the error message (if any)?

Please share your workflow

(Select the nodes on your canvas and use the keyboard shortcuts CMD+C/CTRL+C and CMD+V/CTRL+V to copy and paste the workflow.)

Share the output returned by the last node

Information on your n8n setup

  • n8n version:2.43.5
  • Database (default: SQLite): default
  • n8n EXECUTIONS_PROCESS setting (default: own, main): main
  • Running n8n via (Docker, npm, n8n cloud, desktop app): Docker
  • Operating system: Windows

Hey @AstralVyom, while you wait for a response, here are some things that might help:

Suggested resources

Automatically matched to your question.

Docs:

Forum:

@Mayank1024, @mohamed3nan, @jcuypers - you’ve helped with similar issues before, can you take a look?

Automatically suggested by n8n’s community bot. It’s a pilot - please share feedback here.

The Agent node’s own output is just output (plus intermediateSteps if you enable “Return intermediate steps”) - the token counts live on the chat model sub-node, because that is the only node that sees the provider’s raw response.

Two routes that work:

  1. Put the model call in its own sub-workflow: Basic LLM Chain + Chat Model, called via Execute Workflow. The chain’s item carries tokenUsage ({ promptTokens, completionTokens, totalTokens } on OpenAI-style providers), so the parent gets the answer and the counts together and can sum them into a running total or a cost formula.

  2. Let the provider do the accounting - OpenRouter’s generation endpoint returns the token counts and the cost in USD for a given call, so there is no node output to trust at all.

One trap worth knowing before you build this: a tools agent makes one model call per tool round-trip, not one per workflow run. Summing per workflow execution undercounts by the number of iterations, so count per model execution. And run the workflow once and open the chat model sub-node’s run data first - it shows exactly what your provider returns in your n8n version.

@AstralVyom

Maybe you want to upvote this

The per-call counts are already stored, they’re just not on the Agent’s output. Every time the chat model sub-node answers, n8n records a run for that sub-node with the provider’s usage attached. A tools agent gets one run per model call, which is the level you want for cost tracking.

In the execution data each of those runs looks like this:

runData['<Chat Model node>'][i].data.ai_languageModel[0][0].json.tokenUsage
// { promptTokens, completionTokens, totalTokens }

When the provider sends no usage back, n8n stores its own count as tokenUsageEstimate in the same place, so log which of the two you got.

You can’t read that from inside the execution that is still running, so I’d do it in a small separate logger workflow:

  1. Schedule Trigger every 15 minutes.
  2. HTTP Request to your own instance with an n8n API key: GET /api/v1/executions?workflowId=<id>&status=success&includeData=true&startedAfter=<last checkpoint>
  3. Split Out on data, so each execution becomes one item.
  4. A Code node (Run Once for All Items) that sums every model run in each execution:
const out = [];
for (const item of $input.all()) {
  const ex = item.json;
  const runData = ex.data?.resultData?.runData ?? {};
  let prompt = 0, completion = 0, calls = 0, estimated = false;
  for (const runs of Object.values(runData)) {
    for (const run of runs) {
      const res = run.data?.ai_languageModel?.[0]?.[0]?.json;
      const usage = res?.tokenUsage ?? res?.tokenUsageEstimate;
      if (!usage) continue;
      if (!res.tokenUsage) estimated = true;
      prompt += usage.promptTokens ?? 0;
      completion += usage.completionTokens ?? 0;
      calls++;
    }
  }
  out.push({ json: { executionId: ex.id, workflowId: ex.workflowId, startedAt: ex.startedAt, calls, prompt, completion, estimated } });
}
return out;
  1. Upsert into a Data Table keyed on executionId, so the logger running twice over the same window doesn’t double count. Keep prices per model in a second table and multiply there, since prices change more often than the workflow.

It walks all nodes, so it also catches a second model, like a fallback model or a model inside a sub-agent. Two settings to check: successful production executions have to be saved (workflow settings or EXECUTIONS_DATA_SAVE_ON_SUCCESS), and the logger has to run before pruning deletes them. If you want the cost of failed runs too, do a second pass with status=error. Agents that loop on a tool before failing are often the expensive ones.

For a single request, I’d use HTTP Request to call the provider, preserve the raw JSON, then use Edit Fields or Code to pass usage alongside the answer into your logging node.

With the regular OpenAI node, disable Simplify Output first. For Chat Completions, inspect usage.prompt_tokens, usage.completion_tokens, and usage.total_tokens. Responses uses input_tokens and output_tokens instead.

The AI Agent case needs separate treatment: usage visible in a Chat Model sub-node isn’t necessarily forwarded to the main output. Moving it into a sub-workflow won’t automatically expose missing metadata, and Return Intermediate Steps isn’t complete usage accounting.

Record each model call, including retries, with its response ID and model. Keep missing usage as unknown, calculate input/output costs separately, and account for caching. The HTTP Request example tracks a single call; agent workflows need accounting across their tool loop.

Hi @AstralVyom, for the AI Agent case, enable Save execution progress → Save in the workflow settings. That lets a node after the Agent retrieve the completed model runs while the overall execution is still running.

Add an n8n node after the Agent: Resource: Execution, Operation: Get, Execution ID: ={{ $execution.id }}, and Include Execution Details on. Feed its output into @retailbox_michael’s summing Code, which reads data.resultData.runData and handles multiple model calls.

Progress saving may increase latency because it saves after each node.

One more route that works with the normal AI Agent, without restructuring anything into chains: read the token counts back out of the execution after it finishes.

Every time the chat model sub-node runs, n8n stores its output in the execution data, and on OpenAI style providers that output has tokenUsage with promptTokens, completionTokens and totalTokens. The agent just doesn’t pass it along. So at the end of your workflow (or in a separate workflow triggered by it), add the n8n node, pick Execution > Get, pass in {{ $execution.id }} and turn on Include Execution Details. Note the current execution has to be finished for this to have everything, so the cleanest setup is to have the main workflow call a small logging workflow with Execute Workflow and “Wait for sub-workflow completion” turned off, passing the execution id, then add a Wait of a few seconds before the Get.

In the result, look under data.resultData.runData and find the key with your chat model node’s name, for example “OpenAI Chat Model”. That’s an array with one entry per model call, which matters because a tools agent calls the model once per tool round trip. A Code node can loop over that array and add up the tokenUsage values, then multiply by your per token prices and write a row to a Data Table or Google Sheets with the workflow name, execution id, prompt tokens, completion tokens and cost.

Run it once and click into the chat model node’s run data first so you can see the exact path your provider returns, since some providers name the fields a bit differently. You’ll need an n8n API key set up as the credential for the n8n node too.