Skip to main content

Overview

The getModelUsageCost function calculates the cost in USD for AI model usage based on token consumption. It fetches pricing data from models.dev, an open-source pricing database maintained by SST.

Usage

API Reference

getModelUsageCost

Calculate the cost of model usage based on token consumption.
object
required
Parameters for cost calculation
Effect<UsageCost | null, never, HttpClient>
An Effect that resolves to:
  • UsageCost object if pricing data is available
  • null if the model is not found in the models.dev database
Requires HttpClient from @effect/platform in the context.

UsageCost

The cost breakdown object:
number
Cost in USD for input tokens. Includes cache read costs if applicable.
number
Cost in USD for output tokens.
number
Total cost in USD (input + output).

Complete Example

Supported Models

The function supports models from providers in the models.dev database:
  • OpenAI (GPT-4, GPT-3.5, etc.)
  • Anthropic (Claude 3, Claude 2, etc.)
  • Google (Gemini, PaLM 2)
  • Mistral AI
  • Cohere
  • And many more
If a model is not found, the function returns null.

Provider Normalization

The function automatically normalizes provider names:
Supported normalizations:
  • provider.chatprovider
  • google.generative-aigoogle

Prompt Caching

For models that support prompt caching (like Claude with prompt caching), the function calculates cache costs:
Cache read pricing is typically 90% cheaper than fresh input tokens.

Caching

Pricing data is cached in memory to avoid repeated HTTP requests:
The cache persists for the lifetime of the Node process.

Error Handling

The function handles errors gracefully:
Common scenarios:
  • Model not in database: Returns null
  • Network error: Effect fails with error
  • Invalid TOML: Effect fails with TomlParseError

Budget Tracking Example

Track costs across multiple requests:

Cost Alerts

Implement cost monitoring:

Model Comparison

Compare costs across models:

Custom Pricing Sources

If you need to use custom pricing instead of models.dev:

Best Practices

Always handle the case where pricing is unavailable:
Calculate costs in batches to benefit from caching:
Log costs for monitoring and budgeting:
For long generations, streaming can help manage costs by allowing early termination:

Next Steps

Turn Handler

Calculate costs for conversation turns

Examples

See cost tracking examples

models.dev

Browse the pricing database