Retrieve LLM Token Usage in AI Agents

works like a charm. thanks

1 Like

This works! Thanks

1 Like

I’ve been trying to set this up all day! but I don’t know why sometimes the information is not included in the execution data or it’s path changes!

This is the workflow:

First, I manually set the value (execution.id) into a custom variable (execution_id):

Which I’ll later pass to the last step (calling the sub workflow) like so:

This is the second/sub workflow:

It takes the execution_id from the parent workflow and passes it to the next n8n.get execution step:

The step seems to work fine, but as I mentioned earlier the tokenUsage object can sometimes be missing or if it exists the path isn’t always consistent. in this case it’s missing and I can’t find it at all! here’s the JSON output:

[
  {
    "id": "322",
    "finished": true,
    "mode": "manual",
    "retryOf": null,
    "retrySuccessId": null,
    "status": "success",
    "createdAt": "2025-04-24T07:27:55.882Z",
    "startedAt": "2025-04-24T07:27:55.937Z",
    "stoppedAt": "2025-04-24T07:27:55.971Z",
    "deletedAt": null,
    "workflowId": "viSx5kDpuVAFegqc",
    "waitTill": null,
    "data": {
      "startData": {
        "destinationNode": "workflow_vars",
        "runNodeFilter": [
          "WhatsApp Trigger",
          "workflow_vars"
        ]
      },
      "resultData": {
        "runData": {
          "WhatsApp Trigger": [
            {
              "hints": [],
              "startTime": 1745479660310,
              "executionTime": 0,
              "source": [],
              "executionStatus": "success",
              "data": {
                "main": [
                  [
                    {
                      "json": {
                        "messaging_product": "whatsapp",
                        "metadata": {
                          "display_phone_number": "15556407176",
                          "phone_number_id": "552650594608063"
                        },
                        "contacts": [
                          {
                            "profile": {
                              "name": "Amin AbuDahab"
                            },
                            "wa_id": "962777666266"
                          }
                        ],
                        "messages": [
                          {
                            "from": "962777666266",
                            "id": "wamid.HBgMOTYyNzc3NjY2MjY2FQIAEhggOENGQTJCODlCRUZCOTZERUJFNjEzODU5NEFCQUFERkYA",
                            "timestamp": "1745479658",
                            "text": {
                              "body": "Good morning"
                            },
                            "type": "text"
                          }
                        ],
                        "field": "messages"
                      },
                      "pairedItem": {
                        "item": 0
                      }
                    }
                  ]
                ]
              }
            }
          ],
          "workflow_vars": [
            {
              "hints": [],
              "startTime": 1745479675970,
              "executionTime": 1,
              "source": [
                {
                  "previousNode": "WhatsApp Trigger",
                  "previousNodeOutput": 0,
                  "previousNodeRun": 0
                }
              ],
              "executionStatus": "success",
              "data": {
                "main": [
                  [
                    {
                      "json": {
                        "wa_id": 962777666266,
                        "wa_name": "Amin AbuDahab",
                        "execution_id": 322
                      },
                      "pairedItem": {
                        "item": 0
                      }
                    }
                  ]
                ]
              }
            }
          ]
        },
        "pinData": {},
        "lastNodeExecuted": "workflow_vars"
      },
      "executionData": {
        "contextData": {},
        "nodeExecutionStack": [],
        "metadata": {},
        "waitingExecution": {},
        "waitingExecutionSource": {}
      }
    },
    "workflowData": {
      "id": "viSx5kDpuVAFegqc",
      "name": "ZakZak",
      "active": false,
      "nodes": [
        {
          "parameters": {
            "notice_tip": "",
            "agent": "toolsAgent",
            "promptType": "define",
            "text": "={{ $json.messages[0].text.body }}",
            "hasOutputParser": false,
            "options": {
              "systemMessage": "=# ROLE\nYou are a friendly AI assistant.\n\n# RULES\nWhen a user sends a new message, decide if the user provided any noteworthy information that should be stored in memory. If so, call the Save Memory tool to store this information in memory. DO NOT inform the user that this information was stored in memory.  Simply continue to answer the question or executing the next tasks.\n\n# Tools\n## Save Memory\nUse this tool to store information about the user. Extract and summarize interesting information from the user message and pass it to this tool.\n\n# Memories\nHere are the last noteworthy memories that you've collected from the user sorted from newest to oldest (note: it can be empty):\n{{ $json.memories.toJsonString() }}\n\n# N.B.\nFor context this is time and date now:{{ $now }}\nThe user's country code is: {{ $json.country_code }}\n\n\n\n!! IMPORTANT!\nThink carefully about your responses and take the user's preferences into account!\nAlso consider the order of the memory in order to respond with the most up to date information.\n\n"
            },
            "credentials": ""
          },
          "type": "@n8n/n8n-nodes-langchain.agent",
          "typeVersion": 1.7,
          "position": [
            1360,
            300
          ],
          "id": "455eda4e-8a1e-4b0a-8b4f-1f474c023479",
          "name": "AI Agent"
        },
        {
          "parameters": {
            "mode": "combine",
            "combineBy": "combineByPosition",
            "numberInputs": 2,
            "options": {}
          },
          "type": "n8n-nodes-base.merge",
          "typeVersion": 3,
          "position": [
            1180,
            300
          ],
          "id": "1a21c380-04df-4c0c-bb5f-dea6e62d60e6",
          "name": "Merge"
        },
        {
          "parameters": {
            "notice": "",
            "sessionIdType": "customKey",
            "sessionKey": "={{ $('WhatsApp Trigger').item.json.contacts[0].wa_id }}",
            "contextWindowLength": 50
          },
          "type": "@n8n/n8n-nodes-langchain.memoryBufferWindow",
          "typeVersion": 1.3,
          "position": [
            1440,
            520
          ],
          "id": "c7254f2a-ffd1-4cd4-9516-8b9267f3fbdd",
          "name": "Window Buffer Memory"
        },
        {
          "parameters": {
            "curlImport": "",
            "method": "GET",
            "url": "https://xlw9-snvs-z50z.f2.xano.io/api:Lkzci_RP/message_trigger",
            "authentication": "none",
            "provideSslCertificates": false,
            "sendQuery": true,
            "specifyQuery": "keypair",
            "queryParameters": {
              "parameters": [
                {
                  "name": "wa_id",
                  "value": "={{ $json.wa_id }}"
                },
                {
                  "name": "wa_name",
                  "value": "={{ $json.wa_name }}"
                },
                {
                  "name": "message_type",
                  "value": "={{ $('WhatsApp Trigger').item.json.messages[0].type }}"
                },
                {
                  "name": "message",
                  "value": "={{ $('WhatsApp Trigger').item.json.messages[0].text.body }}"
                }
              ]
            },
            "sendHeaders": false,
            "sendBody": false,
            "options": {},
            "infoMessage": ""
          },
          "type": "n8n-nodes-base.httpRequest",
          "typeVersion": 4.2,
          "position": [
            980,
            440
          ],
          "id": "f9c7bbc5-0aaf-4120-b024-72f8bf99fd26",
          "name": "Get user status and memories",
          "alwaysOutputData": false
        },
        {
          "parameters": {
            "notice": "",
            "toolDescription": "",
            "method": "POST",
            "placeholderNotice": "",
            "url": "https://xlw9-snvs-z50z.f2.xano.io/api:Lkzci_RP/add_memory",
            "authentication": "none",
            "sendQuery": true,
            "specifyQuery": "keypair",
            "parametersQuery": {
              "values": [
                {
                  "name": "memory",
                  "valueProvider": "modelOptional"
                },
                {
                  "name": "wa_id",
                  "valueProvider": "fieldValue",
                  "value": "={{ $('workflow_vars').item.json.wa_id }}"
                }
              ]
            },
            "sendHeaders": false,
            "sendBody": false,
            "placeholderDefinitions": {},
            "optimizeResponse": false
          },
          "type": "@n8n/n8n-nodes-langchain.toolHttpRequest",
          "typeVersion": 1.1,
          "position": [
            1580,
            520
          ],
          "id": "642ab1d3-baf5-43af-b596-8cec8da66b9d",
          "name": "Add memory"
        },
        {
          "parameters": {
            "whatsAppNotice": "",
            "updates": [
              "messages"
            ],
            "options": {}
          },
          "type": "n8n-nodes-base.whatsAppTrigger",
          "typeVersion": 1,
          "position": [
            660,
            280
          ],
          "id": "7f110e57-fb74-417f-99eb-55a6de962383",
          "name": "WhatsApp Trigger",
          "webhookId": "e9a2a0b5-11ec-4172-97dc-661e5a124542",
          "credentials": {
            "whatsAppTriggerApi": {
              "id": "j2QURNIfpF36fjeU",
              "name": "WhatsApp OAuth account"
            }
          }
        },
        {
          "parameters": {
            "resource": "message",
            "operation": "send",
            "messagingProduct": "whatsapp",
            "phoneNumberId": "552650594608063",
            "recipientPhoneNumber": "={{ $('WhatsApp Trigger').item.json.contacts[0].wa_id }}",
            "messageType": "text",
            "textBody": "={{ $json.output }}",
            "additionalFields": {}
          },
          "type": "n8n-nodes-base.whatsApp",
          "typeVersion": 1,
          "position": [
            1720,
            300
          ],
          "id": "681173b7-d764-4a9c-a0c4-83d1dd75f91d",
          "name": "WhatsApp Business Cloud",
          "webhookId": "0e272817-32a5-4fbf-81fd-4a56ee162e83",
          "credentials": {
            "whatsAppApi": {
              "id": "bhwK4BEOJxLBSF1G",
              "name": "WhatsApp account"
            }
          }
        },
        {
          "parameters": {
            "notice": "",
            "model": {
              "__rl": true,
              "mode": "list",
              "value": "gpt-4o-mini"
            },
            "options": {}
          },
          "type": "@n8n/n8n-nodes-langchain.lmChatOpenAi",
          "typeVersion": 1.2,
          "position": [
            1300,
            520
          ],
          "id": "4d994cbf-9fc7-4c0d-948f-71952c2567e7",
          "name": "Chat Model",
          "credentials": {
            "openAiApi": {
              "id": "zSZgvjgxMSNFuR2v",
              "name": "My OpenAI Key"
            }
          }
        },
        {
          "parameters": {
            "operation": "call_workflow",
            "source": "database",
            "workflowId": {
              "__rl": true,
              "value": "vB5r2L24sjm0E0Ya",
              "mode": "list",
              "cachedResultName": "Add message and usage tokens"
            },
            "workflowInputs": {
              "mappingMode": "defineBelow",
              "value": {
                "execution_id": "={{ $('workflow_vars').item.json.execution_id }}"
              },
              "matchingColumns": [
                "execution_id"
              ],
              "schema": [
                {
                  "id": "execution_id",
                  "displayName": "execution_id",
                  "required": false,
                  "defaultMatch": false,
                  "display": true,
                  "canBeUsedToMatch": true,
                  "type": "number",
                  "removed": false
                }
              ],
              "attemptToConvertTypes": false,
              "convertFieldsToString": true
            },
            "mode": "once",
            "options": {}
          },
          "type": "n8n-nodes-base.executeWorkflow",
          "typeVersion": 1.2,
          "position": [
            1940,
            300
          ],
          "id": "e6d93b10-74b4-42ca-9d84-73fa682201b5",
          "name": "Execute Workflow"
        },
        {
          "parameters": {
            "mode": "manual",
            "duplicateItem": false,
            "assignments": {
              "assignments": [
                {
                  "id": "e2f25ebe-60ec-4901-b4a2-75fde03c6bd8",
                  "name": "wa_id",
                  "value": 962777666266,
                  "type": "number"
                },
                {
                  "id": "8a14b8ff-375b-4b48-b0f3-4604ee7edbf6",
                  "name": "wa_name",
                  "value": "Amin AbuDahab",
                  "type": "string"
                },
                {
                  "id": "9d517156-67f2-421a-9ccf-f24b95344eaf",
                  "name": "execution_id",
                  "value": "={{ $execution.id }}",
                  "type": "number"
                }
              ]
            },
            "includeOtherFields": false,
            "options": {}
          },
          "type": "n8n-nodes-base.set",
          "typeVersion": 3.4,
          "position": [
            820,
            440
          ],
          "id": "5cad966b-6d79-44c5-80b9-044dfa6f2ba2",
          "name": "workflow_vars"
        }
      ],
      "connections": {
        "Merge": {
          "main": [
            [
              {
                "node": "AI Agent",
                "type": "main",
                "index": 0
              }
            ]
          ]
        },
        "Window Buffer Memory": {
          "ai_memory": [
            [
              {
                "node": "AI Agent",
                "type": "ai_memory",
                "index": 0
              }
            ]
          ]
        },
        "Get user status and memories": {
          "main": [
            [
              {
                "node": "Merge",
                "type": "main",
                "index": 1
              }
            ]
          ]
        },
        "AI Agent": {
          "main": [
            [
              {
                "node": "WhatsApp Business Cloud",
                "type": "main",
                "index": 0
              }
            ]
          ]
        },
        "Add memory": {
          "ai_tool": [
            [
              {
                "node": "AI Agent",
                "type": "ai_tool",
                "index": 0
              }
            ]
          ]
        },
        "WhatsApp Trigger": {
          "main": [
            [
              {
                "node": "Merge",
                "type": "main",
                "index": 0
              },
              {
                "node": "workflow_vars",
                "type": "main",
                "index": 0
              }
            ]
          ]
        },
        "WhatsApp Business Cloud": {
          "main": [
            [
              {
                "node": "Execute Workflow",
                "type": "main",
                "index": 0
              }
            ]
          ]
        },
        "Chat Model": {
          "ai_languageModel": [
            [
              {
                "node": "AI Agent",
                "type": "ai_languageModel",
                "index": 0
              }
            ]
          ]
        },
        "workflow_vars": {
          "main": [
            [
              {
                "node": "Get user status and memories",
                "type": "main",
                "index": 0
              }
            ]
          ]
        }
      },
      "settings": {
        "executionOrder": "v1"
      },
      "pinData": {}
    },
    "customData": {}
  }
]

