Lompat ke konten

Pelajaran 19 ยท Reliability and Cost

Tokens, Costs and Prompt Caching

Estimate and control OpenAI API costs: read token usage, count input tokens, calculate prices, use prompt caching and set budgets for your app.

Most text calls are billed per token. Input and output have separate prices, and output usually costs several times more. A single call is often cheap. Thousands of calls a day, long histories and large documents are not. This lesson shows how to see what you use, estimate a bill and reduce it without lowering quality.

Read the usage object

Every response reports what it used.

Python
# Read-only
usage = response.usage
print(usage.input_tokens)
print(usage.input_tokens_details.cached_tokens)
print(usage.output_tokens)
print(usage.output_tokens_details.reasoning_tokens)

Reasoning tokens are part of output tokens, so they cost money even though you do not see them. Log usage for every call with the feature name, model and an anonymous user or tenant ID. Then you can find which feature spends the money.

Count input before you send

The API has an endpoint that counts input tokens for a request.

Python
# Read-only
count = client.responses.input_tokens.count(
    model="gpt-6.2-sol",
    input="Summarize this document ...",
)
print(count.input_tokens)

You can pass tools and message lists too. It helps you reject oversized input early. Do not use "four characters per token" for budgets. It is only a rough teaching estimate and varies a lot between languages and content.

The cost formula

For a plain call:

TEXT
cost = (ordinary input  x input price
      + cached input    x cached price
      + cache writes    x write price
      + output          x output price) / 1,000,000

The next block uses the standard prices for gpt-6.2-sol from OpenAI's pricing page, as of December 2026, for requests up to 272K input tokens: input $2.00, cached input $0.10 and output $10.00 per million. Cache writes are priced at 1.25 times the input rate for the 30-minute cache. Update the numbers before you rely on the result.

Python Estimate the cost of a feature

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The estimate ignores cache writes in the warm case and other fees, such as hosted tools. Real traffic does not always hit the cache. Use real usage logs once you have them.

Remember that long-context requests (over 272K input tokens for these models) have higher prices, and tools can add their own fees.

Prompt caching

Prompt caching reuses the processed beginning of a request when later requests start with the same tokens. This can lower cost and delay. As of December 2026, the caching guide says:

  • The shared prefix must be at least 1,024 visible input tokens.
  • Cache reads cost a small fraction of the input price (0.05 times for the GPT-6.2 models).
  • Cache writes cost more than ordinary input: 1.25 times for a 30-minute lifetime, 2.5 times for a 12-hour lifetime.
  • The usage object reports cached_tokens and cache writes.

You can set a prompt_cache_key to keep cache use separate for each customer or user, and there are explicit options for choosing cache breakpoints.

Because matching works on the prefix, order matters:

  1. Stable rules and examples first, in a developer message.
  2. Stable documents and tool definitions next.
  3. Changing data, such as the user's question and the time, last.

For GPT-6.2 models, the documentation says top-level instructions are placed after the input, so put long stable guidance in the first developer message. A single timestamp at the start of your prompt can stop the whole prefix from matching. The prefix helper below shows this.

Python See how an early change breaks the shared prefix

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

This compares words, not real tokens. It only shows the idea.

Other ways to spend less

  • Pick the right model. Test smaller ones on your examples. See models and reasoning.
  • Lower reasoning effort where quality stays good.
  • Send less. Trim history, retrieve only relevant chunks and remove unused tools.
  • Ask for shorter output in instructions, and set a cap with room to spare.
  • Use batch or background windows for work that can wait; they have discounts.
  • Avoid needless calls. Use ordinary code for simple rules.

Do not cut cost blindly. Rerun your tests after every change: a cheaper call that fails and gets retried may cost more.

Budgets and alarms

Set per-user and per-feature limits in your own code, such as requests per hour and maximum input size. Add spend alerts or hard limits in your project settings, and check the usage dashboard. Alert when daily spend or tokens per request jump suddenly. A loop bug can spend a lot of money overnight.

A worked way to find savings

Start with data, not guesses. For one week, group logged usage by feature. For the most expensive feature, look at the average input, cached input, output and reasoning tokens per call, and the calls per user action. The largest number shows where to look.

If input is large, find out what fills it: history, retrieved documents, tool definitions or instructions. Remove or shorten the part that adds least. If reasoning tokens dominate, test a lower effort. If one user action makes many calls, check for a retry loop or an agent that takes needless steps. If the cached share is low despite a long stable prompt, look for something that changes near the start.

After each change, compare cost per successful task, not just cost per call. Write down the result, so you do not repeat experiments. Then set an alert a little above the new normal level.

Common mistakes

  • Estimating from the first message of a chat, although later turns carry the history and cost more.
  • Forgetting reasoning tokens, retries and tool fees in a budget.
  • Judging a change only by price and not noticing that more tasks now fail.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How are reasoning tokens charged?

    They are included in output tokens.
  2. 2. Where should changing content go to help caching?

    Caching matches the beginning of the request, so stable material should come first.
  3. 3. Are cache writes free?

    As of December 2026, writes cost more than ordinary input, so caching pays off when the prefix is reused.
  4. 4. What is the most reliable source for cost planning after launch?

    Real usage data captures history, retries and cache hit rates.

Summary

  • Log usage, including cached and reasoning tokens.
  • Count input before sending when size matters.
  • Calculate costs from current official prices.
  • Put stable content first to benefit from caching, and remember writes cost money.
  • Combine model choice, smaller inputs and budgets with quality tests.

Next: Batch and Background Jobs

Progres Anda disimpan di browser ini. Tidak perlu akun.