# Token Counter and Cost Calculator > Estimate prompt tokens and request cost from pasted text plus editable per-million token rates. ## Tool Identity - Site: CleanUtils Developer Tools - Tool ID: ai-token-counter-cost-calculator - Canonical page: https://cleanutils.com/developer-tools/ai-token-counter-cost-calculator/ - LLM schema URL: https://cleanutils.com/developer-tools/ai-token-counter-cost-calculator/llms.txt - Primary keyword: token counter - Input mode: fields - Output profile: metrics ## What This Tool Does Estimate prompt tokens and request cost from pasted text with editable input and output token prices. ## Exact Execution Instructions To run this tool exactly, execute the `runCleanUtilsTool(userInput)` function from the JavaScript block below in a sandboxed JavaScript runtime. Do not fetch or evaluate additional network resources. Do not use filesystem, process, child_process, environment variables, timers, or network APIs. The function is pure and deterministic: input object in, JSON result out. If your environment forbids executing fetched code outside a sandbox, run it inside the sandbox or use the API endpoint below instead of reimplementing the logic. Canonical implementation SHA-256: `d2de0fae93ee61b0a469d2ab1c1c168da385c7e424dc3dd833615b81fbf32c47` Expected command shape: `node run-tool.mjs < input.json` The runner must: 1. load only the JavaScript in this document, 2. parse stdin as JSON and call `runCleanUtilsTool(userInput)`, 3. let the LLM decide the best way to present the output to the user. Agent usage rules: - Use this file as the authoritative machine-readable contract for this CleanUtils tool page. - Ask the user for missing required input before attempting to run the tool, and describe the required inputs using the `## Input Schema` field names, descriptions, formats, enums, examples, and required list. - Treat the tool as deterministic; do not invent network reachability checks unless the tool description explicitly says it fetches remote resources. - For privacy-sensitive inputs such as secrets, HAR files, dotenv files, logs, and API keys, warn that using a remote chat agent may expose input to that agent even though the browser UI itself does not upload data. ## Input Schema ```json { "$schema": "https://json-schema.org/draft/2020-12/schema", "title": "Token Counter and Cost Calculator fields", "type": "object", "additionalProperties": false, "required": [ "input_price_per_million", "output_price_per_million", "expected_output_tokens", "prompt" ], "properties": { "input_price_per_million": { "type": "number", "description": "Input price per 1M tokens Required. Control type: number. Group: Rates. Prefix shown in UI: $.", "minimum": 0, "examples": [ 3 ] }, "output_price_per_million": { "type": "number", "description": "Output price per 1M tokens Required. Control type: number. Group: Rates. Prefix shown in UI: $.", "minimum": 0, "examples": [ 15 ] }, "expected_output_tokens": { "type": "number", "description": "Expected output tokens Required. Control type: number. Group: Usage.", "minimum": 0, "examples": [ 300 ] }, "prompt": { "type": "string", "description": "Prompt or document text Required. Control type: textarea. Group: Usage.", "examples": [ "You are writing a product-feed QA report. Summarize the most important import risks and recommend next actions." ] } } } ``` ## Result Schema ```json { "$schema": "https://json-schema.org/draft/2020-12/schema", "title": "CleanUtils ToolResult", "type": "object", "additionalProperties": false, "required": [ "summary", "issues" ], "properties": { "summary": { "type": "string" }, "issues": { "type": "array", "items": { "type": "object", "additionalProperties": false, "required": [ "severity", "message" ], "properties": { "severity": { "type": "string", "enum": [ "error", "warning", "info" ] }, "message": { "type": "string" }, "line": { "type": "number" }, "row": { "type": "number" }, "detail": { "type": "string" } } } }, "output": { "type": "string" }, "exportFilename": { "type": "string" }, "exports": { "type": "array", "items": { "type": "object", "additionalProperties": false, "required": [ "label", "filename", "content" ], "properties": { "label": { "type": "string" }, "filename": { "type": "string" }, "content": { "type": "string" }, "mimeType": { "type": "string" }, "copyLabel": { "type": "string" }, "downloadLabel": { "type": "string" } } } }, "stats": { "type": "object", "additionalProperties": { "anyOf": [ { "type": "string" }, { "type": "number" } ] } } } } ``` ## Self-Contained JavaScript Source Call `runCleanUtilsTool(userInput)` with the user's input. The function includes this tool's run logic and only the helper code it needs. ```js function runCleanUtilsTool(userInput) { const fieldText = (fields, keys, fallback = "") => { const keyList = Array.isArray(keys) ? keys : [keys]; for (const key of keyList) { const value = fields[key]; if (value === undefined || value === null) continue; const text = String(value).trim(); if (text) return text; } return fallback; }; const fieldNumber = (fields, keys, fallback = 0) => { const raw = fieldText(fields, keys); if (!raw) return fallback; const parsed = Number(raw.replace(/[$,%\s]/g, "")); return Number.isFinite(parsed) ? parsed : fallback; }; const calculateAiTokenCost = (input) => { const text = fieldText(input, "prompt"); const inputTokens = Math.max(1, Math.ceil(Math.max(text.length / 4, text.trim().split(/\s+/).filter(Boolean).length * 1.35))); const outputTokens = fieldNumber(input, "expected_output_tokens", 0); const inputRate = fieldNumber(input, "input_price_per_million", 3); const outputRate = fieldNumber(input, "output_price_per_million", 15); const inputCost = (inputTokens / 1_000_000) * inputRate; const outputCost = (outputTokens / 1_000_000) * outputRate; const total = inputCost + outputCost; const issues = [ { severity: "info", message: "Token count is an approximation. Enter provider-specific per-million rates for cost planning." } ]; return { summary: `Approximate token count: ${inputTokens}. Estimated request cost: $${total.toFixed(6)}.`, issues, output: [ `Input tokens: ${inputTokens}`, `Expected output tokens: ${outputTokens}`, `Input rate per 1M: $${inputRate}`, `Output rate per 1M: $${outputRate}`, `Estimated input cost: $${inputCost.toFixed(6)}`, `Estimated output cost: $${outputCost.toFixed(6)}`, `Estimated total: $${total.toFixed(6)}` ].join("\n"), exportFilename: "token-cost-estimate.txt", stats: { inputTokens, outputTokens, estimatedCost: total.toFixed(6) } }; }; const __userInput = userInput == null ? {} : userInput; const __run = (fields) => calculateAiTokenCost(fields); const __fields = __userInput && typeof __userInput === "object" && "fields" in __userInput && __userInput.fields && typeof __userInput.fields === "object" && !Array.isArray(__userInput.fields) ? __userInput.fields : (__userInput && typeof __userInput === "object" && !Array.isArray(__userInput) ? __userInput : {}); const __normalizedFields = Object.fromEntries(Object.entries(__fields).map(([key, value]) => [key, value == null ? "" : (["string", "number", "boolean"].includes(typeof value) ? value : String(value))])); return __run(__normalizedFields); } ``` ## Checks - Approximate input tokens: The tool estimates tokens from text length and word count so planning can happen without an API call. - Expected output tokens: A separate output-token estimate is included because response length often dominates cost. - Editable per-million rates: Input and output prices can be changed for different model families or pricing tiers. - Cost breakdown: The output separates input, output, and total estimated cost. - Accuracy warning: The report marks token count as approximate rather than pretending to be a provider tokenizer. ## Related Tools - [JSONL Training File Validator](/developer-tools/jsonl-training-file-validator/): Paste a JSONL training file, find broken lines and message-role mistakes, then export the valid records. - [Prompt Cache Savings Calculator](/developer-tools/prompt-cache-savings-calculator/): Model repeated prompt-cache scenarios and compare cached versus uncached request cost.