LLM costs can escalate quickly in production workflows, especially when processing batch data or using agent loops.
LLM costs can escalate quickly in production workflows, especially when processing batch data or using agent loops. Logging the model name, token count, and estimated cost per execution to a tracking sheet gives you visibility into spending trends and helps identify optimization opportunities.
Real-world example: Every workflow that calls an LLM appends a row to a Google Sheet with execution metadata and cost estimates.
Create a sub-workflow named "Log AI Cost" that all AI workflows call after each LLM node:
[Execute Sub-Workflow Trigger] → [Calculate Cost] → [Google Sheets: Append Row]
```text
Cost calculation Code node:
```javascript
const input = $json;
// Pricing per 1M tokens (update these as pricing changes)
const pricing = {
'gpt-4o': { input: 2.50, output: 10.00 },
'gpt-4o-mini': { input: 0.15, output: 0.60 },
'claude-sonnet-4-20250514': { input: 3.00, output: 15.00 },
'claude-haiku-3-20240307': { input: 0.25, output: 1.25 }
};
const model = input.model || 'unknown';
const inputTokens = input.usage?.prompt_tokens || 0;
const outputTokens = input.usage?.completion_tokens || 0;
const totalTokens = inputTokens + outputTokens;
const rates = pricing[model] || { input: 0, output: 0 };
const cost = (inputTokens * rates.input + outputTokens * rates.output) / 1_000_000;
return [{
json: {
timestamp: new Date().toISOString(),
workflow_name: input.workflow_name || $workflow.name,
execution_id: $execution.id,
model: model,
input_tokens: inputTokens,
output_tokens: outputTokens,
total_tokens: totalTokens,
estimated_cost_usd: cost.toFixed(6),
node_name: input.node_name || 'unknown'
}
}];
```text
Google Sheet structure:
| Timestamp | Workflow | Execution ID | Model | Input Tokens | Output Tokens | Total | Cost (USD) | Node |
|-----------|----------|--------------|-------|-------------|---------------|-------|-----------|------|
| 2025-03-15T10:30:00Z | Support Classifier | abc123 | gpt-4o-mini | 450 | 85 | 535 | $0.000119 | Classify |
| 2025-03-15T10:30:01Z | Support Classifier | abc123 | claude-sonnet-4-20250514 | 1200 | 650 | 1850 | $0.013350 | Generate |
Call the logging sub-workflow after each LLM node:
```json
// Execute Sub-Workflow node input
{
"workflow_name": "Support Classifier",
"node_name": "Classify Intent",
"model": "{{ $json.model }}",
"usage": {
"prompt_tokens": "{{ $json.usage.prompt_tokens }}",
"completion_tokens": "{{ $json.usage.completion_tokens }}"
}
}
```text
> **Tip: Weekly Cost Report**
>
> Create a scheduled workflow that reads the Google Sheet, aggregates costs by workflow and model, and sends a weekly Slack summary. Set alerts for workflows that exceed a per-execution cost threshold (e.g., $0.50 per run).
Token tracking pays for itself the first time it reveals a workflow burning through tokens due to an unexpectedly large input or a runaway agent loop.
---
> **Summary: Summary**
>
> Effective AI integration in n8n is about more than connecting an LLM node. Use structured output to get parseable responses, route intelligently between cheap and expensive models, add memory for conversations, chunk documents properly for RAG, moderate before publishing, handle rate limits gracefully, and track every token spent. These patterns transform fragile AI prototypes into production-grade automation.
**Related:** [Use Manual Trigger During Development Instead of Webhook or Schedule](../api-cost-optimization/01-use-manual-trigger-during-development-instead-of-webhook-or-schedule.md) | [Flatten Deeply Nested API Responses](../code-node-mastery/01-flatten-deeply-nested-api-responses.md)
I build production n8n and Cloudflare automation for teams — the same engineering behind HarperFlow. Fixed-price, escrow-protected, US-based.