Lesson 1 of 4 · Claude API & Development

The Claude Model Family

reading20 min

Story: When the Right Model Changes Everything

Last summer, a startup called MediScan was building an AI-powered medical document analyzer. Their CTO, Priya, made what seemed like an obvious choice: use the most powerful AI model available for everything. Within two weeks, their API bills hit $47,000. The app was burning through tokens on simple tasks -- extracting patient names, parsing dates, classifying document types -- that didn't need a genius-level model. Meanwhile, the truly complex tasks -- synthesizing multi-page medical reports into actionable summaries -- weren't getting the specialized attention they deserved.

Priya's mistake wasn't using AI. It was using the same AI for everything.

73%

Cost Reduction

How much MediScan saved by routing tasks to the right Claude model tier instead of using Opus for everything.

When she restructured her architecture to use three different Claude models -- Haiku for simple extraction, Sonnet for mid-complexity analysis, and Opus for the hardest synthesis tasks -- costs dropped 73% and quality actually improved. The right model for the right job isn't just a cost optimization. It's an architectural decision that shapes everything from user experience to system reliability.

This lesson teaches you the Claude model family so you can make that decision confidently from day one.


Concept: Understanding the Claude Model Family

The Three Tiers

Anthropic organizes Claude into three model tiers, each optimized for different trade-offs between capability, speed, and cost:

ModelIntelligenceSpeedCostContext Window
Claude Opus 4HighestSlowestMost expensive200K tokens
Claude Sonnet 4HighFastModerate200K tokens
Claude Haiku 3.5GoodFastestLeast expensive200K tokens
Concept Card

Think of it like hiring for a company. You wouldn't hire a senior architect to file paperwork, and you wouldn't ask an intern to design the building. Each role exists because different tasks demand different levels of expertise.

Claude Opus 4: The Deep Thinker

Opus is Anthropic's most capable model. It excels at tasks requiring:

  • Complex reasoning chains -- multi-step logic, mathematical proofs, strategic analysis
  • Nuanced writing -- creative fiction, persuasive essays, tone-sensitive content
  • Deep code understanding -- architectural decisions, security audits, complex refactoring
  • Agentic tasks -- sustained, autonomous work that requires initiative and planning
  • Ambiguous instructions -- situations where the model needs to infer intent

When to use Opus: You reach for Opus when the task is genuinely hard -- when a wrong answer has serious consequences, when the reasoning chain is long, or when you need the model to exercise judgment rather than follow templates.

Python
import anthropic

client = anthropic.Anthropic()

# Opus for complex legal analysis
response = client.messages.create(
    model="claude-opus-4-20250514",
    max_tokens=4096,
    messages=[{
        "role": "user",
        "content": """Analyze this contract clause for potential risks
        to the licensee. Consider jurisdictional variations across
        US, EU, and APAC markets. Identify any ambiguities that
        could be exploited in litigation.

        Clause: "Licensor reserves the right to modify the service
        at any time, with or without notice, and Licensee agrees
        that continued use constitutes acceptance of modifications."
        """
    }]
)

print(response.content[0].text)
typescript
import Anthropic from "@anthropic-ai/sdk";

const client = new Anthropic();

// Opus for complex legal analysis
const response = await client.messages.create({
  model: "claude-opus-4-20250514",
  max_tokens: 4096,
  messages: [{
    role: "user",
    content: `Analyze this contract clause for potential risks
    to the licensee. Consider jurisdictional variations across
    US, EU, and APAC markets. Identify any ambiguities that
    could be exploited in litigation.

    Clause: "Licensor reserves the right to modify the service
    at any time, with or without notice, and Licensee agrees
    that continued use constitutes acceptance of modifications."`
  }]
});

console.log(response.content[0].text);

Claude Sonnet 4: The Versatile Workhorse

Sonnet strikes the balance that most applications need. It's remarkably capable while being significantly faster and cheaper than Opus. Sonnet excels at:

Tip

Use Claude Model Family in a low-risk branch or scratch project first. That keeps the lesson concrete without making your first attempt carry production pressure.

  • Code generation -- writing, debugging, and explaining code across languages
  • Analysis and summarization -- processing documents, extracting insights
  • Conversational AI -- chatbots, customer support, interactive experiences
  • Content creation -- marketing copy, technical writing, structured content
  • Data processing -- classification, extraction, transformation at scale

When to use Sonnet: Sonnet is your default choice. Start here unless you have a specific reason to go up (Opus for complexity) or down (Haiku for speed/cost). Most production applications run primarily on Sonnet.

