Skip to content
OpenAI logo

GPT-5 mini

Text GenerationOpenAI

GPT-5 Mini is the lightweight, low-cost variant of GPT-5, well suited to high-volume coding and reasoning tasks.

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-mini',
{ messages: [{ content: 'What are the three laws of thermodynamics?', role: 'user' }] },
)
console.log(response)
Briefly, the fundamental laws are:

- Zeroth law (often counted separately): If system A is in thermal equilibrium with B, and B is in thermal equilibrium with C, then A is in thermal equilibrium with C. This justifies the concept of temperature and allows the use of thermometers.

- First law (conservation of energy): Energy is conserved. For a closed system,
  ΔU = Q − W,
  where ΔU is the 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): Natural processes increase the total entropy of an isolated system. A standard mathematical statement:
  ΔS ≥ ∫ δQ_rev/T,
  and for an isolated system ΔS ≥ 0. Equivalent formulations: no cyclic engine can convert all heat into work (Kelvin–Planck), and heat cannot spontaneously flow from a colder to a hotter body (Clausius).

- Third law (zero‑temperature limit): As T → 0, the entropy of a perfect crystalline substance approaches a constant (often taken as zero). Consequences include the unattainability principle: absolute zero cannot be reached in a finite number of steps.

(Traditionally textbooks list the First, Second and Third laws; the Zeroth law was named later because it underpins the concept of temperature.)

Examples

With System Message — Using a system message to set context
TypeScript
const response = await env.AI.run(
'openai/gpt-5-mini',
{
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)
The built‑in json module is the usual way. Use json.load() to parse a file object into Python objects (dicts, lists, strings, numbers, booleans, None).

Basic example:
```python
import json

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

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

Read from a JSON string:
```python
s = '{"name": "Alice", "age": 30}'
obj = json.loads(s)
```

Common extras

- Error handling:
```python
import json

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

- Newline-delimited JSON (NDJSON / JSON Lines):
```python
import json

with open("lines.jsonl", "r", encoding="utf-8") as f:
    for line in f:
        if line.strip():
            obj = json.loads(line)
            # process obj
```

- Large files (streaming): for very large JSON arrays, use a streaming parser like ijson to avoid loading everything into memory:
```python
import ijson

with open("big.json", "rb") as f:
    for item in ijson.items(f, "item"):  # "item" is path for array elements
        # process item
```

- Compressed JSON:
```python
import gzip, json

with gzip.open("data.json.gz", "rt", encoding="utf-8") as f:
    data = json.load(f)
```

- Convert Python back to JSON:
```python
with open("out.json", "w", encoding="utf-8") as f:
    json.dump(data, f, ensure_ascii=False, indent=2)
```

If your JSON maps naturally to tabular data, pandas.read_json can be convenient:
```python
import pandas as pd
df = pd.read_json("data.json")
```

That covers the usual ways — if you share the structure of your JSON or constraints (huge file, NDJSON, custom types), I can give a more specific example.
Multi-turn Conversation — Continuing a conversation with context
TypeScript
const response = await env.AI.run(
'openai/gpt-5-mini',
{
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)
Great — here are several good stop options and a few sample itineraries depending on how much time you have and which route you take (PCH/Highway 1 for scenery, US‑101 for a balance of speed and towns, I‑5 if you want the fastest drive).

High-level route choices
- Pacific Coast Highway (CA‑1 / PCH): Most scenic — cliffs, beaches, Big Sur. Slow, can be winding and has occasional closures/traffic.
- US‑101: Faster than CA‑1 and still scenic through coastal towns, wine country, and beaches.
- I‑5: Fastest (about 5–6 hours), but mostly inland and not scenic. Good if you want to minimize driving time.

Useful tip: check Caltrans for road conditions and CA‑1/Big Sur closures before you go; plan around LA rush hour (avoid entering LA 3–7 pm) and leaving SF early to beat Bay Area traffic.

Stops (north → south) — highlights by route

Common coastal highlights (CA‑1 & 101 overlap in places)
- Half Moon Bay (30–45 min from SF)
  - Quick beach walk, pastries (Local bakeries), coastal trail views.
- Santa Cruz (1–1.5 hr from SF)
  - Boardwalk, surf spots, downtown restaurants.
- Capitola (near Santa Cruz)
  - Colorful seaside village good for a short stroll and lunch.

Monterey/Carmel area (great for families/couples)
- Monterey Bay Aquarium (Monterey)
  - World-class aquarium, Cannery Row dining.
- 17‑Mile Drive / Pebble Beach (Carmel/Monterey)
  - Scenic loop with coastal viewpoints and Lone Cypress.
- Carmel-by-the-Sea
  - Charming village, galleries, beach.

Big Sur (must-see if you have time)
- Bixby Creek Bridge (iconic photo stop)
- Pfeiffer Big Sur State Park (hiking)
- Pfeiffer Beach (purple sand, limited parking)
- McWay Falls / Julia Pfeiffer Burns State Park (waterfall onto beach)
- Note: limited services and cell coverage — fuel up in Monterey or Carmel.

San Simeon / Cambria / Hearst Castle
- Piedras Blancas elephant seal rookery (near San Simeon)
- Hearst Castle tour (advance tickets recommended)
- Cambria — quaint village for dinner/overnight.

San Luis Obispo / Pismo Beach / Morro Bay
- San Luis Obispo (downtown, bubblegum alley)
- Pismo Beach (cliffs, monarch butterflies seasonally)
- Morro Bay (Morro Rock, kayaking)

Santa Ynez Valley / Solvang (inland detour off PCH/101)
- Danish-style Solvang, wineries in Santa Ynez and Los Olivos — great for wine tasting and a slower afternoon.

Santa Barbara (the “American Riviera”)
- State Street, waterfront, mission, good dining and beaches.

Last stretch into Los Angeles (via US‑101 or PCH)
- Ventura (surf, harbor)
- Malibu (beaches, Zuma, Point Dume)
- Santa Monica / Venice (pier, boardwalk, restaurants) before heading to downtown LA or other neighborhoods.

If you take I‑5 (fastest) — practical stops
- Gilroy (garlic/food if you want a quick break)
- Kettleman City or Harris Ranch (famous steakhouse stop)
- Tejon Ranch outlets near the Grapevine (shopping, quick break)
- Pyramid Lake/ghost-town stops are possible but mostly freeway views

Sample itineraries

1) One-day drive, scenic highlights (long day)
- Early SF departure (6–7 am) → Santa Cruz (coffee, 1 hr) → Monterey (lunch, Aquarium optional, 1.5–2 hr) → Big Sur (Bixby Bridge & viewpoints, 1–1.5 hr) → San Simeon (elephant seals) → Santa Barbara arrival late evening. Expect 10–12+ hours including stops.

2) Two-day relaxed coastal trip (recommended)
Day 1: SF → Half Moon Bay → Santa Cruz → Monterey/Carmel (overnight)
Day 2: Carmel → Big Sur (Pfeiffer Beach, McWay Falls) → San Simeon or Pismo → Santa Barbara → LA
- Overnight options: Carmel, Big Sur (if available), or San Luis Obispo/Santa Barbara to split driving times.

