Skip to content
OpenAI logo

o3

Text GenerationOpenAI

o3 is OpenAI’s general-purpose reasoning model, balancing strong analytical performance with reasonable latency and cost.

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(
'openai/o3',
{ messages: [{ content: 'What are the three laws of thermodynamics?', role: 'user' }] },
)
console.log(response)
The three fundamental laws of thermodynamics can be stated informally as follows:

1. First Law (Law of Energy Conservation)  
   Energy cannot be created or destroyed; it can only change form. For any closed system the change in internal energy equals the heat added to the system minus the work done by the system.

2. Second Law (Law of Entropy)  
   In any natural (spontaneous) process the total entropy of an isolated system always increases or, at best, remains constant. Equivalently, heat cannot spontaneously flow from a colder body to a hotter body, and no heat engine operating in a cycle can be 100 % efficient.

3. Third Law (Absolute-zero Limit)  
   As the temperature of a perfect crystalline substance approaches absolute zero, its entropy approaches a minimum value (taken as zero). Therefore it is impossible to reach absolute zero by any finite series of processes.

Examples

With System Message — Using a system message to set context
TypeScript
const response = await env.AI.run(
'openai/o3',
{
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)
Reading a JSON file in Python is straightforward with the built-in json module. Below are the most common patterns, from the simplest one-liner to approaches that add error handling, use pathlib, or parse to a pandas DataFrame.

────────────────────────
1. Quick start (basic usage)
────────────────────────
```python
import json

with open("data.json", "r", encoding="utf-8") as f:
    data = json.load(f)      # `data` is now a Python dict or list
```
• json.load() converts the JSON in the file to native Python objects (dict, list, int, float, str, bool, None).  
• encoding="utf-8" is often optional but safest—especially on Windows.

────────────────────────────────────────────────
2. Using pathlib (cleaner path handling, cross-platform)
───────────────────────────────────────────────────────
```python
from pathlib import Path
import json

json_path = Path("path") / "to" / "data.json"

with json_path.open(encoding="utf-8") as f:
    data = json.load(f)
```

──────────────────────────────────────────────
3. Adding error handling / validation
──────────────────────────────────────────────
```python
import json
from pathlib import Path

def read_json(path):
    try:
        with Path(path).open(encoding="utf-8") as f:
            return json.load(f)
    except FileNotFoundError:
        print(f"File not found: {path}")
    except json.JSONDecodeError as exc:
        print(f"Invalid JSON in {path}: {exc}")
    return None

data = read_json("data.json")
```

──────────────────────────────────────────────────────
4. Loading a JSON lines (NDJSON) file (one JSON per line)
──────────────────────────────────────────────────────
```python
import json

records = []
with open("data.ndjson", encoding="utf-8") as f:
    for line in f:
        records.append(json.loads(line))
```

──────────────────────────────────────
5. Directly into a pandas DataFrame
──────────────────────────────────────
If your JSON is an array of objects (list of dicts) or NDJSON:
```python
import pandas as pd

df = pd.read_json("data.json")          # Works for many cases
# For NDJSON:
df = pd.read_json("data.ndjson", lines=True)
```

────────────────────────
6. Writing JSON back out
────────────────────────
```python
with open("output.json", "w", encoding="utf-8") as f:
    json.dump(data, f, indent=2, ensure_ascii=False)
```
• indent adds pretty-printing.  
• ensure_ascii=False keeps non-ASCII characters intact.

That’s all you need to read (and write) JSON in Python!
Multi-turn Conversation — Continuing a conversation with context
TypeScript
const response = await env.AI.run(
'openai/o3',
{
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)
Below are two classic ways to get from San Francisco to Los Angeles, followed by the best stops on each. Pick the route (or combine sections of both) that matches the time you have and the mood you’re after.

────────────────────────
1. SCENIC COAST ROUTE
   Highway 1 / Pacific Coast Highway (PCH)
────────────────────────
Total distance: ≈ 460 mi  
Driving time (no stops): ≈ 9 hrs  
Ideal trip length: 2–4 days

North-to-South Highlights
1. Santa Cruz (75 mi / 1½ hr from SF)  
   • Surfing scene at Steamer Lane, Beach Boardwalk amusement park, funky downtown cafés.  
   • 10 min detour inland: Roaring Camp steam train through redwoods.

2. Monterey & Pacific Grove (45 mi)  
   • Monterey Bay Aquarium, Cannery Row, whale-watch/via kayak, 17-Mile Drive coastal loop.

3. Carmel-by-the-Sea (5 mi)  
   • Fairy-tale cottages, white-sand Carmel Beach, art galleries.  
   • Food tip: La Bicyclette or picnic from 5th Ave Deli.

4. Big Sur Corridor (25-90 mi)  
   • Bixby Creek Bridge photo stop.  
   • Garrapata & Pfeiffer Big Sur State Parks (purple-sand Pfeiffer Beach).  
   • Nepenthe Restaurant for clifftop views.  
   • McWay Falls at Julia Pfeiffer Burns SP (¼-mile walk to overlook).  
   • Overnight options: Big Sur Lodge, Ventana glamping, or campground sites book early.

5. Ragged Point (35 mi)  
   • “Gateway to Big Sur” cliffside vista + coffee/snack.

6. San Simeon / Hearst Castle (15 mi)  
   • 2-hr hilltop tour of William Randolph Hearst’s mansion.  
   • Elephant seal rookery at Piedras Blancas (free, near parking lot).

7. Cambria (8 mi)  
   • Moonstone Beach boardwalk, galleries, Linn’s pies.

8. Morro Bay (22 mi)  
   • Kayak around Morro Rock, sea otters in the marina, fish-n-chips on Embarcadero.

9. San Luis Obispo (13 mi)  
   • Thursday night farmers market, Mission San Luis Obispo, Bubblegum Alley.  
   • Unique stay: Madonna Inn’s themed rooms.

10. Pismo Beach / Oceano Dunes (12 mi)  
    • Walk the pier at sunset; rent an ATV on the dunes. Splash Café for chowder.

11. Danish Village of Solvang (55 mi)  
    • Windmills, aebleskiver pastries, nearby Santa Ynez wine tasting.

12. Santa Barbara (35 mi)  
    • Mediterranean downtown, Funk Zone wine bars, Stearns Wharf.  
    • Quick hike: Inspiration Point (3 mi round-trip).

13. Ventura & Channel Islands Gateway (30 mi)  
    • If you have a half-day, boat to Anacapa or Santa Cruz Island for hiking/kayaking.  
    • Otherwise stroll Ventura Pier and old-town Main St.

14. Malibu (29 mi)  
    • Lunch at Malibu Farm Café on the pier, surf at Zuma Beach, quick cliff walk at Point Dume.

15. Santa Monica & LA arrival (18 mi)  
    • Ferris wheel on the pier, bike path to Venice Beach.  
    • From here it’s 15–25 mi into Hollywood/Downtown depending on traffic.

────────────────────────
2. QUICK(ER) INLAND ROUTE
   US-101 ➜ CA-154 ➜ US-101 or I-5
────────────────────────
Total distance: ≈ 385 mi  
Driving time (no stops): ≈ 5 hrs 45 min  
Ideal trip length: 1–2 days  
Character: Rolling hills, vineyards, missions, fewer hairpin turns than Hwy 1.

Key Stops (North-to-South)
• Gilroy – Garlic capital, outlet shopping.  
• Paso Robles – 200+ wineries, Tin City craft beverage hub, Sensorio light--field art installation (night).  
• San Luis Obispo / Pismo (see above).  
• Solvang & Santa Ynez wine region (see above).  
• Santa Barbara (see above).  
• Optional fast cutover: at Gaviota take CA-154 (San Marcos Pass) to shave ~20 min and drop into Santa Barbara’s north side.  
• From Santa Barbara you can stay on 101 along the coast or jump to I-5 at Ventura (via CA-126) for a straight shot into LA.

────────────────────────
3. PLANNING TIPS
────────────────────────
Time of year
• Winter–spring: Whale migrations, lush green hills in Big Sur, chance of mudslides (check Caltrans).  
• Summer: Long daylight, heavier traffic, book lodgings far ahead. Coastal fog (“June Gloom”) often burns off by noon.  
• Fall: Warm, clear, vineyards in harvest, lighter crowds.

Road & safety
• Fill up before Big Sur; fuel is scarce/pricey between Carmel and Cambria.  
• Cell service is sporadic in Big Sur—download offline maps.  
• Carry layers: temperatures swing 30 °F between sun and coastal fog.

Lodging snapshot
• Quick overnights: Monterey, Cambria, San Luis Obispo, Santa Barbara.  
• Camping gems: Pfeiffer Big Sur SP, Kirk Creek (ocean bluff), Morro Bay SP, Refugio State Beach (just past Santa Barbara).  
• Boutique splurges: Post Ranch Inn (Big Sur), Hotel Cheval (Paso Robles), El Encanto (Santa Barbara).

Driving pace guide (coast route)
SF → Santa Cruz: 1½ hr  
Santa Cruz → Monterey/Carmel: 45 min  
Carmel → Ragged Point (start of Big Sur): 2 hrs (allow 3-4 hrs with view stops)  
Ragged Point → SLO: 1½ hrs  
SLO → Santa Barbara: 1½ hrs  
Santa Barbara → LA (Santa Monica): 1½ hrs (traffic can double this)

────────────────────────
4. SAMPLE ITINERARIES
────────────────────────
Two-day “Greatest Hits” (coast)
Day 1: SF → Monterey (aquarium & 17-Mile Drive) → Bixby Bridge sunset → overnight in Big Sur or Cambria.  
Day 2: Hearst Castle → Morro Bay lunch → Santa Barbara stroll/dinner → evening arrival in LA.

Three-day Leisure (mixed routes)
Day 1: SF → Santa Cruz boardwalk → Carmel lunch → Big Sur hiking → overnight in Cambria.  
Day 2: Cambria → Paso Robles wine tasting → Pismo Beach ATV at dunes → overnight in San Luis Obispo (Thursday farmers market).  
Day 3: Solvang pastries → Santa Barbara beach and mission → Malibu sunset → LA.

Express one-day (inland)
Morning: Leave SF 7 a.m. → coffee in Paso Robles (~11 a.m.) → lunch in Santa Barbara (~2 p.m.) → LA by dinner (~6 p.m.), assuming light traffic.

Enjoy the ride, keep an eye on real-time road conditions at quickmap.dot.ca.gov, and don’t forget your camera—this stretch is one of America’s finest coastal drives!
Creative Writing — Longer completion for creative output
TypeScript
const response = await env.AI.run(
'openai/o3',
{
max_completion_tokens: 8192,
messages: [
{
content: 'Write a short story opening about a detective finding an unusual clue.',
role: 'user',
},
],
},
)
console.log(response)
Detective Lila Navarro crouched beside the overturned rowboat, lantern light trembling across the damp boards. The crime scene smelled of salt, river mud, and something sweeter—freshly ground cinnamon. That scent didn’t belong anywhere near the derelict wharf, yet here it lingered, strongest beneath one splintered plank. She wedged her penknife into the crack and lifted. Nestled in the dark hollow was a single, spotless chess pawn carved from cinnamon bark, its base stamped with today’s date. Lila straightened, pulse quickening. Whoever killed the dock watchman hadn’t just left a calling card; they’d seasoned the night with a puzzle only she would taste.
Streaming Response — Enable streaming for real-time output
TypeScript
const response = await env.AI.run(
'openai/o3',
{
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 in which a function (or procedure) solves a task by calling itself on smaller or simpler parts of the original problem. Each self-call works on a reduced input until a condition is met that stops further calls; this stopping condition is called the base case.  

Why it works:  
1. Every call handles only a small piece of the work.  
2. The base case guarantees the chain of calls eventually ends.  
3. After the base case is reached, the results “bubble back” through the earlier calls to build the final answer.

Simple example: computing the factorial of a non-negative integer n (written n!).  
Factorial definition:  
• n! = n × (n − 1) × (n − 2) × … × 2 × 1  
• 0! is defined as 1.

Recursive idea:  
– Base case: 0! = 1 (also 1! = 1).  
– Recursive step: n! = n × (n − 1)! for n > 0.

Python-like pseudocode:

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

How factorial(4) is evaluated:

1. factorial(4) = 4 × factorial(3)  
2. factorial(3) = 3 × factorial(2)  
3. factorial(2) = 2 × factorial(1)  
4. factorial(1) = 1 × factorial(0)  
5. factorial(0) = 1  ← base case reached  
Now the results return:  
– factorial(1) = 1 × 1 = 1  
– factorial(2) = 2 × 1 = 2  
– factorial(3) = 3 × 2 = 6  
– factorial(4) = 4 × 6 = 24

Thus factorial(4) = 24.

Key points to remember:  
• A recursive function must have at least one base case.  
• Each recursive call should bring the problem closer to that base case.  
• Recursion often leads to concise, readable solutions for problems that exhibit self-similar structure (e.g., factorial, Fibonacci numbers, tree traversal).

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