DS DevShelfHub Projects · AI tools
Pay-per-token LLM API 200K Context Prompt Caching

Anthropic API Review: Claude — Built for Long-Context and Structured Reasoning

The Anthropic API gives you access to Claude — built differently from GPT. 200K-token context window, prompt caching that saves up to 90% on repeated prompts, constitutional AI training, and computer use (beta). For applications that depend on long documents, multi-turn reasoning, or careful output formatting, Claude often wins.

Anthropic API — Claude with 200K context, prompt caching, and tool use

What is the Anthropic API?

The Anthropic API is a REST endpoint for Claude models. Unlike OpenAI's ChatGPT interface or other competitors, Anthropic has built Claude from the ground up with different design choices: long context as a first-class feature, constitutional AI (interpretable, aligned training), and structured outputs as core.

The API is not OpenAI-compatible by default. You use Anthropic's Python SDK or make direct HTTP calls. The response schema is similar but not identical. This is intentional — Anthropic values clarity over compatibility.

Core Capabilities

1

Messages API

The main interface. Send system prompt and messages (user, assistant, tool), get back completions. Up to 200K input tokens (Claude 3.5 Sonnet) — can digest entire legal documents in a single request.

2

Tool Use

Define tools as JSON schema. Claude can call functions; you execute them and return results. First-class feature, well-designed. Works alongside text generation.

3

Vision / Multimodal

Pass images (JPEG, PNG, WebP, GIF) or PDF documents alongside text. Claude analyzes them natively. Cost is charged based on image size.

4

Prompt Caching

Repeat a system prompt or long document across multiple requests. Claude caches the embedding; subsequent requests cost only 10% of input tokens. Huge savings for workflows with fixed context (e.g., analyzing files against a knowledge base repeatedly).

5

Computer Use (Beta)

Claude can interact with desktop UIs — click, type, read. Currently in beta; production stability not guaranteed. Opens possibilities for AI agents that automate GUI-based workflows.

Messages API Request Flow

  1. 1

    Authenticate with your API key

    Set the x-api-key header. Unlike OpenAI, Anthropic does not use a Bearer token format — the raw key goes in its own header.

  2. 2

    Send messages with optional cache control

    Include model, messages, and optionally cache_control blocks to mark cacheable sections.

  3. 3

    Claude runs inference with cache lookup

    Cached system prompts are loaded at 10% cost. Messages are processed, tools evaluated, and a response generated (text or tool_use block).

  4. 4

    Handle the response and usage tokens

    The response includes content[0].type (text or tool_use), plus usage with cache_read_input_tokens for billing transparency.

Your App
    │
    ▼
Anthropic Messages API
    │
    ├─ Authenticate (x-api-key header)
    ├─ Validate request (no OpenAI-compatible auto-conversion)
    ├─ Check rate limits
    ├─ Count tokens (input, output, cache cost)
    │
    ├─ If system prompt is cached: load from cache
    ├─ Process messages (user, assistant, tool)
    │
    ▼
Claude inference
    │
    ├─ If tools defined: evaluate whether to call
    ├─ Generate response (text OR tool_use)
    │
    ▼
Response object
    │
    ├─ content[0].type: "text" OR "tool_use"
    ├─ usage.input_tokens, output_tokens
    ├─ usage.cache_creation_input_tokens (if caching)
    ├─ usage.cache_read_input_tokens (if using cache)
    ├─ stop_reason (end_turn, tool_use, max_tokens)
    │
    ▼
Your App (process response)

Cost = (input tokens × rate) + (cache_read tokens × 0.1 × rate) + (output tokens × rate) + cache creation (write once, amortize over requests). Streaming changes flow but pricing remains the same.

Python Example — Messages API with Tool Use

python
from anthropic import Anthropic

client = Anthropic()

tools = [
    {
        "name": "get_weather",
        "description": "Get weather for a location",
        "input_schema": {
            "type": "object",
            "properties": {
                "location": {"type": "string", "description": "City name"}
            },
            "required": ["location"]
        }
    }
]

messages = [
    {"role": "user", "content": "What's the weather in NYC?"}
]

response = client.messages.create(
    model="claude-3-5-sonnet-20241022",
    max_tokens=1024,
    tools=tools,
    messages=messages
)

# Process tool calls
while response.stop_reason == "tool_use":
    tool_use = next(b for b in response.content if b.type == "tool_use")
    tool_name = tool_use.name
    tool_input = tool_use.input

    # Execute tool (example: get_weather)
    result = get_weather(**tool_input)

    # Add assistant response and tool result to messages
    messages.append({"role": "assistant", "content": response.content})
    messages.append({
        "role": "user",
        "content": [
            {
                "type": "tool_result",
                "tool_use_id": tool_use.id,
                "content": str(result)
            }
        ]
    })

    # Call API again
    response = client.messages.create(
        model="claude-3-5-sonnet-20241022",
        max_tokens=1024,
        tools=tools,
        messages=messages
    )

print(response.content[0].text)

Available Models

Model Context Price (per 1M tokens) Best for
Claude 3.5 Sonnet 200K $3 input / $15 output Best all-rounder; long context at cheap price
Claude 3 Opus 200K $15 input / $75 output Complex reasoning; legacy (3.5 Sonnet is better)
Claude 3 Haiku 200K $0.80 input / $4 output Fast, cheap, simple tasks

Prices approximate; verify on claude.com/pricing.

