Skip to main content

24 - Opus 4.6 and Sonnet 4.6: Adaptive Thinking and 1M Context

Opus 4.6 and Sonnet 4.6: Adaptive Thinking and 1M Context February-March 2026 marks a decisive turning point in the evolution of Claude models.

What do you think about this article?

At a Glance

Opus 4.6 and Sonnet 4.6: Adaptive Thinking and 1M Context February-March 2026 marks a decisive turning point in the evolution of Claude models.

Opus 4.6 and Sonnet 4.6: Adaptive Thinking and 1M Context

February-March 2026 marks a decisive turning point in the evolution of the Claude models. Anthropic has introduced two new releases that redefine the developer AI landscape: Claude Opus 4.6 (5 February 2026) e Claude Sonnet 4.6 (February 17, 2026). These models bring three crucial innovations: adaptive thinking (automatic deep reasoning, without manual budgeting), 1M context window (one million tokens, no surcharges), e Compaction API (beta, for infinite sessions).

For developers working on complex monorepos - like our Spring Boot + Angular + FastAPI stack - these capabilities represent a quantum leap. A single API request can now swallow the entire codebase, thinking happens in the background without draining your manual budget, and long sessions compact to continue indefinitely.

In this twenty-fourth article of the series Claude, we will analyze the technical specifications, pricing models, migration patterns from the old budget_tokens, and how to leverage these capabilities in your pair programming and agent development workflow.

What You Will Learn

  • The specifications of Claude Opus 4.6 and Claude Sonnet 4.6 released February 2026
  • How automatic adaptive thinking works (no more manual budget_tokens)
  • Configure extended thinking via SDK API (Python and TypeScript)
  • Use the Compaction API for agents who work 8+ hours continuously
  • Leverage the 1M context window for entire monorepo in single prompt
  • Migrate from budget_tokens to effort parameter (manual deprecation Feb 5, 2026)
  • Fast Mode 2.5x preview - when to speed up output vs. think in depth
  • Breaking changes: withdrawn models, pricing tiers, long-context costs

Complete Series Overview

#ItemFocus
1Claude as Technical PartnerSetup and first steps
2Project Context and SetupCLAUDE.md and configuration
3Concept and RequirementsMVP and user personas
4Backend and Frontend ArchitectureSpring Boot and Angular
5Structure of the CodeOrganization and conventions
6Advanced Engineering PromptAdvanced techniques
7Testing and qualityStrategies and test generation
8Professional DocumentationREADME, API, ADR
9Deploy and DevOpsDocker, CI/CD, monitoring
10Evolution and MaintenanceRefactoring and scalability
11Real Project IntegrationClaude Code in production
12Claude Code CLICommands and configuration
13Agent SkillsModular capabilities
14Specialized SubagentsAgents with specific roles
15Hooks and AutomationEvent-driven workflows
16Ralph Wiggum MethodTest-driven development
17BMAD MethodStructured project management
18Multi-Agent OrchestrationAgent pipeline
19Collaborative WorkTeam and pair programming AI
20Security and Best PracticesHardening and compliance
21Monitoring and ObservabilityMetrics and debugging
22Opus vs Sonnet vs HaikuWhen to choose which model
23Extended Thinking: Budget TokensManual deep reasoning
24Opus 4.6 and Sonnet 4.6 (you are here)Adaptive thinking and 1M context

1. Timeline: February-March 2026

The timeline is crucial to understanding the roadmap and deprecation schedules:

Releases and Deprecation

DateEventImpact
5 Feb 2026 Claude Opus 4.6 GA SWE-bench 80.8%, Terminal-Bench SOTA 65.4%, effort parameter GA, fast mode 2.5x preview
Feb 13, 2026 1M Context GA (Opus 4.6) Exits beta, 100→600 images/request, no surcharge vs standard 200K
Feb 17, 2026 Claude Sonnet 4.6 GA SWE-bench 79.6%, OSWorld 72.5%, agentic search 2x, 1M context beta
Feb 19, 2026 Deprecation Sonnet 3.7 + Haiku 3.5 Removed from marketplace, support ends April 19, 2026
13 Mar 2026 1M Context GA (Sonnet 4.6) Exiting beta for Sonnet 4.6 ($3/$15 standard, $6/$22.50 long-context premium)
14 Apr 2026 Deprecation notice: Sonnet 4, Opus 4 Preview, retired effective June 15, 2026

