Skip to content
xAI logo

Grok 4.20 Reasoning

Text GenerationxAIProxied

xAI's Grok 4.20 reasoning model. Uses extended thinking to work through complex problems, returning a reasoning trace alongside the final answer.

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

Usage

TypeScript
const response = await env.AI.run(
'xai/grok-4.20-0309-reasoning',
{ messages: [{ content: 'What are the three laws of thermodynamics?', role: 'user' }] },
)
console.log(response)
**The Three Laws of Thermodynamics** (in plain language):

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

- In equation form: **ΔU = Q − W**
  - ΔU = change in the system’s internal energy
  - Q = heat added to the system
  - W = work done *by* the system

This is basically the law of conservation of energy applied to thermodynamic systems. If you add heat to a gas, that energy has to go somewhere — it can increase the gas’s temperature (internal energy) or be used to push a piston (work).

### 2. Second Law (Entropy and Directionality)
**The entropy (disorder) of an isolated system always increases over time.**

Key implications:
- Heat flows spontaneously from hot to cold, never the reverse.
- It is impossible to build a perfectly efficient heat engine (some energy is always “wasted” as heat).
- Processes have a natural direction; time has an arrow.

Popular statement: “You can’t even break even.” Every real process increases the total entropy of the universe.

### 3. Third Law (Absolute Zero)
**As the temperature of a system approaches absolute zero (0 K or −273.15 °C), its entropy approaches a minimum value (often zero for a perfect crystal).**

Key consequences:
- It is impossible to reach absolute zero in a finite number of steps.
- Many materials exhibit strange quantum behaviors near 0 K (superconductivity, superfluidity, etc.).

---

### Bonus: The Zeroth Law (The “Temperature Law”)
Although not one of the original three, it’s so fundamental it was named *after* them:

**If two systems are each in thermal equilibrium with a third system, they are in thermal equilibrium with each other.**

This is what allows us to define temperature and use thermometers.

Would you like a more technical/deep-dive version of any of these laws?

Examples

With System Message — Using a system message to set context
TypeScript
const response = await env.AI.run(
'xai/grok-4.20-0309-reasoning',
{
messages: [
{ content: 'You are a helpful coding assistant specializing in Python.', role: 'system' },
{ content: 'How do I read a JSON file in Python?', role: 'user' },
],
},
)
console.log(response)
**Best way to read a JSON file in Python:**

### Method 1: Using `json.load()` (Recommended)

```python
import json
from pathlib import Path

# Method A: Using pathlib (modern and clean)
def read_json(file_path: str | Path):
    path = Path(file_path)
    with path.open('r', encoding='utf-8') as file:
        return json.load(file)

# Usage
data = read_json('data.json')
print(data)
```

### Method 2: Simple version (most common)

```python
import json

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

print(data)
```

---

### Complete Example

```python
import json
from pathlib import Path
from typing import Any

def load_json(file_path: str | Path) -> dict | list:
    """Safely load a JSON file."""
    try:
        path = Path(file_path)
        with path.open('r', encoding='utf-8') as file:
            return json.load(file)
    except FileNotFoundError:
        print(f"Error: File '{file_path}' not found.")
        return {}
    except json.JSONDecodeError as e:
        print(f"Error: Invalid JSON in '{file_path}': {e}")
        return {}
    except Exception as e:
        print(f"Unexpected error: {e}")
        return {}

# Usage
data = load_json('config.json')

# Access the data
if isinstance(data, dict):
    print(data.get('name'))
    print(data.get('settings', {}))
```

---

### Key Points:

- **`json.load()`** → reads from a **file object**
- **`json.loads()`** → reads from a **string** (note the 's')
- Always specify `encoding='utf-8'` to avoid encoding issues
- Use `pathlib.Path` for better path handling (recommended in modern Python)

---

### Bonus: One-liner (for quick scripts)

```python
import json
data = json.loads(Path('data.json').read_text(encoding='utf-8'))
```

