Cost Engineering
Anthropic
The Frugal Approach to Anthropic Claude API Costs
Craig Conboy

Last updated: November 2026

With usage-billed AI services like Anthropic Claude, cost optimization starts with your code. It's not just that applications generate the API calls; applications spend. Every model selection, every prompt, every generated token contributes to your bill.

Taking an application- and code-centric approach to cost reduction means understanding what your code does before and after each API call. Here's a practical walk-through of what to look for and how to optimize Claude API costs at the code level.

Cost Trap Efficiency Pattern
Using expensive models for simple tasks Route tasks to cheapest capable model (Haiku 5.5/Sonnet 5.5/Opus 5.5)
Leaving effort at the default Set effort per task and monitor thinking tokens
Verbose natural language prompts Compress prompts to minimize input tokens
Sending full conversation history Trim history without breaking the cache
No preprocessing of input Filter irrelevant content before sending to API
Not using prompt caching Structure prompts to leverage caching (90-95% discount on reads)
No deduplication or application caching Cache responses for identical/similar requests
Treating max_tokens as a length control Control length with output shape and effort; keep max_tokens as a backstop
Requesting unstructured text responses Use structured outputs
Processing batch workloads synchronously Use Message Batches API for 50% discount
Including excessive examples in prompts Test minimum effective example count
Comparing models on per-token price alone Re-baseline token counts when switching models
Bloated tool definitions and agent loops Load tools on demand and keep loops lean
Paying pricing premiums by default Opt into fast mode and data residency per route

Retiring soon: Claude Sonnet 4.5 retires on November 30, 2026, and Claude Opus 4.1, Haiku 3, and Haiku 3.5 are already retired. The patterns below use their current replacements.

Attribute the Costs

Start with your bill. Break down costs by endpoint, feature, and request type to understand where spend concentrates. Your bill reveals whether you're burning budget on input tokens (large prompts, excessive conversation history, tool definitions), thinking tokens (the reasoning current Claude models do before answering), or output tokens (unbounded generation, verbose responses). It also shows if you're using expensive models (Opus, Fable) for tasks that cheaper models (Haiku, Sonnet) could handle, and whether premium options like fast mode are switched on.

This attribution guides which of the 14 efficiency patterns below deliver the highest impact. If 70% of costs come from output tokens, focus on patterns #2 and #8-10. If you're using Opus everywhere, pattern #1 is your priority. If input tokens dominate, look at patterns #4-6 and #13.

1. Route tasks to cheapest capable model

Anthropic's current lineup spans a 100x price range:

  • Claude Haiku 5.5 ($0.10 / $0.50 per 1M input/output tokens, for prompts up to 100K tokens): high-volume classification, extraction, routing, and sub-agent work
  • Claude Sonnet 5.5 ($2 / $10): everyday coding, agents, and enterprise work
  • Claude Opus 5.5 ($4 / $20): complex reasoning and long-horizon agentic work
  • Claude Fable 5.1 ($10 / $50): the most demanding reasoning tasks

The gap between Sonnet and Opus has narrowed: Opus 5.5 costs 2x Sonnet 5.5, not the 5x it used to. The gap at the bottom has widened: Haiku 5.5 is 20x cheaper than Sonnet 5.5 on input.

Tier your tasks by actual requirements:

def select_claude_model(task_type):
    """Route tasks to the cheapest model that can handle them."""

    # Simple: classification, extraction, formatting, simple Q&A
    if task_type in ['classify', 'extract', 'format', 'simple_qa']:
        return "claude-haiku-5-5"  # $0.10 per 1M input, $0.50 output

    # Most tasks: coding, analysis, reasoning, writing, vision
    # This is your default
    elif task_type in ['code', 'analyze', 'reason', 'write', 'vision', 'complex_qa']:
        return "claude-sonnet-5-5"  # $2 per 1M input, $10 output

    # Complex multi-step reasoning and long-running agents
    # Test Sonnet first - only escalate when evals show the gap
    elif task_type in ['complex_reasoning', 'multi_step_research', 'long_agentic']:
        return "claude-opus-5-5"  # $4 per 1M input, $20 output

    else:
        # Default to Sonnet for unknown tasks (not Opus!)
        return "claude-sonnet-5-5"

Before building a cascade, test the simpler alternative. Lowering effort (pattern #2) on a more capable model often matches a cheaper model at higher effort, and one model means one prompt cache—caches are per-model, so every model in a cascade writes and reads its own copy of your prompt. Compare cost per completed task, not cost per request.

Implement tiered retry logic for structured tasks:

For tasks with deterministic validation (classification, extraction, formatting), starting cheap and escalating only when validation fails can still pay off:

import json
import anthropic

client = anthropic.Anthropic()

def classify_sentiment_with_fallback(text):
    """Sentiment classification: start with Haiku, escalate if needed."""

    models = [
        "claude-haiku-5-5",   # $0.10 per 1M input
        "claude-sonnet-5-5",  # $2.00 per 1M input
        "claude-opus-5-5"     # $4.00 per 1M input
    ]

    prompt = f"Classify sentiment as positive/negative/neutral. Return only valid JSON.\nText: {text}"

    for model in models:
        response = client.messages.create(
            model=model,
            max_tokens=1024,
            output_config={"effort": "low"},  # Simple task - keep thinking minimal
            messages=[{"role": "user", "content": prompt}]
        )

        # Thinking blocks may precede the answer - read the text block
        answer = next((b.text for b in response.content if b.type == "text"), "")

        # Deterministic validation: check if response is valid JSON with required field
        try:
            result = json.loads(answer)
            if result.get('sentiment') in ['positive', 'negative', 'neutral']:
                return result, model  # Success - don't try more expensive model
        except json.JSONDecodeError:
            continue  # Failed validation - try next tier

    raise Exception("All models failed to produce valid output")

# If Haiku handles 85% of requests, Sonnet 10%, and Opus 5%,
# and escalated requests pay for every attempt along the way:
# 0.85 x $0.10 + 0.10 x $2.10 + 0.05 x $6.10 = ~$0.60 per 1M input tokens
# vs. $2/1M if always using Sonnet - about 70% savings

This pattern works for any task with objective quality criteria: code that must compile, SQL that must parse, structured data with required fields, regex patterns, etc. Measure your own escalation rates—if many requests escalate, the cascade costs more than starting on the bigger model.

2. Set effort per task and monitor thinking tokens

Current Claude models think before they answer, and thinking tokens are billed at output rates—$10 per 1M on Sonnet 5.5, $20 per 1M on Opus 5.5. Thinking is now on by default: it can't be turned off on Opus 5.5 at all, and it's on by default even on Haiku 5.5. By default you don't see the thinking either (it's omitted from the response), but you pay for it.

The control is effort. The effort setting (low, medium, high, xhigh, max) governs how much the model thinks and how many tokens it spends overall. Defaults vary: medium on Opus 5.5 and Haiku 5.5, high on Sonnet 5.5. Set it explicitly on every route:

# Simple, high-volume task: minimal thinking
response = client.messages.create(
    model="claude-haiku-5-5",
    max_tokens=1024,
    output_config={"effort": "low"},
    messages=[{"role": "user", "content": "Sentiment (positive/negative/neutral): I love this product"}]
)

# Hard task: more thinking is worth paying for - but measure before going above high
response = client.messages.create(
    model="claude-sonnet-5-5",
    max_tokens=64000,
    output_config={"effort": "high"},
    messages=[{"role": "user", "content": complex_task}]
)

Monitor what you're paying for. Thinking tokens are counted inside usage.output_tokens—there's no separate line item and no special response header. A request that returns a 500-token answer might bill 5,000 output tokens. Track output tokens per route against the length of the visible answer, and treat a large, persistent gap as a sign that the route's effort is set higher than the task needs.

Workloads like classification, chat, and high-volume extraction usually do well at low. Coding and long-running agent work respond to higher effort. Tune per route on a sample of real requests rather than raising a global default.

3. Compress prompts to minimize input tokens

Every input token costs money. The goal: send exactly what's needed, nothing more.

Compress your prompts. Every unnecessary word is wasted spend:

# Verbose: 27 tokens
user_message = "Please carefully analyze the sentiment expressed in the following text and provide a classification of whether it is positive, negative, or neutral:"

# Compressed: 6 tokens
user_message = "Sentiment classification (positive/negative/neutral):"

# Even more efficient: 3 tokens + structured output
user_message = "Sentiment:"

At 1M API calls, that 24-token difference is 24M tokens = $48 in Sonnet 5.5 input costs (or $2.40 in Haiku 5.5 costs).

Prompts written for older models are worth a second look too. Long lists of "be sure to" and "do not forget" instructions that older models needed can make newer models over-work—spending more tokens for no gain in quality.

4. Trim conversation history without breaking the cache