2. Claude Opus 4.6 (5 February 2026)

Opus 4.6 is Anthropic's flagship model for 2026, specializing in tasks of maximum complexity. It's not just an iteration; it is a reinvention of the deep reasoning approach.

Benchmarks and Performance

Opus 4.6 sets new standards on three critical benchmarks:

  • SWE-bench 80.8% (vs Opus 4.3: 72.4%) - Codebase understanding, refactoring, autonomous bug fixes
  • Terminal-Bench 2.0 65.4% SOTA (state-of-the-art) - Complex terminal tasks, command orchestration, debugging
  • Humanity's Last Exam leader - Multidisciplinary benchmark test (mathematics, physics, history, law)

These benchmarks are not just numbers. They reflect the model's ability understand complex context, plan multi-step resolutions, and self-correct. For developers, it means that Opus 4.6 can read an entire monorepo (1M token), understand interdependencies between modules, and suggest refactorings that preserve the semantics of the code.

Novelty: Adaptive Thinking (Deprecation budget_tokens)

The most revolutionary feature of Opus 4.6 is theadaptive thinking. In the previous model (Opus 4.3 with extended thinking), the developer had to manually choose the budget_tokens - how many tokens to dedicate to internal reasoning. Too little = superficial reasoning; too much = unsustainable latency.

With adaptive thinking, it is Claude who decides when and how much to reason. The configuration is no longer:

OLD: budget_tokens manual (deprecated Feb 5, 2026)
// Python SDK - Extended Thinking old style (DEPRECATO)
response = client.messages.create(
    model="claude-opus-4-3",
    max_tokens=16000,
    thinking={
        type="enabled",
        budget_tokens=10000  # Scelgo manualmente
    },
    messages=[{
        role="user",
        content="Analizza questo codebase di 500KB..."
    }]
)
print(response.content[0].thinking)  # Ragionamento interno
print(response.content[1].text)      # Risposta finale

Rather:

NEW: Adaptive Thinking (Opus 4.6 and Sonnet 4.6, GA 5 Feb 2026)
// Python SDK - Adaptive Thinking NEW
response = client.messages.create(
    model="claude-opus-4-6",  # oppure "claude-sonnet-4-6"
    max_tokens=16000,
    thinking={
        type="adaptive"  # Claude decide automaticamente
    },
    messages=[{
        role="user",
        content="Analizza questo codebase di 500KB e suggerisci refactoring..."
    }]
)

# Accedi al ragionamento interno (se esiste)
for block in response.content:
    if block.type == "thinking":
        print(f"Thinking tokens: {len(block.thinking.split())}")
        print(block.thinking)
    elif block.type == "text":
        print("Response:", block.text)

The advantage is immediate: there is no more need for trial and error. Claude knows when deep reasoning is necessary (architecture refactoring, complex debugging) vs. when a quick response is enough (ask for the list of files). Adaptive thinking also acts as an automatic latency regulator: for simple tasks, output arrives in a few seconds; for complex tasks, it takes the necessary time.

Effort Parameter GA

Accompanying adaptive thinking, theeffort parameter. If you still need more control (e.g. "this is a critical task, spend what you need"), you use:

Effort Parameter: low | medium | high | max
// TypeScript SDK - Effort parameter
const response = await client.messages.create({
  model: "claude-opus-4-6",
  max_tokens: 16000,
  thinking: {
    type: "adaptive",
    effort: "high"  // Spingi Claude a ragionare più profondamente
  },
  messages: [{
    role: "user",
    content: "Redesign la logica di caching Redis in produzione per il nostro monorepo..."
  }]
});

// Costi approssimativi per effort:
// - "low":    ~20% meno thinking + 10% faster
// - "medium": baseline (default)
// - "high":   ~50% più thinking + latenza +2-3x
// - "max":    thinking massimo, latenza fino a +10x ma risultati premium

Pricing: Unchanged

