Overview
ThegetModelUsageCost 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:
UsageCostobject if pricing data is availablenullif the model is not found in the models.dev database
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
null.
Provider Normalization
The function automatically normalizes provider names:provider.chat→providergoogle.generative-ai→google
Prompt Caching
For models that support prompt caching (like Claude with prompt caching), the function calculates cache costs:Caching
Pricing data is cached in memory to avoid repeated HTTP requests:Error Handling
The function handles errors gracefully:- 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
Check for null
Check for null
Always handle the case where pricing is unavailable:
Batch cost calculations
Batch cost calculations
Calculate costs in batches to benefit from caching:
Monitor costs in production
Monitor costs in production
Log costs for monitoring and budgeting:
Use streaming for long responses
Use streaming for long responses
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