Python
import anthropic

client = anthropic.Anthropic()

# Sonnet for code generation -- fast, capable, affordable
response = client.messages.create(
    model="claude-sonnet-4-20250514",
    max_tokens=2048,
    messages=[{
        "role": "user",
        "content": """Write a Python function that implements
        exponential backoff with jitter for API retries. Include
        type hints, docstring, and handle both timeout and
        rate-limit errors."""
    }]
)

print(response.content[0].text)
typescript
import Anthropic from "@anthropic-ai/sdk";

const client = new Anthropic();

// Sonnet for code generation -- fast, capable, affordable
const response = await client.messages.create({
  model: "claude-sonnet-4-20250514",
  max_tokens: 2048,
  messages: [{
    role: "user",
    content: `Write a TypeScript function that implements
    exponential backoff with jitter for API retries. Include
    proper types and handle both timeout and rate-limit errors.`
  }]
});

console.log(response.content[0].text);

Claude Haiku 3.5: The Speed Demon

Haiku is optimized for speed and cost efficiency. It's the fastest model in the Claude family and costs a fraction of the others. Haiku excels at:

  • Classification -- routing, categorization, sentiment analysis
  • Extraction -- pulling structured data from unstructured text
  • Simple Q&A -- FAQ bots, lookup-based answers
  • Moderation -- content filtering, safety classification
  • High-volume processing -- when you need to process thousands of items quickly

When to use Haiku: Haiku is your choice when speed matters more than depth, when the task is well-defined and doesn't require creative reasoning, or when you're processing high volumes where per-call cost adds up fast.

Python
import anthropic

client = anthropic.Anthropic()

# Haiku for fast classification -- sub-second responses
response = client.messages.create(
    model="claude-haiku-3-5-20241022",
    max_tokens=100,
    messages=[{
        "role": "user",
        "content": """Classify this support ticket into exactly one
        category: billing, technical, account, or general.

        Ticket: "I can't log in to my account. I've tried
        resetting my password but the email never arrives."

        Respond with only the category name."""
    }]
)

print(response.content[0].text)  # "account"
typescript
import Anthropic from "@anthropic-ai/sdk";

const client = new Anthropic();

// Haiku for fast classification -- sub-second responses
const response = await client.messages.create({
  model: "claude-haiku-3-5-20241022",
  max_tokens: 100,
  messages: [{
    role: "user",
    content: `Classify this support ticket into exactly one
    category: billing, technical, account, or general.

    Ticket: "I can't log in to my account. I've tried
    resetting my password but the email never arrives."

    Respond with only the category name.`
  }]
});

console.log(response.content[0].text); // "account"

Model Naming Convention

Claude models use a consistent naming pattern:

claude-{tier}-{version}-{date}

Examples:

  • claude-opus-4-20250514 -- Opus 4, released May 14, 2025
  • claude-sonnet-4-20250514 -- Sonnet 4, released May 14, 2025
  • claude-haiku-3-5-20241022 -- Haiku 3.5, released October 22, 2024

Tighten the Context for Claude Model Family

  1. Update CLAUDE.md, a directory-level note, or another context source mentioned here.
  2. Add only the high-signal information that would change Claude's decisions.
  3. Re-run a common task and compare the first answer before and after the update.

The date suffix pins you to a specific snapshot. Anthropic may release updated versions, but your existing calls won't change behavior unexpectedly. You can also use convenience aliases like claude-sonnet-4-20250514 which always point to the latest version of that tier.

The 200K Context Window

All current Claude models share a 200,000-token context window. That's roughly 150,000 words -- enough to fit an entire novel, a full codebase, or hundreds of pages of documentation in a single request.

This massive context window is one of Claude's distinguishing features. While other models may offer similar raw intelligence, Claude's ability to reason over enormous inputs opens architectural possibilities:

  • Feed an entire codebase for comprehensive code review
  • Analyze complete legal contracts without chunking
  • Process full research papers with all references
  • Maintain very long conversation histories
Python
import anthropic

client = anthropic.Anthropic()

# Reading a large codebase for review
with open("entire_codebase.txt", "r") as f:
    codebase = f.read()

response = client.messages.create(
    model="claude-sonnet-4-20250514",
    max_tokens=4096,
    messages=[{
        "role": "user",
        "content": f"""Review this entire codebase for security
        vulnerabilities, focusing on SQL injection, XSS, and
        authentication bypass risks.

        {codebase}"""
    }]
)

