Skip to content
xAI logo

Grok 4.3

Text GenerationxAIProxied

xAI's Grok 4.3 model with a 1M-token context window and strong agentic tool calling with minimal hallucinations. Accepts text and image inputs, and supports function calling, structured outputs, and configurable reasoning effort (none, low, medium, high).

Model Info
Context Window1,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.3',
{ messages: [{ content: 'What are the three laws of thermodynamics?', role: 'user' }] },
)
console.log(response)
The three main laws of thermodynamics (often called the First, Second, and Third Laws) are fundamental principles describing energy, entropy, and absolute temperature. (A "Zeroth Law" was added later to define thermal equilibrium and temperature, but it is not usually counted among the classic three.)

**First Law (Conservation of Energy)**  
Energy cannot be created or destroyed, only converted from one form to another or transferred. For a closed system, the change in internal energy \(\Delta U\) equals heat added to the system \(Q\) minus work done by the system \(W\):  
\[
\Delta U = Q - W
\]  
(This is essentially a statement of energy conservation.)

**Second Law (Entropy and Direction of Processes)**  
The total entropy of an isolated system (or the universe) always increases over time for irreversible processes and remains constant for reversible ones. Heat naturally flows from hotter to colder bodies, and not all heat can be converted into work without losses. Mathematically, for any real process:  
\[
\Delta S_{\text{universe}} > 0
\]  
(where \(S\) is entropy). This law sets the arrow of time and limits the efficiency of heat engines.

**Third Law (Absolute Zero)**  
As the temperature of a perfect crystal approaches absolute zero (0 K or −273.15 °C), its entropy approaches a minimum value (usually taken as zero). This implies that absolute zero is unattainable in a finite number of steps, and it becomes impossible to remove all thermal energy from a system.  
\[
\lim_{T \to 0} S = 0 \quad \text{(for a perfect crystal)}
\]

These laws apply to macroscopic systems and form the foundation of classical thermodynamics.

Examples

With System Message — Using a system message to set context
TypeScript
const response = await env.AI.run(
'xai/grok-4.3',
{
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)
To read a JSON file in Python, use the built-in `json` module. Here's the standard way:

```python
import json

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

print(data)  # data is now a Python dict or list
```

### Key Points

- **`json.load()`** reads from a file object (as shown above).
- Use the `with` statement to automatically close the file.
- Add `encoding='utf-8'` for safety with non-ASCII characters.
- If you have JSON as a string instead of a file, use `json.loads()`:

```python
import json

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

### Handling Errors

```python
import json

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

This is the recommended approach for most use cases.
Multi-turn Conversation — Continuing a conversation with context
TypeScript
const response = await env.AI.run(
'xai/grok-4.3',
{
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 along the scenic Pacific Coast Highway (Hwy 1) route from San Francisco to Los Angeles, which is far more enjoyable than the faster I-5 inland drive. This path is about 450 miles and takes 8–10 hours of driving time, so plan for 1–2 days with breaks. I've focused on a mix of nature, food, and landmarks, spaced out roughly every 1–2 hours:

### Early Stops (First 2–3 hours from SF)
- **Monterey/Carmel**: Stop for the Monterey Bay Aquarium (world-class marine life exhibits) or a walk along Cannery Row. Nearby, 17-Mile Drive offers stunning coastal views and Pebble Beach golf scenery. Great for lunch—try fresh seafood.
- **Big Sur**: Iconic cliffs, redwoods, and ocean vistas. Pull over at Bixby Creek Bridge for photos or hike in Julia Pfeiffer Burns State Park (McWay Falls is a highlight). Limited services, so gas up beforehand.

### Mid-Trip Stops (Around 4–6 hours in)
- **San Simeon/Hearst Castle**: Tour the opulent Hearst Castle (book ahead) with its pools, gardens, and art collection. Nearby, elephant seal rookeries at Piedras Blancas are free to view from the roadside—amazing wildlife.
- **Morro Bay or Cambria**: Relaxed beach towns. Morro Rock is a volcanic landmark perfect for kayaking or a quick hike. Cambria has cute shops and Moonstone Beach for tidepooling.

### Later Stops (Last 2–3 hours to LA)
- **San Luis Obispo or Pismo Beach**: SLO for a charming downtown with the historic mission and bubblegum alley. Pismo for classic California beach vibes, sand dunes, and clam chowder.
- **Santa Barbara**: "American Riviera" with beautiful beaches, the Spanish-style courthouse for panoramic views, and State Street for shopping/dining. Ideal for an overnight if you're splitting the trip.

### Tips
- **Route note**: Stick to Hwy 1 for scenery (it's slower but worth it); parts can close due to weather/landslides, so check Caltrans updates.
- **Food/essentials**: Pack snacks, as services thin out in Big Sur. Stops like Nepenthe in Big Sur offer cliffside dining.
- **Customization**: If you prefer nature, wine tasting (e.g., near Paso Robles), or family-friendly spots, let me know your interests, group size, or how many days you have—I can refine this or suggest an itinerary with hotels!
Creative Writing — Longer completion for creative output
TypeScript
const response = await env.AI.run(
'xai/grok-4.3',
{
max_completion_tokens: 8192,
messages: [
{
content: 'Write a short story opening about a detective finding an unusual clue.',
role: 'user',
},
],
},
)
console.log(response)
Detective Mara Ellison crouched in the rain-slicked alley behind the shuttered theater, her gloved fingers brushing aside a crumpled playbill. The victim—a reclusive playwright—lay a few feet away, but it was the clue that stopped her cold: a single, flawless chess pawn carved from what looked like human bone, its base etched with the playwright’s own initials in a script too precise for any hurried killer. A faint scent of stage grease clung to it, and when she tilted it toward the streetlight, tiny notches along its side formed a pattern that looked suspiciously like Morse code.
Streaming Response — Enable streaming for real-time output
TypeScript
const response = await env.AI.run(
'xai/grok-4.3',
{
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 programming technique where a function solves a problem by calling *itself* with a smaller or simpler version of the original problem. It keeps breaking the problem down until it reaches a simple case that can be solved directly (called the **base case**).
### Simple Example: Factorial
The factorial of a number *n* (written as *n!*) is the product of all positive integers from 1 to *n*. For example:
- 5! = 5 × 4 × 3 × 2 × 1 = 120
Mathematically, we can define it recursively as:
- **Base case**: 0! = 1 or 1! = 1
- **Recursive case**: n! = n × (n-1)!
Here's how this looks in Python:
```python
def factorial(n):
 if n == 0 or n == 1: # Base case
 return 1
 else:
 return n * factorial(n - 1) # Recursive call
```
### How it works (step-by-step for `factorial(5)`)
1. `factorial(5)` → returns `5 * factorial(4)`
2. `factorial(4)` → returns `4 * factorial(3)`
3. `factorial(3)` → returns `3 * factorial(2)`
4. `factorial(2)` → returns `2 * factorial(1)`
5. `factorial(1)` → hits the **base case** and returns `1`
The results then "unwind" back up:
- `2 * 1 = 2`
- `3 * 2 = 6`
- `4 * 6 = 24`
- `5 * 24 = 120`
So `factorial(5)` returns **120**.
### Key Points
- **Base case** is crucial — without it, the function would call itself forever (causing a stack overflow).
- Recursion uses the **call stack** to keep track of each function call.
- While elegant for some problems (like tree traversals or divide-and-conquer algorithms), recursion can be less efficient than iteration for simple tasks due to the overhead of 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