Managing and Reducing Costs › Strategy 1: Use the Cheapest Model That Works
Michael BrenndoerferAugust 26, 20252 min read
AI Agent HandbookAll chapters Part 15 of 15Performance and Cost Optimization - Doing More with Less
Managing and Reducing Costs › Strategy 1: Use the Cheapest Model That WorksOne section · Sections in this chapter4 / 15 ↓
Sections in this chapter15
The most effective cost reduction strategy is simple: use cheaper models when possible. Not every task needs your most powerful model.
Think of it like choosing transportation. You wouldn't hire a helicopter to go to the grocery store. A car works fine. Similarly, you don't need Claude Sonnet 4.5 for every query.
Example: Cost-Aware Model Selection (Multi-Provider)
In[5]:
Codeimport os
from anthropic import Anthropic
from openai import OpenAI
from google import genai
class CostOptimizedAgent:
"""Agent that chooses the most cost-effective model for each task."""
def __init__(self):
# Initialize clients for different providers
self.anthropic = Anthropic(api_key=os.getenv("ANTHROPIC_API_KEY"))
self.openai = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
self.gemini = genai.Client(api_key=os.getenv("GEMINI_API_KEY"))
def _classify_task_complexity(self, query):
"""Determine what level of model capability is needed."""
# High complexity: needs reasoning, tool use, or complex understanding
high_complexity_indicators = [
"explain why", "analyze", "compare and contrast",
"step by step", "reasoning", "pros and cons",
"evaluate", "critique"
]
# Medium complexity: straightforward questions or tasks
medium_complexity_indicators = [
"how to", "what is", "describe", "summarize"
]
query_lower = query.lower()
if any(ind in query_lower for ind in high_complexity_indicators):
return "high"
elif any(ind in query_lower for ind in medium_complexity_indicators):
return "medium"
else:
return "low"
def respond(self, query):
"""Route to the most cost-effective model."""
complexity = self._classify_task_complexity(query)
if complexity == "high":
# Use Claude Sonnet 4.5 for complex reasoning
# Cost: ~$0.012 per interaction
response = self.anthropic.messages.create(
model="claude-sonnet-4-5",
max_tokens=1024,
messages=[{"role": "user", "content": query}]
)
return response.content[0].text, "claude-sonnet-4-5", "high"
elif complexity == "medium":
# Use GPT-5 for general tasks
# Cost: ~$0.008 per interaction (33% savings)
response = self.openai.chat.completions.create(
model="gpt-5",
max_completion_tokens=512,
messages=[{"role": "user", "content": query}]
)
return response.choices[0].message.content, "gpt-5", "medium"
else:
# Use Gemini 2.5 Flash for simple queries
# Cost: ~$0.001 per interaction (92% savings!)
response = self.gemini.models.generate_content(
model="gemini-2.5-flash",
contents=query
)
return response.text, "gemini-2.5-flash", "low"
## Test with different complexity levels
agent = CostOptimizedAgent()
queries = [
("What's the capital of France?", "low"),
("What is machine learning?", "medium"),
("Analyze the pros and cons of different database architectures", "high")
]
for query, expected in queries:
result, model, complexity = agent.respond(query)
print(f"Query: {query}")
print(f"Complexity: {complexity} (expected: {expected})")
print(f"Model: {model}")
print(f"Response: {result[:100]}...")
print()Out[5]:
ConsoleQuery: What's the capital of France? Complexity: low (expected: low) Model: gemini-2.5-flash Response: The capital of France is **Paris**....
Query: What is machine learning? Complexity: medium (expected: medium) Model: gpt-5 Response: Machine learning is a branch of artificial intelligence where computers learn patterns from data to ...
Query: Analyze the pros and cons of different database architectures Complexity: high (expected: high) Model: claude-sonnet-4-5 Response: # Database Architecture Analysis ## 1. **Relational Databases (RDBMS)** ### Pros - **ACID Complian...
By routing simple queries to Gemini 2.5 Flash, you can save 90% or more on those interactions. If 50% of your queries are simple, you've just cut your total costs by 45%.