Any help is much appreciated and thanks in advance

I’ve noticed that this approach works better when The Usage Calculating workflow is called via webhook.

Btw, you can simply access {{ $execution.id }} in the node that send it to the calculating workflow, without adding it to the workflow_vars.

1 Like

I’ll try that, thanks a lot

What may be the reason for the output to be empty despite the fact that the data exists on the n8n execution?

I’m seeing the execution’s data in n8n’s output (also in its integral chat) but it is missing when sent to a hosted chat.

+1 for the feature!

I’ve just released a workflow that might help with that.
It works well with OpenAI, Google and Anthropic LLMs.

You guys might be interested @david.diaz.dev @artildo @cwysong85 @Joejoe @Renne_Jaskonis @Alex_R @Steven_Flecha @serhato @rodgerblom @Daniel_952

4 Likes

DUDE YOU ARE A GENIUS THIS WORKS LIKE A CHARM, THANK YOU VERY MUCH

3 Likes

it even works with openRouter! you really are a savior, thank you so much

1 Like

Hahaha you’re welcome. This is actually the result of many pieces of information that other people gave here in the community.

I’m glad to know it works well with Open router too!

1 Like

Hi thank you for your interest in that topic. You are saving lives here :smiley:

I tried to replicate your workflow but the n8n get:execution node kept throwing the following error.

