APIコストの計算と予測
token数を数えてモデルごとの料金を適用し、リクエスト送信前にコストを見積もるPythonヘルパーを作成して、予期しない請求を防ぎます。
「APIコストの計算と予測」はCoddyKit上の無料AI Engineering Academyレッスンです。 これはレッスン3/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応のAIチューターでハンズオン演習できます。 これはAI Engineering Academy学習パスの一部であり、ウェブとCoddyKitアプリ全体で進捗が同期されます。 AI Engineering Academyコースには全4レッスンが含まれています。
このレッスンの一部はまだ翻訳されておらず、英語で表示されています。
Why Cost Prediction Matters
API costs for LLM applications can be surprisingly large at scale. A single query that seems cheap at $0.002 becomes $200 when run 100,000 times. Without cost prediction and monitoring, AI features can generate unexpected cloud bills that dwarf your entire infrastructure spend.
The good news is that LLM costs are entirely predictable before you send a request: you know the model, you can count the input tokens with tiktoken, and you can estimate output tokens based on your max_tokens setting or historical averages. Building cost prediction into your application from day one prevents billing surprises.
OpenAI Pricing Structure
OpenAI charges separately for input tokens and output tokens, with output typically costing 3-4x more. Prices vary by model. As a guide for 2025 (always check the current pricing page as it changes):
- gpt-4o-mini: ~$0.15/million input, ~$0.60/million output
- gpt-4o: ~$2.50/million input, ~$10.00/million output
- text-embedding-3-small: ~$0.02/million tokens
The cost difference between models is enormous: gpt-4o is approximately 17x more expensive than gpt-4o-mini per input token. Model selection is your biggest lever for cost control — always start with the cheapest model that meets your quality requirements.
A Cost Estimation Helper Function
Build a cost estimator that you call before sending any request. It counts input tokens with tiktoken, estimates output tokens from your max_tokens parameter, looks up the per-model price, and returns the estimated cost in dollars. Call this in development and log the results so you build intuition for what different query types cost.
import tiktoken
# Prices per million tokens as of early 2025
PRICING = {
'gpt-4o': {'input': 2.50, 'output': 10.00},
'gpt-4o-mini': {'input': 0.15, 'output': 0.60},
'gpt-4-turbo': {'input': 10.00, 'output': 30.00},
'text-embedding-3-small': {'input': 0.02, 'output': 0.0},
}
def estimate_cost(messages, model='gpt-4o-mini', expected_output_tokens=500):
enc = tiktoken.encoding_for_model(model)
input_tokens = sum(
len(enc.encode(m.get('content', ''))) + 4
for m in messages
) + 3
if model not in PRICING:
raise ValueError(f'Unknown model: {model}')
rates = PRICING[model]
input_cost = (input_tokens / 1_000_000) * rates['input']
output_cost = (expected_output_tokens / 1_000_000) * rates['output']
total = input_cost + output_cost
print(f'Model: {model}')
print(f'Input tokens: {input_tokens} (${input_cost:.6f})')
print(f'Est. output tokens: {expected_output_tokens} (${output_cost:.6f})')
print(f'Estimated total: ${total:.6f}')
return totalTracking Actual Costs from API Responses
After each API call, the response object contains the actual token counts used. Extract these to log real costs and compare them to your estimates. Over time, the gap between estimated and actual output tokens tells you how accurately you are predicting usage, and the logs give you a cost breakdown by feature or user segment.
import openai
client = openai.OpenAI()
PRICING = {
'gpt-4o-mini': {'input': 0.15, 'output': 0.60},
}
def chat_with_cost_tracking(model, messages):
response = client.chat.completions.create(
model=model, messages=messages
)
usage = response.usage
rates = PRICING.get(model, {'input': 0, 'output': 0})
actual_cost = (
(usage.prompt_tokens / 1_000_000) * rates['input'] +
(usage.completion_tokens / 1_000_000) * rates['output']
)
print(f'Input: {usage.prompt_tokens} tokens')
print(f'Output: {usage.completion_tokens} tokens')
print(f'Total: {usage.total_tokens} tokens')
print(f'Actual cost: ${actual_cost:.6f}')
return response, actual_costProjecting Monthly Costs
Once you know the average cost per request and the expected request volume, projecting monthly costs is straightforward. Build a cost model spreadsheet or a simple Python script that lets you test different assumptions: what if daily active users doubles? What if we add a feature that makes 3 API calls per user action instead of 1?
def project_monthly_cost(
avg_cost_per_request,
requests_per_day,
days=30
):
daily_cost = avg_cost_per_request * requests_per_day
monthly_cost = daily_cost * days
print(f'Avg cost/request: ${avg_cost_per_request:.6f}')
print(f'Requests/day: {requests_per_day:,}')
print(f'Daily cost: ${daily_cost:.2f}')
print(f'Monthly cost: ${monthly_cost:.2f}')
# Growth scenarios
for multiplier in [2, 5, 10]:
scaled = monthly_cost * multiplier
print(f' At {multiplier}x traffic: ${scaled:.2f}/month')
# Example: customer support bot
project_monthly_cost(
avg_cost_per_request=0.002, # 2 cents per support query
requests_per_day=5000
)The Cost Impact of Model Choice
The single biggest lever for cost reduction is using the cheapest model that meets your quality requirement. For many tasks, gpt-4o-mini performs comparably to gpt-4o but at ~17x lower cost. Before defaulting to the most powerful model, benchmark the cheaper model on your specific task and switch to the more expensive one only if quality falls below your threshold.
A tiered routing strategy is even more effective: classify incoming requests by complexity and route simple queries to cheap models and complex ones to expensive models. Even routing 70% of traffic to the cheap model while 30% goes to the expensive one saves approximately 70% of your AI costs.
Prompt Length and Cost
Every token in your prompt costs money. A verbose system prompt that could be condensed without losing meaning directly increases your API bill for every request. Benchmark the token count of your prompts and look for opportunities to tighten wording. Similarly, long few-shot examples can often be replaced by shorter equivalents without sacrificing accuracy.
For RAG systems, the retrieved context is often the largest part of the prompt. Returning 10 large chunks when 3 well-chosen smaller ones would suffice wastes tokens on every query. Tune your retrieval to minimize redundant context while maximizing relevance.
Batching for Cost Efficiency
OpenAI offers a Batch API that processes requests asynchronously at 50% off the standard price. If your use case is not latency-sensitive — document processing, nightly analysis jobs, bulk content generation — the Batch API can halve your costs with minimal code changes.
Batch requests are submitted as JSONL files, processed within 24 hours, and results retrieved from the API. This is ideal for preprocessing pipelines that run on a schedule and do not need real-time responses.
import openai
import json
client = openai.OpenAI()
# Create batch request file
requests = [
{'custom_id': f'doc-{i}',
'method': 'POST',
'url': '/v1/chat/completions',
'body': {
'model': 'gpt-4o-mini',
'messages': [{'role': 'user', 'content': f'Summarize document {i}'}],
'max_tokens': 200
}}
for i in range(100)
]
# Write to JSONL
with open('/tmp/batch_input.jsonl', 'w') as f:
for req in requests:
f.write(json.dumps(req) + '\n')
# Upload and submit (50% off list price)
print('Would submit batch for 100 documents at 50% discount')
# batch_file = client.files.create(file=open('/tmp/batch_input.jsonl','rb'), purpose='batch')
# batch = client.batches.create(input_file_id=batch_file.id, endpoint='/v1/chat/completions', completion_window='24h')Setting Spending Limits
Always configure spending limits to prevent runaway costs. In the OpenAI dashboard, you can set monthly spending caps that cut off API access when the limit is reached. Set a hard limit at your maximum acceptable spend and a soft limit at 80% of that value to receive an email warning before hitting the hard cap.
In your application code, implement a per-user or per-feature budget tracked in your database. Check the budget before each API call and return an error if it is exhausted. This prevents a single runaway user or a bug in a batch job from consuming your entire monthly quota in hours.
Caching to Avoid Redundant API Calls
The cheapest API call is the one you never make. Implement caching at the application layer to serve identical requests from cache rather than calling the API again. Even a simple Redis cache keyed on the SHA256 hash of the prompt can eliminate a significant fraction of redundant calls in a production application.
For embeddings, caching is especially impactful: the same text should only be embedded once. Store embeddings in your vector database with the original text as a key, and check for an existing embedding before calling the embeddings API. In a RAG pipeline, document embeddings are computed once at index time and reused for every query that retrieves them.
import hashlib
import json
# Simple in-memory cache (use Redis in production)
_cache = {}
def cached_completion(client, model, messages, **kwargs):
cache_key = hashlib.sha256(
json.dumps({'model': model, 'messages': messages}).encode()
).hexdigest()
if cache_key in _cache:
print('Cache HIT - no API call made')
return _cache[cache_key]
response = client.chat.completions.create(
model=model, messages=messages, **kwargs
)
_cache[cache_key] = response
print('Cache MISS - API call made')
return responseBuilding a Cost Dashboard
In production, you need visibility into your AI costs broken down by feature, user, and model. Build a cost dashboard by logging every API call's token counts and associated metadata (user ID, feature name, model) to a time-series database. Then aggregate to answer questions like: which feature is driving the most spend? Are power users generating disproportionate costs? Is cost per query trending up after a prompt change?
This visibility is essential for making data-driven optimization decisions rather than guessing where to cut costs. Most companies discover that 20% of their features account for 80% of their AI spend, and optimizing those features has outsized impact.
Quick Check
Test your understanding of AI Engineering concepts from this lesson.
Lesson Recap
In this lesson you learned: API costs can be predicted before sending by counting input tokens with tiktoken and estimating output tokens, model selection is the biggest cost lever — gpt-4o-mini can be 17x cheaper than gpt-4o for appropriate tasks, and caching, batching, and spending limits prevent runaway costs in production. Next up we explore strategies for managing long conversations that exceed the context window.
よくある質問
「APIコストの計算と予測」レッスンは無料ですか?
はい。「APIコストの計算と予測」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、AI Engineering Academyコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 AI Engineering Academyコースには全4レッスンが含まれています。
「APIコストの計算と予測」で何を学びますか?
token数を数えてモデルごとの料金を適用し、リクエスト送信前にコストを見積もるPythonヘルパーを作成して、予期しない請求を防ぎます。 ブラウザで直接実行するハンズオンコードでAI Engineering Academyを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。
AI Engineering Academyを始めるのに経験は必要ですか?
事前経験は必要ありません。CoddyKitのAI Engineering Academyは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン3/4です。
「APIコストの計算と予測」レッスンにはどのくらい時間がかかりますか?
ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。
このAI Engineering Academyレッスンでコードを書いて実行できますか?
はい。すべてのAI Engineering Academyレッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。
このコースのすべてのレッスン
- Tokenとは何か
- Context Window:サイズと影響
- APIコストの計算と予測
- Context内に収めるための戦略