3) Three-day scenic + wine-country
Day 1: SF → Santa Cruz → Monterey/Carmel (explore 17‑Mile Drive)
Day 2: Carmel → Big Sur → San Simeon → Pismo/Morro Bay (overnight)
Day 3: Pismo → Solvang (wine tasting) → Santa Barbara → LA

Practical tips
- Time: Without stops SF→LA on PCH/101 is 8–10 hours; I‑5 ~5–6 hours.
- Fuel and services: Fill up before Big Sur; limited gas and few restaurants in stretches.
- Reservations: Hotels in Big Sur and popular towns fill up fast — book ahead. Hearst Castle requires timed tickets.
- Weather/season: Summer fog near SF; Big Sur can have wind and cooler temps. CA‑1 sometimes closes after storms/landslides.
- Parking: Popular spots (Pfeiffer Beach, Bixby turnout, McWay Falls) can have limited parking — arrive early.
- Safety: Drive carefully on winding sections, keep an eye on fuel, cell coverage is spotty in Big Sur.

If you tell me:
- how many days you have,
- whether you prefer beaches, hiking, wine, food stops, or quick travel,
I’ll draft a detailed day‑by‑day plan with drive times, restaurants and where to stay.
Creative Writing — Longer completion for creative output
TypeScript
const response = await env.AI.run(
'openai/gpt-5-mini',
{
max_completion_tokens: 8192,
messages: [
{
content: 'Write a short story opening about a detective finding an unusual clue.',
role: 'user',
},
],
},
)
console.log(response)
The stairwell smelled like old coffee and lemon oil; the landlord kept the cleaner’s bottle on the second landing like a totem. I’d been up and down those stairs enough to know the rhythm of the building—how the pipes sang at night, which door stuck in winter—but the little hallway outside 3B hit a chord I hadn’t heard before: silence so neat it felt deliberate.

Her coat was still on the back of a chair, collar up like a small, pale stack of waves. No sign of forced entry, no overturned furniture, just the slow, inevitable disorder of someone who left thinking she’d be right back. I moved to the chair because detectives move where other people don’t: to pockets. Fingers downed in fabric, searching for lint and receipts and the kind of trash that forgets its own story.

Folded twice, tucked in the inner pocket, was a drawing on cheap paper—crayon blue and stubborn as truth. A stick figure, two dots for eyes, and across the forehead a jagged line of darker crayon. At the bottom, in a child’s hurried script, the name: Jonah. My Jonah. The line across the forehead was the scar I got when I was eight and dared a chain-link fence like a daredevil out of hindsight. A scar nobody I worked with would know about; a scar I had never told anyone about.

The paper smelled faintly of rain and something waxy. I held it up to the single strip of window light and the crayon wax glowed like it had a pulse. The building hummed. Downstairs, someone laughed at nothing. In my chest, something rearranged—an old drawer opened, and a key I’d misplaced years ago slid into my hand. Not a clue so much as an accusation: someone had been in her pockets and had known the exact shape of my face.
Streaming Response — Enable streaming for real-time output
TypeScript
const response = await env.AI.run(
'openai/gpt-5-mini',
{
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 calls itself to solve a smaller instance of the same problem. Two parts are essential:
- Base case: a simple instance that can be answered directly (stops recursion).
- Recursive case: reduces the problem toward the base case by calling the function again.

Simple example — factorial (n! = n × (n−1) × ... × 1)

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

Trace for factorial(4):
factorial(4)
→ 4 * factorial(3)
→ 4 * (3 * factorial(2))
→ 4 * (3 * (2 * factorial(1)))
→ 4 * (3 * (2 * (1 * factorial(0))))
→ 4 * 3 * 2 * 1 * 1 = 24

Another simple example — sum of a list:
def sum_list(lst):
    if not lst:          # base case: empty list
        return 0
    return lst[0] + sum_list(lst[1:])  # recursive case

Notes:
- Always ensure the base case will be reached (otherwise you get infinite recursion and eventually a stack overflow).
- Recursion can make code clearer for problems that naturally break into smaller subproblems (tree traversal, divide-and-conquer). For very deep recursion, consider iterative solutions or tail recursion (if the language optimizes it).

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