Skip to content
Anthropic logo

Claude Opus 4.8

Text GenerationAnthropic

Claude Opus 4.8 is Anthropic's most capable generally available model, with a step-change improvement in agentic coding over Claude Opus 4.7. It uses adaptive thinking to calibrate reasoning per task and supports a one million token context window at standard pricing.

Model Info
Context Window1,000,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-opus-4.8',
{
max_tokens: 1024,
messages: [{ content: 'What are the three laws of thermodynamics?', role: 'user' }],
},
)
console.log(response)
# The Three Laws of Thermodynamics

## First Law (Conservation of Energy)
Energy cannot be created or destroyed, only transferred or converted from one form to another. The total energy of an isolated system remains constant.

**Common expression:** ΔU = Q − W
- ΔU = change in internal energy
- Q = heat added to the system
- W = work done by the system

## Second Law (Entropy)
The total entropy (disorder) of an isolated system always increases over time, or remains constant in ideal reversible processes. Heat naturally flows from hot to cold, never spontaneously the reverse.

**Key implications:**
- No process is 100% efficient
- Perpetual motion machines are impossible
- The universe tends toward greater disorder

## Third Law (Absolute Zero)
As a system approaches absolute zero (0 Kelvin, −273.15°C), its entropy approaches a minimum constant value. It's impossible to reach absolute zero in a finite number of steps.

---

**A popular informal summary:**
1. You can't win (you can't get more energy out than you put in)
2. You can't break even (you'll always lose some energy to entropy)
3. You can't quit the game (you can't reach absolute zero)

*Note:* There's also a **Zeroth Law**, which states that if two systems are each in thermal equilibrium with a third system, they are in equilibrium with each other—this establishes the concept of temperature.

Would you like a deeper explanation of any particular law?

Examples

