Skip to content
Anthropic logo

Claude Sonnet 4.6

Text GenerationAnthropic

Claude Sonnet 4.6 is Anthropic's latest balanced model offering strong coding, reasoning, and agentic capabilities with improved instruction following.

Model Info
Context Window200,000 tokens
Terms and Licenselink
More informationlink
Zero data retentionYes
Request formatsAnthropic Messages
PricingView pricing in the Cloudflare dashboard

Usage

TypeScript
const response = await env.AI.run(
'anthropic/claude-sonnet-4.6',
{
max_tokens: 1024,
messages: [{ content: 'What are the three laws of thermodynamics?', role: 'user' }],
},
)
console.log(response)
There are actually **four** laws of thermodynamics (including the Zeroth Law):

## The Laws of Thermodynamics

**Zeroth Law**
If two systems are each in thermal equilibrium with a third system, they are in thermal equilibrium with each other. (This establishes the concept of temperature.)

**First Law**
Energy cannot be created or destroyed, only converted from one form to another. (Conservation of energy)

**Second Law**
Entropy of an isolated system tends to increase over time. Heat naturally flows from hot to cold, not the reverse. (No perfectly efficient engine is possible.)

**Third Law**
As temperature approaches absolute zero, the entropy of a perfect crystal approaches zero. It is impossible to reach absolute zero in a finite number of steps.

---

The laws are often summarized humorously as:
- **You can't win** (can't get more energy out than you put in)
- **You can't break even** (you always lose some energy to entropy)
- **You can't quit the game** (you can never reach absolute zero)

Would you like more detail on any of these?

Examples

With System Message — Using a system message to set context
TypeScript
const response = await env.AI.run(
'anthropic/claude-sonnet-4.6',
{
max_tokens: 1024,
messages: [{ content: 'How do I read a JSON file in Python?', role: 'user' }],
system: 'You are a helpful coding assistant specializing in Python.',
temperature: 0.3,
},
)
console.log(response)
## Reading a JSON File in Python

### Basic Method using `json` module

```python
import json

# Open and read the JSON file
with open('data.json', 'r') as file:
    data = json.load(file)

print(data)
```

### Common Approaches

**1. Read as a dictionary/list (most common)**
```python
import json

with open('data.json', 'r') as file:
    data = json.load(file)  # Returns a Python dict or list

# Access values
print(data['name'])
print(data['age'])
```

**2. Read JSON string manually**
```python
import json

with open('data.json', 'r') as file:
    content = file.read()          # Read as string
    data = json.loads(content)     # Parse the string (note the 's')
```

**3. Handle encoding (for special characters)**
```python
import json

with open('data.json', 'r', encoding='utf-8') as file:
    data = json.load(file)
```

### Error Handling (Recommended)
```python
import json

try:
    with open('data.json', 'r') as file:
        data = json.load(file)
except FileNotFoundError:
    print("File not found")
except json.JSONDecodeError:
    print("Invalid JSON format")
```

### Key Differences

| Function | Use Case |
|----------|----------|
| `json.load(file)` | Read directly from a **file object** |
| `json.loads(string)` | Parse a **JSON string** |

### Example JSON file (`data.json`)
```json
{
    "name": "Alice",
    "age": 30,
    "hobbies": ["reading", "coding"]
}
```

**Output:**
```python
data['name']    # → "Alice"
data['age']     # → 30
data['hobbies'] # → ["reading", "coding"]
```

> **Tip:** Use `with open()` to ensure the file is automatically closed after reading.
Multi-turn Conversation — Continuing a conversation with context
TypeScript
const response = await env.AI.run(
'anthropic/claude-sonnet-4.6',
{
max_tokens: 1024,
messages: [
{
content: 'I need help planning a road trip from San Francisco to Los Angeles.',
role: 'user',
},
{
content:
"I'd be happy to help! The drive is about 380 miles and takes roughly 5-6 hours. Would you like suggestions for scenic routes or interesting stops along the way?",
role: 'assistant',
},
{ content: 'Yes, what are some good places to stop?', role: 'user' },
],
},
)
console.log(response)
Here are some great stops depending on which route you take:

**Pacific Coast Highway (Highway 1) - Scenic Route**
- **Santa Cruz** - Fun boardwalk and beach town
- **Monterey** - Great aquarium and Cannery Row
- **Big Sur** - Stunning coastal views and hiking
- **San Simeon** - Hearst Castle tours
- **Morro Bay** - Charming harbor town
- **Santa Barbara** - Beautiful city with great food and beaches

**Highway 101 - Middle Route**
- **San Jose** - Tech museums and good food
- **Paso Robles** - Wine country and wineries
- **San Luis Obispo** - Charming college town
- **Santa Barbara** - connects with PCH route

**Interstate 5 - Fastest Route**
- This is the most direct but least scenic
- Good if you just want to get there quickly

