Skip to content
OpenAI logo

GPT-5.1

Text GenerationOpenAI

GPT-5.1 is OpenAI’s incremental improvement over GPT-5, with stronger coding, reasoning, and writing.

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

Usage

TypeScript
const response = await env.AI.run(
'openai/gpt-5.1',
{ messages: [{ content: 'What are the three laws of thermodynamics?', role: 'user' }] },
)
console.log(response)
The three classical laws of thermodynamics (often listed as 0th–3rd, but you asked for three) are:

**First Law (Conservation of Energy)**  
Energy cannot be created or destroyed, only transformed from one form to another.  
Mathematically for a system:  
\[
\Delta U = Q - W
\]  
where ΔU is change in internal energy, Q is heat added to the system, and W is work done by the system.

**Second Law (Direction of Processes / Entropy)**  
The total entropy of an isolated system never decreases; it either increases or, in an ideal reversible process, stays constant.  
This implies:
- Heat flows spontaneously from hot to cold, not the reverse.
- No heat engine can be 100% efficient.

**Third Law (Absolute Zero and Entropy)**  
As the temperature of a perfect crystalline substance approaches absolute zero (0 K), its entropy approaches a minimum value (often taken as zero).  
Consequence: It is impossible, by any finite number of steps, to cool a system all the way to absolute zero.

Examples

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

### Basic example

```python
import json

# Path to your JSON file
file_path = "data.json"

with open(file_path, "r", encoding="utf-8") as f:
    data = json.load(f)

print(data)
print(type(data))  # usually dict or list
```

- `json.load(f)` reads JSON from an open file object.
- The result is usually a Python `dict` (for JSON objects) or `list` (for JSON arrays).

### If you have JSON as a string

```python
import json

json_str = '{"name": "Alice", "age": 30}'
data = json.loads(json_str)  # note the "s" at the end
```