Extended Thinking

Opus and Sonnet support extended thinking -- a mode where Claude reasons step-by-step before producing its final answer. This is particularly powerful for:

  • Math and logic problems
  • Complex code debugging
  • Multi-step analysis
  • Decision-making with many factors

We'll cover extended thinking in depth in Chapter 5, but know that it's available on the higher-tier models and can dramatically improve accuracy on hard problems.

Quick Check

What is the main benefit of using Claude Model Family well in Claude Code?


Apply: Building a Model Router

Now let's put this knowledge to work. One of the most impactful patterns in production Claude applications is a model router -- a system that automatically selects the right model based on the task.

Here's a complete, working implementation:

Python
import anthropic
from dataclasses import dataclass
from enum import Enum

class ModelTier(Enum):
    HAIKU = "claude-haiku-3-5-20241022"
    SONNET = "claude-sonnet-4-20250514"
    OPUS = "claude-opus-4-20250514"

@dataclass
class RoutingDecision:
    model: ModelTier
    reason: str
    estimated_cost_per_1k: float

class ModelRouter:
    """Routes requests to the optimal Claude model based on task complexity."""

    def __init__(self):
        self.client = anthropic.Anthropic()

        # Keywords that suggest different complexity levels
        self.opus_signals = [
            "analyze", "synthesize", "compare and contrast",
            "evaluate risks", "strategic", "ambiguous",
            "creative writing", "architectural review",
            "security audit", "legal analysis"
        ]
        self.haiku_signals = [
            "classify", "extract", "categorize",
            "true or false", "yes or no", "pick one",
            "sentiment", "moderate", "filter", "route"
        ]

    def route(self, task_description: str,
              max_cost_tier: ModelTier = ModelTier.OPUS) -> RoutingDecision:
        """Determine the optimal model for a given task."""

        task_lower = task_description.lower()

        # Check for Opus signals
        opus_score = sum(1 for s in self.opus_signals if s in task_lower)
        haiku_score = sum(1 for s in self.haiku_signals if s in task_lower)

        # Route based on signals
        if opus_score >= 2 and max_cost_tier == ModelTier.OPUS:
            return RoutingDecision(
                model=ModelTier.OPUS,
                reason=f"Complex task detected ({opus_score} complexity signals)",
                estimated_cost_per_1k=0.075
            )
        elif haiku_score >= 1:
            return RoutingDecision(
                model=ModelTier.HAIKU,
                reason=f"Simple task detected ({haiku_score} simplicity signals)",
                estimated_cost_per_1k=0.004
            )
        else:
            return RoutingDecision(
                model=ModelTier.SONNET,
                reason="Default routing to balanced model",
                estimated_cost_per_1k=0.015
            )

    def call(self, task: str, user_message: str,
             system_prompt: str = None, max_tokens: int = 2048) -> dict:
        """Route and execute an API call."""

        decision = self.route(task)

        kwargs = {
            "model": decision.model.value,
            "max_tokens": max_tokens,
            "messages": [{"role": "user", "content": user_message}]
        }
        if system_prompt:
            kwargs["system"] = system_prompt

        response = self.client.messages.create(**kwargs)

        return {
            "content": response.content[0].text,
            "model_used": decision.model.value,
            "routing_reason": decision.reason,
            "input_tokens": response.usage.input_tokens,
            "output_tokens": response.usage.output_tokens
        }

# Usage
router = ModelRouter()

# This routes to Haiku (classification task)
result = router.call(
    task="classify this email",
    user_message="Is this email spam? 'You've won a free iPhone!'"
)
print(f"Model: {result['model_used']}")  # claude-haiku-3-5-20241022

# This routes to Opus (complex analysis)
result = router.call(
    task="analyze and evaluate risks in this strategic proposal",
    user_message="Evaluate this merger proposal for regulatory risks..."
)
print(f"Model: {result['model_used']}")  # claude-opus-4-20250514

# This routes to Sonnet (general task)
result = router.call(
    task="write a product description",
    user_message="Write a description for our new wireless headphones"
)
print(f"Model: {result['model_used']}")  # claude-sonnet-4-20250514
typescript
import Anthropic from "@anthropic-ai/sdk";

enum ModelTier {
  HAIKU = "claude-haiku-3-5-20241022",
  SONNET = "claude-sonnet-4-20250514",
  OPUS = "claude-opus-4-20250514",
}

interface RoutingDecision {
  model: ModelTier;
  reason: string;
  estimatedCostPer1k: number;
}

