Steps
Make one sub-workflow for all paid API calls
Create a workflow that starts with the When Executed by Another Workflow trigger and accepts the fields you send (model, messages). Every workflow that needs OpenAI calls it with an Execute Workflow node instead of calling OpenAI directly, so cost tracking lives in one place.
Call OpenAI with an HTTP Request node
POST to
https://api.openai.com/v1/chat/completionswith your OpenAI credential and a JSON body like{"model": "{{ $json.model }}", "messages": {{ JSON.stringify($json.messages) }}}. The raw API response includes ausageblock withprompt_tokensandcompletion_tokens(the Responses API calls theminput_tokensandoutput_tokens). Calling the API directly makes sure you get that block back.Retry rate limits instead of failing
In the HTTP Request node's Settings, turn on Retry On Fail (for example 3 tries, 5000 ms apart) so a 429 Too Many Requests gets another go. Set On Error to Continue (using error output) so a call that still fails gets logged as well and doesn't silently kill the parent workflow.
Work out the cost in a Code node
Add a Code node after both outputs and paste the snippet below. Put your model's current prices per million tokens at the top (copy them from OpenAI's pricing page; the numbers in the snippet are only examples).
// $ per 1 million tokens for YOUR model. Example numbers only: copy the real ones from openai.com/api/pricing const PRICE_IN = 0.40, PRICE_OUT = 1.60; return $input.all().map(item => { const r = item.json; const u = r.usage || {}; const inTok = u.prompt_tokens ?? u.input_tokens ?? 0; const outTok = u.completion_tokens ?? u.output_tokens ?? 0; return { json: { time: new Date().toISOString(), workflow: $workflow.name, model: r.model || '', input_tokens: inTok, output_tokens: outTok, cost_usd: Number(((inTok * PRICE_IN + outTok * PRICE_OUT) / 1e6).toFixed(6)), error: r.error ? (r.error.message || String(r.error)) : '' } }; });Append a row to Google Sheets, then return the answer
Add a Google Sheets node (Append Row) with columns
time, workflow, model, input_tokens, output_tokens, cost_usd, error. Then return the model's reply to the parent workflow. A pivot table or=SUMIFon the sheet now shows the spend per workflow and per day.
What the snippet does
- Reads tokens from either API shape (
prompt_tokens/completion_tokensorinput_tokens/output_tokens). - Cost = input tokens × input price + output tokens × output price, divided by one million. We checked it: 1,200 input and 300 output tokens at the example prices of $0.40 and $1.60 per million come to $0.00096.
- Calls that ended on the error output get a row with 0 tokens and the error message, so you can count failures per workflow.
- Uses
$workflow.name, so each row says which workflow made the call.
Good to know
- Node errors: quota, rate limit, cut-off replies and the
output[0].content[0].textpath of the OpenAI node are decoded in n8n OpenAI node not working. - Cached input: the usage block can include
prompt_tokens_details.cached_tokens, which OpenAI bills at a lower rate. If you rely on prompt caching, subtract those from the input tokens and price them separately. - Other providers: Anthropic and most OpenAI-compatible APIs return a usage block too, with slightly different field names. Adjust the two lines that read the tokens.
- A budget alert: add a daily Schedule Trigger that sums today's
cost_usdand posts to a Discord webhook when it passes a limit. If your error alerts go there too, see the n8n error workflow guide.
Start from a working agent
FAQ
Why not use the OpenAI node or AI Agent node?
You can, but what they pass on varies between n8n versions and node options, and the usage block isn't always in the output. A plain HTTP Request node gives you the full API response, so the token counts are always there.
Is the cost exact?
It's as exact as the prices you type in. The token counts come from OpenAI's own response. Compare a week of rows with your OpenAI usage dashboard once to be sure the prices are right.
Does this slow my workflows down?
A little: one extra sub-workflow call and one Google Sheets append per request. For high-volume workflows, log to a database or write rows in batches instead.
Can I stop a workflow when the budget runs out?
Yes. Before the HTTP Request, read today's total from the sheet and stop with a Stop and Error node when it's over your limit.
Related guides
- n8n Google Sheets node not working: Bad request, invalid_grant, private key fixes
- n8n Google Calendar node not working: "Not a valid Google Calendar ID", OAuth2 fixes
- n8n Google Sheets Trigger not working: not firing, activation errors and fixes
- n8n Google Drive node not working: Bad request, binary file not found, OAuth2 fixes
- n8n Notion node not working: "API token is invalid.", data source and 404 fixes
New guides
- GitHub release notifications in Slack (any public repo, stable releases only)
- Send RSS feeds to Slack with a keyword filter (free, incoming webhook)
- Forward emails to a Slack channel (Gmail, Outlook, any IMAP), free with an incoming webhook
- n8n Gmail Trigger not working: not firing, silent errors and fixes