**Some Tips:**
- The PCH route adds several hours but is worth it for the views
- Big Sur can have road closures, so check conditions ahead of time
- Santa Barbara is a great overnight stop
- Try to drive Big Sur during daylight for the best views

Would you like more details about any specific stop or help planning an overnight itinerary?
Creative Writing — Higher temperature for creative output
TypeScript
const response = await env.AI.run(
'anthropic/claude-sonnet-4.6',
{
max_tokens: 512,
messages: [
{
content: 'Write a short story opening about a detective finding an unusual clue.',
role: 'user',
},
],
temperature: 0.8,
},
)
console.log(response)
# The Weight of Paper

Detective Mara Osei had seen plenty of strange things in fourteen years on the job. She had once found a murder weapon wrapped in a birthday cake. She had once interviewed a parrot that knew the killer's name.

But this was different.

The victim's apartment was ordinary enough — takeout containers, a dying fern, furniture that looked purchased in a single defeated afternoon at a discount store. Nothing about Leonard Voss suggested a man with enemies. Nothing suggested a man with much of anything.

Except the paper.

Mara crouched beside the coffee table and studied it without touching it. A single sheet, handwritten, covered edge to edge in the same two words repeated hundreds of times in shrinking letters, spiraling inward like a drain.

*I remember. I remember. I remember.*

The handwriting started bold and confident at the outer edge. By the center, the letters were barely visible, scratched by what must have been a nearly dead pen — or a nearly dead hand.

The medical examiner appeared in the doorway. "No signs of struggle. No forced entry." He paused. "Honestly, Mara, it looks like he just *stopped*."

She stood up slowly, slipping her hands into her pockets.

"Then what," she said quietly, "was he trying so hard not to forget?"

---

*The fern, she noticed, had been recently watered.*
Streaming Response — Enable streaming for real-time output
TypeScript
const response = await env.AI.run(
'anthropic/claude-sonnet-4.6',
{
max_tokens: 1024,
messages: [{ content: 'Explain the concept of recursion with a simple example.', role: 'user' }],
stream: true,
},
)
console.log(response)
# Recursion

## Core Concept

Recursion is when a **function calls itself** to solve a smaller version of the same problem, until it reaches a simple base case it can solve directly.

Think of it like Russian nesting dolls — each doll contains a smaller version of itself, until you reach the smallest one.

---

## Two Essential Parts

| Part | Purpose |
|------|---------|
| **Base Case** | Stops the recursion (prevents infinite loop) |
| **Recursive Case** | Breaks the problem into a smaller version |

---

## Simple Example: Countdown

```python
def countdown(n):
    # Base case — stop here
    if n == 0:
        print("Go!")
        return

    # Recursive case — call itself with a smaller value
    print(n)
    countdown(n - 1)  # ← calls itself

countdown(3)
```

**Output:**
```
3
2
1
Go!
```

---

## How It Executes Step by Step

```
countdown(3)
  → prints 3, calls countdown(2)
      → prints 2, calls countdown(1)
          → prints 1, calls countdown(0)
              → prints "Go!", returns   ✓ BASE CASE
```

---

## Classic Example: Factorial

```python
def factorial(n):
    if n == 0:          # base case
        return 1
    return n * factorial(n - 1)   # recursive case

print(factorial(4))  # → 24
```

**Why it works:**
```
factorial(4)
= 4 × factorial(3)
= 4 × 3 × factorial(2)
= 4 × 3 × 2 × factorial(1)
= 4 × 3 × 2 × 1 × factorial(0)
= 4 × 3 × 2 × 1 × 1
= 24
```

---

## ⚠️ Common Mistake: Missing Base Case

```python
def broken(n):
    print(n)
    broken(n - 1)  # never stops → stack overflow!
```

---

## When to Use Recursion

✅ **Good fit for:**
- Tree/folder traversal
- Sorting algorithms (merge sort)
- Problems naturally defined recursively (Fibonacci, factorials)

⚠️ **Be careful of:**
- Deep recursion causing stack overflow
- Repeated calculations (use memoization to fix)

---

**The key insight:** Trust that your function works for a smaller input, use that result to solve the current input, and define where to stop.
Web Search — Letting Claude use Anthropic's server-side web search tool to answer with current information
TypeScript
const response = await env.AI.run(
'anthropic/claude-sonnet-4.6',
{
max_tokens: 4096,
messages: [
{
content:
'What were the top news stories about Cloudflare this week? Summarise in three bullets.',
role: 'user',
},
],
tools: [{ max_uses: 3, name: 'web_search', type: 'web_search_20250305' }],
},
)
console.log(response)
Here's a summary of the top Cloudflare news stories this week:

---

• **AI Agent Verification in Bot Management** — 

Parameters

max_tokens
numberrequiredexclusiveMinimum: 0
system
string
temperature
numberminimum: 0maximum: 1
top_p
numberminimum: 0maximum: 1
top_k
numberexclusiveMinimum: 0
stream
boolean

API Schemas (Raw)

Input
Output