Despite the expanded capabilities, Anthropic has pricing was kept unchanged compared to Opus 4.3:

  • $5 / 1M input tokens
  • $25 / 1M output tokens
  • No surcharge for 1M context (GA beta Feb 13, 2026)
  • Thinking tokens counted as input (standard cost, not extra)

1M Context Window (Beta → GA Feb 13)

Opus 4.6 supports 1M token context window a no additional costs above the standard 200K. It means you can send:

  • Entire monorepo codebase (Spring Boot + Angular + FastAPI + Infra) = ~200-400KB = 50-100K tokens
  • 100 blog posts in markdown = ~300-500K = 75-125K tokens
  • CSV dataset with 100K rows = ~400KB = 100K tokens
  • Full prompt system + context = 500K tokens + images
  • Support 100→600 images per single request (vs 20 before)

For developers on monorepo, it's a game-changer: instead of sending individual files one by one (complex prompt engineering), you send the entire codebase and say "I understand the context". Claude has a holistic vision and makes consistent suggestions across layers (domain, application, infrastructure, presentation).

3. Claude Sonnet 4.6 (17 February 2026)

If Opus 4.6 is the flagship model, Sonnet 4.6 is the pragmatic choice: 70% of Opus performance, a 1/5 of the cost, and often smart enough for everyday tasks.

Benchmark Sonnet 4.6

  • SWE-bench 79.6% (vs Sonnet 4.5: 75.2%) - Almost equal to Opus 4.3
  • OSWorld 72.5% - Automazione desktop e webapp complesse
  • Agentic search 2x migliorata - Trova informazioni rilevanti più velocemente
  • Preferito 70% nei trial vs Sonnet 4.5 - Sviluppatori scelgono 4.6 per trade-off latenza/qualità

1M Context (Beta → GA 13 mar)

Sonnet 4.6 supporta 1M context window in beta da 17 feb, con GA annunciata per 13 marzo 2026. A GA, il pricing è:

Sonnet 4.6 Pricing (standard vs long-context)

TierInputOutputContext MaxUse Case
Standard $3 / 1M $15 / 1M 200K token Chat, coding routine, pair programming
Long-Context Premium $6 / 1M $22.50 / 1M 1M token Monorepo, codebase review, document analysis

Il premium è pagato solo se usi context oltre 200K. Se mandi richieste sotto 200K, paghi standard. È un modello equo: non punisce chi non ha bisogno della capacità extra.

Extended Thinking Support

Sonnet 4.6 supporta extended thinking con adaptive thinking, uguale a Opus 4.6. Molti developer preferiscono Sonnet 4.6 per task quotidiane proprio per questo: ragionamento + velocità + costo basso.

4. Adaptive Thinking: Meccanica e Configurazione

Adaptive thinking non è magia. È il risultato di training sofisticato dove il modello ha imparato quando il ragionamento interno migliora la qualità della risposta. Analizziamo come funziona dal lato pratico.

Esecuzione: Cosa Accade in Background

Quando invii una richiesta con thinking: { type: "adaptive" }:

  1. Claude valuta la task - È semplice (informazione diret) o complessa (reasoning multi-step)?
  2. Decide il budget di thinking - Alloca token per ragionamento interno (0 fino a ~20K, dipende da task)
  3. Ragiona in background - Esplora ipotesi, rivede assunzioni, debugga logica
  4. Genera risposta - Basandosi sul ragionamento interno, produce output finale
  5. Ritorna pensiero + risposta - API response contiene sia thinking che text

Caso d'Uso 1: Task Semplice (Niente Thinking)

Quando chiedi "quali sono le dipendenze nel pom.xml di questo progetto?", Claude vede che è una task di lettura diretta. Niente thinking: va al punto, risponde subito.

Simple task: No thinking necessary
// Richiesta
{
  "messages": [{
    "role": "user",
    "content": "Estrai tutte le dipendenze Maven dal seguente pom.xml:\n\n[pom.xml content ~5KB]"
  }],
  "thinking": { "type": "adaptive" }
}

// Response: ~150ms (no thinking block)
{
  "content": [
    {
      "type": "text",
      "text": "Dipendenze principali:\n- spring-boot-starter-web\n- spring-data-jpa\n- ..."
    }
  ]
}

