Skip to content

Instantly share code, notes, and snippets.

@freakynit
Created February 17, 2025 05:42
Show Gist options
  • Save freakynit/e8b2c173290f210a1cb7644a6e41752c to your computer and use it in GitHub Desktop.
Save freakynit/e8b2c173290f210a1cb7644a6e41752c to your computer and use it in GitHub Desktop.
Calculates total costs of your chatgpt chats if you were using API (text only, no muiltimedia consideration)
const fs = require('fs');
// ToDo: Update these values if needed
const CONVERSATIONS_FILE_PATH = './conversations.json'; // From your chatGPT data export
const CHARACTERS_PER_TOKEN = 4;
const PRICING_DOLLARS_PER_MILLION_TOKENS = {
input: 2.50,
output: 10
};
let jsonData = JSON.parse(fs.readFileSync(CONVERSATIONS_FILE_PATH, 'utf-8'));
function processMessages(conversation) {
let messages = [];
let currentNode = conversation.current_node;
while (currentNode != null) {
let node = conversation.mapping[currentNode];
if (
node.message &&
node.message.content &&
node.message.content.parts &&
node.message.content.parts.length > 0 &&
(node.message.author.role !== "system" || node.message.metadata.is_user_system_message)
) {
if (node.message.content.content_type == "text" || node.message.content.content_type == "multimodal_text") {
for (let i = 0; i < node.message.content.parts.length; i++) {
let part = node.message.content.parts[i];
if (typeof part === "string" && part.length > 0) {
if (node.message.author.role === "assistant" || node.message.author.role === "tool") {
outputCharacters += part.length;
} else {
inputCharacters += part.length;
}
}
}
}
}
currentNode = node.parent;
}
}
let inputCharacters = 0;
let outputCharacters = 0;
for (let i = 0; i < jsonData.length; i++) {
let conversation = jsonData[i];
processMessages(conversation);
}
const inputTokens = inputCharacters/CHARACTERS_PER_TOKEN;
const outputTokens = outputCharacters/CHARACTERS_PER_TOKEN;
console.log(`\nExtracted character counts`);
console.log({inputCharacters, outputCharacters});
console.log(`\nTokens (using given factor of ${CHARACTERS_PER_TOKEN} characters per token)`);
console.log({inputTokens, outputTokens});
console.log(`\nTotal cost (using given input/output token pricing (dollars) of per million token units ${PRICING_DOLLARS_PER_MILLION_TOKENS.input}, ${PRICING_DOLLARS_PER_MILLION_TOKENS.output})`);
console.log((inputTokens * PRICING_DOLLARS_PER_MILLION_TOKENS.input / 1e6) + (outputTokens * PRICING_DOLLARS_PER_MILLION_TOKENS.output / 1e6));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment