Cost Tracking

Every completion carries a cost estimate derived from reported token counts

Every completion carries a cost estimate — PraisonAI derives it from the token counts your provider reports.

Diagram

Cost Estimation

📝 Prompt

🤖 LLM

📊 Usage input/output

💲 Pricing Table

🧮 Local estimate

🧾 Reported cost

max

✅ Cost USD

Cost is computed from the input_tokens and output_tokens your provider returns, multiplied by a per-model rate. Prompt-cache hits are priced at a discount, and a higher cost reported by the provider wins over the local estimate. When litellm is installed it covers 1000+ models; otherwise a built-in fallback table prices the most common models.

Quick Start

  1. Run an agent and read its token counts

    A bare Agent(llm="gpt-4o-mini") records usage automatically. Read the counts back with the global collector:

    python
    from praisonaiagents import Agent
    from praisonaiagents.telemetry.token_collector import get_token_collector
    
    agent = Agent(llm="gpt-4o-mini")
    agent.start("Summarise the theory of relativity in one paragraph")
    
    summary = get_token_collector().get_session_summary()
    print(summary["total_metrics"]["input_tokens"], summary["total_metrics"]["output_tokens"])
    # cost is derived from these counts via calculate_llm_cost()
  2. Estimate the cost from those counts

    Pass the counts and the model name to calculate_llm_cost():

    python
    from praisonaiagents.utils.cost_utils import calculate_llm_cost
    
    cost = calculate_llm_cost(
        prompt_tokens=1000,
        completion_tokens=500,
        model="gpt-4o-mini",
    )
    print(f"${cost}")  # $0.00045  →  (1000/1M × $0.15) + (500/1M × $0.60)
  3. Read cost from an async agent

    An async run reports the same telemetry as sync — every tool-loop iteration emits llm_end with tokens, cost, and latency.

    python
    import asyncio
    from praisonaiagents import Agent
    from praisonaiagents.telemetry.token_collector import get_token_collector
    
    agent = Agent(llm="gpt-4o-mini")
    
    async def main():
        await agent.astart("Summarise the theory of relativity in one paragraph")
    
    asyncio.run(main())
    
    summary = get_token_collector().get_session_summary()
    print(summary["total_metrics"]["input_tokens"], summary["total_metrics"]["output_tokens"])
    # Same non-zero counts you would see from a sync agent.start(...)
  4. Price a call with prompt caching

    Cached tokens are picked up from the response automatically — no code change needed:

    python
    from praisonaiagents.utils.cost_utils import calculate_llm_cost
    
    # Anthropic-style response from a cached run
    response = {
        "usage": {
            "prompt_tokens": 1_000_000,
            "cache_read_input_tokens": 500_000,
            "cache_creation_input_tokens": 100_000,
        }
    }
    cost = calculate_llm_cost(1_000_000, 0, "claude-3-5-sonnet-20241022", response=response)
    print(f"${cost}")  # $1.725

    Agents do the same for you. agent.total_cost already reflects cache pricing when the LLM returns cache usage:

    python
    from praisonaiagents import Agent
    
    agent = Agent(
        instructions="You are a helpful assistant.",
        llm="anthropic/claude-3-5-sonnet-20241022",
    )
    agent.start("Summarise this long document ...")
    print(agent.total_cost)  # already reflects cache_read pricing

How It Works

Cost is input_tokens × input_rate + output_tokens × output_rate. The only question is which rate applies to a given model name.

Diagram

Longest exact/prefix key

No match

🏷️ Model name

✂️ Strip provider prefix

🔍 Match fallback table

💲 Model rate

💲 default rate

✅ Cost

Prompt-cache aware pricing

Diagram

📝 prompt_tokens

Uncached × 1.0

Cached × cache_read

Cache write × cache_write

× input rate

✅ Input cost

  • Cached and cache-write tokens are part of prompt_tokens (the OpenAI/litellm convention).
  • Their sum is capped at prompt_tokens, so nothing is counted twice.
  • A model with no cache_read / cache_write multiplier uses 1.0 — the flat input rate.

Reported cost as a floor-raiser

Diagram

🧾 Reported cost

max

🧮 Local estimate

✅ Final cost

  • A reported cost can raise the figure above the estimate (for example, OpenRouter billing above list price).
  • A reported cost cannot lower it — a misreporting proxy can’t trick the budget guard.
  • A reported 0.0 means “unknown”, so the estimate is used.

Supported cache fields

ShapeField readExample provider
OpenAI-styleusage.prompt_tokens_details.cached_tokensOpenAI, Azure OpenAI
Anthropic-styleusage.cache_read_input_tokensAnthropic
Anthropic-styleusage.cache_creation_input_tokensAnthropic (cache write)
OpenRouter-styleusage.cost (reported, raises floor)OpenRouter
litellm-wrapped_hidden_params["response_cost"] (raises floor)litellm