Use Case 2: Complex Task (Adaptive Thinking ~5K tokens)

When you ask “redesign the architecture of this monorepo system to improve testability and performance,” Claude knows it requires deep thinking. Activate thinking automatically.

Complex task: Adaptive thinking ~5K tokens
// Richiesta
{
  "messages": [{
    "role": "user",
    "content": "Analizza questo monorepo [Spring+Angular+FastAPI, ~150KB] e proponi una architettura target per:\n1. Separazione responsabilità fra servizi\n2. Migliorare test coverage dal 45% all'80%\n3. Ottimizzare latenza API da 500ms a 200ms"
  }],
  "thinking": { "type": "adaptive", "effort": "high" }
}

// Response: ~3-5 secondi (con thinking block)
{
  "content": [
    {
      "type": "thinking",
      "thinking": "L'utente chiede una redesign architetturale. Devo:\n1. Analizzare i layer attuali\n2. Identificare violazioni di SRP\n3. Proporre splitting dei moduli\n4. Calcolare impact di testing\n5. Valutare trade-off latenza vs. consistenza\n\n[5K token di ragionamento interno, invisibile all'utente]"
    },
    {
      "type": "text",
      "text": "Proposta architettura target:\n1. Separare Domain dal Presentation layer...\n2. Usare pattern Repository per testabilità...\n..."
    }
  ]
}

5. Compaction API (Beta): Agents Working 8+ Hours

Even with 1M context, a long session (agent working for 8+ hours continuously) will eventually fill the buffer. Compaction API is the solution: automatically summarizes the past conversation, maintaining critical context, and continues indefinitely.

The Problem: Context Window Fills Up

Imagine a developer agent who:

  1. 09:00 am - Analyze the monorepo (200K tokens remaining on 1M)
  2. 10:00 am - Writes tests for 5 modules (500K tokens used, 300K remaining)
  3. 11:00 am - Refactoring service layer (750K tokens used, 150K remaining)
  4. 12pm - Adds logging and monitoring (900K used, 50K remaining)
  5. 1.00 pm - CRASH: Context full, cannot continue

Without Compaction, the agent would be stationary. With Compaction:

Solution: Compaction API

Before the context fills, the agent calls Compaction API That:

  1. Read the full conversation (900K history tokens)
  2. Summarizes critically - "User requests refactoring of Spring Boot monorepo for 80% test coverage. We have already fixed 5 modules, implemented logging, identified 3 anti-patterns in SecurityConfig"
  3. Compact the context - Converts 900K tokens to ~100K structured summary tokens
  4. Continue the session - Agent resumes with 900K free tokens and the conversation compacted

Implementation (Beta Header)

Compaction API is in beta (March 2026), accessible via special header:

Python SDK - Compaction API for long-running agents
import anthropic

client = anthropic.Anthropic()

# Invia il messaggio con header beta
response = client.messages.create(
    model="claude-opus-4-6",
    max_tokens=16000,
    system="Sei un code-review agent. Lavora continuativamente finché non ricevi uno stop explicit.",
    messages=[
        {
            "role": "user",
            "content": "Analizza il monorepo su 8 ore. Refactor, test, documenta. Se ctx quasi pieno, compatta automaticamente."
        }
    ],
    # Richiedi compaction automatica
    extra_headers={
        "anthropic-beta": "interleaved-thinking-2025-05-14"
    }
)

# Ciclo agente
conversation_history = []
total_tokens_used = 0
MAX_TOKENS = 1_000_000

while True:
    # Monitorizza uso contesto
    tokens_remaining = MAX_TOKENS - total_tokens_used

    if tokens_remaining < 100_000:
        print("[Agent] Context quasi pieno, compatto...")

        # Chiama Compaction API
        compaction_response = client.messages.create(
            model="claude-opus-4-6",
            max_tokens=1000,
            system="Riassumi criticamente questa conversazione di lavoro.",
            messages=[
                {"role": "user", "content": "Compatta questa conversazione"},
                *conversation_history
            ],
            extra_headers={
                "anthropic-beta": "interleaved-thinking-2025-05-14"
            }
        )

        # Uso il riassunto compattato per continuar e la sessione
        conversation_history = [
            {
                "role": "assistant",
                "content": f"[CONVERSAZIONE COMPATTATA]\n{compaction_response.content[0].text}"
            }
        ]
        total_tokens_used = 100_000  # Reset conteggio, ora sotto controllo

    # Continua il loop agente
    print("[Agent] Continuo analisi...")
    # ... logica agente ...

