Skip to content
Anthropic logo

Claude Sonnet 5

Text GenerationAnthropic

Claude Sonnet 5 is Anthropic's most agentic Sonnet model yet, built for coding, tool use, reasoning, and long-horizon professional work at lower cost than Opus-class models.

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

Usage

TypeScript
const response = await env.AI.run(
'anthropic/claude-sonnet-5',
{
max_tokens: 1024,
messages: [{ content: 'What are the three laws of thermodynamics?', role: 'user' }],
},
)
console.log(response)
# The Three (Four) Laws of Thermodynamics

Here are the fundamental laws, typically numbered 1-3 (with a "Zeroth Law" often included as foundational):

## 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 as a measurable property.

## First Law (Conservation of Energy)
**Energy cannot be created or destroyed, only transformed or transferred.**
- Often expressed as: ΔU = Q − W
- (Change in internal energy = Heat added − Work done by the system)
- This means the total energy of an isolated system remains constant.

## Second Law (Entropy)
**The total entropy of an isolated system can never decrease over time; it tends to increase or remain constant.**
- Heat flows spontaneously from hot to cold objects, not the reverse.
- This law explains why certain processes are irreversible and establishes the "arrow of time."
- No heat engine can be 100% efficient at converting heat into work.

## Third Law
**As the temperature of a system approaches absolute zero (0 Kelvin), the entropy of the system approaches a minimum (constant) value.**
- Absolute zero is unattainable in a finite number of steps.
- At absolute zero, a perfect crystal would have exactly zero entropy.

---

**Quick summary often used colloquially:**
1. You can't win (can't get more energy out than you put in)
2. You can't break even (some energy is always lost as unusable heat)
3. You can't get out of the game (can't reach absolute zero)

Examples

With System Message — Using a system message to set context
TypeScript
const response = await env.AI.run(
'anthropic/claude-sonnet-5',
{
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.',
},
)
console.log(response)
# Reading a JSON File in Python

Python's built-in `json` module makes this straightforward.

## Basic Example

```python
import json

with open('data.json', 'r') as file:
    data = json.load(file)

print(data)
```

## Explanation

- **`json.load(file)`** — reads from a file object and parses JSON into Python objects
- **`json.loads(string)`** — use this instead if you have a JSON *string* (not a file) to parse

## Example with Sample Data

Suppose `data.json` contains:

```json
{
    "name": "Alice",
    "age": 30,
    "skills": ["Python", "SQL"]
}
```

You can read and use it like this:

```python
import json

with open('data.json', 'r') as file:
    data = json.load(file)

print(data['name'])      # Alice
print(data['skills'])    # ['Python', 'SQL']
```

## Handling Errors

It's good practice to handle common issues like missing files or invalid JSON:

```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.")
```

## Reading JSON from a String

If your JSON is already a string in memory:

```python
import json

json_string = '{"name": "Bob", "age": 25}'
data = json.loads(json_string)
print(data['name'])  # Bob
```

## Key Type Mappings

| JSON Type | Python Type |
|-----------|-------------|
| object    | dict        |
| array     | list        |
| string    | str         |
| number    | int / float |
| true/false| bool        |
| null      | None        |

That covers the essentials — let me know if you need help with nested data, writing JSON, or working with large files.
Creative Writing with High Effort — Use adaptive thinking with high effort for deeper reasoning.
TypeScript
const response = await env.AI.run(
'anthropic/claude-sonnet-5',
{
max_tokens: 2048,
messages: [
{
content: 'Write a short story opening about a detective finding an unusual clue.',
role: 'user',
},
],
output_config: { effort: 'high' },
thinking: { type: 'adaptive' },
},
)
console.log(response)
Detective Mara Voss crouched beside the overturned chair, careful not to let her coat brush the chalk outline still drying on the hardwood floor. The apartment smelled of lavender and something underneath it—copper, sharp and unmistakable.

"You seeing this?" she called to her partner, Reyes, who was photographing the bookshelf.

He crossed the room, careful of the evidence markers scattered like yellow teeth across the carpet. Mara pointed at the small object resting in the dead man's open palm: a single playing card, the seven of diamonds, except where the diamonds should have been, someone had drawn seven tiny, perfect spirals in red ink.

"Could be nothing," Reyes said, though his voice suggested he didn't believe it.

"Could be." Mara pulled an evidence bag from her pocket but didn't reach for the card yet. Something about it held her still. The spirals weren't random—she'd seen that pattern before, scratched into the doorframe of a cold case file she'd inherited three years ago. A case that had never made sense, that had kept her awake on more nights than she cared to admit.

"Mara?"

She blinked, realized she'd been staring. "This isn't our first body with this signature," she said quietly. "I just didn't know there'd be a second."

Outside, rain began to tap against the window, and somewhere in the building, a door clicked shut—soft, deliberate, like someone had been listening.
Streaming Response — Enable streaming for real-time output
TypeScript
const response = await env.AI.run(
'anthropic/claude-sonnet-5',
{
max_tokens: 1024,
messages: [{ content: 'Explain the concept of recursion with a simple example.', role: 'user' }],
stream: true,
},
)
console.log(response)
# Recursion

**Recursion** is a programming technique where a function calls itself to solve a problem by breaking it down into smaller, similar subproblems.

## Key Components

Every recursive function needs:
1. **Base case** – a condition that stops the recursion (prevents infinite loops)
2. **Recursive case** – where the function calls itself with a smaller/simpler input

## Simple Example: Factorial

The factorial of a number `n` (written `n!`) is the product of all positive integers up to `n`.

Mathematically: `5! = 5 × 4 × 3 × 2 × 1 = 120`

This can be defined recursively as:
```
n! = n × (n-1)!
0! = 1  (base case)
```

### Code Example (Python)

```python
def factorial(n):
    # Base case
    if n == 0:
        return 1
    # Recursive case
    else:
        return n * factorial(n - 1)

print(factorial(5))  # Output: 120
```

### How It Works (Step-by-Step)

```
factorial(5)
= 5 * factorial(4)
= 5 * (4 * factorial(3))
= 5 * (4 * (3 * factorial(2)))
= 5 * (4 * (3 * (2 * factorial(1))))
= 5 * (4 * (3 * (2 * (1 * factorial(0)))))
= 5 * (4 * (3 * (2 * (1 * 1))))
= 120
```

The function keeps calling itself with smaller values until it hits the **base case** (`n == 0`), then the results "unwind" back up, multiplying together to produce the final answer.

## Why Use Recursion?

- Makes code **cleaner** for problems that are naturally recursive (trees, fractals, divide-and-conquer algorithms)
- Mirrors **mathematical definitions** closely
- Useful for problems like: tree traversal, sorting algorithms (quicksort, mergesort), the Fibonacci sequence, and navigating file systems

## Caution ⚠️
Without a proper base case, recursion leads to **infinite recursion** and a stack overflow error!

Parameters

max_tokens
numberrequiredexclusiveMinimum: 0
system
string
stream
boolean

API Schemas (Raw)

Input
Output