If you show me a sample of your JSON file, I can suggest the exact code to access its fields.
Multi-turn Conversation — Continuing a conversation with context
TypeScript
const response = await env.AI.run(
'openai/gpt-5.1',
{
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 two main route options with good stops between San Francisco and Los Angeles. You can mix and match depending on your time.

---

## 1. Scenic Coastal Route (Highway 1 / Pacific Coast Highway)

Best if you have at least 1.5–2 days and want views and small towns.

### Between SF and Monterey / Carmel
- **Half Moon Bay**  
  - Quick stop: Harbor, coastal bluffs, coffee on Main St.
- **Pescadero**  
  - Tiny town, great sandwiches and baked goods at Arcangeli Grocery.
  - Pigeon Point Lighthouse viewpoint nearby.

### Monterey & Carmel-by-the-Sea
- **Monterey**  
  - Cannery Row & Old Fisherman’s Wharf (touristy but atmospheric).  
  - Monterey Bay Aquarium (needs 2–3 hours minimum).
- **17-Mile Drive** (between Pacific Grove & Carmel)  
  - Paid scenic drive with coastal lookouts, Lone Cypress, golf course views.
- **Carmel-by-the-Sea**  
  - Walkable village, art galleries, Carmel Beach at sunset.

### Big Sur Area (spectacular coastline)
Plan extra time between Carmel and Ragged Point.

- **Bixby Creek Bridge**  
  - Iconic photo stop; small turnouts on either side.
- **Pfeiffer Beach**  
  - Known for purple-ish sand and rock arch (watch for narrow access road).
- **Julia Pfeiffer Burns State Park / McWay Falls**  
  - Short walk to a viewpoint of a waterfall onto the beach.
- **Nepenthe**  
  - Restaurant with incredible views; good for a snack or drink.
- **Ragged Point**  
  - Scenic overlook, café, restrooms; last dramatic cliff views heading south.

### San Simeon to Pismo Beach
- **Hearst Castle (San Simeon)**  
  - Mansion tours on a hill with ocean views (reserve ahead if possible).
- **Elephant Seal Vista Point (Piedras Blancas)**  
  - Large colony of elephant seals right off the road.
- **Cambria**  
  - Cute town, Moonstone Beach boardwalk, wine tasting.
- **Morro Bay**  
  - Harbor town with Morro Rock; good lunch spot on the water.
- **Pismo Beach**  
  - Classic beach town; pier, dunes, clam chowder (e.g., Splash Café).

### Central Coast to LA
- **San Luis Obispo (SLO)**  
  - Lively college town; great for dinner or an overnight.
- **Solvang**  
  - Danish-style village with bakeries and windmills.
- **Santa Barbara**  
  - Beachfront, Stearns Wharf, State Street shops and restaurants.
- **Malibu**  
  - Coastal pullouts, Zuma Beach, Malibu Pier (cafés, views).
- Continue along PCH into **Santa Monica** and **LA**.

---

## 2. Faster Inland Route (US-101 or I-5)

Best if you want to get there quicker but still have a couple of interesting stops.

### Via US-101 (balanced speed + scenery)
- **Gilroy** – Outlet shopping; garlic-themed everything.  
- **Paso Robles** – Wine country; nice downtown square and tasting rooms.  
- Then connect back to the coast near **San Luis Obispo** and follow the SLO → Santa Barbara → Malibu stops above.

### Via I-5 (fastest, most direct)
More utilitarian, but:

- **Harris Ranch (Coalinga)** – Big steakhouse, hotel, and rest stop.  
- **Tejon Pass / Fort Tejon** – Mountain views as you cross into SoCal.

---

## Quick Templates Depending on Time

- **1 long day, some scenery:**  
  SF → Monterey lunch → Bixby Bridge / McWay Falls stops → San Simeon seals → SLO dinner → LA.

- **2 days, overnight on Central Coast:**  
  Day 1: SF → Half Moon Bay → Monterey → Big Sur sights → overnight in Cambria or SLO.  
  Day 2: SLO → Pismo → Santa Barbara (lunch / explore) → Malibu → LA.

If you tell me:
- which month you’re going,
- how many days you have,
- whether you care more about food, hikes, beaches, or towns,

I can turn this into a specific, timed itinerary with suggested departure times and where to stay.
Creative Writing — Longer completion for creative output
TypeScript
const response = await env.AI.run(
'openai/gpt-5.1',
{
max_completion_tokens: 8192,
messages: [
{
content: 'Write a short story opening about a detective finding an unusual clue.',
role: 'user',
},
],
},
)
console.log(response)
The rain had turned Ashford Lane into a smear of reflections—red tail-lights, yellow windows, blue police strobes bleeding into the black river of asphalt. Detective Mara Leland hunched her shoulders against the weather and ducked under the sagging strip of crime-scene tape, the plastic snapping against her coat like impatient fingers.

The alley smelled of wet cardboard and old grease. Uniforms stood around in the practiced way of people trying not to look curious: hands tucked, mouths tight, eyes everywhere. The body lay where it had dropped beside the overflowing dumpster, face turned toward the brick wall as if listening to it.

“Male, mid-thirties,” the medical examiner said, barely glancing up as Mara approached. “Blunt force trauma, back of the head. Wallet’s missing. So is his phone.” He nodded toward the glistening puddles. “If there was anything else on him, the rain’s not doing us favors.”

Mara crouched, the cold water seeping through the knees of her slacks. The victim’s suit was inexpensive but clean, his tie knotted with deliberate care. No wedding ring. The bruise at the base of his skull was already swelling beneath the wet shine of his hair.

Robbery gone bad, the scene wanted her to think. It almost worked.

Then she saw his hand.

His right fist was clenched tight, the knuckles scraped, as if he’d hit something before he went down—or tried to hold on to it. Mara waited for the tech to finish with his photos, then slid on a fresh pair of gloves.

“Let’s see what you didn’t want to give up,” she murmured.

She pried his fingers open, one by stiffening one. It took effort; the chill had already started to set the muscles. Inside his palm, slick with rainwater and blood, lay a small paper rectangle, folded twice, the edges softened but the center still stiff.

Not a photograph. Not cash. Not a receipt.

A library card.

The laminate was cracked down one side, the blue logo of the Ashford Public Library almost worn away. The name typed beneath it, though, was unmistakable.

“Is that his?” one of the uniforms asked.

Mara shook her head slowly. “No.”

The card was ten years expired.

And it had her own name on it.
Streaming Response — Enable streaming for real-time output
TypeScript
const response = await env.AI.run(
'openai/gpt-5.1',
{
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 when a function solves a problem by calling **itself**, each time working on a **smaller or simpler** version of the original problem, until it reaches a **base case** where it stops.

Two key ideas:
1. **Base case** – when to stop.
2. **Recursive step** – how the function calls itself with a simpler input.

### Simple example: Factorial

The factorial of a number `n` (written `n!`) is:
- `5! = 5 × 4 × 3 × 2 × 1 = 120`
- `1! = 1`
- By definition, `0! = 1`

We can define factorial recursively:
- Base case:  
  If `n = 0`, return `1`.
- Recursive step:  
  If `n > 0`, return `n × factorial(n - 1)`.

In (pseudo)code:

```python
def factorial(n):
    if n == 0:          # base case
        return 1
    else:               # recursive step
        return n * factorial(n - 1)
```

How `factorial(3)` works:
- `factorial(3)`  
  = `3 * factorial(2)`
- `factorial(2)`  
  = `2 * factorial(1)`
- `factorial(1)`  
  = `1 * factorial(0)`
- `factorial(0)`  
  = `1`  (base case)

Now substitute back:
- `factorial(1) = 1 * 1 = 1`
- `factorial(2) = 2 * 1 = 2`
- `factorial(3) = 3 * 2 = 6`

That chain of a function calling itself with smaller inputs is recursion.

Parameters

frequency_penalty
numbermaximum: 2minimum: -2
max_completion_tokens
numberexclusiveMinimum: 0
max_tokens
numberexclusiveMinimum: 0
presence_penalty
numbermaximum: 2minimum: -2
response_format
stream
boolean
temperature
numbermaximum: 2minimum: 0
tool_choice
top_p
numbermaximum: 1minimum: 0

API Schemas (Raw)

Input
Output