AI Token Cost Math: Input, Output and Cached Tokens Explained

AI Token Cost Math: Input, Output and Cached Tokens Explained

Short answer: cost per task equals input tokens times the input rate, plus output tokens times the output rate, plus retries and cache reads. Output tokens usually cost several times more than input tokens, so response length drives the bill.

The basic formula

cost = (input_tokens / 1M × input_rate) + (output_tokens / 1M × output_rate)

Rates are quoted per million tokens and differ by model. Use the current price list from your provider; the arithmetic matters more than the exact numbers here.

A worked example

Suppose a request sends 4,000 input tokens and receives 800 output tokens. With example rates of $0.30 per million input and $1.20 per million output:

  • Input: 4,000 / 1,000,000 × $0.30 = $0.0012
  • Output: 800 / 1,000,000 × $1.20 = $0.00096
  • Total: about $0.0022 per request

At 10,000 requests per day, that is roughly $22 per day. Small per-request costs become real at volume, which is why caching and output limits matter.

Where the money actually goes

Driver Effect Control
Long system prompts Repeated input cost on every call Prompt caching, shorter instructions
Verbose answers Output tokens at the higher rate Max tokens, format instructions
Retries Full request paid again Backoff, validation, fallback model
Context growth Each turn resends history Summarise, trim, window history

Cached tokens

Prompt caching stores a stable prefix, such as a long system prompt or reference document, so repeat calls read it at a lower rate. Cache reads are cheaper than fresh input, and cache writes may carry a small premium. The saving depends on reuse: a cache only pays off when the same prefix is sent many times within its lifetime. Our prompt caching guide covers the implementation details.

Compare cost per success

Add retries and human review to the per-request price. A model that costs half as much but fails one in five tasks may cost more per finished task. Track successful completions, not API calls, and review the ratio weekly.

Practical budget rules

  • Set a max output token limit for every endpoint.
  • Log input, output and cached tokens per request.
  • Alert on cost per successful task, not total spend alone.
  • Test a smaller model on classification and extraction first.

Model choice affects both quality and unit cost; see DeepSeek vs Qwen vs Kimi. Top-ups are listed in the TOKEN category.

Frequently asked questions

Are input and output tokens priced the same?

No. Output tokens usually cost more, so answer length has a larger effect on the bill than a long prompt.

Do cached tokens reduce cost?

Cache reads are billed at a lower rate. The saving appears when the same prefix is reused often enough to offset any cache write cost.

How do I estimate monthly spend?

Multiply cost per request by daily volume and days, then add retries and peak usage. Measure real token counts instead of estimating from character counts.

Share your thoughts

Did this post help you? Leave a comment below — we read every single one and reply to as many as we can.

Comments are moderated and published after a quick review.

¿Te ayudó esta publicación? Deja un comentario abajo: leemos todos y respondemos a la mayoría.

Los comentarios se moderan y se publican tras una revisión rápida.

这篇文章对您有帮助吗?请在下方留言——我们会阅读每一条评论并尽可能回复。

评论需经过审核后才会显示。

Hat dir dieser Beitrag geholfen? Hinterlasse unten einen Kommentar – wir lesen jeden einzelnen und antworten so vielen wie möglich.

Kommentare werden moderiert und nach einer kurzen Prüfung veröffentlicht.

Cet article vous a-t-il aidé ? Laissez un commentaire ci-dessous – nous les lisons tous et répondons au plus grand nombre.

Les commentaires sont modérés et publiés après une vérification rapide.

Este artigo ajudou você? Deixe um comentário abaixo – lemos todos e respondemos à maioria.

Os comentários são moderados e publicados após uma revisão rápida.

Heeft dit bericht je geholpen? Laat hieronder een reactie achter – we lezen ze allemaal en beantwoorden zoveel mogelijk.

Reacties worden gemodereerd en na een korte controle gepubliceerd.

Czy ten post Ci pomógł? Zostaw komentarz poniżej – czytamy każdy i odpowiadamy na tyle, na ile możemy.

Komentarze są moderowane i publikowane po szybkiej weryfikacji.

Эта статья помогла вам? Оставьте комментарий ниже — мы читаем каждый и отвечаем на большинство.

Комментарии модерируются и публикуются после быстрой проверки.

هل ساعدك هذا المقال؟ اترك تعليقًا أدناه — نقرأ كل تعليق ونرد على أكبر عدد ممكن.

تتم مراجعة التعليقات وتنشر بعد التحقق السريع.

この記事は役に立ちましたか?下のコメント欄にぜひ投稿してください。すべて読んで、できる限り返信します。

コメントはモデレーション後に公開されます。

이 글이 도움이 되었나요? 아래에 댓글을 남겨주세요 — 모든 댓글을 읽고 최대한 많이 답변합니다.

댓글은 검토 후 게시됩니다.

บทความนี้ช่วยคุณได้ไหม? แสดงความคิดเห็นด้านล่าง — เราอ่านทุกความเห็นและตอบกลับให้มากที่สุด

ความคิดเห็นจะถูกตรวจสอบและเผยแพร่หลังจากการพิจารณา

האם המאמר עזר לכם? השאירו תגובה למטה — אנחנו קוראים כל תגובה ועונים לרובן.

תגובות עוברות ניהול ומתפרסמות לאחר בדיקה מהירה.

Bài viết này có giúp bạn không? Hãy để lại bình luận bên dưới — chúng tôi đọc từng bình luận và phản hồi nhiều nhất có thể.

Bình luận được kiểm duyệt và xuất hiện sau khi xét duyệt nhanh.

Apakah artikel ini membantu Anda? Tinggalkan komentar di bawah — kami membaca semuanya dan membalas sebanyak mungkin.

Komentar dimoderasi dan dipublikasikan setelah pemeriksaan cepat.

Бұл мақала сізге көмектесті ме? Төменде пікір қалдырыңыз — біз әрқайсысын оқып, мүмкіндігінше көбіне жауап береміз.

Пікірлер модерациядан өтіп, тексерілгеннен кейін жарияланады.

Comments (0)

No comments yet. Be the first to share your thoughts!