DEV Community

Cover image for How to use Claude Sonnet 4.6 API?
Preecha
Preecha

Posted on

How to use Claude Sonnet 4.6 API?

TL;DR / Quick Answer

Claude Sonnet 4.6 is Anthropic's latest mid-tier model, combining frontier-level coding performance with a 1M token context window (beta) at just $3/$15 per million input/output tokens. To start using the API: 1) Get an API key from console.anthropic.com, 2) Install the SDK (pip install anthropic), 3) Use model ID claude-sonnet-4-6, and 4) Switch to adaptive thinking (thinking: {type: "adaptive"}) for best results. Early testers preferred it over Sonnet 4.5 by 70% and even over Opus 4.5 by 59%.

Try Apidog today

Introduction

Anthropic released Claude Sonnet 4.6, and it immediately reshapes the mid-tier AI model category. This isn't an incremental update—it's a model that beats the previous premium-tier Opus 4.5 in head-to-head testing by 59% according to early adopters, all while keeping Sonnet's price tag.

Claude Sonnet 4.6

The headline changes: a 1M token context window entering beta, a new adaptive thinking mode that replaces the old binary extended thinking approach, and a suite of tools—web search, code execution, memory, and tool search—graduating to general availability. For developers building agentic applications, Sonnet 4.6 delivers the capabilities previously reserved for expensive frontier models at roughly a third of the cost.

The coding improvements are tangible. Users report better instruction-following in code generation, smarter context comprehension before making modifications, and reduced code duplication through automatic logic consolidation. Computer use reaches 94% accuracy on complex insurance workflows. The SWE-bench Verified score lands at 79.6%.

This guide covers everything you need to start building with the Claude Sonnet 4.6 API today: authentication, practical code examples in Python and JavaScript, the new adaptive thinking parameter, how to unlock the 1M context window, and how to test your integration with Apidog's visual API client.

💡Build faster with Apidog. Testing Claude API calls manually is slow. Download Apidog to configure requests, inspect streaming responses, debug authentication, and generate SDK code—all from a single interface. No boilerplate required.

What's New in Claude Sonnet 4.6

Adaptive Thinking Mode

The old thinking: {type: "enabled", budget_tokens: N} pattern is deprecated on Sonnet 4.6. The replacement is adaptive thinking: thinking: {type: "adaptive"}. Claude now decides dynamically how much reasoning a task needs.

Pair adaptive thinking with the effort parameter (available in GA now) to tune cost versus performance:

  • effort: "high" (default) — Claude almost always thinks, best for complex problems
  • effort: "medium" — recommended for most Sonnet 4.6 use cases, balances speed and quality
  • effort: "low" — minimal thinking, fastest responses for simple tasks

Improved Coding Performance

Sonnet 4.6 brings three concrete improvements to code generation:

  • Better instruction-following — generates code matching specifications more precisely
  • Context comprehension — reads and understands existing code before modifying it, reducing regressions
  • Logic consolidation — identifies duplicate patterns and suggests shared abstractions

Early testers running coding benchmarks reported preferring Sonnet 4.6 outputs over Sonnet 4.5 in 70% of cases and over Opus 4.5 in 59% of cases.

Computer Use Improvements

Computer use accuracy reaches 72.5% on OSWorld-Verified (within 0.2% of Opus 4.6), up significantly from Sonnet 4.5. The model shows 94% accuracy on insurance workflows requiring UI navigation, spreadsheet manipulation, and multi-step form completion. It's also more resistant to prompt injection attacks during automated tasks.

Computer Use Improvements

ARC-AGI-2 Breakthrough

The most striking benchmark number: ARC-AGI-2 performance jumps from 13.6% to 58.3% — a 4.3x improvement. This measures novel problem-solving on tasks the model hasn't seen patterns for, suggesting genuine reasoning improvements rather than memorization.

API Specs and Pricing

Feature Value
API model ID claude-sonnet-4-6
AWS Bedrock ID anthropic.claude-sonnet-4-6
GCP Vertex AI ID claude-sonnet-4-6
Context window 200K tokens (1M beta with header)
Max output tokens 64K
Input pricing $3 / million tokens
Output pricing $15 / million tokens
Prompt caching savings Up to 90%
Batch API savings Up to 50%
Knowledge cutoff (reliable) August 2025
Training data cutoff January 2026
Extended thinking Yes
Adaptive thinking Yes
Priority Tier Yes

Cost reduction options:

  • Prompt caching: Cache static portions of your system prompt and save up to 90%
  • Batch API: Process requests asynchronously for 50% off
  • Long context pricing: Requests exceeding 200K tokens use a separate long-context rate

For production budgets: a million-token conversation in adaptive thinking mode at effort: "medium" costs roughly $3 in input tokens. Most single API calls fall well under a cent.

Getting Started with the Claude Sonnet 4.6 API