With System Message — Using a system message to set context
TypeScript
const response = await env.AI.run(
'anthropic/claude-opus-4.8',
{
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 Method

```python
import json

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

print(data)
```

- `json.load()` reads from a **file object**
- The `with` statement automatically closes the file

## Reading from a JSON String

If you have JSON as a string (not a file), use `json.loads()` (note the "s" for "string"):

```python
import json

json_string = '{"name": "Alice", "age": 30}'
data = json.loads(json_string)

print(data['name'])  # Alice
```

## Example with Error Handling

```python
import json

try:
    with open('data.json', 'r', encoding='utf-8') as file:
        data = json.load(file)
        print(data)
except FileNotFoundError:
    print("The file was not found.")
except json.JSONDecodeError:
    print("The file contains invalid JSON.")
```

## How JSON Maps to Python

| JSON          | Python   |
|---------------|----------|
| object        | `dict`   |
| array         | `list`   |
| string        | `str`    |
| number (int)  | `int`    |
| number (real) | `float`  |
| true / false  | `True` / `False` |
| null          | `None`   |

## Accessing the Data

```python
# Given: {"users": [{"name": "Alice"}, {"name": "Bob"}]}

print(data['users'][0]['name'])  # Alice

# Loop through items
for user in data['users']:
    print(user['name'])
```

Let me know if you'd like help with **writing** JSON files or handling more complex structures!
Multi-turn Conversation — Continuing a conversation with context
TypeScript
const response = await env.AI.run(
'anthropic/claude-opus-4.8',
{
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 along the way, depending on which route you take:

## Coastal Route (Highway 1 / Pacific Coast Highway)
*More scenic but slower—adds a few hours*

- **Santa Cruz** – Beach boardwalk and classic seaside vibes
- **Monterey** – Famous aquarium and Cannery Row
- **Carmel-by-the-Sea** – Charming village with art galleries
- **Big Sur** – Stunning coastline, Bixby Bridge, McWay Falls
- **Hearst Castle** (San Simeon) – Historic mansion tours
- **Pismo Beach** – Sand dunes and laid-back beach town

## Inland Route (I-5)
*Fastest but less scenic*

- **Not many highlights**—mostly farmland, but quick gas/food stops
- Good if you're short on time

## Middle Route (Highway 101)
*A nice balance of speed and scenery*

- **Gilroy** – Garlic capital, outlet shopping
- **Paso Robles** – Wine country with great tasting rooms
- **San Luis Obispo** – Cute college town, historic mission
- **Santa Barbara** – Beautiful "American Riviera," beaches and Spanish architecture
- **Solvang** – Quaint Danish-style village

## A Few Questions to Narrow It Down:
1. How much time do you have for the trip?
2. Are you more interested in nature, food/wine, or towns and attractions?
3. Are you doing it one-way or round-trip?

Let me know and I can help build a more detailed itinerary!
Creative Writing with Adaptive Thinking — Use adaptive thinking with high effort to steer creative output -- the recommended replacement for the deprecated `temperature` parameter.
TypeScript
const response = await env.AI.run(
'anthropic/claude-opus-4.8',
{
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 had seen a thousand crime scenes, but never one this tidy.

The apartment was immaculate—books aligned by height, not a dish in the sink, the dead man arranged on his sofa as if posing for a portrait. No signs of struggle. No forced entry. Just Walter Crane, sixty-three, eyes closed, hands folded across his chest like a man who'd decided to nap forever.

It was the chess set that stopped her.

She crouched beside the small table, careful not to touch. The board was mid-game, pieces scattered in the chaos of a real match—except for one. A black knight, removed from play, stood at the very center of the board where no square could hold it properly. Balanced on the dividing line between two squares, defying the geometry of the game.

Someone had placed it there. Deliberately. The angle was too perfect, the position too impossible to be an accident.

Mara pulled a pen from her jacket and leaned closer. There, etched into the felt base of the knight in letters so small she had to squint, was a single word.

*Soon.*

She felt the cold travel up her spine before her mind caught up to it.

"Detective?" Officer Reyes called from the doorway. "Coroner's saying natural causes. Heart gave out."

Mara didn't look away from the knight. "No," she said quietly. "Somebody wanted us to think that."

She straightened, scanning the too-perfect room with new eyes.

The game wasn't over. It had just begun.
Streaming Response — Enable streaming for real-time output
TypeScript
const response = await env.AI.run(
'anthropic/claude-opus-4.8',
{
max_tokens: 1024,
messages: [{ content: 'Explain the concept of recursion with a simple example.', role: 'user' }],
stream: true,
},
)
console.log(response)
# Understanding Recursion

**Recursion** is a programming technique where a function solves a problem by calling itself on a smaller version of the same problem.

## The Two Essential Parts

Every recursive function needs:

1. **Base case** — the condition that stops the recursion (prevents infinite loops)
2. **Recursive case** — where the function calls itself with a simpler input

---

## Simple Example: Factorial

The factorial of a number (written as `n!`) is the product of all numbers from 1 to n.

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

Notice that `5! = 5 × 4!`, which means we can define factorial **in terms of itself**.

### Code Example (Python)

```python
def factorial(n):
    # Base case: stop when we reach 1
    if n == 1:
        return 1
    # Recursive case: n × factorial of (n-1)
    else:
        return n * factorial(n - 1)

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

---

## How It Works (Step by Step)

When you call `factorial(5)`, it unfolds like this:

```
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)))      ← base case reached!
             = 120
```

The function keeps calling itself until it hits the **base case** (`n == 1`), then the results "bubble back up."

---

## A Helpful Analogy 🪆

Think of **Russian nesting dolls**:
- To open the biggest doll, you open the next smaller one, and so on.
- Eventually you reach the **smallest doll** that can't be opened (the base case).
- Then you put them all back together.

---

## Key Takeaway

> A recursive function breaks a big problem into smaller, identical sub-problems until it reaches a case simple enough to solve directly.

**⚠️ Warning:** Always include a base case! Without it, the function calls itself forever and crashes (a "stack overflow" error).

Would you like to see another example, like calculating a Fibonacci sequence?

Parameters

max_tokens
numberrequiredexclusiveMinimum: 0
system
string
stream
boolean

API Schemas (Raw)

Input
Output