8
n8n 中文网amn8n.com

在Google Sheets上追踪LLM令牌使用量和Agent可观测性

中级

这是一个Engineering, Multimodal AI领域的自动化工作流,包含 9 个节点。主要使用 If, Set, GoogleSheets, Code, Agent 等节点。 使用Google Sheets仪表板追踪OpenAI令牌使用量和AI Agent指标

前置要求
  • Google Sheets API 凭证
工作流预览
可视化展示节点连接关系,支持缩放和平移
导出工作流
复制以下 JSON 配置到 n8n 导入,即可使用此工作流
{
  "id": "B68FORPfxycLElJZ",
  "meta": {
    "instanceId": "36fee986cc83112881fb12ec7cc2d0221d7bddd71c11715c196899b114e8b0d2"
  },
  "name": "在 Google Sheets 上追踪 LLM Token 使用量和 Agent 可观测性",
  "tags": [],
  "nodes": [
    {
      "id": "74b8b8f2-8152-4a8f-991b-6eb8dea2ad4a",
      "name": "当收到聊天消息时",
      "type": "@n8n/n8n-nodes-langchain.chatTrigger",
      "position": [
        0,
        0
      ],
      "webhookId": "5e11697c-dfc4-457e-b535-43f65ba8da81",
      "parameters": {
        "public": true,
        "options": {},
        "initialMessages": "Welcome to Troopers!\n\nSo glad you’re here! 😊 Are you already a Troopers client, or just getting started?"
      },
      "typeVersion": 1.1
    },
    {
      "id": "cbcf9a4b-1f17-4dac-8ee2-0c58766923d2",
      "name": "AI Agent",
      "type": "@n8n/n8n-nodes-langchain.agent",
      "position": [
        464,
        0
      ],
      "parameters": {
        "text": "={{  $('When chat message received').item.json.chatInput }}",
        "options": {
          "systemMessage": "=You are a helpful assistant",
          "returnIntermediateSteps": true
        },
        "promptType": "define"
      },
      "typeVersion": 2.1
    },
    {
      "id": "482a8e1a-3d9e-419c-a671-932fc0724c1c",
      "name": "Token 使用记录",
      "type": "n8n-nodes-base.googleSheetsTool",
      "position": [
        528,
        432
      ],
      "parameters": {
        "columns": {
          "value": {
            "date": "={{ $fromAI(\"date\") }}",
            "model": "={{ $fromAI(\"model\") }}",
            "llm_node": "={{ $fromAI(\"llm_node\") }}",
            "client_id": "={{ $fromAI(\"client_id\") }}",
            "input_cost": "={{ $fromAI(\"input_cost\") }}",
            "total_cost": "={{ $fromAI(\"total_cost\") }}",
            "output_cost": "={{ $fromAI(\"output_cost\") }}",
            "workflow_id": "={{ $fromAI(\"workflow_id\") }}",
            "execution_id": "={{ $fromAI(\"execution_id\") }}",
            "input_tokens": "={{ $fromAI(\"input_tokens\") }}",
            "total_tokens": "={{ $fromAI(\"total_tokens\") }}",
            "output_tokens": "={{ $fromAI(\"output_tokens\") }}",
            "input_token_cost ($ / million)": "={{ $fromAI(\"input_token_cost\") }}",
            "output_token_cost ($ / million)": "={{ $fromAI(\"output_token_cost\") }}"
          },
          "schema": [
            {
              "id": "date",
              "type": "string",
              "display": true,
              "removed": false,
              "required": false,
              "displayName": "date",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "llm_node",
              "type": "string",
              "display": true,
              "removed": false,
              "required": false,
              "displayName": "llm_node",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "model",
              "type": "string",
              "display": true,
              "removed": false,
              "required": false,
              "displayName": "model",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "workflow_id",
              "type": "string",
              "display": true,
              "removed": false,
              "required": false,
              "displayName": "workflow_id",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "execution_id",
              "type": "string",
              "display": true,
              "removed": false,
              "required": false,
              "displayName": "execution_id",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "client_id",
              "type": "string",
              "display": true,
              "removed": false,
              "required": false,
              "displayName": "client_id",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "input_tokens",
              "type": "string",
              "display": true,
              "removed": false,
              "required": false,
              "displayName": "input_tokens",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "input_token_cost ($ / million)",
              "type": "string",
              "display": true,
              "removed": false,
              "required": false,
              "displayName": "input_token_cost ($ / million)",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "output_tokens",
              "type": "string",
              "display": true,
              "removed": false,
              "required": false,
              "displayName": "output_tokens",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "output_token_cost ($ / million)",
              "type": "string",
              "display": true,
              "removed": false,
              "required": false,
              "displayName": "output_token_cost ($ / million)",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "total_tokens",
              "type": "string",
              "display": true,
              "removed": false,
              "required": false,
              "displayName": "total_tokens",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "input_cost",
              "type": "string",
              "display": true,
              "removed": false,
              "required": false,
              "displayName": "input_cost",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "output_cost",
              "type": "string",
              "display": true,
              "removed": false,
              "required": false,
              "displayName": "output_cost",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "total_cost",
              "type": "string",
              "display": true,
              "removed": false,
              "required": false,
              "displayName": "total_cost",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            }
          ],
          "mappingMode": "autoMapInputData",
          "matchingColumns": [],
          "attemptToConvertTypes": false,
          "convertFieldsToString": false
        },
        "options": {},
        "operation": "append",
        "sheetName": {
          "__rl": true,
          "mode": "list",
          "value": "gid=0",
          "cachedResultUrl": "https://docs.google.com/spreadsheets/d/1O4PVOD584KWLzzj8gEym95hs8z3-Y4UjImMwKfby98c/edit#gid=0",
          "cachedResultName": "Token cost tracker"
        },
        "documentId": {
          "__rl": true,
          "mode": "list",
          "value": ""
        }
      },
      "credentials": {
        "googleSheetsOAuth2Api": {
          "id": "wOT0EGRAXG51Ihtb",
          "name": "Google Sheets account (Augra)"
        }
      },
      "typeVersion": 4.5
    },
    {
      "id": "34d054aa-9ad4-4381-8707-77903eef3b71",
      "name": "## 为什么选择 4o 模型?👆",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -832,
        304
      ],
      "parameters": {
        "width": 624,
        "height": 560,
        "content": "## 从这里开始:分步 YouTube 教程 :star:"
      },
      "typeVersion": 1
    },
    {
      "id": "78fa52a2-c7c4-4c88-a357-57e6b03541e1",
      "name": "便签",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -832,
        -368
      ],
      "parameters": {
        "width": 624,
        "height": 640,
        "content": "**从这里开始(必需设置)**"
      },
      "typeVersion": 1
    },
    {
      "id": "ae40d18f-8bc8-4a4f-8ddb-f31099fcd24b",
      "name": "设置 • 工作流 + 客户端元数据",
      "type": "n8n-nodes-base.set",
      "position": [
        224,
        0
      ],
      "parameters": {
        "options": {},
        "assignments": {
          "assignments": [
            {
              "id": "ca1744cf-69e7-4a85-81d3-2fb2b936e496",
              "name": "workflow_id",
              "type": "string",
              "value": "={{ $workflow.id }}"
            },
            {
              "id": "205c7c4d-2dfa-471f-9306-33d30e16722a",
              "name": "execution_id",
              "type": "string",
              "value": "={{ $execution.id }}"
            },
            {
              "id": "3fa4932f-c3cc-41a8-90a4-d1b3a2d32cdd",
              "name": "client_id",
              "type": "string",
              "value": "123"
            }
          ]
        }
      },
      "typeVersion": 3.4
    },
    {
      "id": "0b9d9c4b-7bc7-4057-a78f-bc5fc9b6f857",
      "name": "LangChain 聊天模型 + Token 回调",
      "type": "@n8n/n8n-nodes-langchain.code",
      "position": [
        448,
        224
      ],
      "parameters": {
        "code": {
          "supplyData": {
            "code": "const { ChatOpenAI } = require(\"@langchain/openai\");\n\n// 1. Configure as required.\n// - costs are per million tokens and depends on the model.\nconst openAIApiKey = process.env.OPENAI_API_KEY;\nconst model = \"gpt-5-mini-2025-08-07\";\nconst input_token_cost = 0.25;\nconst output_token_cost = 2.00;\n\n// 2. Customize LLM token tracker\nconst tools = await this.getInputConnectionData('ai_tool', 0);\nconst googleSheetTool = tools[0];\n\nconst {\n  workflow_id,\n  execution_id,\n  client_id } = $('Set metadata').first().json;\n\nconst llm = new ChatOpenAI({\n  apiKey: openAIApiKey,\n  model,\n  callbacks: [\n    {\n      handleLLMEnd: async function(output,runId,parentId) {\n        const generation = output.generations[0][0];\n        const message = generation.message;\n        const row = {\n          date: (new Date()).toGMTString(),\n          workflow_id,\n          execution_id,\n          client_id,\n          model,\n          input_tokens: message.usage_metadata.input_tokens,\n          output_tokens: message.usage_metadata.output_tokens,\n          total_tokens: message.usage_metadata.total_tokens,\n          input_cost: (message.usage_metadata.input_tokens / 1_000_000) * input_token_cost,\n          output_cost: (message.usage_metadata.output_tokens / 1_000_000) * output_token_cost,\n        };\n        row.total_cost = row.input_cost + row.output_cost;\n        await googleSheetTool.func(row);\n      }\n    }\n  ]\n});\n\nreturn llm;"
          }
        },
        "inputs": {
          "input": [
            {
              "type": "ai_tool",
              "required": true
            }
          ]
        },
        "outputs": {
          "output": [
            {
              "type": "ai_languageModel"
            }
          ]
        }
      },
      "typeVersion": 1
    },
    {
      "id": "383dc17c-d479-4f3d-965f-f708931c4865",
      "name": "分支 • 是否使用工具?",
      "type": "n8n-nodes-base.if",
      "position": [
        816,
        0
      ],
      "parameters": {
        "options": {},
        "conditions": {
          "options": {
            "version": 2,
            "leftValue": "",
            "caseSensitive": true,
            "typeValidation": "strict"
          },
          "combinator": "and",
          "conditions": [
            {
              "id": "9c8947e8-fa44-4e3e-b869-9284afc03a61",
              "operator": {
                "type": "array",
                "operation": "empty",
                "singleValue": true
              },
              "leftValue": "={{ $json.intermediateSteps }}",
              "rightValue": ""
            }
          ]
        }
      },
      "typeVersion": 2.2
    },
    {
      "id": "e9f7bef2-c21e-45e1-ade5-33fdcee5fc0a",
      "name": "记录 • Token 指标到 Sheets (工具)",
      "type": "n8n-nodes-base.googleSheets",
      "position": [
        1040,
        0
      ],
      "parameters": {
        "columns": {
          "value": {
            "date": "={{ $now }}",
            "input": "={{ $('When chat message received').item.json.chatInput }}",
            "output": "={{ $json.output }}",
            "Tool use": "={{ $json.intermediateSteps[0].action.tool }}",
            "client_id": "={{ $('Set • Workflow + Client Metadata').item.json.client_id }}",
            "workflow_id": "={{ $('Set • Workflow + Client Metadata').item.json.workflow_id }}",
            "execution_id": "={{ $('Set • Workflow + Client Metadata').item.json.execution_id }}"
          },
          "schema": [
            {
              "id": "date",
              "type": "string",
              "display": true,
              "removed": false,
              "required": false,
              "displayName": "date",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "workflow_id",
              "type": "string",
              "display": true,
              "removed": false,
              "required": false,
              "displayName": "workflow_id",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "execution_id",
              "type": "string",
              "display": true,
              "removed": false,
              "required": false,
              "displayName": "execution_id",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "client_id",
              "type": "string",
              "display": true,
              "removed": false,
              "required": false,
              "displayName": "client_id",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "input",
              "type": "string",
              "display": true,
              "removed": false,
              "required": false,
              "displayName": "input",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "Tool use",
              "type": "string",
              "display": true,
              "removed": false,
              "required": false,
              "displayName": "Tool use",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "output",
              "type": "string",
              "display": true,
              "removed": false,
              "required": false,
              "displayName": "output",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            }
          ],
          "mappingMode": "defineBelow",
          "matchingColumns": [],
          "attemptToConvertTypes": false,
          "convertFieldsToString": false
        },
        "options": {},
        "operation": "append",
        "sheetName": {
          "__rl": true,
          "mode": "list",
          "value": 94625050,
          "cachedResultUrl": "https://docs.google.com/spreadsheets/d/1O4PVOD584KWLzzj8gEym95hs8z3-Y4UjImMwKfby98c/edit#gid=94625050",
          "cachedResultName": "Observability"
        },
        "documentId": {
          "__rl": true,
          "mode": "list",
          "value": "1O4PVOD584KWLzzj8gEym95hs8z3-Y4UjImMwKfby98c",
          "cachedResultUrl": "https://docs.google.com/spreadsheets/d/1O4PVOD584KWLzzj8gEym95hs8z3-Y4UjImMwKfby98c/edit?usp=drivesdk",
          "cachedResultName": "Track LLM Tokens"
        }
      },
      "credentials": {
        "googleSheetsOAuth2Api": {
          "id": "wOT0EGRAXG51Ihtb",
          "name": "Google Sheets account (Augra)"
        }
      },
      "typeVersion": 4.6
    }
  ],
  "active": false,
  "pinData": {},
  "settings": {
    "executionOrder": "v1"
  },
  "versionId": "67022965-a398-44c9-b241-bd09709760ec",
  "connections": {
    "AI Agent": {
      "main": [
        [
          {
            "node": "Branch • Tool Used?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Token Usage Log": {
      "ai_tool": [
        [
          {
            "node": "LangChain Chat Model + Token Callback",
            "type": "ai_tool",
            "index": 0
          }
        ]
      ]
    },
    "Branch • Tool Used?": {
      "main": [
        [],
        [
          {
            "node": "Log • Token Metrics to Sheets (Tool)",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "When chat message received": {
      "main": [
        [
          {
            "node": "Set • Workflow + Client Metadata",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Set • Workflow + Client Metadata": {
      "main": [
        [
          {
            "node": "AI Agent",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "LangChain Chat Model + Token Callback": {
      "ai_languageModel": [
        [
          {
            "node": "AI Agent",
            "type": "ai_languageModel",
            "index": 0
          }
        ]
      ]
    }
  }
}
常见问题

如何使用这个工作流?

复制上方的 JSON 配置代码,在您的 n8n 实例中创建新工作流并选择「从 JSON 导入」,粘贴配置后根据需要修改凭证设置即可。

这个工作流适合什么场景?

中级 - 工程, 多模态 AI

需要付费吗?

本工作流完全免费,您可以直接导入使用。但请注意,工作流中使用的第三方服务(如 OpenAI API)可能需要您自行付费。

工作流信息
难度等级
中级
节点数量9
分类2
节点类型8
难度说明

适合有一定经验的用户,包含 6-15 个节点的中等复杂度工作流

作者
Hunyao

Hunyao

@hun-yao

Hun Yao is a founder-engineer obsessed with building scalable automation that actually moves the needle - with a focus in the E-commerce space. A self-taught product builder with roots in marketing and AI, he uses n8n as his playground to ship MVPs fast - turning modular workflows into elegant, revenue-generating systems.

外部链接
在 n8n.io 查看

分享此工作流