I copied this workflow as-is into the same version (1.84.3) of n8n (community) and my output doesn’t have that part (tokenUsage) at all. Is there something you have enabled in your settings for your actual OpenAI account to make that appear in the response?
In case you want to cross this off your list of things to try, or build on the idea and see if you can get it to work, this looked promising (a document got inserted), but the actual info wasn’t stored.
IDK. I just thought it would be worth a try. I would assume if anything in the workflow has access to the tokenUsage info from the model, it would be the agent.
However, it would be a weird interaction. What I tried would essentially be telling the AI to return tool-usage instructions to the agent (somehow) with enough understanding of n8n internals, and the MongoDB client tool, and itself, to create a document, populate its data, and insert it. So, it “knew” some of the MongoDB part, but I was just speculating on whether it would “know” enough to tell the agent how to grab the tokenUsage stats. It was probably futile.
Also, adding that to the System Message ends up making another “tool usage” call to the AI, using up more tokens, so observing it changes it.
I run n8n as the backend of a SaaS project. Whenever the users intereact with our agents, I want to save the token usage, so I can deduct from their token balance.
Right now the temporary solution is to use the OpenAI nodes, instead of using the AI Agent node.
Since the solution provided by @jcuypers contains this information (although it’s a paid one) I’ll mark his reply as the solution and append my reply on my question at the top.
This way both useful informations are easy to find by future people having the same issue.
You should put it in a subworkflow.
It can be contained in the same workflow file, but I wouldn’t use it in the same execution. Otherwise you’ll end up processing a lot more data.
thanks for the response. I just noticed that with the data.
Is there a way to somehow subscribe to a workflow and get results?
One more thing is what if i add a custom node at the end of the workflow?