Use Case: Automatic Code Review 8 Hours

Practical scenario: I launch an agent who reviews our Spring Boot + Angular monorepo for 8 hours continuously:

  1. 09:00 am - Parse 50 Java files, 30 TS, infra config (150K tokens)
  2. 11:00 am - Generate 20 unit tests, 5 integration tests (500K used)
  3. 1pm - Self-activated Compaction. Converts 500K history to 80K summary
  4. 1.30pm - Agent resumes with 920K free. Continue refactoring SecurityConfig
  5. 4pm - Deliverable: Refactored codebase, 80+ new tests, ADR documentation, all seamless

6. 1M Context Window: What Comes In?

1M context is abstract until you think about it how much code/data actually goes in. Here is a concrete table:

1M Context: Token conversion→real data

ContentTypical SizeToken Approx.Percentage 1M
Entire repo monorepo (backend 150K + frontend 100K + ml 30K) 280KB 70,000 7%
100 markdown blog posts (3KB each) 300KB 75,000 7.5%
CSV dataset with 100K rows (4 columns) 12MB 300,000 30%
600 PNG/WebP images (for viewing) N/A (equiv token) 600,000 (100 tokens each) 60%
100 previous conversations (Q&A, 2KB medium) 200KB 50,000 5%
Realistic total stack monorepo + 50 articles + 100 conversations 195,000 ~19.5%

Practical translation: With 19.5% context used (195K tokens), you still have 800K tokens free for actual work - task description, prompt engineering, generated output. It's a huge space.

Images: 100→600

A concrete improvement of 1M context is support for 600 images per request (vs 20 in 200K context). Use cases:

  • Analyze 300 screenshots of a webapp to replicate it (design → code)
  • Process 500 architectural diagrams to extract patterns
  • Analyze 200 financial graphs to detect anomalies

7. Breaking Changes: Retired Models and Migration

Every Anthropic release brings deprecation. It's important to know so you don't get stuck.

Deprecation already active (February 2026)

  • Sonnet 3.7 - Removed from marketplace Feb 19, 2026, support ends Apr 19
  • Haiku 3.5 - Removed from marketplace Feb 19, 2026, support ends Apr 19
  • budget_tokens parameter - Deprecated Feb 5 (extended thinking old style). USA effort in place

Expected Deprecation (April 2026)

  • Sonnet 4 - Preview Apr 14, 2026, retired Jun 15, 2026
  • Opus 4 - Preview Apr 14, 2026, retired Jun 15, 2026

Migration: Checklist

Breaking Change Checklist

  1. Audit codebase for references to deprecated models
    grep -r "claude-sonnet-4.0\|claude-opus-4" . --include="*.py" --include="*.ts" --include="*.java"
  2. Replace model ID
    • claude-opus-4 → claude-opus-4-6
    • claude-sonnet-4 → claude-sonnet-4-6
    • claude-haiku-3.5 → claude-haiku-4-5 (if it exists)
  3. Migrate thinking parameters
    • If you use thinking.budget_tokens, replace with thinking.type: "adaptive" + optional effort
    • Test carefully: adaptive thinking may use fewer tokens than the old budget_tokens allocated
  4. Check pricing
    • If you use Sonnet 4.6 with context >200K, activate premium pricing ($6/$22.50 vs $3/$15)
    • Calculate impact in your application's API costs
  5. Test staging before production
    • Run test suite with Opus 4.6 / Sonnet 4.6
    • Check output quality vs. old models (could be better/different)
    • Monitor latency - adaptive thinking adds variability

8. Fast Mode Preview: 2.5x Output Rate

A feature in preview on Opus 4.6 is Fast Mode: 2.5x faster output while sacrificing some quality. It is useful for real-time interactions (IDE autocompletion, interactive chat).

When to use Fast Mode