Would you like me to also show how to:
- Read JSON from a URL?
- Handle very large JSON files?
- Write JSON files?
- Use `pydantic` or `dataclasses` with JSON?
Multi-turn Conversation — Continuing a conversation with context
TypeScript
const response = await env.AI.run(
'xai/grok-4.20-0309-reasoning',
{
max_completion_tokens: 8192,
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 excellent stops on the San Francisco to Los Angeles drive**, ordered from north to south. I’m assuming you’re taking the **scenic Pacific Coast Highway (Highway 1)** route, which is far more enjoyable than the fast I-5 inland route. The full coastal drive is roughly 450–500 miles and works best as a **2–3 day trip**.

### Top Recommended Stops (North to South)

**1. Half Moon Bay (45–60 min from SF)**  
- Cute coastal town with dramatic cliffs and beaches.  
- Great for a quick breakfast/coffee stop or a short hike at coastal bluffs.  
- *Pro tip:* Try the bakery at **Half Moon Bay Coffee Company**.

**2. Santa Cruz (1.5–2 hours from SF)**  
- Classic California beach town with a historic boardwalk, surfing culture, and redwood forests nearby.  
- Excellent for lunch (strong seafood scene) or a quick ride on the Giant Dipper roller coaster.  
- If you like nature, detour to **Henry Cowell Redwoods** for a short walk among giant trees.

**3. Monterey & Carmel-by-the-Sea (2–2.5 hours from SF)**  
- **Monterey**: World-class **Monterey Bay Aquarium**, Cannery Row, and fresh seafood.  
- **Carmel**: Storybook village with beautiful beaches, art galleries, and the famous **17-Mile Drive** (pebble beach, cypress trees, multi-million dollar homes).  
- Many people spend their first night here.

**4. Big Sur (3–4 hours from SF)**  
- The **highlight** of the entire drive.  
- Must-sees:  
  - **Bixby Bridge** (iconic photo stop)  
  - **McWay Falls** (waterfall that lands directly on the beach)  
  - **Pfeiffer Beach** (purple sand, keyhole rock formations)  
  - **Julia Pfeiffer Burns State Park** (great short hikes)  
- Stop for lunch at **Nepenthe** (iconic cliffside restaurant with insane views).  
- *Note:* Cell service is spotty here — plan accordingly.

**5. Hearst Castle (San Simeon) (~5–6 hours from SF)**  
- The extravagant mansion built by William Randolph Hearst.  
- Guided tours are impressive if you have 2+ hours. Even just stopping at the visitor center for views is worthwhile.

**6. Cambria or Morro Bay**  
- Relaxed coastal towns perfect for an overnight or dinner.  
- **Moonstone Beach** in Cambria is lovely for a sunset walk.  
- Morro Bay has the famous giant volcanic rock “Morro Rock.”

**7. Pismo Beach / Avila Beach (~7–8 hours from SF)**  
- Classic beach town with good restaurants and fewer crowds than Big Sur.  
- Great midway overnight spot before the final push to LA.

**8. Santa Barbara (9–10 hours from SF)**  
- The “American Riviera.” Spanish architecture, beautiful beaches, excellent wine country nearby.  
- Walk **State Street**, visit the historic **Mission**, or grab seafood at the harbor.  
- Many people spend their second night here.

**9. Malibu (closer to LA)**  
- Stop at **El Matador State Beach** or **Point Dume** for dramatic cliffs and ocean views before hitting the LA traffic.

---

### Quick Itinerary Suggestions

- **2-Day Trip**: SF → Big Sur/Cambria (overnight) → Santa Barbara → LA  
- **3-Day Trip**: SF → Monterey/Carmel (night 1) → Big Sur/Cambria (night 2) → Santa Barbara → LA

Would you like me to:
- Customize this based on your interests (hiking, food, photography, wine, history, etc.)?
- Suggest specific restaurants or hikes?
- Recommend places to stay?
- Give you a Google Maps-ready list or estimated driving times?

Just tell me how many days you have and what kind of vibe you’re going for!
Creative Writing — Longer completion for creative output
TypeScript
const response = await env.AI.run(
'xai/grok-4.20-0309-reasoning',
{
max_completion_tokens: 8192,
messages: [
{
content: 'Write a short story opening about a detective finding an unusual clue.',
role: 'user',
},
],
},
)
console.log(response)
**The Bone Key**

Detective Lena Voss had seen every kind of horror a city could offer, but the silence in apartment 4C unsettled her more than the blood. The victim, Dr. Elias Marrow, lay curled on the kitchen floor like a dropped marionette, throat opened with surgical precision. No defensive wounds. No signs of forced entry. Just the copper stink of blood and the faint smell of ozone, as if lightning had struck indoors.

She was about to call it in when her flashlight caught something clenched in the dead man’s left hand.

Lena crouched, gloved fingers prying open stiffening knuckles. Nestled against the palm was a small key carved from what looked like yellowed bone. Its bow was shaped like a human vertebra. The bit was far too intricate for any normal lock—almost organic, like the inside of an ear.

She turned it toward the light and felt her stomach tighten.

The key was warm.

Not room temperature. *Body* temperature. And as she watched, a thin crimson line—fresh blood—rose through the bone like ink through a straw, tracing a pattern that hadn’t been there a second earlier.

A map.

Lena’s pulse thudded in her ears. She had cleared the apartment herself twenty minutes ago. The key had not been in the victim’s hand then.

Something behind her exhaled, soft as a secret.
Streaming Response — Enable streaming for real-time output
TypeScript
const response = await env.AI.run(
'xai/grok-4.20-0309-reasoning',
{
messages: [{ content: 'Explain the concept of recursion with a simple example.', role: 'user' }],
stream: true,
stream_options: { include_usage: true },
},
)
console.log(response)
**Recursion** is a problem-solving technique where a function **calls itself** to solve smaller versions of the same problem.

It works like this:
- You break a big problem down into smaller, similar problems.
- You keep doing this until you reach a problem so small that you can solve it directly (this is called the **base case**).
- Then you combine the results as the function calls "unwind."

### Simple Example: Factorial

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

**Mathematical definition:**
- 5! = 5 × 4 × 3 × 2 × 1 = 120

**Recursive definition:**
- `factorial(n) = n × factorial(n-1)`
- `factorial(0) = 1` (this is the **base case** — the stopping point)

### How it works step by step:

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

**Calling `factorial(5)`:**

```
factorial(5)
   → 5 * factorial(4)
         → 4 * factorial(3)
               → 3 * factorial(2)
                     → 2 * factorial(1)
                           → 1 * factorial(0)
                                 → 1  (base case reached)
```

Now it starts returning back up:
- `1 * 1 = 1`
- `2 * 1 = 2`
- `3 * 2 = 6`
- `4 * 6 = 24`
- `5 * 24 = 120`

**Final result:** `120`

### Analogy

Think of recursion like a **stack of Russian nesting dolls**. You keep opening smaller and smaller dolls until you reach the tiniest one (base case). Then you put them all back together, multiplying the results as you go back up.

Recursion is elegant for problems that have a naturally recursive structure (tree traversals, directory/file searching, certain mathematical sequences), but it can be less efficient than loops for very large problems due to the memory cost of all those function calls.

Parameters

deferred
boolean | null
frequency_penalty
number | null
logprobs
boolean | null
max_completion_tokens
integer | null
max_tokens
integer | null
n
integer | null
parallel_tool_calls
boolean | null
presence_penalty
number | null
reasoning_effort
string | null
seed
integer | null
stop
array | null
stream
boolean | null
temperature
number | null
tools
array | null
top_logprobs
integer | null
top_p
number | null
user
string | null

API Schemas (Raw)

Input
Output