Both dict-shaped and attribute-shaped responses work.


How Pricing Is Resolved

The fallback matcher resolves a model name to a rate in three steps:

  1. Strip the provider prefix. openai/gpt-4o-mini becomes gpt-4o-mini, so provider-qualified names resolve the same as bare names.
  2. Match longest-key-first, on exact match or prefix boundary. The table is searched from the longest key down, and a key only matches when the model name is exactly that key or starts with <key>-…. So gpt-4o-mini is billed at $0.15/1M, not gpt-4o‘s $2.50/1M, and o1-mini no longer matches o1.
  3. Fall back to default. If no key matches, the default rate applies. default is never matched by name — it is only the last resort.

Fallback Pricing Table

These are the built-in rates the SDK ships in _FALLBACK_PRICING (USD per 1M tokens). They apply when litellm is not installed.

ModelInput ($/1M)Output ($/1M)Cache read ×Cache write ×
gpt-4o2.5010.000.5
gpt-4o-mini0.150.600.5
gpt-4-turbo10.0030.00
gpt-430.0060.00
gpt-3.5-turbo0.501.50
o115.0060.000.5
o1-mini1.104.400.5
o1-preview15.0060.00
o3-mini1.104.400.5
claude-3-5-sonnet3.0015.000.11.25
claude-3-5-haiku0.804.000.11.25
claude-3-opus15.0075.000.11.25
claude-3-sonnet3.0015.00
claude-3-haiku0.251.250.11.25
gemini-1.5-pro1.255.000.25
gemini-1.5-flash0.0750.300.25
gemini-2.0-flash0.100.400.25
gemini-2.0-flash-exp0.100.40
gemini-pro0.501.50
deepseek-chat0.140.280.1
deepseek-reasoner0.552.190.25
default1.003.00

Cache multipliers apply to the input rate. Blank = flat input rate.


Common Patterns

Price a whole session

Read the session totals, then price them once:

python
from praisonaiagents import Agent
from praisonaiagents.telemetry.token_collector import get_token_collector
from praisonaiagents.utils.cost_utils import calculate_llm_cost

agent = Agent(llm="gpt-4o-mini")
agent.start("Draft a product announcement")

totals = get_token_collector().get_session_summary()["total_metrics"]
cost = calculate_llm_cost(totals["input_tokens"], totals["output_tokens"], model="gpt-4o-mini")
print(f"${cost}")
Read spend from a provider/model agent
python
from praisonaiagents import Agent

agent = Agent(llm="anthropic/claude-3-5-sonnet-20240620")
agent.start("Summarise the theory of relativity in one paragraph")

print(agent.total_cost)                 # non-zero
print(agent.cost_summary["llm_calls"])  # >= 1
Provider-prefixed model names resolve correctly

openai/gpt-4o-mini is stripped to gpt-4o-mini before matching, so it prices at the mini rate:

python
from praisonaiagents.utils.cost_utils import calculate_llm_cost

print(calculate_llm_cost(1000, 500, model="openai/gpt-4o-mini"))  # 0.00045
print(calculate_llm_cost(1000, 500, model="gpt-4o-mini"))         # 0.00045 — same
Pass cache counts explicitly

No full response object? Pass the cache counts directly. Both are part of prompt_tokens:

python
from praisonaiagents.utils.cost_utils import calculate_llm_cost

cost = calculate_llm_cost(
    prompt_tokens=1_000_000,
    completion_tokens=200_000,
    model="claude-3-5-sonnet",
    cached_tokens=800_000,
    cache_write_tokens=0,
)
print(f"${cost}")  # $3.84
OpenRouter / litellm proxy

A positive usage.cost or _hidden_params["response_cost"] on the response is picked up automatically:

python
from praisonaiagents.utils.cost_utils import calculate_llm_cost

response = {"usage": {"cost": 0.5}}  # cost reported by OpenRouter
print(calculate_llm_cost(1000, 500, model="gpt-4o-mini", response=response))  # 0.5 — max(reported, estimate)

Best Practices

Use realistic model names

Pass the exact model string you run with (e.g. gpt-4o-mini, claude-3-5-sonnet). The longest-key-first matcher relies on the full name to avoid billing a -mini model at its larger sibling’s rate.

Install litellm for uncommon models

The fallback table covers common models only. For anything outside it, install litellm and call calculate_llm_cost(..., use_litellm=True) for accurate, up-to-date pricing.

Cost is an estimate, not a bill

These numbers estimate spend from token counts and published rates. Use your provider’s dashboard for authoritative billing.


Related