✅ Yes, use Fast Mode for:

  • Autocomplete inline IDE (<500ms response desired)
  • Interactive chat with user (perception of responsiveness)
  • API gateway with SLA 1s (helper microservice)
  • Non-critical batch processing (dummy data generation)

❌ NO, do not use Fast Mode for:

  • Architectural code review (priority: quality)
  • Autonomous agent writing tests/refactors (priority: correctness)
  • Compliance/security analysis (priority: completeness)
  • Generation of technical documentation (priority: precision)
Fast Mode Preview (not GA yet)
// TypeScript - Fast Mode (preview, header beta)
const response = await client.messages.create({
  model: "claude-opus-4-6",
  max_tokens: 1000,
  messages: [{
    role: "user",
    content: "Suggerisci 3 function name alternatives per 'handleUserAuthStateChange'"
  }],
  extra_headers: {
    "anthropic-beta": "fast-mode-2025-05-14"
  }
});

// Latenza attesa:
// - Normal mode: ~1.2s
// - Fast mode:  ~500ms (2.5x più veloce)

9. Practical Cases: Monorepo Spring + Angular + FastAPI

Let's see how to leverage Opus 4.6 / Sonnet 4.6 with our real stack.

Use Case 1: Full Monorepo Code Review (1M Context)

Scenario: Complete code review of the monorepo portfolio (backend 150KB, frontend 100KB, ml-service 30KB, infra 20KB). Without 1M context, I would have to send single files. With 1M context, send everything.

Python - Full monorepo review with Opus 4.6
import anthropic
import subprocess

client = anthropic.Anthropic()

# 1. Raccogli intero monorepo
def gather_monorepo():
    result = subprocess.run(
        ["find", ".", "-type", "f",
         "-name", "*.java", "-o", "-name", "*.ts", "-o", "-name", "*.py",
         "-o", "-name", "*.yml", "-o", "-name", "*.yaml"],
        capture_output=True, text=True
    )

    monorepo_content = ""
    for file_path in result.stdout.strip().split('\n'):
        if file_path and len(monorepo_content) < 900_000:  # Lascia 100K per prompt
            try:
                with open(file_path, 'r') as f:
                    monorepo_content += f"# File: {file_path}\n"
                    monorepo_content += f.read() + "\n\n"
            except:
                pass

    return monorepo_content

# 2. Code review con adaptive thinking
monorepo = gather_monorepo()
print(f"[Info] Monorepo size: {len(monorepo):,} characters (~{len(monorepo)//4:,} token)")

response = client.messages.create(
    model="claude-opus-4-6",
    max_tokens=16000,
    thinking={
        "type": "adaptive",
        "effort": "high"
    },
    messages=[{
        "role": "user",
        "content": f"""Analizza questo monorepo completo e fornisci:

1. **Violazioni architetturali** (Clean Architecture, 4-layer pattern)
2. **Opportunità di refactoring** (DRY, SOLID, testing)
3. **Performance bottleneck** (database query, caching, API latency)
4. **Security issue** (input validation, XSS, SSRF, SQL injection)
5. **Test coverage gap** (unità mancanti, edge case)

Focus: Priorità P0 (critico), P1 (importante), P2 (nice-to-have)

Monorepo:
{monorepo}
"""
    }]
)

# 3. Output
for block in response.content:
    if block.type == "thinking":
        print(f"\n[Claude Thinking]\n{block.thinking[:500]}...")
    elif block.type == "text":
        print(f"\n[Code Review Report]\n{block.text}")

Use Case 2: 8 Hour Autonomous Agent (Compaction API)

Scenario: I launch an agent that works autonomously for 8 hours: analyzes test gaps, writes tests, refactors, updates documentation. With Compaction API, it doesn't get stuck.

Python - Autonomous agent with Compaction API
import anthropic
import time
from datetime import datetime

client = anthropic.Anthropic()