Request failed with status code 404

It took me quite some time to realise that the execution data is only available in the Pro and Enterprise plan. The error message is not very helpful and is misleading.

If someone has the same issue this will save some headache. :slight_smile:

1 Like

Hey! I had the exact same issue and spent quite some time scratching my head over that 404 error too :sweat_smile:

In my case, the solution was to make sure that the N8N credential URL ends with /api/v1 — once I added that, the n8n get:execution node started working perfectly and all the execution data loaded correctly.

Hope this helps someone else avoid the same rabbit hole! :rocket:

2 Likes

Hi! is the get excecution data a paid node? I only got basic information

{
    "id": "625",
    "finished": true,
    "mode": "webhook",
    "retryOf": null,
    "retrySuccessId": null,
    "status": "success",
    "createdAt": "2025-07-21T18:42:25.760Z",
    "startedAt": "2025-07-21T18:42:25.773Z",
    "stoppedAt": "2025-07-21T18:42:42.966Z",
    "deletedAt": null,
    "workflowId": "ZqX4o8KpIe8GB7HQ",
    "waitTill": null
}

Does anyone knows when will this be solved in a n8n update? any tracking about the issue?
Thanks for the alternative solutions!

This is a solution to get the all information and calculate cost per each node you use in your template: Comprehensive LLM Usage Tracker & Cost Monitor with Node-Level Analytics | n8n workflow template

  • No external tool needed
  • All info is available (actual input and output, tokens, execution time, …)
  • You can add the cost for any model you use and the calculator would give you the cost. Minimum modification needed to get correct cost.