Step 1: Get Your API Key

  • Log into platform.anthropic.com
  • Navigate to API Keys in the settings
  • Click Create Key and copy the value immediately (it's only shown once)

API Key Setup

Store your key as an environment variable—never hardcode it:

export ANTHROPIC_API_KEY="sk-ant-..."
Enter fullscreen mode Exit fullscreen mode

Step 2: Install the SDK

Python:

pip install anthropic
Enter fullscreen mode Exit fullscreen mode

JavaScript/Node.js:

npm install @anthropic-ai/sdk
Enter fullscreen mode Exit fullscreen mode

Step 3: Make Your First Request

Python:

import anthropic

client = anthropic.Anthropic()  # reads ANTHROPIC_API_KEY from environment

response = client.messages.create(
    model="claude-sonnet-4-6",
    max_tokens=1024,
    messages=[
        {"role": "user", "content": "Explain the difference between async/await and promises in JavaScript."}
    ]
)

print(response.content[0].text)
Enter fullscreen mode Exit fullscreen mode

That's the minimum viable call. The response object includes usage stats (input tokens, output tokens), stop reason, and model version.

Python Code Examples

Basic Text Generation

import anthropic

client = anthropic.Anthropic()

def ask_claude(question: str, system: str = None) -> str:
    """Simple wrapper for Claude Sonnet 4.6 text generation."""
    messages = [{"role": "user", "content": question}]

    kwargs = {
        "model": "claude-sonnet-4-6",
        "max_tokens": 2048,
        "messages": messages,
    }
    if system:
        kwargs["system"] = system

    response = client.messages.create(**kwargs)
    return response.content[0].text

# Example usage
answer = ask_claude(
    "Review this Python function for performance issues:\n\ndef find_duplicates(lst):\n    return [x for x in lst if lst.count(x) > 1]",
    system="You are a senior Python engineer. Be specific and provide corrected code."
)
print(answer)
Enter fullscreen mode Exit fullscreen mode

Streaming Responses

For long outputs or real-time UX, use streaming:

import anthropic

client = anthropic.Anthropic()

with client.messages.stream(
    model="claude-sonnet-4-6",
    max_tokens=4096,
    messages=[{
        "role": "user",
        "content": "Write a complete REST API handler in FastAPI for user authentication with JWT."
    }]
) as stream:
    for text in stream.text_stream:
        print(text, end="", flush=True)

# Get final message with usage stats after stream completes
message = stream.get_final_message()
print(f"\n\nTokens used: {message.usage.input_tokens} in, {message.usage.output_tokens} out")
Enter fullscreen mode Exit fullscreen mode

Tool Calling / Function Use

import anthropic
import json

client = anthropic.Anthropic()

# Define tools
tools = [
    {
        "name": "get_repository_info",
        "description": "Fetch information about a GitHub repository including stars, forks, and recent commits.",
        "input_schema": {
            "type": "object",
            "properties": {
                "owner": {
                    "type": "string",
                    "description": "Repository owner or organization name"
                },
                "repo": {
                    "type": "string",
                    "description": "Repository name"
                }
            },
            "required": ["owner", "repo"]
        }
    }
]

response = client.messages.create(
    model="claude-sonnet-4-6",
    max_tokens=1024,
    tools=tools,
    messages=[{
        "role": "user",
        "content": "What can you tell me about the anthropics/anthropic-sdk-python repository?"
    }]
)

# Handle tool use response
for block in response.content:
    if block.type == "tool_use":
        print(f"Tool called: {block.name}")
        print(f"Arguments: {json.dumps(block.input, indent=2)}")
        # In production, call your actual implementation here
        # result = get_repository_info(block.input["owner"], block.input["repo"])
Enter fullscreen mode Exit fullscreen mode

Vision and Image Analysis

import anthropic
import base64
from pathlib import Path

client = anthropic.Anthropic()

def analyze_image(image_path: str, question: str) -> str:
    """Analyze an image with Claude Sonnet 4.6."""
    image_data = base64.standard_b64encode(Path(image_path).read_bytes()).decode("utf-8")

    # Detect media type from extension
    ext = Path(image_path).suffix.lower()
    media_type_map = {
        ".jpg": "image/jpeg",
        ".jpeg": "image/jpeg",
        ".png": "image/png",
        ".gif": "image/gif",
        ".webp": "image/webp"
    }
    media_type = media_type_map.get(ext, "image/jpeg")

    response = client.messages.create(
        model="claude-sonnet-4-6",
        max_tokens=1024,
        messages=[{
            "role": "user",
            "content": [
                {
                    "type": "image",
                    "source": {
                        "type": "base64",
                        "media_type": media_type,
                        "data": image_data,
                    },
                },
                {
                    "type": "text",
                    "text": question
                }
            ],
        }]
    )
    return response.content[0].text

# Example: analyze a UI screenshot for accessibility issues
result = analyze_image(
    "screenshot.png",
    "Identify any accessibility issues in this UI design. Check contrast ratios, missing alt text indicators, and keyboard navigation concerns."
)
print(result)
Enter fullscreen mode Exit fullscreen mode

JavaScript/Node.js Examples

Basic Setup and Request

import Anthropic from "@anthropic-ai/sdk";

const client = new Anthropic({
  apiKey: process.env.ANTHROPIC_API_KEY, // default, shown explicitly for clarity
});

async function askClaude(userMessage, systemPrompt = null) {
  const params = {
    model: "claude-sonnet-4-6",
    max_tokens: 2048,
    messages: [{ role: "user", content: userMessage }],
  };

  if (systemPrompt) {
    params.system = systemPrompt;
  }

  const response = await client.messages.create(params);
  return response.content[0].text;
}

// Usage
const answer = await askClaude(
  "Refactor this Express route to use async/await:\n\napp.get('/users', (req, res) => {\n  User.find({}, (err, users) => {\n    if (err) return res.status(500).send(err);\n    res.json(users);\n  });\n});",
  "You are a senior Node.js developer. Return only the refactored code with a brief explanation."
);

console.log(answer);
Enter fullscreen mode Exit fullscreen mode

Streaming with TypeScript

import Anthropic from "@anthropic-ai/sdk";

const client = new Anthropic();

async function streamCodeReview(codeSnippet: string): Promise<void> {
  const stream = await client.messages.stream({
    model: "claude-sonnet-4-6",
    max_tokens: 4096,
    messages: [
      {
        role: "user",
        content: `Perform a thorough code review of this TypeScript function:\n\n\`\`\`typescript\n${codeSnippet}\n\`\`\`\n\nFocus on: type safety, edge cases, performance, and security.`,
      },
    ],
  });

  // Stream text as it arrives
  stream.on("text", (text) => {
    process.stdout.write(text);
  });

  // Get final stats
  const finalMessage = await stream.finalMessage();
  console.log(
    `\n\n---\nTotal tokens: ${finalMessage.usage.input_tokens + finalMessage.usage.output_tokens}`
  );
}
Enter fullscreen mode Exit fullscreen mode

Multi-turn Conversation

import Anthropic from "@anthropic-ai/sdk";

const client = new Anthropic();

class ConversationManager {
  constructor(systemPrompt = null) {
    this.messages = [];
    this.systemPrompt = systemPrompt;
  }

  async chat(userMessage) {
    this.messages.push({ role: "user", content: userMessage });

    const params = {
      model: "claude-sonnet-4-6",
      max_tokens: 2048,
      messages: this.messages,
    };

    if (this.systemPrompt) {
      params.system = this.systemPrompt;
    }

    const response = await client.messages.create(params);
    const assistantMessage = response.content[0].text;

    // Maintain conversation history
    this.messages.push({ role: "assistant", content: assistantMessage });

    return assistantMessage;
  }
}

// Example: multi-turn debugging session
const debugSession = new ConversationManager(
  "You are an expert debugger. Ask clarifying questions and walk through issues step by step."
);

console.log(await debugSession.chat("My API keeps returning 401 errors."));
console.log(await debugSession.chat("I'm including the Authorization header."));
console.log(
  await debugSession.chat("The token is coming from localStorage after login.")
);
Enter fullscreen mode Exit fullscreen mode

Adaptive Thinking: The New Extended Thinking

Adaptive thinking replaces the old extended thinking model on Sonnet 4.6. The key difference: instead of setting a fixed token budget for thinking, you set an effort level and Claude determines how much reasoning the problem actually warrants.

How to Use Adaptive Thinking

import anthropic

client = anthropic.Anthropic()

# Recommended: adaptive thinking with medium effort for most use cases
response = client.messages.create(
    model="claude-sonnet-4-6",
    max_tokens=16000,
    thinking={"type": "adaptive"},
    effort="medium",  # options: "low", "medium", "high" (default: high)
    messages=[{
        "role": "user",
        "content": """
        Design a database schema for a SaaS analytics platform that needs to:
        - Track events from millions of users
        - Support real-time queries on the last 24 hours
        - Archive historical data cost-effectively
        - Handle tenant isolation for enterprise customers
        """
    }]
)

# Thinking blocks appear before the text response
for block in response.content:
    if block.type == "thinking":
        print(f"[Claude's reasoning - {len(block.thinking)} chars]")
    elif block.type == "text":
        print(block.text)
Enter fullscreen mode Exit fullscreen mode

Effort Levels in Practice

Effort Best For Relative Cost Relative Speed
low Classification, simple Q&A, formatting 1x Fastest
medium Code generation, analysis, most tasks 1.5-2x Fast
high Architecture decisions, complex debugging, math 3-5x Moderate

Migration note: If you're using thinking: {type: "enabled", budget_tokens: N}, that syntax still works on Sonnet 4.6 but is deprecated. Migrate to thinking: {type: "adaptive"} with effort before the next major release removes it.

1M Token Context Window

The 1M token context window lets you feed Claude entire codebases, extensive document sets, or months of conversation history. That's roughly 750,000 words or the equivalent of 5–10 full codebases in a single request.

How to Enable 1M Context

Pass the context-1m-2025-08-07 beta header in your request:


python
import anthropic

client = anthropic.Anthropic()

# Read an entire large codebase
with open("large_codebase.txt", "r") as f:
    codebase_content = f.read()

response = client.beta.messages.create(
    model="claude-sonnet-4-6",
    max_tokens=4096,
    betas=["context-1m
Enter fullscreen mode Exit fullscreen mode

Top comments (0)