You can store data about your bot’s AI spend in a table that automatically updates throughout all your bot’s conversations. This includes cost from any of your bot’s AI usage, including:
// Convert spend from nano-dollars to dollarsconst llm_spend = metadata.tokens.cost / 1000000000;// Create a row for the current turn's AI spendclient.createTableRows({ table: 'SpendTable', rows: [ { Cost: llm_spend, ConversationID: event.conversationId, } ]});
This Hook runs after each turn — that is, after the bot has received a message, processed it, and sent its response. The code snippet above does the following:
Retrieves the AI spend for the current turn
Convert the cost from nano-dollars into standard dollars
Saves the cost and conversation ID to the SpendTable
Try chatting with your bot in the emulator. After every message your bot sends, your table should automatically create a new row. The AI spend will display in the Cost column:
Your table will now keep a record of your bot’s AI spend for each turn.
// Finds table rows with the current conversation IDconst tableResponse = await client.findTableRows({ table: 'SpendTable', filter: { ConversationID: event.conversationId }});// Calculates the total AI spend for the conversationlet totalSpend = 0;for (let i = 0; i < tableResponse.rows.length; i++) { totalSpend += tableResponse.rows[i].Cost;};// Creates a row in the new table with the total AI spend for the conversationclient.createTableRows({ table: 'TotalSpendTable', rows: [ { Cost: totalSpend, ConversationID: event.conversationId, } ]});
This Hook runs after the end of each conversation. The code snippet above does the following:
Retrieves the AI spend for each turn of the conversation
Sums them up to get the total AI spend for the conversation
Creates a row in TotalSpendTable with the total AI spend for the conversation
If you’re using an Autonomous Node in your main Workflow, the conversation will only end when it times out. This means you’ll need to wait for the duration of your bot’s inactivity timeout before your table updates with the total AI spend.