GPT-5 nano

Text Generation • OpenAI

openai/gpt-5-nano

  • Third-party
  • Zero data retention

GPT-5 Nano is OpenAI’s smallest GPT-5 variant, optimized for low latency and cheap, high-throughput tasks.

Model Info
Context Window ↗ 128,000 tokens
Terms and License link ↗
More information link ↗
Zero data retention Yes
Request formats Responses, Chat Completions
Pricing <ul><li>Input (per 1M tokens)$0.05</li><li>Output (per 1M tokens)$0.40</li><li>Cached input (per 1M tokens)$0.005</li></ul>

Usage

const response = await env.AI.run(
  'openai/gpt-5-nano',
  { messages: [{ content: 'What are the three laws of thermodynamics?', role: 'user' }] },
)
console.log(response)
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "openai/gpt-5-nano",
  "messages": [
    {
      "content": "What are the three laws of thermodynamics?",
      "role": "user"
    }
  ]
}'
There are four laws in the standard formulation, but many introductions refer to the three fundamental ones (the Zeroth law is often treated separately). Here are the three most commonly cited (plus a note about the fourth):

Three fundamental laws (often taught as the main ones)
- First Law (Energy conservation): For a closed system, the change in internal energy equals heat added minus work done by the system.
  ΔU = Q − W
  (Q is heat in, W is work done by the system on the surroundings.)

- Second Law (Entropy and direction of processes): In any spontaneous process, the total entropy of an isolated system increases (or stays the same for reversible processes).
  ΔS ≥ 0
  Equivalently, you can state that you cannot convert all heat into work in a cyclic process (Kelvin–Planck) and that heat cannot spontaneously flow from cold to hot (Clausius).

- Third Law (Asymptotic behavior at low temperature): As temperature approaches absolute zero, the entropy of a perfect crystal approaches a constant minimum (often taken as zero). Practically, absolute zero cannot be reached in a finite number of steps (unattainability).

Note on Zeroth Law
- Zeroth Law: If two systems are each in thermal equilibrium with a third system, they are in thermal equilibrium with each other. This provides the definition of temperature: if A and C are in equilibrium, and B and C are in equilibrium, then A and B are in equilibrium. It underpins the concept of temperature as a property that can be compared.

If you want, I can also give a few simple examples illustrating each law.
{
  "choices": [
    {
      "finish_reason": "stop",
      "index": 0,
      "message": {
        "annotations": [],
        "content": "There are four laws in the standard formulation, but many introductions refer to the three fundamental ones (the Zeroth law is often treated separately). Here are the three most commonly cited (plus a note about the fourth):\n\nThree fundamental laws (often taught as the main ones)\n- First Law (Energy conservation): For a closed system, the change in internal energy equals heat added minus work done by the system.\n  ΔU = Q − W\n  (Q is heat in, W is work done by the system on the surroundings.)\n\n- Second Law (Entropy and direction of processes): In any spontaneous process, the total entropy of an isolated system increases (or stays the same for reversible processes).\n  ΔS ≥ 0\n  Equivalently, you can state that you cannot convert all heat into work in a cyclic process (Kelvin–Planck) and that heat cannot spontaneously flow from cold to hot (Clausius).\n\n- Third Law (Asymptotic behavior at low temperature): As temperature approaches absolute zero, the entropy of a perfect crystal approaches a constant minimum (often taken as zero). Practically, absolute zero cannot be reached in a finite number of steps (unattainability).\n\nNote on Zeroth Law\n- Zeroth Law: If two systems are each in thermal equilibrium with a third system, they are in thermal equilibrium with each other. This provides the definition of temperature: if A and C are in equilibrium, and B and C are in equilibrium, then A and B are in equilibrium. It underpins the concept of temperature as a property that can be compared.\n\nIf you want, I can also give a few simple examples illustrating each law.",
        "refusal": null,
        "role": "assistant"
      }
    }
  ],
  "created": 1777319975,
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "id": "chatcmpl-DZMP9juESnbcNqeQyt9DdJmF9QM0t",
  "model": "gpt-5-nano-2025-08-07",
  "object": "chat.completion",
  "service_tier": "default",
  "system_fingerprint": null,
  "usage": {
    "completion_tokens": 1307,
    "completion_tokens_details": {
      "accepted_prediction_tokens": 0,
      "audio_tokens": 0,
      "reasoning_tokens": 960,
      "rejected_prediction_tokens": 0
    },
    "prompt_tokens": 15,
    "prompt_tokens_details": {
      "audio_tokens": 0,
      "cached_tokens": 0
    },
    "total_tokens": 1322
  }
}

