StudyVisuallyStart studying
Part 02 · OpenAI API · Card 4 of 9

Usage and cost

Every response includes a usage object: prompt_tokens (what you sent) and completion_tokens (what it wrote). That is your bill.

Last updated

Analogy

The itemised receipt stapled to every response. Read it, or get surprised by the monthly total.

Code example

usage.tsTypeScript
const { prompt_tokens, completion_tokens } = res.usage;
const PRICE_PER_MILLION_INPUT = 0.15;
const PRICE_PER_MILLION_OUTPUT = 0.6;
const costInDollars =
(prompt_tokens * PRICE_PER_MILLION_INPUT +
completion_tokens * PRICE_PER_MILLION_OUTPUT) / 1_000_000;

In an agent

Agents make many calls per task. Log usage on every step so you can see which tasks are expensive.

Questions people ask

How do I calculate the cost of an OpenAI API call?

Read the usage object on the response. Multiply prompt_tokens by the model's input price and completion_tokens by its output price, both usually listed per million tokens, then add them. Log this for every call. In an agent, add it up per task so you can see which tasks are expensive.

Why are agents more expensive than single calls?

One task makes many model calls, and each call resends the growing history, including every earlier tool result. So the same tokens are paid for several times. Logging usage per step shows where the money goes; short tool results and small models for simple steps usually cut the bill the most.