Calculando e prevendo custos de API
Escreva um auxiliar em Python que estime o custo antes de enviar uma solicitação, contando tokens e aplicando o preço de cada modelo, para que você nunca receba uma cobrança inesperada.
Calculando e prevendo custos de API é uma aula grátis de AI Engineering Academy no CoddyKit. Esta é a aula 3 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de AI Engineering Academy, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de AI Engineering Academy inclui 4 aulas no total.
Partes desta aula ainda não foram traduzidas e aparecem em inglês.
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.
Perguntas Frequentes
A aula “Calculando e prevendo custos de API” é grátis?
Sim — o texto completo de “Calculando e prevendo custos de API” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de AI Engineering Academy, atualize para CoddyKit PRO. O curso de AI Engineering Academy inclui 4 aulas no total.
O que vou aprender em “Calculando e prevendo custos de API”?
Escreva um auxiliar em Python que estime o custo antes de enviar uma solicitação, contando tokens e aplicando o preço de cada modelo, para que você nunca receba uma cobrança inesperada. Você pratica AI Engineering Academy com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.
Preciso ter experiência prévia para começar AI Engineering Academy?
Nenhuma experiência prévia é necessária. AI Engineering Academy no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 3 de 4.
Quanto tempo leva a aula “Calculando e prevendo custos de API”?
A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.
Posso escrever e executar código nesta aula de AI Engineering Academy?
Sim. Cada aula de AI Engineering Academy inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.
Todas as aulas deste curso
- O que é um token?
- Janelas de contexto: tamanho e implicações
- Calculando e prevendo custos de API
- Estratégias para permanecer dentro do contexto