Practical Gotchas

  • --
    NOT OpenAI-compatible by default: You can't drop in the Anthropic API as a replacement for OpenAI without code changes. Response schema, message format, error handling all differ. Tools like OpenRouter provide compatibility layers.
  • --
    Prompt caching requires explicit setup: To use cache, you must mark blocks with cache_control={"type": "ephemeral"}. Without it, no cache. Planning upfront is essential.
  • --
    "Lost in the Middle" on long contexts: Even with 200K tokens, Claude performs worse on information at the middle of the context vs beginning/end. For document search, rank by relevance before including.
  • --
    Rate limits tighter than OpenAI on new accounts: Starting tier ~60 RPM, lower than OpenAI. Anthropic's tier system is less transparent than OpenAI's.
  • --
    Computer use is beta: Not production-ready. Accuracy, speed, and API stability not guaranteed. Expect breaking changes.
  • --
    Tool use output still costs tokens: When Claude decides to call a tool, the tool_use block counts toward output tokens. Multiple tools = higher per-call cost.

Anthropic API vs OpenAI API

Both are production-ready. Key differences:

Feature Anthropic API OpenAI API
Context window 200K (Claude 3.5) 128K (GPT-4o)
Tool use Yes Yes (function calling)
Prompt caching Yes (90% savings) No
Vision Yes (Claude 3.5) Yes (GPT-4o)
Computer use Yes (Beta) No
Structured output Beta Yes (Guaranteed)
Price (input / output) $3 / $15 (3.5 Sonnet) $5 / $15 (GPT-4o)
SDK compatibility Custom SDK (Anthropic) OpenAI SDK standard

Pros and Cons

Pros

  • +200K context window (56% more than GPT-4o)
  • +Prompt caching saves up to 90% on repeated prompts
  • +Excellent at long-document analysis
  • +Constitutional AI training (safety-first design)
  • +Computer use (beta) for GUI automation
  • +Cheaper per token than GPT-4o

Cons

  • -Not OpenAI-compatible (requires code changes)
  • -Structured output still in beta
  • -Tighter rate limits on new accounts
  • -Computer use not production-ready
  • -Smaller ecosystem of third-party integrations
  • -"Lost in the Middle" on very long contexts

Pricing

Pay-per-token

No monthly subscription. Claude 3.5 Sonnet: $3 per 1M input tokens, $15 per 1M output tokens. With caching, read tokens cost 10% of the base rate — massive savings on repeated context. Cache creation costs full price once, then amortized over requests.

Free trial

$5 free credits on sign-up. Enough to experiment but not for sustained use.

Verify pricing at claude.com/pricing.

When NOT to Use It

  • --
    You need OpenAI-compatible tooling ecosystem: If your stack relies on tools built for the OpenAI API, swapping Anthropic requires adaptation or using a compatibility layer (OpenRouter).
  • --
    You need guaranteed structured output: Anthropic's structured output is beta. OpenAI's is stable and production-ready.
  • --
    Your budget is tight and you need vision: GPT-4o vision may be more cost-effective at scale than Claude depending on image size and volume.

Who Should Use the Anthropic API?

Best for applications requiring long-context processing (legal analysis, research synthesis, large codebases), cost-sensitive workflows where prompt caching applies, or teams prioritizing safety-first AI (constitutional AI). Good alternative to OpenAI if you don't need OpenAI compatibility.

Caveat: if your stack heavily depends on OpenAI SDK or integrations, switching costs more than it saves. Compare with the OpenAI API or Google AI Studio to find the best fit.

Tips for Getting the Most from the Anthropic API

  • 01.
    Design your system prompt for caching: Structure prompts so the static parts (system instructions, reference documents) come first and are marked with cache_control. Keep dynamic content at the end where it won't invalidate the cache.
  • 02.
    Use extended thinking for hard reasoning: Claude 3.5 Sonnet supports extended thinking mode — it reasons through problems step by step before answering. Enable with thinking={"type": "enabled", "budget_tokens": 10000} for complex analytical tasks.
  • 03.
    Rank documents before feeding them: For long-context tasks, put the most relevant content at the beginning and end of the context. Information in the middle is harder for Claude to retrieve accurately.
  • 04.
    Use OpenRouter as a compatibility bridge: If you're migrating from OpenAI, use OpenRouter to route requests to Claude via an OpenAI-compatible interface. This lets you test Claude without rewriting your client code.
  • 05.
    Monitor cache_read tokens in usage: Check usage.cache_read_input_tokens in every response. If this is zero, your cache isn't being used — review your prompt structure and cache_control placement.

Frequently Asked Questions

Is the Anthropic API free?
No. New accounts get $5 in free credits. After that, you pay per token. Claude 3.5 Sonnet costs $3 per million input tokens and $15 per million output tokens. Prompt caching reduces repeated-context costs by up to 90%.
What is Claude's context window?
Claude 3.5 Sonnet supports up to 200K tokens — roughly 150,000 words or about 500 pages. That is 56% more than GPT-4o's 128K window, making it ideal for processing entire legal documents or large codebases in one request.
How does Anthropic API prompt caching work?
Mark sections of your prompt with cache_control={'type': 'ephemeral'}. On the first call, Anthropic caches that block. Subsequent calls with the same block pay only 10% of the normal input token rate — a dramatic saving when the same system prompt or document is reused across many requests.
Is the Anthropic API OpenAI-compatible?
No. Anthropic uses its own SDK and a different request/response schema. You cannot swap the Anthropic API in as a direct replacement for OpenAI without code changes. Tools like OpenRouter provide a compatibility layer if needed.
What are the main alternatives to the Anthropic API?
The main alternatives are the OpenAI API (GPT-4o, broader ecosystem), Google AI Studio (Gemini with a free tier), and OpenRouter for routing across multiple providers including Claude.
What is computer use in the Anthropic API?
Computer use is a beta capability that lets Claude interact with desktop UIs — clicking buttons, typing, and reading screen content. It is not production-ready and may have breaking changes, but it opens up GUI automation workflows for developers.