1 Like

I’m unable to see the token usage from the Agent. Each model call’s/node’s token usage is available in the Get Execution, but not the Agent node’s.
Also, I’m not able to see the execution duration (1.814s and 942ms) in the execution data.

Am I missing something here?

Note: I’m on 1.107 version, self hosted.

Below is the setup and I’ve enabled ā€œInclude Intermediate Stepsā€ on the Agent node and ā€œInclude Execution Dataā€ on the Get an Execution node. Neither of the code is able to get the actual/all the token usage along with the execution duration.

Agent:

image

Open AI Model:

image

I see the issue: when the Execution node isn’t the final node (i.e., it’s connected to another node), the workflow isn’t considered finished. As a result, Get an Execution waits for the execution ID. At the same time, n8n won’t provide that ID because it assumes the run is still in progress and should continue to the Code or Token Usage Analyzer node.

I understand why you set it up this way, but you’ll need a different pattern if later steps rely on these values. You could persist the results to Google Sheets, or trigger a separate workflow to continue the process. For example, in my Telegram bot I pass the username, chat session ID, and message ID into Get an Execution (with nothing after that node). Then, in the Get an Execution workflow, a Telegram node edits the original message and appends the token-usage cost as a footnote.

The core problem is that n8n won’t expose this information until the execution is marked FINISHED. I don’t know whether that’s intentional or a technical limitation, but it’s frustrating to jump through extra hoops just to access intermediate values that already exist within the same run.

Interesting solution!

I wonder whether it’s possible to modify the Agent Node code. As far as I understood, Agent root node has a JSON with and output key. Maybe it should be possible to add extra keys for tracking the token usage right after the Agent finishes

1 Like

I dont see how you get it to work with OpenRouter, Im trying the workflow, just replaced the Chat Model to OpenRouter and I get no outputs.