Examples

<details>

<summary>With System Message — Using a system message to set context</summary>

const response = await env.AI.run(
  'openai/gpt-5-nano',
  {
    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)
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "openai/gpt-5-nano",
  "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"
    }
  ]
}'
You can read a JSON file in Python using the built-in json module. Open the file and use json.load to parse it into Python objects (usually dictionaries or lists).

A simple example:
- read a JSON object from a file into a Python dict

```python
import json

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

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

Notes and variations:
- If you have a JSON string (not a file), use json.loads:
```python
import json

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

- Handle errors:
```python
import json

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

- Use pathlib for nicer path handling:
```python
from pathlib import Path
import json

p = Path('data.json')
with p.open('r', encoding='utf-8') as f:
    data = json.load(f)
```

- Large files: json.load reads the whole file into memory. If the file is huge, consider:
  - processing a newline-delimited JSON (NDJSON) file line by line
  - or using a streaming parser like ijson

Example for NDJSON:
```python
import json

with open('data.ndjson', 'r', encoding='utf-8') as f:
    for line in f:
        obj = json.loads(line)
        # process obj
```

- Optional customization: you can use object_hook to customize how dicts are turned into objects:
```python
import json
from dataclasses import dataclass

@dataclass
class Person:
    name: str
    age: int

def decode_person(d):
    if 'name' in d and 'age' in d:
        return Person(d['name'], d['age'])
    return d

with open('people.json', 'r', encoding='utf-8') as f:
    data = json.load(f, object_hook=decode_person)
```

If you tell me the shape of your JSON (dict vs list, any large size concerns), I can tailor the example.
{
  "choices": [
    {
      "finish_reason": "stop",
      "index": 0,
      "message": {
        "annotations": [],
        "content": "You can read a JSON file in Python using the built-in json module. Open the file and use json.load to parse it into Python objects (usually dictionaries or lists).\n\nA simple example:\n- read a JSON object from a file into a Python dict\n\n```python\nimport json\n\nwith open('data.json', 'r', encoding='utf-8') as f:\n    data = json.load(f)\n\nprint(type(data))  # dict or list\nprint(data)\n```\n\nNotes and variations:\n- If you have a JSON string (not a file), use json.loads:\n```python\nimport json\n\ns = '{\"name\": \"Alice\", \"age\": 30}'\ndata = json.loads(s)\n```\n\n- Handle errors:\n```python\nimport json\n\ntry:\n    with open('data.json', 'r', encoding='utf-8') as f:\n        data = json.load(f)\nexcept json.JSONDecodeError as e:\n    print(\"Invalid JSON:\", e)\n```\n\n- Use pathlib for nicer path handling:\n```python\nfrom pathlib import Path\nimport json\n\np = Path('data.json')\nwith p.open('r', encoding='utf-8') as f:\n    data = json.load(f)\n```\n\n- Large files: json.load reads the whole file into memory. If the file is huge, consider:\n  - processing a newline-delimited JSON (NDJSON) file line by line\n  - or using a streaming parser like ijson\n\nExample for NDJSON:\n```python\nimport json\n\nwith open('data.ndjson', 'r', encoding='utf-8') as f:\n    for line in f:\n        obj = json.loads(line)\n        # process obj\n```\n\n- Optional customization: you can use object_hook to customize how dicts are turned into objects:\n```python\nimport json\nfrom dataclasses import dataclass\n\n@dataclass\nclass Person:\n    name: str\n    age: int\n\ndef decode_person(d):\n    if 'name' in d and 'age' in d:\n        return Person(d['name'], d['age'])\n    return d\n\nwith open('people.json', 'r', encoding='utf-8') as f:\n    data = json.load(f, object_hook=decode_person)\n```\n\nIf you tell me the shape of your JSON (dict vs list, any large size concerns), I can tailor the example.",
        "refusal": null,
        "role": "assistant"
      }
    }
  ],
  "created": 1777319979,
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "id": "chatcmpl-DZMPDVD85J31ue22YYuw6KL8rE5q5",
  "model": "gpt-5-nano-2025-08-07",
  "object": "chat.completion",
  "service_tier": "default",
  "system_fingerprint": null,
  "usage": {
    "completion_tokens": 2035,
    "completion_tokens_details": {
      "accepted_prediction_tokens": 0,
      "audio_tokens": 0,
      "reasoning_tokens": 1536,
      "rejected_prediction_tokens": 0
    },
    "prompt_tokens": 30,
    "prompt_tokens_details": {
      "audio_tokens": 0,
      "cached_tokens": 0
    },
    "total_tokens": 2065
  }
}

