### Install AI Cost Calculator Package Source: https://www.npmjs.com/package/ai-cost-calculator/index_activeTab=readme Command to install the ai-cost-calculator package using npm. ```bash npm i ai-cost-calculator ``` -------------------------------- ### Install ai-cost-calculator npm Package Source: https://www.npmjs.com/package/ai-cost-calculator/index_activeTab=readme Install the ai-cost-calculator package using npm. This package requires Node.js version 18 or higher. ```bash npm install ai-cost-calculator ``` -------------------------------- ### E2E Test Configuration with Environment Variables Source: https://www.npmjs.com/package/ai-cost-calculator/index_activeTab=code End-to-end tests in `tests/e2e/live.test.ts` run only when `LLMCOST_E2E_LIVE=true` is set in the root `.env` file. In live mode, tests prioritize OpenRouter (using `OPENROUTER_API_KEY`) and fall back to native OpenAI (using `OPENAI_API_KEY`). OpenAI endpoint coverage includes Responses API, Chat Completions API, and Legacy Completions API (conditionally). ```bash LLMCOST_E2E_LIVE=true OPENROUTER_API_KEY=your_openrouter_key OPENAI_API_KEY=your_openai_key LLMCOST_E2E_OPENAI_COMPLETIONS_MODEL=gpt-3.5-turbo-instruct ``` -------------------------------- ### Accessing Raw Pricing Data (TypeScript) Source: https://www.npmjs.com/package/ai-cost-calculator/index_activeTab=readme Demonstrates how to fetch the raw pricing data maps directly from different providers, allowing inspection of pricing details. ```typescript import { getBerriPricingMap, getOpenRouterPricingMap, getPortkeyPricingMap, getJinaPricingMap, getHeliconePricingMap, } from "ai-cost-calculator"; const berriPricing = await getBerriPricingMap(); // Map const pricing = berriPricing.get("gpt-4o-mini"); // { modelId: "gpt-4o-mini", inputCostPer1M: 0.15, outputCostPer1M: 0.6, currency: "USD" } ``` -------------------------------- ### Handling Google Response Format (TypeScript) Source: https://www.npmjs.com/package/ai-cost-calculator/index_activeTab=readme Shows how the SDK processes response payloads from Google models, utilizing the `usageMetadata` field for token counts. ```typescript import { BestEffortCalculator } from "ai-cost-calculator"; const result = await BestEffortCalculator.getCost({ model: "gemini-2.0-flash", usageMetadata: { promptTokenCount: 1500, candidatesTokenCount: 600, totalTokenCount: 2100, }, }); ``` -------------------------------- ### Unit Test Script Source: https://www.npmjs.com/package/ai-cost-calculator/index_activeTab=versions The `npm test` command executes the unit tests for the package using the Bun runtime. This ensures that individual components of the library function as expected. ```bash npm test ``` -------------------------------- ### Build and Test Scripts for NPM Package Source: https://www.npmjs.com/package/ai-cost-calculator/index_activeTab=readme Standard npm scripts for building the TypeScript project, performing type checking, and running unit and end-to-end tests using Bun. ```bash npm run build npm run typecheck npm run test npm run test:e2e ``` -------------------------------- ### Handling Anthropic Response Format (TypeScript) Source: https://www.npmjs.com/package/ai-cost-calculator/index_activeTab=readme Demonstrates how the SDK automatically handles the specific response format for Anthropic models, including different token usage keys. ```typescript import { BestEffortCalculator } from "ai-cost-calculator"; const result = await BestEffortCalculator.getCost({ model: "claude-sonnet-4-20250514", usage: { input_tokens: 2000, output_tokens: 800 }, }); ``` -------------------------------- ### Unit Test Script Source: https://www.npmjs.com/package/ai-cost-calculator/index_activeTab=dependents Runs the unit tests for the package using the Bun runtime. This script is essential for verifying the functionality of individual components. ```bash npm run test ``` -------------------------------- ### Extending Provider Support with Configuration Files Source: https://www.npmjs.com/package/ai-cost-calculator/index_activeTab=code To add or update provider support, modify JSON files in the `configs/` directory. `response-mappings.json` uses JSONPath expressions to extract token usage per provider, while `provider-pricing-mappings.json` normalizes pricing payloads. No code changes are required for these updates. ```json { "response-mappings.json": "JSONPath expressions for extracting token usage per provider", "provider-pricing-mappings.json": "JSONPath expressions for normalizing pricing payloads" } ``` -------------------------------- ### Scripts Source: https://www.npmjs.com/package/ai-cost-calculator/index_activeTab=versions Available npm scripts for building, type-checking, and running tests. ```APIDOC ## Scripts - **`npm run build`**: Compiles the TypeScript source code into the `dist/` directory. - **`npm run typecheck`**: Performs TypeScript type checking without generating JavaScript output. - **`npm test`**: Executes the unit tests using the Bun runtime. - **`npm run test:e2e`**: Runs the end-to-end tests. ``` -------------------------------- ### End-to-End Test Configuration for Live Mode Source: https://www.npmjs.com/package/ai-cost-calculator/index_activeTab=readme End-to-end tests can be run in live mode by setting the `LLMCOST_E2E_LIVE` environment variable. In live mode, tests prioritize OpenRouter and fall back to native OpenAI APIs, with specific configurations for different OpenAI endpoints. ```bash # Set in root .env file LLMCOST_E2E_LIVE=true OPENROUTER_API_KEY=sk-... OPENAI_API_KEY=sk-... LLMCOST_E2E_OPENAI_COMPLETIONS_MODEL=gpt-3.5-turbo-instruct ``` -------------------------------- ### E2E Live Test Configuration Source: https://www.npmjs.com/package/ai-cost-calculator/index_activeTab=dependents The `tests/e2e/live.test.ts` script runs only when the `LLMCOST_E2E_LIVE` environment variable is set to `true`. In live mode, it prioritizes OpenRouter API keys and falls back to native OpenAI API keys for testing various OpenAI endpoints. ```typescript When live mode is enabled, tests prefer OpenRouter (`OPENROUTER_API_KEY`) and fall back to native OpenAI (`OPENAI_API_KEY`). OpenAI endpoint coverage includes: * Responses API (`/v1/responses`) * Chat Completions API (`/v1/chat/completions`) * Legacy Completions API (`/v1/completions`) — runs only when `LLMCOST_E2E_OPENAI_COMPLETIONS_MODEL` is configured ``` -------------------------------- ### Basic Cost Calculation with ai-cost-calculator (TypeScript) Source: https://www.npmjs.com/package/ai-cost-calculator/index_activeTab=readme Demonstrates the simplest way to calculate LLM API costs using the BestEffortCalculator. It attempts to use multiple pricing sources until one succeeds and returns the cost in USD. ```typescript import { BestEffortCalculator } from "ai-cost-calculator"; const response = { model: "gpt-4o-mini", usage: { prompt_tokens: 1000, completion_tokens: 500, total_tokens: 1500, }, }; const result = await BestEffortCalculator.getCost(response); console.log(result); // { currency: "USD", cost: 0.000225 } ``` -------------------------------- ### Handling Provider-Prefixed Models (TypeScript) Source: https://www.npmjs.com/package/ai-cost-calculator/index_activeTab=readme Illustrates how the BestEffortCalculator automatically normalizes model IDs that are prefixed with a provider name, such as those from OpenRouter. ```typescript import { BestEffortCalculator } from "ai-cost-calculator"; const result = await BestEffortCalculator.getCost({ model: "openai/gpt-4o-mini", usage: { prompt_tokens: 1000, completion_tokens: 500, total_tokens: 1500 }, }); ``` -------------------------------- ### Specific Pricing Source Calculation (TypeScript) Source: https://www.npmjs.com/package/ai-cost-calculator/index_activeTab=readme Shows how to use a specific pricing backend for cost calculation by importing and using individual calculator classes like BerrilmBasedCalculator. ```typescript import { OpenRouterBasedCalculator, BerrilmBasedCalculator, PortkeyBasedCalculator, JinaBasedCalculator, HeliconeBasedCalculator, } from "ai-cost-calculator"; const response = { model: "gpt-4o-mini", usage: { prompt_tokens: 1000, completion_tokens: 500, total_tokens: 1500, }, }; const result = await BerrilmBasedCalculator.getCost(response); ``` -------------------------------- ### Extending Provider Support Source: https://www.npmjs.com/package/ai-cost-calculator/index_activeTab=versions Instructions on how to add or update provider support by modifying configuration files without code changes. ```APIDOC ## Extending Provider Support To add support for new AI providers or update existing ones, modify the JSON configuration files in the `configs/` directory: - **`response-mappings.json`**: Contains JSONPath expressions used to extract token usage details (input tokens, output tokens) from provider-specific response formats. - **`provider-pricing-mappings.json`**: Contains JSONPath expressions used to extract and normalize pricing information (model ID, input cost per 1M tokens, output cost per 1M tokens) from provider API responses. No modifications to the package's source code are necessary for these mapping updates. ``` -------------------------------- ### E2E Test Environment Variables Source: https://www.npmjs.com/package/ai-cost-calculator/index_activeTab=dependencies Details the environment variables required for running end-to-end tests, particularly when live mode is enabled. It specifies preferences for API keys (OpenRouter, OpenAI) and model configurations. ```bash LLMCOST_E2E_LIVE=true OPENROUTER_API_KEY=... OPENAI_API_KEY=... LLMCOST_E2E_OPENAI_COMPLETIONS_MODEL=... ``` -------------------------------- ### Build Script Source: https://www.npmjs.com/package/ai-cost-calculator/index_activeTab=versions The `npm run build` command is used to compile the TypeScript source code into JavaScript, typically outputting to the `dist/` directory. This is a standard step in preparing a Node.js package for distribution. ```bash npm run build ``` -------------------------------- ### Extracting Response Metadata (TypeScript) Source: https://www.npmjs.com/package/ai-cost-calculator/index_activeTab=readme Demonstrates how to extract the model name and infer the provider from a given response payload using dedicated functions. ```typescript import { extractResponseModel, extractResponseMetadata } from "ai-cost-calculator"; const response = { model: "gpt-4o-mini", usage: { prompt_tokens: 1000, completion_tokens: 500, total_tokens: 1500, }, }; const model = extractResponseModel(response); // "gpt-4o-mini" const metadata = await extractResponseMetadata(response); // { model: "gpt-4o-mini", provider: "openai" } ``` -------------------------------- ### Model ID Normalization and Resolution (TypeScript) Source: https://www.npmjs.com/package/ai-cost-calculator/index_activeTab=readme Illustrates functions for normalizing model IDs to a consistent format, stripping provider prefixes, and resolving them to a canonical form. ```typescript import { normalizeModelId, stripProviderPrefix, resolveCanonicalModelId, } from "ai-cost-calculator"; normalizeModelId("GPT-4o-Mini"); // "gpt-4o-mini" stripProviderPrefix("openai/gpt-4o-mini"); // "gpt-4o-mini" const canonical = await resolveCanonicalModelId("openai/gpt-4o-mini"); // "gpt-4o-mini" ``` -------------------------------- ### TokenUsage Interface Definition Source: https://www.npmjs.com/package/ai-cost-calculator/index_activeTab=readme Defines the structure for tracking token usage, including input tokens, output tokens, and the total number of tokens. ```typescript interface TokenUsage { inputTokens: number; outputTokens: number; totalTokens: number; } ``` -------------------------------- ### End-to-End Test Script Source: https://www.npmjs.com/package/ai-cost-calculator/index_activeTab=versions The `npm run test:e2e` command runs the end-to-end tests for the package. These tests validate the integration of various components and their behavior in a more realistic environment. ```bash npm run test:e2e ``` -------------------------------- ### Errors Source: https://www.npmjs.com/package/ai-cost-calculator/index_activeTab=versions Lists the custom errors that can be thrown by the ai-cost-calculator package, all extending `LlmcostError`. ```APIDOC ## Errors All errors thrown by this package extend the base `LlmcostError`. - **UsageNotFoundError**: Indicates that token usage could not be extracted from the provided response. - **ModelNotFoundError**: Indicates that the AI model could not be found in the configured pricing sources. - **PricingUnavailableError**: Indicates that the pricing values obtained are invalid or unavailable. - **ModelInferenceError**: Indicates an issue with reading the model ID from the response. - **ProviderInferenceError**: Indicates an issue determining the AI model's provider from the response. - **BestEffortCalculationError**: Occurs when all pricing sources fail. The `.causes` property will contain individual errors from each source. ``` -------------------------------- ### Types Source: https://www.npmjs.com/package/ai-cost-calculator/index_activeTab=versions Defines the data structures used for cost results, token usage, normalized pricing models, and response metadata. ```APIDOC ## Types ### CostResult Represents the calculated cost. - **currency** (string) - The currency of the cost, fixed to "USD". - **cost** (number) - The calculated cost amount. ### TokenUsage Represents the token counts for an AI model's response. - **inputTokens** (number) - The number of input tokens. - **outputTokens** (number) - The number of output tokens. - **totalTokens** (number) - The total number of tokens (input + output). ### NormalizedPricingModel Represents standardized pricing information for a model. - **modelId** (string) - The identifier for the model. - **inputCostPer1M** (number) - The cost per 1 million input tokens. - **outputCostPer1M** (number) - The cost per 1 million output tokens. - **currency** (string) - The currency of the pricing, fixed to "USD". ### ResponseMetadata Contains metadata extracted from the AI model's response. - **model** (string) - The name or ID of the model used. - **provider** (string) - The provider of the AI model. ``` -------------------------------- ### NPM Scripts for Building and Testing the Package Source: https://www.npmjs.com/package/ai-cost-calculator/index_activeTab=code Provides standard NPM scripts for managing the ai-cost-calculator package. `npm run build` compiles TypeScript to the `dist/` directory, `npm run typecheck` performs type checking without emitting files, `npm test` runs unit tests using Bun, and `npm run test:e2e` executes end-to-end tests. ```bash npm run build npm run typecheck npm test npm run test:e2e ``` -------------------------------- ### Inferring Provider from Model ID (TypeScript) Source: https://www.npmjs.com/package/ai-cost-calculator/index_activeTab=readme Shows how to programmatically determine the AI provider associated with a given model ID. ```typescript import { inferProviderFromModel } from "ai-cost-calculator"; const provider = await inferProviderFromModel("gpt-4o-mini"); // "openai" ``` -------------------------------- ### E2E Tests Source: https://www.npmjs.com/package/ai-cost-calculator/index_activeTab=versions Details on running end-to-end tests, including live mode and specific API endpoint coverage. ```APIDOC ## E2E Tests The end-to-end tests, located in `tests/e2e/live.test.ts`, are executed only when the `LLMCOST_E2E_LIVE=true` environment variable is set in the root `.env` file. When live mode is active, the tests prioritize using the OpenRouter API (requires `OPENROUTER_API_KEY`). If OpenRouter is unavailable, it falls back to using the native OpenAI API (requires `OPENAI_API_KEY`). OpenAI endpoint coverage includes: - Responses API (`/v1/responses`) - Chat Completions API (`/v1/chat/completions`) - Legacy Completions API (`/v1/completions`) - This specific endpoint is tested only if `LLMCOST_E2E_OPENAI_COMPLETIONS_MODEL` is configured in the environment. ``` -------------------------------- ### NormalizedPricingModel Interface Definition Source: https://www.npmjs.com/package/ai-cost-calculator/index_activeTab=readme Defines the structure for normalized pricing information for a model. It includes the model ID, input and output costs per million tokens, and the currency (USD). ```typescript interface NormalizedPricingModel { modelId: string; inputCostPer1M: number; outputCostPer1M: number; currency: "USD"; } ``` -------------------------------- ### Extracting Token Usage from Response Source: https://www.npmjs.com/package/ai-cost-calculator/index_activeTab=dependencies Extracts token counts (input, output, and total) from a given response object without calculating the cost. It can optionally infer the provider to correctly parse the usage details. ```typescript import { extractTokenUsage } from "ai-cost-calculator"; const response = { usage: { prompt_tokens: 10, completion_tokens: 5, total_tokens: 15 } }; const usage = extractTokenUsage( response, "openai" ); // { inputTokens: 10, outputTokens: 5, totalTokens: 15 } ``` -------------------------------- ### Error Handling in Cost Calculation (TypeScript) Source: https://www.npmjs.com/package/ai-cost-calculator/index_activeTab=readme Shows how to handle potential errors during cost calculation, such as `BestEffortCalculationError`, `ModelNotFoundError`, and `UsageNotFoundError`, using try-catch blocks. ```typescript import { BestEffortCalculator, BestEffortCalculationError, ModelNotFoundError, UsageNotFoundError, } from "ai-cost-calculator"; const response = { model: "gpt-4o-mini", usage: { prompt_tokens: 1000, completion_tokens: 500, total_tokens: 1500, }, }; try { const result = await BestEffortCalculator.getCost(response); } catch (error) { if (error instanceof BestEffortCalculationError) { console.error("All pricing sources failed:"); for (const cause of error.causes) { console.error(` - ${cause.message}`); } } } ``` -------------------------------- ### ResponseMetadata Interface Definition Source: https://www.npmjs.com/package/ai-cost-calculator/index_activeTab=readme Defines the structure for metadata extracted from a response, including the model name and the provider. ```typescript interface ResponseMetadata { model: string; provider: string; } ``` -------------------------------- ### Typecheck Script Source: https://www.npmjs.com/package/ai-cost-calculator/index_activeTab=versions The `npm run typecheck` command performs type checking on the TypeScript codebase without generating any JavaScript output. This is useful for verifying code correctness during development. ```bash npm run typecheck ``` -------------------------------- ### Extracting Token Usage (TypeScript) Source: https://www.npmjs.com/package/ai-cost-calculator/index_activeTab=readme Provides a function to extract token usage details from a response payload without calculating the cost. It can optionally infer the provider. ```typescript import { extractTokenUsage } from "ai-cost-calculator"; const usage = extractTokenUsage( { usage: { prompt_tokens: 10, completion_tokens: 5, total_tokens: 15 } }, "openai" ); // { inputTokens: 10, outputTokens: 5, totalTokens: 15 } ``` -------------------------------- ### Calculator Static Method for Cost Calculation Source: https://www.npmjs.com/package/ai-cost-calculator/index_activeTab=readme All calculator classes in this package expose a static asynchronous method `getCost` to calculate the cost based on a given response. This method returns a `CostResult` object containing the cost and currency. ```typescript static async getCost(response: unknown): Promise ``` -------------------------------- ### Calculators - getCost Method Source: https://www.npmjs.com/package/ai-cost-calculator/index_activeTab=versions All calculator implementations expose a static asynchronous method `getCost` to retrieve cost information from a given response. ```APIDOC ## POST /calculate/cost ### Description Calculates the cost of an AI model's response. This endpoint is a conceptual representation as the `getCost` method is a static method within the library. ### Method `POST` (Conceptual - actual usage is a static method call) ### Endpoint `/calculate/cost` (Conceptual) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **response** (unknown) - Required - The response object from which to extract cost and token usage information. ### Request Example ```json { "response": { ... } } ``` ### Response #### Success Response (200) - **currency** (string) - The currency of the cost, always "USD". - **cost** (number) - The calculated cost of the AI model's response. #### Response Example ```json { "currency": "USD", "cost": 0.0005 } ``` ``` -------------------------------- ### Cache Management for Pricing Data (TypeScript) Source: https://www.npmjs.com/package/ai-cost-calculator/index_activeTab=readme Provides functions to clear the cached pricing data for individual providers or aliases, forcing a refresh on the next request. ```typescript import { clearBerriCache, clearOpenRouterCache, clearPortkeyCache, clearJinaCache, clearHeliconeCache, clearAliasCache, } from "ai-cost-calculator"; clearBerriCache(); clearOpenRouterCache(); ``` -------------------------------- ### Error Hierarchy Source: https://www.npmjs.com/package/ai-cost-calculator/index_activeTab=dependents All custom errors in the ai-cost-calculator package extend the base `LlmcostError`. This provides a consistent error handling mechanism. ```typescript All errors extend `LlmcostError`: ``` -------------------------------- ### Error Hierarchy for LLM Cost Calculation Source: https://www.npmjs.com/package/ai-cost-calculator/index_activeTab=readme All custom errors in the ai-cost-calculator package extend the base `LlmcostError`. Specific error types include issues with usage extraction, model identification, pricing availability, and calculation failures. ```typescript class LlmcostError extends Error {} class UsageNotFoundError extends LlmcostError {} class ModelNotFoundError extends LlmcostError {} class PricingUnavailableError extends LlmcostError {} class ModelInferenceError extends LlmcostError {} class ProviderInferenceError extends LlmcostError {} class BestEffortCalculationError extends LlmcostError {} ``` -------------------------------- ### Error Hierarchy Source: https://www.npmjs.com/package/ai-cost-calculator/index_activeTab=versions All custom errors in the ai-cost-calculator package inherit from `LlmcostError`. This provides a consistent error handling mechanism. Specific errors like `UsageNotFoundError` and `ModelNotFoundError` indicate distinct failure conditions during cost calculation. ```typescript All errors extend `LlmcostError`: Error | Description ---|--- `UsageNotFoundError` | Token usage cannot be extracted from the response `ModelNotFoundError` | Model not found in the pricing source `PricingUnavailableError` | Pricing values are invalid `ModelInferenceError` | Model ID cannot be read from the response `ProviderInferenceError` | Provider cannot be determined from the model `BestEffortCalculationError` | All sources failed; `.causes` contains individual errors ``` -------------------------------- ### CostResult Interface Definition Source: https://www.npmjs.com/package/ai-cost-calculator/index_activeTab=readme Defines the structure for the result of a cost calculation. It includes the monetary cost and the currency, which is fixed to USD. ```typescript interface CostResult { currency: "USD"; cost: number; } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.