Use this advanced n8n workflow to accurately track OpenAI token usage and cost per client using the Langchain Code n8n node, enabling automated billing via Google Sheets and Gmail.
Download this n8n workflow template and start using it instantly.
AI Service Providers: Companies offering AI-powered APIs or services to multiple customers. Developers using n8n: Users looking for advanced examples of how to hook into the LLM lifecycle for custom metrics. Finance Teams: Organizations needing granular cost attribution for generative AI usage. Self-Hosted n8n Users: This particular n8n templates uses the Langchain Code n8n node, which is optimized for self-hosted n8n environments.
Managing the costs associated with Large Language Models (LLMs) is crucial, especially when servicing multiple clients. This comprehensive n8n workflow addresses the challenge of accurately tracking and attributing token usage and financial cost to individual customers.
The core of this n8n automation is the use of a custom LLM subnode built with the Langchain Code n8n node. This allows the workflow to tap into the LLM response metadata before the data is passed to the next step, ensuring every token used is captured. The captured metrics—including input tokens, output tokens, and calculated cost—are immediately logged to Google Sheets using a specialized 'tool' connection. This log forms the basis for accurate, automated monthly billing, which is handled in a secondary, scheduled part of the n8n workflow that retrieves logs, aggregates totals, and uses the Gmail n8n node to send a finalized invoice.
This powerful n8n workflow is divided into two main logical streams: the usage tracking service and the scheduled billing process.
clientid, workflowid, and executionid).handleLLMEnd callback. Inside this custom code, the usagemetadata (containing token counts) is accessed, costs are calculated using predefined rates, and the entire transaction record is appended to the Google Sheets 'Client Usage Log' using the Google Sheets Tool connected to the subnode.sumtotaltokens) and total cost (sumtotalcost).To deploy this token cost tracking n8n workflow, follow these steps:
date, clientid, totaltokens, totalcost, etc.).openAIApiKey: Replace the placeholder with your actual OpenAI API key.model: Adjust the model name if necessary (it currently uses gpt-4o-mini).inputtokencost and outputtoken_cost: Update these variables to reflect the current market cost per million tokens for your chosen model. On form submission (n8n trigger):
Function: Serves as the client-facing front end, allowing file upload to trigger the service.
Key Configuration: Configured to accept a required PDF file upload and an acknowledgment checkbox.
Custom LLM Subnode (Langchain Code n8n node):
Function: Acts as the custom LLM provider for the data extractor. It contains Javascript logic to listen for the LLM response completion event (handleLLMEnd) and extract token usage metadata.
Key Configuration: Calculates costs based on hardcoded per-million-token rates and calls the connected Google Sheets tool to log the transaction data.
Client Usage Log (Google Sheets Tool n8n node):
Function: Used as a 'tool' connection to the custom LLM subnode, allowing the custom code to append usage data to a specific spreadsheet instantaneously.
Key Configuration: Operation set to 'append'; targets the spreadsheet '89. Langchain Code Node - Client Usage Log'.
Extract Resume Data (Information Extractor n8n node):
Function: Uses the custom LLM to convert raw text (from the PDF) into a structured JSON schema (for CV/Resume data).
Key Configuration: Uses a detailed JSON schema defining fields like name, email, work history, and skills.
Every End of Month (Schedule n8n trigger):
Function: Initiates the financial aggregation and invoicing process monthly.
Key Configuration: Scheduled to run on the 31st of the month at 18:00.
Calculate Totals (Summarize n8n node):
Function: Aggregates the costs and tokens from the retrieved client logs.
Key Configuration: Summarizes the sum of totalcost and totaltokens.
Send Invoice (Gmail n8n node):
Function: Composes and sends the final billing email to the client.
* Key Configuration: Email body dynamically constructed using the aggregated totals from the previous n8n node, including tax calculations.
Use this n8n workflow to automatically log coffee counts from a Jura machine API via webhook directly into Google Sheets for real-time monitoring and reporting. Discover more n8n templates.

Use this comprehensive n8n workflow to calculate dynamic Jira Epic health scores (based on cycle time, bugs, and blockers). Automatically alert Slack, update Jira labels, and log data to Google Sheets and Monday.com.

Instantly deploy this powerful n8n workflow to automatically pull fresh investor data from Crunchbase daily and append it cleanly to Google Sheets for market analysis. Start leveraging n8n templates today.

Use this powerful n8n workflow template to automate LinkedIn profile tracking. It scrapes professional data, detects changes in job titles or status, stores history in Google Sheets, and notifies your team instantly via Slack. A robust n8n automation.

Automate marketing performance tracking with this robust n8n workflow. Fetch HighLevel won deals, calculate lead source metrics, and report instantly via Google Sheets and Slack.


Freelance consultant based in the UK specialising in AI-powered automations. I work with select clients tackling their most challenging projects. For business enquiries, send me an email at [email protected] LinkedIn: https://www.linkedin.com/in/jimleuk/ X/Twitter: https://x.com/jimle_uk







