Conversational applications accumulate context over time. Sending the entire conversation history on every request multiplies input costs with each turn. Most tasks don't need full history—recent context is usually sufficient.

But on current Claude models, how you trim matters as much as whether you trim. Two things have changed:

  1. Prompt caching rewards a stable history. Cache reads cost 5-10% of the normal input rate (pattern #6). If you drop the oldest message on every turn, the prefix changes every turn and nothing after the system prompt ever caches. A long, cached history can be cheaper than a short, uncached one.
  2. Editing earlier turns invalidates thinking. Current models (Opus 5.5, Sonnet 5.5, Haiku 5.5) carry their earlier thinking forward and check that the conversation they're handed hasn't been edited. Trimming or rewriting earlier turns on the client drops that reasoning, and for accounts created on or after August 31, 2026, the API rejects edited history with an error.

Trim at natural boundaries instead. When history crosses a threshold, summarize it and start a fresh conversation seeded with that summary:

def maybe_restart_with_summary(system_prompt, conversation, token_limit=50_000):
    """When history gets long, start a new conversation from a summary
    instead of trimming old turns one at a time."""

    count = client.messages.count_tokens(
        model="claude-sonnet-5-5",
        system=system_prompt,
        messages=conversation,
    ).input_tokens

    if count <= token_limit:
        return conversation  # Append-only: keeps the cache and thinking intact

    summary = client.messages.create(
        model="claude-haiku-5-5",
        max_tokens=2000,
        output_config={"effort": "low"},
        messages=conversation + [{
            "role": "user",
            "content": "Summarize this conversation: decisions made, open questions, and facts needed to continue."
        }],
    )
    summary_text = next(b.text for b in summary.content if b.type == "text")

    # One summary message replaces the history - a fresh start, not an edit
    return [{"role": "user", "content": f"Summary of our conversation so far:\n{summary_text}"}]

A 30-turn conversation without management might send 50K tokens per request. Restarting from a 2K-token summary cuts that by 95%, and you pay for one cache write instead of breaking the cache every turn. For long-running agent sessions, Anthropic's server-side compaction (in beta) does the same summarize-and-continue step for you without counting as an edit.

5. Filter irrelevant content before sending to API

Raw inputs often contain bloat: HTML boilerplate, navigation elements, repeated footers, excessive whitespace. This noise inflates token counts without adding value. Preprocess inputs to extract signal and discard irrelevant content before sending to the API.

def clean_document(text):
    """Extract signal, discard noise."""
    from bs4 import BeautifulSoup
    import re

    # If HTML, extract text
    if '<' in text and '>' in text:
        soup = BeautifulSoup(text, 'html.parser')

        # Remove non-content elements
        for tag in soup(['script', 'style', 'nav', 'footer', 'aside', 'header']):
            tag.decompose()

        text = soup.get_text(separator=' ')

    # Normalize whitespace
    text = re.sub(r'\s+', ' ', text).strip()

    # Remove repeated boilerplate
    text = re.sub(r'(Copyright \d{4}.*?)(\n|$)', '', text)

    return text

Preprocessing can reduce "web page as text" from 20K tokens to 3K tokens—an 85% reduction.

The same applies to images and PDFs. Image tokens scale with pixel area, not with how much information the image holds, so a full-resolution screenshot costs far more than a downscaled one that's just as readable. Resize images to what the task needs before sending them.

6. Structure prompts for prompt caching

Prompt caching can reduce input costs by 90-95% for repeated content.

How it works:

  • Structure your prompt with a static prefix (tools, system instructions, examples, context) and mark the end of it with cache_control
  • Minimum cacheable size: 512 tokens on current models (4,096 on Haiku 4.5)—shorter prefixes silently don't cache, with no error
  • Cache read cost: 0.05x the normal input rate on Sonnet 5.5 and Opus 5.5, 0.1x on most other models
  • Cache write cost: 1.25x for the default 5-minute lifetime, 2x for the optional 1-hour lifetime
  • Each cache read refreshes the lifetime at no extra cost

Basic implementation:

For high-volume applications with large static system prompts, cache the prompt once and pay a fraction on subsequent calls.

import anthropic

client = anthropic.Anthropic()

# System instructions (5000 tokens) - this gets cached
system_prompt = """
You are a specialized customer service assistant with the following guidelines:
[... 5000 tokens of detailed instructions, examples, policies ...]
"""

def call_with_caching(user_question):
    message = client.messages.create(
        model="claude-sonnet-5-5",
        max_tokens=4000,
        system=[
            {
                "type": "text",
                "text": system_prompt,
                "cache_control": {"type": "ephemeral"}  # Mark for caching (5-minute TTL)
            }
        ],
        messages=[
            {"role": "user", "content": user_question}
        ]
    )
    return message

# Uncached: 5000 tokens x $2.00/1M = $0.01 per call
# First call (cache write at 1.25x): $0.0125
# Subsequent calls within the TTL (cache read at 0.05x): $0.0005
# Savings: 95% on the system prompt portion

Advanced: Multi-level caching with context:

For Q&A applications where users ask multiple questions about the same document, cache both system instructions and document content in separate layers to maximize cache hit rates.

def call_with_layered_cache(user_question, document_context):
    """Cache both system prompt and document context."""

    message = client.messages.create(
        model="claude-sonnet-5-5",
        max_tokens=4000,
        system=[
            {
                "type": "text",
                "text": system_instructions,  # 3000 tokens
                "cache_control": {"type": "ephemeral"}
            },
            {
                "type": "text",
                "text": f"Document context:\n{document_context}",  # 10000 tokens
                "cache_control": {"type": "ephemeral"}
            }
        ],
        messages=[
            {"role": "user", "content": user_question}  # 50 tokens
        ]
    )
    return message

# Uncached: 13,050 tokens x $2.00/1M = $0.026 per call
# Subsequent calls on same document: 13,000 cached tokens at $0.10/1M + 50 at $2.00/1M
# Effective input cost: ~$0.0014 instead of $0.026 - about 95% lower

For applications with large context (documentation, long articles, code repositories), prompt caching is the difference between affordable and unsustainable.

What silently breaks the cache: any change to the prefix invalidates everything after it. Common culprits are a timestamp or request ID in the system prompt, tool definitions in a different order, and non-deterministic JSON serialization. Caches are also per-model and per-workspace, so traffic split across models or workspaces writes separate entries. Verify with usage.cache_read_input_tokens—if it stays at zero across repeated requests, something is invalidating the prefix, and every request is paying the 1.25x write premium for nothing.

When to use caching:

Cache static, reusable content above the model's minimum: system instructions, few-shot examples, document context, code repositories, or style guides. Use the default 5-minute TTL when requests sharing the prefix arrive less than 5 minutes apart; the 1-hour TTL only pays off when gaps run between 5 and 60 minutes. Skip caching for highly variable content—a prefix that never repeats only pays the write premium.

7. Cache application responses for identical requests

Cache full API responses by request signature (messages + model + max_tokens) to avoid redundant API calls—30-50% cache hit rates on FAQs or repeated classifications translate directly to 30-50% cost reduction.

import hashlib
import json

cache = {}  # Use Redis/Memcached in production

def cached_claude_call(messages, model, max_tokens):
    """Cache by request signature."""

    cache_key = hashlib.sha256(
        json.dumps({
            'messages': messages,
            'model': model,
            'max_tokens': max_tokens
        }, sort_keys=True).encode()
    ).hexdigest()

    if cache_key in cache:
        return cache[cache_key]

    response = client.messages.create(
        model=model,
        max_tokens=max_tokens,
        messages=messages
    )

    # In production, set an expiry (e.g., 1 hour)
    cache[cache_key] = response

    return response

For applications with repeated queries (FAQs, common classifications, identical document analyses), 30-50% cache hit rates mean 30-50% cost reduction.

8. Control output length with shape and effort, not max_tokens

Output tokens are expensive—5x the cost of input tokens on every current Claude model—and thinking tokens are billed as output. Bounding output matters, but max_tokens isn't the lever for it.

max_tokens is required on every request, so there's no truly unbounded call. The trap runs the other way: the model never sees max_tokens, so a cap set to "make answers shorter" doesn't make them shorter—it cuts them off mid-thought with stop_reason: "max_tokens". You pay for the truncated output (and the thinking behind it), then pay again for the retry.

# Trap: a tight cap as a length control
message = client.messages.create(
    model="claude-sonnet-5-5",
    max_tokens=200,  # Thinking alone can exceed this - answer truncated or missing
    messages=[{"role": "user", "content": prompt}]
)

# Better: say what you want, set effort for the task, keep a generous backstop
message = client.messages.create(
    model="claude-sonnet-5-5",
    max_tokens=16000,                   # Backstop against runaway generation
    output_config={"effort": "low"},    # Less thinking for a simple task
    messages=[{"role": "user", "content": f"{prompt}\n\nAnswer in at most two sentences."}]
)

Control length with things the model can see: an explicit output format (ideally with an example), structured outputs (pattern #9), and effort (pattern #2). Stop sequences help too—register a sentinel the model emits when it can't proceed (for example <CANNOT_ANSWER>) so it stops instead of spending tokens explaining. Treat stop_reason: "max_tokens" as a failed attempt to investigate, not something to retry at the same cap.

9. Use structured outputs

Structured outputs force machine-readable responses instead of verbose natural language, reducing output tokens by 50-80% and eliminating parsing failures and retries.

message = client.messages.create(
    model="claude-haiku-5-5",
    max_tokens=1024,
    output_config={
        "effort": "low",
        "format": {
            "type": "json_schema",
            "schema": {
                "type": "object",
                "properties": {
                    "customer_id": {"type": "string"},
                    "email": {"type": "string"},
                    "phone": {"type": "string"}
                },
                "required": ["customer_id", "email", "phone"],
                "additionalProperties": False
            }
        }
    },
    messages=[
        {"role": "user", "content": f"Extract the customer ID, email, and phone from: {ticket_text}"}
    ]
)

# Response is guaranteed to match the schema - no fluff, no retries

When you want Claude to call your functions, add "strict": True to the tool definition so the arguments always match its schema.

If you used tool use to force JSON, check your code. A common older pattern forced a specific tool with tool_choice just to get structured output. On Opus 5.5 and Sonnet 5.5, forcing a tool (tool_choice of any or a named tool) returns an error. Structured outputs are the replacement.

10. Use Message Batches API for 50% discount

For work that can wait up to 24 hours, use the Message Batches API for a 50% discount:

import time

# Create batch of requests
requests = [
    {
        "custom_id": f"request-{i}",
        "params": {
            "model": "claude-sonnet-5-5",
            "max_tokens": 4000,
            "messages": [
                {"role": "user", "content": task}
            ]
        }
    }
    for i, task in enumerate(bulk_tasks)
]

# Submit batch
batch = client.messages.batches.create(requests=requests)

# Poll for completion
while batch.processing_status != "ended":
    time.sleep(60)
    batch = client.messages.batches.retrieve(batch.id)

# Retrieve results (they arrive in any order - match on custom_id)
for result in client.messages.batches.results(batch.id):
    if result.result.type == "succeeded":
        handle(result.custom_id, result.result.message)

# Same output quality, 50% cost, 24-hour window

The batch discount stacks with prompt caching—cache reads and writes inside a batch are also half price.

Perfect for: content generation, data analysis, bulk classification, document processing, eval runs—anything asynchronous.

11. Test minimum effective example count

Test example counts systematically (0, 1, 3, 5, 10, 20) to find the minimum needed for your target accuracy. In many tasks, accuracy plateaus after a handful of examples while every extra example adds input tokens to every call.

def test_example_count(task, example_pool, test_set):
    """Find minimum examples needed for target accuracy."""

    results = {}
    previous = None

    for n_examples in [0, 1, 3, 5, 10, 20]:
        examples = example_pool[:n_examples]

        # Format as conversation history
        example_messages = []
        for ex in examples:
            example_messages.extend([
                {"role": "user", "content": ex['input']},
                {"role": "assistant", "content": ex['output']}
            ])

        accuracy = evaluate_on_test_set(task, example_messages, test_set)
        input_tokens_per_call = sum(count_tokens(msg['content']) for msg in example_messages)

        results[n_examples] = {
            'accuracy': accuracy,
            'tokens': input_tokens_per_call
        }

        # Stop at diminishing returns
        if previous is not None and accuracy - results[previous]['accuracy'] < 0.01:
            break
        previous = n_examples

    return results

# If 3 examples = 92% accuracy and 10 examples = 94% accuracy,
# those extra 7 examples cost 3x more for a 2% gain

12. Re-baseline token counts when switching models

Per-token prices only tell half the story. The other half is how many tokens the same text becomes—and that changes between model generations.

Newer Claude tokenizers count the same text as more tokens: Opus 4.7 and later models use roughly 1-1.35x as many tokens as earlier ones, and Haiku 5.5 counts the same text as about 30% more tokens than Haiku 4.5. A migration that looks like a straight price cut on the pricing page can deliver a smaller saving than expected.

Haiku 5.5 also has a long-prompt price cliff. Prompts up to 100K tokens cost $0.10 / $0.50 per 1M. Over 100K tokens, the whole request costs $0.50 / $2.50—five times more—including cache reads and writes. Other current models include their full 1M context window at standard pricing, so this cliff is easy to miss.

def compare_token_counts(system_prompt, messages, models):
    """Count the same request under each candidate model before migrating."""
    for model in models:
        count = client.messages.count_tokens(
            model=model,
            system=system_prompt,
            messages=messages,
        ).input_tokens
        flag = " ⚠️ over Haiku 5.5's 100K threshold" if model == "claude-haiku-5-5" and count > 100_000 else ""
        print(f"{model}: {count} input tokens{flag}")

compare_token_counts(system_prompt, sample_messages,
                     ["claude-haiku-4-5", "claude-haiku-5-5", "claude-sonnet-5-5"])

Run token counting on a sample of real traffic before and after a model change, and compare cost per completed task rather than price per token.

13. Load tools on demand and keep agent loops lean

Agents add input costs that don't show up in your prompt: every tool definition is sent with every request, and every tool result stays in the conversation for every turn that follows.

Tool definitions add up fast. Connecting a few MCP servers can put tens of thousands of tokens of tool schemas into every call. If schemas run past roughly 10K tokens, use tool search: mark rarely used tools with defer_loading: true so their definitions load only when the model needs them. Also delete any system prompt text that re-describes your tools—the schemas are already in the request.

Tool results accumulate. A tool that returns a 20K-token data dump costs 20K tokens on that turn and every turn after it. Prefer narrow tools (get_policy(claim_id) over get_all_policies()), give list tools limit and fields parameters, and hand self-contained, reading-heavy steps to a sub-agent on a cheaper model that returns only a short result.

Clearing old tool results isn't a savings lever. Anthropic's context editing feature clears old tool results to make room in the context window, but each clearing pass rewrites the cached conversation. In Anthropic's own measurements it cost more than it saved. Use it to stay inside the context window, with clears kept infrequent. For long sessions, server-side compaction (pattern #4) is the option that actually reduces cost.

14. Opt into pricing premiums per route

Several Claude options are billed at a premium over standard rates. Each is worth paying for in the right place—and each is easy to switch on globally and forget:

  • Fast mode runs Opus 5.5 at higher output speed for 2x the price ($8 / $40 per 1M instead of $4 / $20). It's not available with the Batch API.
  • US-only inference (inference_geo: "us") applies a 1.1x multiplier to every token category, including cache reads and writes.
  • Server tools bill per use on top of tokens—web search costs $10 per 1,000 searches, and the search results it retrieves are billed as input tokens on that turn and every turn after.

These modifiers stack with each other and with caching multipliers, and none of them show up in token counts alone. Check which routes set speed, inference_geo, or server tools, and keep each one only where the route needs it: fast mode where a person is waiting on Opus output, US-only inference where compliance requires it, and web search with a max_uses limit.

Closing Thoughts

Careful model selection is table stakes—use Claude Sonnet 5.5 ($2/$10) as your default, route simple, high-volume tasks to Haiku 5.5 ($0.10/$0.50), and justify Opus 5.5 ($4/$20) with evals. Set effort explicitly on every route, because thinking is on by default and billed whether you see it or not. This baseline discipline prevents the worst cost traps.

Getting to the next level of savings requires two steps. First, let observed costs guide what needs optimization. Attribute your bill to specific application behaviors—which endpoints, features, and request types drive spend. This reveals which of the 14 efficiency patterns above matter most for your application. Second, apply the optimizations that address your cost concentrations. These patterns reduce tokens without sacrificing functionality: a stable cached prefix cuts input costs by 90-95%, append-only history with summary restarts keeps the cache and the model's reasoning intact, structured outputs replace verbose natural language, the Batch API halves async costs, and per-route premiums keep you paying only for what each route needs.

You don't lose capability. You gain precision. Cost-effective AI is an engineering discipline—treat each API call as a budget allocation and optimize based on measured impact.

Looking for help with cost optimizations like these? Book a Demo or Explore the Sandbox to see Frugal in action. Frugal attributes Anthropic Claude API costs to your code, finds inefficient usage, provides Frugal Fixes that reduce your bill, and helps keep you out of cost traps for new and changing code.

Back to Top
background Image
Robo Image

Take Frugal for a live test drive

Explore how Frugal scans your code and cloud services to find waste, recommend optimizations, and generate ready-to-use fixes in a secure, read-only environment.
background Image
robo image