class AutonomousCodeAgent:
    def __init__(self):
        self.conversation = []
        self.total_tokens = 0
        self.start_time = datetime.now()

    def add_message(self, role, content):
        self.conversation.append({"role": role, "content": content})

    def run_iteration(self, task):
        """Esegui una iteration dell'agente"""
        self.add_message("user", task)

        # Chiama Claude
        response = client.messages.create(
            model="claude-opus-4-6",
            max_tokens=8000,
            thinking={"type": "adaptive", "effort": "medium"},
            messages=self.conversation
        )

        # Accumula tokens
        self.total_tokens += response.usage.input_tokens + response.usage.output_tokens

        # Aggiungi risposta al conversation
        assistant_message = ""
        for block in response.content:
            if block.type == "text":
                assistant_message += block.text

        self.add_message("assistant", assistant_message)

        # Compaction se context sta per riempirsi
        if self.total_tokens > 900_000:
            self.compact_conversation()

        elapsed = (datetime.now() - self.start_time).total_seconds()
        print(f"[{elapsed:5.0f}s] Tokens: {self.total_tokens:,} | {task[:60]}...")

        return assistant_message

    def compact_conversation(self):
        """Compatta la conversazione via Compaction API"""
        print("[Agent] ⚡ Compacting conversation...")

        compaction_prompt = "Riassumi questa conversazione di lavoro in 2K token, mantenendo solo le info critiche."

        response = client.messages.create(
            model="claude-opus-4-6",
            max_tokens=2000,
            messages=[
                *self.conversation,
                {"role": "user", "content": compaction_prompt}
            ]
        )

        summary = response.content[0].text

        # Sostituisci conversazione con summary
        self.conversation = [
            {"role": "user", "content": "Ecco il riassunto della nostra conversazione precedente:\n" + summary}
        ]

        # Reset token counter
        self.total_tokens = 0

# 3. Run agente per 8 ore di task
agent = AutonomousCodeAgent()

tasks = [
    "Analizza il file backend/src/main/java/.../UserService.java e identifica test gap",
    "Scrivi 5 unit test per il metodo login() in UserService",
    "Refactor il SecurityConfig per rispettare OWASP Top 10",
    "Aggiungi logging estrutturato in formato JSON per debug",
    "Aggiorna la documentazione API nel README.md",
    "Suggerisci ottimizzazioni di performance per la query findByEmail",
    "Valuta coverage del test suite attuale e identifica weak point",
    "Implementa circuit breaker per il call esterno (Firebase verificazione)"
]

for task in tasks:
    response = agent.run_iteration(task)
    time.sleep(1)  # Rate limiting

10. When to Choose Which Model

The choice between Opus 4.6 and Sonnet 4.6 depends on tasks, budget, and SLA. Here is a practical guide:

Decision Matrix: Opus 4.6 vs Sonnet 4.6

ScenarioModelReasonApprox. Cost
Real-time pair programming
(10-50 requests/session, <200K context)
Sonnet 4.6 Low latency, sufficient quality, low cost $0.10 / session
Architectural code review
(1 request, 1M context, quality priority)
Opus 4.6 Better understanding of context, analysis depth $1-2 / review
Autonomous agent (<8 hours)
(10-50 iterations, compaction API)
Sonnet 4.6 (for ≤4h)
Opus 4.6 (for >4h)
Fast + cheap sonnet; Opus for critical tasks $10-50
Test generation from scratch
(high cohesion required, 5-10 iterations)
Opus 4.6 Better edge case understanding, fewer iterations = lower total cost $2-3 / suite
Simple Chat / FAQ
(user-facing, latency <1s preferred)
Sonnet 4.6 + Fast Mode Guaranteed speed, economical $0.01-0.05
Database Schema Refactoring
(high impact, high risk)
Opus 4.6 Depth analysis, consistency check, migration planning $2-4

11. Migration from budget_tokens to Effort Parameter

If you had code that used extended thinking with manual budget_tokens, here's how to migrate.

BEFORE (Deprecated): Manual budget_tokens
// Python - Extended Thinking OLD STYLE (deprecato 5 feb 2026)
response = client.messages.create(
    model="claude-opus-4-3",
    max_tokens=16000,
    thinking={
        "type": "enabled",
        "budget_tokens": 8000  # Scelgo manualmente
    },
    messages=[{
        "role": "user",
        "content": "Analizza questo monorepo e proponi refactoring architetturale..."
    }]
)

