Class: Tracebook::PricingRule

Inherits:
ApplicationRecord show all
Defined in:
app/models/tracebook/pricing_rule.rb

Overview

Pricing rule for calculating LLM interaction costs.

Defines cost per 1000 tokens for a provider/model pattern. Supports glob patterns for matching multiple models and date-based effective periods.

Fields

  • provider - Provider name (e.g., "openai", "anthropic")
  • model_glob - Glob pattern for matching models (e.g., "gpt-4o*", "claude-3-5-*")
  • input_per_1k - Cost per 1000 input tokens
  • output_per_1k - Cost per 1000 output tokens
  • currency - Currency code (e.g., "USD")
  • effective_from - Date this pricing takes effect
  • effective_to - Optional end date for this pricing

Examples:

Creating pricing rules

PricingRule.create!(
  provider: "openai",
  model_glob: "gpt-4o",
  input_per_1k: 2.50,
  output_per_1k: 10.00,
  currency: "USD",
  effective_from: Date.new(2024, 8, 6)
)

Glob patterns

# Exact match
model_glob: "gpt-4o"

# All GPT-4o variants
model_glob: "gpt-4o*"

# All Claude 3.5 models
model_glob: "claude-3-5-*"

# Fallback for any model
model_glob: "*"

Finding applicable rule

rule = PricingRule
  .where(provider: "openai")
  .where("? >= effective_from", Date.current)
  .where("effective_to IS NULL OR ? < effective_to", Date.current)
  .find { |r| r.matches_model?("gpt-4o-mini") }

Instance Method Summary collapse

Instance Method Details

#active_on?(date) ⇒ Boolean

Returns true if this rule is active on the given date.

Examples:

rule.active_on?(Date.current) # => true
rule.active_on?(Date.new(2020, 1, 1)) # => false

Parameters:

  • date (Date)

    The date to check

Returns:

  • (Boolean)

    true if rule is effective on this date



62
63
64
# File 'app/models/tracebook/pricing_rule.rb', line 62

def active_on?(date)
  date >= effective_from && (effective_to.nil? || date < effective_to)
end

#matches_model?(model) ⇒ Boolean

Returns true if this rule's glob pattern matches the given model.

Uses case-insensitive file glob matching.

Examples:

rule = PricingRule.new(model_glob: "gpt-4o*")
rule.matches_model?("gpt-4o") # => true
rule.matches_model?("gpt-4o-mini") # => true
rule.matches_model?("claude-3-5-sonnet") # => false

Parameters:

  • model (String)

    Model identifier to match

Returns:

  • (Boolean)

    true if pattern matches



78
79
80
# File 'app/models/tracebook/pricing_rule.rb', line 78

def matches_model?(model)
  File.fnmatch?(model_glob, model, File::FNM_CASEFOLD)
end