AI Agent Token Usage and Cost Tracker in Google Sheets - n8n Workflow

Use this essential n8n workflow to accurately track AI Agent token usage (prompt and completion tokens) across various models and log cost estimates in Google Sheets. This n8n templates solution is crucial for cost management.

Workflow Preview

Ready to automate?

Download this n8n workflow template and start using it instantly.

Who is this best for?


  • AI/ML Developers: Who need to monitor the operational costs of their LLM-powered applications running on n8n. - Automation Engineers: Seeking robust cost tracking solutions for complex, multi-step n8n workflow executions involving LangChain agents. - Finance/Ops Teams: Requiring transparent reporting on API usage and estimated monthly expenditures for AI services. - Users of n8n templates: Looking for a highly technical example of how to retrieve execution metadata using the n8n node API.

Overview

Managing the cost of AI Agents and large language models (LLMs) is crucial. Unlike simple API calls, complex n8n workflow designs involving AI Agents and tools can obscure the actual token consumption. This specialized n8n workflow provides a solution by tapping directly into the n8n execution metadata.

This powerful n8n templates solution utilizes a self-calling sub-workflow structure and the n8n API node to reliably extract token usage (prompt and completion tokens) from the execution data after the primary task is complete. The aggregated usage data is then recorded in a Google Sheets document, which is pre-configured with formulas to calculate estimated costs based on specific LLM pricing.

By deploying this n8n workflow, users gain unprecedented transparency into their AI operational expenses, helping them optimize their prompts and model choices.

How it Works

This n8n workflow operates in two distinct phases: the main execution and the asynchronous tracking process.


  1. Initiating the AI Task: The process starts with the manual n8n trigger or any other desired n8n trigger. An AI Agent n8n node executes a complex task involving tool calls and LLM interactions.

  2. Asynchronous Tracking Call: Immediately after the AI Agent finishes, the workflow executes the Call sub-workflow n8n node. Crucially, this node calls the same n8n workflow ID but disables the 'Wait For Sub-Workflow Completion' option. It passes the current execution ID ($execution.id). This ensures the main execution fully logs its usage data before the tracking process begins.

  3. Tracking n8n Trigger: The sub-workflow begins with the When Executed by Another Workflow n8n trigger, receiving the execution ID.

  4. Retrieving Execution Data: The Get execution data n8n node uses the n8n API credential to query the n8n instance and retrieve the complete JSON metadata for the execution ID.

  5. Extracting Token Metrics: The Extract token usage data n8n node uses a sophisticated JMESPath expression to deeply parse the execution JSON, identifying every language model call and extracting the associated model name and tokenUsage metrics.

  6. Splitting and Summarizing: The extracted token data is split using the Split Out n8n node and then aggregated using the Sum Token Totals n8n node. This groups all prompt and completion tokens by the specific LLM model used (e.g., gpt-4o-mini).

  7. Recording to Google Sheets: Finally, the Record token usage n8n node appends the summarized tokens, model name, workflow name, and execution ID to the designated Google Sheets document, enabling accurate cost estimation based on the prices defined in the spreadsheet.

Installation Guide

To set up this essential n8n workflow, follow these steps:


  1. Import the n8n Workflow: Copy the provided JSON data and import it into your n8n instance.

  2. Create Google Sheet: Make a copy of the provided template Google Sheets file ([TEMPLATE] Calculate LLM Token Usage).

  3. Credentials Setup (Google Sheets): Configure the Google Sheets n8n node (Record token usage) with your Google Sheets OAuth2 API credentials and select the copied spreadsheet and the 'Executions' sheet.

  4. Credentials Setup (n8n API): The Get execution data n8n node requires n8n API credentials. You must create an API key for your n8n instance (Settings > API Keys) and connect it.

  5. LLM Credentials: Ensure your AI Agent and related Language Model n8n nodes (OpenAI, Gemini, Anthropic, etc.) are configured with valid credentials.

  6. Update Workflow ID: Verify the Call sub-workflow n8n node. If you did not change the workflow ID after import, the expression ={{ $workflow.id }} should automatically reference the current n8n workflow. If you moved the tracking logic to a separate n8n template, update the ID accordingly.

Node Details

When clicking ‘Test workflow’ (n8n trigger): Serves as the initiation point for testing the n8n workflow.
AI Agent (LangChain Agent n8n node): Executes the main AI logic, simulating a task that involves interacting with language models.
Call sub-workflow (Execute Workflow n8n node): Calls the current n8n workflow asynchronously (waitForSubWorkflow: false), passing the execution ID. This is key for cost tracking in this n8n templates solution.
When Executed by Another Workflow (n8n trigger): The dedicated n8n trigger for the tracking branch, activated by the sub-workflow call, receiving the execution ID input.
Get execution data (n8n node - resource: execution): Retrieves the comprehensive execution log data from the n8n API, which contains the token usage metrics.
Extract token usage data (Set n8n node): Uses a complex JMESPath query to meticulously extract token usage (promptTokens and completionTokens) and the corresponding model_name from the deep structure of the n8n execution data.
Sum Token Totals - aggregate by model (Summarize n8n node): Aggregates the token counts, calculating the total prompt and completion tokens for each distinct LLM model used within the execution.
Record token usage (Google Sheets n8n node): Appends the final aggregated token usage data to the 'Executions' sheet in Google Sheets, enabling automatic cost calculation.

Related n8n Workflows

Free

Nodes: 14 Nodes
Updated: December 26 2025
View all
Created by

Teaching at the Scrapes Academy (see link below). For business inquiries: [email protected] | Telegram: t.me/salomaoguilherme | LinkedIn: linkedin.com/in/guisalomao/

Featured*