Skip to content
Anthropic logo

Claude Sonnet 4

Text GenerationAnthropicProxied

Claude Sonnet 4 delivers superior coding and reasoning while responding more precisely to instructions, a significant upgrade over previous versions.

Model Info
Context Window200,000 tokens
Terms and Licenselink
More informationlink
PricingView pricing in the Cloudflare dashboard

Usage

TypeScript
const response = await env.AI.run(
'anthropic/claude-sonnet-4',
{
messages: [
{
role: 'user',
content: 'What are the three laws of thermodynamics?',
},
],
max_tokens: 1024,
},
{
gateway: { id: 'default' },
}
)
console.log(response)
The three laws of thermodynamics are fundamental principles that govern energy and heat:

## First Law of Thermodynamics
**Energy cannot be created or destroyed, only converted from one form to another.**
- Also known as the law of conservation of energy
- The total energy of an isolated system remains constant
- Mathematically: ΔU = Q - W (change in internal energy equals heat added minus work done by the system)

## Second Law of Thermodynamics
**The entropy (disorder) of an isolated system always increases over time.**
- Heat flows naturally from hot to cold objects, never the reverse (without external work)
- No heat engine can be 100% efficient
- It's impossible to convert heat completely into work without some energy being lost as waste heat

## Third Law of Thermodynamics
**The entropy of a perfect crystal approaches zero as temperature approaches absolute zero.**
- Absolute zero (0 Kelvin or -273.15°C) represents the theoretical point where molecular motion stops
- It's impossible to reach absolute zero in a finite number of steps

*Note: Some formulations include a "zeroth law" about thermal equilibrium, making it technically four laws, but the three above are the classical formulation.*

Examples

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

## Basic Method

```python
import json

# Read JSON file
with open('data.json', 'r') as file:
    data = json.load(file)
    print(data)
```

## With Error Handling

```python
import json

try:
    with open('data.json', 'r') as file:
        data = json.load(file)
        print(data)
except FileNotFoundError:
    print("File not found!")
except json.JSONDecodeError:
    print("Invalid JSON format!")
except Exception as e:
    print(f"An error occurred: {e}")
```

## Specifying Encoding

```python
import json

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

## Reading JSON String (if you have JSON as a string)

```python
import json

json_string = '{"name": "John", "age": 30}'
data = json.loads(json_string)  # Note: loads() not load()
print(data)
```

## Example with Sample Data

Let's say you have a file called `example.json`:
```json
{
    "name": "Alice",
    "age": 25,
    "city": "New York",
    "hobbies": ["reading", "swimming"]
}
```

Reading and accessing the data:
```python
import json

with open('example.json', 'r') as file:
    data = json.load(file)
    
    print(f"Name: {data['name']}")
    print(f"Age: {data['age']}")
    print(f"Hobbies: {', '.join(data['hobbies'])}")
```

## Key Points:
- Use `json.load()` for files
- Use `json.loads()` for strings
- Always use `with open()` for proper file handling
- Add error handling for production code
- The JSON data becomes a Python dictionary/list after loading
Multi-turn Conversation — Continuing a conversation with context
TypeScript
const response = await env.AI.run(
'anthropic/claude-sonnet-4',
{
messages: [
{
role: 'user',
content:
'I need help planning a road trip from San Francisco to Los Angeles.',
},
{
role: 'assistant',
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: 'user',
content: 'Yes, what are some good places to stop?',
},
],
max_tokens: 1024,
},
{
gateway: { id: 'default' },
}
)
console.log(response)
Here are some great stops along the SF to LA route:

**If taking the coastal route (Highway 1/PCH):**
- **Monterey/Carmel** - Monterey Bay Aquarium, charming Carmel-by-the-Sea
- **Big Sur** - Stunning coastal views, McWay Falls, Bixby Creek Bridge
- **Hearst Castle** - Historic mansion in San Simeon
- **Morro Bay** - Iconic Morro Rock and waterfront
- **San Luis Obispo** - Charming downtown and historic mission
- **Pismo Beach** - Beautiful beaches and dunes

**If taking the faster inland route (I-5):**
- **Gilroy** - Famous garlic capital
- **Paso Robles** - Wine country with great tastings
- **Santa Ynez Valley** - More wine regions, Danish-style Solvang

**Mixed route option:** Take Highway 1 partway for scenery, then cut inland via Highway 46 or 101.

The coastal route takes 7-9 hours with stops but offers incredible views. The inland route is faster (5-6 hours) but less scenic.

What type of experience are you looking for - scenic beauty, food, wine, or quick travel time?
Creative Writing — Higher temperature for creative output
TypeScript
const response = await env.AI.run(
'anthropic/claude-sonnet-4',
{
messages: [
{
role: 'user',
content:
'Write a short story opening about a detective finding an unusual clue.',
},
],
max_tokens: 512,
temperature: 0.8,
},
{
gateway: { id: 'default' },
}
)
console.log(response)
Detective Sarah Chen crouched beside the mahogany desk, her latex gloves squeaking against the wood as she carefully lifted what appeared to be an ordinary paper clip. But this one was different—twisted into an intricate knot that seemed to defy the laws of physics, its metal curves flowing impossibly through themselves like a three-dimensional puzzle.

"Henderson, come look at this," she called to her partner, who was dusting for prints near the shattered window. The morning light caught the paper clip's surface, revealing tiny etchings along its length—symbols that looked almost like writing, but in no alphabet she recognized.

The victim, renowned mathematician Dr. Marcus Webb, lay slumped in his chair just inches away, no visible wounds, no signs of struggle. Just him, his cluttered study, and this impossible piece of bent metal that hurt her eyes to look at directly.

Henderson whistled low as he peered over her shoulder. "That's... that's not possible. Metal doesn't bend that way."

Sarah felt a chill run down her spine as she realized the paper clip was warm to the touch, despite the October morning air seeping through the broken window. Whatever had happened in this room last night, she was certain this strange little object held the key to understanding it.
Streaming Response — Enable streaming for real-time output
TypeScript
const response = await env.AI.run(
'anthropic/claude-sonnet-4',
{
messages: [
{
role: 'user',
content: 'Explain the concept of recursion with a simple example.',
},
],
max_tokens: 1024,
stream: true,
},
{
gateway: { id: 'default' },
}
)
console.log(response)
# Recursion Explained

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

## Key Components of Recursion

1. **Base case**: A condition that stops the recursion
2. **Recursive case**: The function calling itself with a modified input

## Simple Example: Calculating Factorial

Let's calculate the factorial of a number (n! = n × (n-1) × (n-2) × ... × 1):

```python
def factorial(n):
    # Base case: stop the recursion
    if n == 0 or n == 1:
        return 1
    
    # Recursive case: function calls itself
    else:
        return n * factorial(n - 1)

# Example usage
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 = 120
```

## Real-world Analogy

Think of **Russian nesting dolls**: To see what's inside, you open one doll, then another smaller doll inside, and so on, until you reach the smallest doll (base case). Then you put them back together in reverse order.

## Why Use Recursion?

- Makes complex problems simpler to understand and code
- Natural fit for problems with repetitive, self-similar structure
- Common in tree traversal, mathematical sequences, and divide-and-conquer algorithms

**Remember**: Always ensure you have a proper base case to avoid infinite recursion!

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