class ModelRouter {
  private client: Anthropic;
  private opusSignals: string[];
  private haikuSignals: string[];

  constructor() {
    this.client = new Anthropic();
    this.opusSignals = [
      "analyze", "synthesize", "compare and contrast",
      "evaluate risks", "strategic", "ambiguous",
      "creative writing", "architectural review",
    ];
    this.haikuSignals = [
      "classify", "extract", "categorize",
      "true or false", "yes or no", "pick one",
      "sentiment", "moderate", "filter", "route",
    ];
  }

  route(taskDescription: string): RoutingDecision {
    const taskLower = taskDescription.toLowerCase();
    const opusScore = this.opusSignals.filter(
      s => taskLower.includes(s)
    ).length;
    const haikuScore = this.haikuSignals.filter(
      s => taskLower.includes(s)
    ).length;

    if (opusScore >= 2) {
      return {
        model: ModelTier.OPUS,
        reason: `Complex task (${opusScore} signals)`,
        estimatedCostPer1k: 0.075,
      };
    } else if (haikuScore >= 1) {
      return {
        model: ModelTier.HAIKU,
        reason: `Simple task (${haikuScore} signals)`,
        estimatedCostPer1k: 0.004,
      };
    }
    return {
      model: ModelTier.SONNET,
      reason: "Default balanced model",
      estimatedCostPer1k: 0.015,
    };
  }

  async call(task: string, userMessage: string) {
    const decision = this.route(task);

    const response = await this.client.messages.create({
      model: decision.model,
      max_tokens: 2048,
      messages: [{ role: "user", content: userMessage }],
    });

    return {
      content: response.content[0].type === "text"
        ? response.content[0].text
        : "",
      modelUsed: decision.model,
      routingReason: decision.reason,
      inputTokens: response.usage.input_tokens,
      outputTokens: response.usage.output_tokens,
    };
  }
}

Try This Now

Build your own model router by modifying the code above:

  1. Add a token_count parameter -- if the input is very large (>50K tokens), automatically route to a model with extended thinking enabled.
  2. Add a latency_requirement parameter -- if the caller needs sub-2-second responses, force Haiku.
  3. Log every routing decision to a file so you can analyze patterns over time.

Reflect: Choosing Your Starting Point

Tip

The Model Selection Rule of Thumb: Start with Sonnet. Only move to Opus when Sonnet's quality isn't sufficient for your specific task. Only move to Haiku when Sonnet is overkill and you need the speed or cost savings. Most production apps use 80% Sonnet, 15% Haiku, 5% Opus.

Here are the questions you should ask yourself before every new project:

  1. What's the hardest task my application needs to handle? If it involves multi-step reasoning, creative judgment, or ambiguous inputs, you'll need Opus for at least some requests.

  2. What's my latency budget? If users expect instant responses (like autocomplete or classification), Haiku is your friend. If they're willing to wait 2-3 seconds (like a chatbot), Sonnet works great.

  3. What's my cost sensitivity? At scale, the difference between Haiku and Opus can be 20x. A task that costs $100/day on Haiku would cost $2,000/day on Opus.

  4. Can I split my workload? The most cost-effective architectures use different models for different stages of a pipeline. Haiku classifies and routes, Sonnet handles the bulk of work, Opus tackles the hardest cases.

Warning

Common Pitfall: Don't assume Opus is always "better." For well-defined tasks with clear instructions, Haiku and Sonnet often produce identical results to Opus -- at a fraction of the cost and latency. Opus shines on ambiguous, complex, and creative tasks where its extra reasoning capability makes a measurable difference.

Key Takeaways

  • Claude comes in three tiers: Opus (most capable), Sonnet (balanced), and Haiku (fastest and cheapest)
  • All models share a 200K token context window -- enough for entire codebases or books
  • Sonnet is your default choice for most applications -- it balances quality, speed, and cost
  • Use Opus for genuinely complex tasks: legal analysis, creative writing, security audits, agentic workflows
  • Use Haiku for simple, high-volume tasks: classification, extraction, moderation, routing
  • Model routing -- automatically selecting the right model per request -- is one of the most impactful production patterns
  • Model names follow the pattern claude-{tier}-{version}-{date} for reproducible behavior
  • The right model choice is an architectural decision, not just a cost optimization

Next lesson: We'll explore what makes Claude fundamentally different from other AI models -- the constitutional AI approach, safety properties, and why these design choices matter for your applications.