# Problema: devo indovinare il budget. Troppo poco = risultato superficiale, troppo = latenza +10s
AFTER (GA): adaptive thinking + effort
// Python - Adaptive Thinking NEW STYLE (GA 5 feb 2026)
response = client.messages.create(
    model="claude-opus-4-6",  # Update model ID
    max_tokens=16000,
    thinking={
        "type": "adaptive",      # Claude decide automaticamente
        "effort": "high"         # Linea guida opzionale: low|medium|high|max
    },
    messages=[{
        "role": "user",
        "content": "Analizza questo monorepo e proponi refactoring architetturale..."
    }]
)

# Vantaggio: no tuning manuale. Claude alloca il budget necessario automaticamente.

Mapping budget_tokens → effort

If you had budget_tokens: X, you can map to effort like this:

budget_tokens OLDeffort NEWToken Thinking Approx.
1000-2000"low"1000-2000
3000-5000"medium"3000-5000
6000-12000"high"6000-12000
15000-20000"max"15000-20000+

12. Renamed Parameters and API New Features

Beyond thinking e effort, Opus 4.6 / Sonnet 4.6 introduce small variations:

Parameters and Renames (GA 5 Feb 2026)

ParameterStateNotes
output_format Deprecated Renamed to output_config.format for consistency
thinking.type: "adaptive" ✅ GA 5 Feb Replace thinking.type: "enabled" + budget_tokens
effort: "low"|"medium"|"high"|"max" ✅ GA 5 Feb Optional, default "medium". Check depth thinking.
max_output_tokens ✅ Unchanged Limit token output (e.g. 16000 for Opus, 4096 for Sonnet)
temperature ✅ Unchanged 0-2, default 1. Varies creativity/determinism
stop_sequences ✅ Unchanged Array of strings that stop generation

13. Realistic Cost Calculator

How much does a pair programming session with Opus 4.6 / Sonnet 4.6 cost in the real world?

Typical Cost per Task (input ≠ output)

TasksInput TokensOutput TokensModelCost
Simple chat ("explain this feature") 500 1000 Sonnet 4.6 ($3 × 500 + $15 × 1000) / 1M = $0.018
Code review file (10KB) 2500 5000 Sonnet 4.6 ($3 × 2500 + $15 × 5000) / 1M = $0.090
Full monorepo review (1M context) 250000 8000 Opus 4.6 ($5 × 250000 + $25 × 8000) / 1M = $1,450
Autonomous agent 8h (50 iterations) 100000 (average) 60000 (average) Sonnet 4.6 50 × ($3 × 100 + $15 × 120) / 1M = $22.50
Autonomous agent 8h (50 iterations) 100000 60000 Opus 4.6 50 × ($5 × 100 + $25 × 120) / 1M = $52.50

14. Conclusion: Opus 4.7 Coming Soon

Opus 4.6 and Sonnet 4.6 represent a significant leap. For developers of complex monorepos, the impact is immediate: 1M context means no more prompt splitting, adaptive thinking means no more manual tuning, Compaction API means truly autonomous agents.

But Anthropic doesn't stop. Opus 4.7 (Q2 2026 preview) rumors talk about:

  • SWE-bench 87.6% (vs Opus 4.6: 80.8%) - Gap between Claude and human dev even smaller
  • xhigh effort mode - Even deeper thinking for critical architectural tasks
  • Compaction API GA - Exiting beta, SLA guaranteed
  • Multi-modal thinking - Image analysis with internal reasoning

For now, Opus 4.6 remains the model of choice for serious pair programming and agentic development. Sonnet 4.6 is the economical workhorse that covers 70% of the tasks with 20% of the cost.

Next steps:

  1. Migrate your codebase from budget_tokens to adaptive thinking
  2. Test the 1M context window with your entire monorepo
  3. Try Compaction API if you have long-running agents
  4. Consider Fast Mode for interactive chat
  5. Track Anthropic roadmap for Opus 4.7 (Q2 2026)

Official References

Try These Tools

Free developer tools related to this topic.

Commenti

Caricamento commenti...

Sign in to comment

Discuss this article in the community

Join the Telegram group to discuss with other developers, ask questions and share your experiences.

Did you like this article?

Explore other content on the blog or discover my projects