</details>

<details>

<summary>Multi-turn Conversation — Continuing a conversation with context</summary>

const response = await env.AI.run(
  'openai/gpt-5-nano',
  {
    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)
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "openai/gpt-5-nano",
  "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"
    }
  ]
}'

``` Great question. Here are some standout stops for two popular SF-to-LA routes. Pick the vibe you want and I can tailor a day-by-day plan.

Option 1 — Scenic Pacific Coast Highway (CA-1 / US-101) - Santa Cruz: Beach boardwalk, Wharf, redwood forests nearby (Henry Cowell Redwoods State Park). - Monterey: Monterey Bay Aquarium, Cannery Row, Old Fisherman’s Wharf; consider the 17-Mile Drive for spectacular coastal scenery. - Carmel-by-the-Sea: Charming village, art galleries, white-sand beaches; great for a stroll and lunch. - Big Sur: Breathtaking coastline. Must-see spots include Bixby Creek Bridge, Pfeiffer Beach, and McWay Falls (Julia Pfeiffer Burns State Park). - San Simeon: Hearst Castle tours (book in advance); possible elephant seal viewing at Piedras Blancas Beach. - Morro Bay / San Luis Obispo: Morro Rock views, water activities in Morro Bay; stroll SLO’s downtown and Bubblegum Alley. - Pismo Beach or Santa Barbara: Long beaches, pier, and laid-back coastal vibes; Santa Barbara adds Mission, Stearns Wharf, and the Funk Zone wine area (or detour to Solvang, a Danish-style village). - Santa Barbara to Malibu/Ventura: Beautiful coastal towns and beaches; good for a lunch stop. - Malibu to Santa Monica / Venice Beach: Classic Southern California coast with great seafood spots and iconic piers. - Los Angeles area: If you’re ending in LA, you’ll have countless options for museums, beaches, and dining.

Option 2 — Inland I-5 Corridor (fastest, more practical for a quick trip) - Gilroy: Garlic farms and a solid stop for a quick bite or a stroll through the outlets. - Harris Ranch (Coalinga area): Famous steakhouse lunch stop; a handy fuel/thematic break. - Kettleman City / Buttonwillow: Quick rest stops with gas, snacks, and bathrooms. - Bakersfield: A larger stop with a few cultural options (Buck Owens Crystal Palace, Kern County Museum, downtown stroll). - (Optional detour if you want a wine break) Paso Robles or Santa Ynez wine country a short detour off the main I-5 route. - Santa Clarita / Valencia (near LA): If you want a theme-park or city-break break before hitting the LA basin. - Then onward to the Los Angeles area (Malibu, Santa Monica, Venice, or downtown LA depending on your end point).

A few ready-made itinerary ideas - 3-day coastal loop (full coast life, slower pace): Day 1: SF → Santa Cruz → Monterey/Carmel (overnight in Monterey or Carmel) Day 2: Big Sur coast → San Simeon (Hearst Castle) → Morro Bay (overnight) Day 3: Morro Bay → Santa Barbara → Malibu/Santa Monica (overnight or continue to LA) - 4–5 days for a relaxed coastal trip: Add: Pismo Beach, Santa Barbara wine country detour (Solvang nearby), a longer stay in Santa Monica or Malibu, plus time in LA’s beach areas or neighborhoods.