3. Now data is a normal Python dict/list

print(data) print(type(data)) # e.g. <class 'dict'> print(data["someKey"]) # access fields as usual


Explanation:

1. `open(..., "r", encoding="utf-8")` opens in read-mode.
 2. `json.load(f)` reads the entire file and deserializes it to a Python object.
 3. You can now work with it like any dict or list.

If you already have a JSON string in memory, use `json.loads()`:

```python
import json

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

Error handling example:

import json

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

Alternative with pathlib:

from pathlib import Path
import json

text = Path("data.json").read_text(encoding="utf-8")
data = json.loads(text)

That’s all you need to read JSON files in Python! ````

{
  "choices": [
    {
      "finish_reason": "stop",
      "index": 0,
      "message": {
        "annotations": [],
        "content": "Here’s the most common way, using Python’s built-in json module:\n\n```python\nimport json\n\n# 1. Open the file\nwith open(\"data.json\", \"r\", encoding=\"utf-8\") as f:\n    # 2. Parse the JSON into a Python object (dict or list)\n    data = json.load(f)\n\n# 3. Now `data` is a normal Python dict/list\nprint(data)\nprint(type(data))      # e.g. &lt;class 'dict'>\nprint(data[\"someKey\"]) # access fields as usual\n```\n\nExplanation:\n\n 1. `open(..., \"r\", encoding=\"utf-8\")` opens in read-mode.\n 2. `json.load(f)` reads the entire file and deserializes it to a Python object.\n 3. You can now work with it like any dict or list.\n\nIf you already have a JSON string in memory, use `json.loads()`:\n\n```python\nimport json\n\njson_str = '{\"name\": \"Alice\", \"age\": 30}'\ndata = json.loads(json_str)\n```\n\nError handling example:\n\n```python\nimport json\n\ntry:\n    with open(\"data.json\", encoding=\"utf-8\") as f:\n        data = json.load(f)\nexcept FileNotFoundError:\n    print(\"File not found\")\nexcept json.JSONDecodeError as e:\n    print(\"Invalid JSON:\", e)\nelse:\n    # success\n    print(data)\n```\n\nAlternative with pathlib:\n\n```python\nfrom pathlib import Path\nimport json\n\ntext = Path(\"data.json\").read_text(encoding=\"utf-8\")\ndata = json.loads(text)\n```\n\nThat’s all you need to read JSON files in Python!",
        "refusal": null,
        "role": "assistant"
      }
    }
  ],
  "created": 1776470984,
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "id": "chatcmpl-DVnXkrglfCO4sLEI5BodnMzerw1Ev",
  "model": "o4-mini-2025-04-16",
  "object": "chat.completion",
  "service_tier": "default",
  "system_fingerprint": null,
  "usage": {
    "completion_tokens": 499,
    "completion_tokens_details": {
      "accepted_prediction_tokens": 0,
      "audio_tokens": 0,
      "reasoning_tokens": 128,
      "rejected_prediction_tokens": 0
    },
    "prompt_tokens": 30,
    "prompt_tokens_details": {
      "audio_tokens": 0,
      "cached_tokens": 0
    },
    "total_tokens": 529
  }
}

</details>

<details>

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

const response = await env.AI.run(
  'openai/o4-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)
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/o4-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"
    }
  ]
}'
Here are two popular ways to make the trip—with suggested stops—so you can pick the one that best fits your interests and schedule.

1. Coastal Highway (CA-1 / Pacific Coast Highway)  
   Total driving time: ~8–10 hours (no major traffic), 450 miles  
   Recommended pace: 2–3 days

• Half Moon Bay (30 mi / 45 min from SF)  
     – Stroll the beaches, grab coffee or seafood at the harbor.  
     – Quick dune hike at Poplar Beach or Fitzgerald Marine Reserve.

• Santa Cruz (50 mi / 1 hr from Half Moon Bay)  
     – Santa Cruz Beach Boardwalk for rides & arcade.  
     – Downtown Pacific Avenue for shops and local brews.

• Capitola (5 mi / 10 min from Santa Cruz)  
     – Colorful seaside village with boutique shops and cafés.  
     – Great spot for sunset on Capitola Beach.

• Monterey & Carmel (45 mi / 1 hr from Capitola)  
     – Monterey Bay Aquarium, Cannery Row, coastal bike path.  
     – Carmel-by-the-Sea: fairy-tale cottages, art galleries, Carmel Mission.  
     – 17-Mile Drive (pebbled beaches, peacocks, iconic Lone Cypress).

• Big Sur (30 mi / 1 hr from Carmel)  
     – Bixby Creek Bridge photo-op.  
     – Pfeiffer Beach (purple sand) and McWay Falls at Julia Pfeiffer Burns State Park.  
     – Ragged Point for coastal vistas and snacks.  
     Overnight option: Big Sur Lodge or camping.

• San Simeon & Cambria (45 mi / 1 hr from Big Sur)  
     – Hearst Castle tour.  
     – Elephant Seal Vista Point just north of San Simeon.  
     – Cambria’s Moonstone Beach Boardwalk and quaint Main Street.

• Morro Bay (25 mi / 35 min from Cambria)  
     – Morro Rock, waterfront restaurants, kayaking and bird-watching.

• San Luis Obispo (30 mi / 35 min from Morro Bay)  
     – Mission San Luis Obispo de Tolosa.  
     – Bubblegum Alley and bustling Higuera Street for dinner or a brew.  
     Overnight option: downtown SLO.

• Pismo Beach & Solvang (option)  
     – Pismo: pier, ATV dunes at nearby Oceano Dunes.  
     – Solvang: Danish-style village and bakeries (20 mi inland from Pismo).

• Santa Barbara (100 mi / 2 hrs from SLO)  
     – State Street shopping, Stearns Wharf, Mission Santa Barbara.  
     – Wine tasting in the nearby Funk Zone or Santa Ynez Valley.

• Malibu & Santa Monica (90 mi / 1½–2 hrs from SB)  
     – Malibu’s Zuma Beach or Point Dume.  
     – Santa Monica Pier, Third Street Promenade.

• Los Angeles (20 mi / 30 min from Santa Monica)  
     – Welcome to LA!

2. Faster Inland Route (I-5)  
   Total driving time: ~6 hrs, 380 miles  
   Good if you’re pressed for time;  fewer scenic overlooks but easier mileage.

Key stops along I-5:  
   • Gilroy (40 mi / 45 min from SF) – Home of the Garlic Festival; farm stands.  
   • Kettleman City (160 mi / 2½ hrs from Gilroy) – Bravo Farms for ice cream and picnic.  
   • Harris Ranch (80 mi / 1 hr from Kettleman) – Large steakhouse, deli and wine shop.  
   • Grapevine / Tejon Pass (65 mi / 1 hr from Harris) – Decent rest-stop restaurants and views as you descend into Southern California.  
   • Valencia / Santa Clarita (30 mi / 30 min from Grapevine) – Valencia Town Center for shops.  
   • Los Angeles (35 mi / 40 min from Valencia)

—  
Tips:  
• Plan fuel and rest stops in Big Sur — services are sparse.  
• Book lodging early if traveling weekends or holidays (Big Sur, SLO, Santa Barbara are popular).  
• Allow extra time for traffic, especially near Malibu, Santa Barbara, and LA.

Enjoy your trip! Let me know if you need more detail on any stop or lodging suggestions.
{
  "choices": [
    {
      "finish_reason": "stop",
      "index": 0,
      "message": {
        "annotations": [],
        "content": "Here are two popular ways to make the trip—with suggested stops—so you can pick the one that best fits your interests and schedule.  \n\n1. Coastal Highway (CA-1 / Pacific Coast Highway)  \n   Total driving time: ~8–10 hours (no major traffic), 450 miles  \n   Recommended pace: 2–3 days  \n\n   • Half Moon Bay (30 mi / 45 min from SF)  \n     – Stroll the beaches, grab coffee or seafood at the harbor.  \n     – Quick dune hike at Poplar Beach or Fitzgerald Marine Reserve.  \n\n   • Santa Cruz (50 mi / 1 hr from Half Moon Bay)  \n     – Santa Cruz Beach Boardwalk for rides & arcade.  \n     – Downtown Pacific Avenue for shops and local brews.  \n\n   • Capitola (5 mi / 10 min from Santa Cruz)  \n     – Colorful seaside village with boutique shops and cafés.  \n     – Great spot for sunset on Capitola Beach.  \n\n   • Monterey & Carmel (45 mi / 1 hr from Capitola)  \n     – Monterey Bay Aquarium, Cannery Row, coastal bike path.  \n     – Carmel-by-the-Sea: fairy-tale cottages, art galleries, Carmel Mission.  \n     – 17-Mile Drive (pebbled beaches, peacocks, iconic Lone Cypress).  \n\n   • Big Sur (30 mi / 1 hr from Carmel)  \n     – Bixby Creek Bridge photo-op.  \n     – Pfeiffer Beach (purple sand) and McWay Falls at Julia Pfeiffer Burns State Park.  \n     – Ragged Point for coastal vistas and snacks.  \n     Overnight option: Big Sur Lodge or camping.  \n\n   • San Simeon & Cambria (45 mi / 1 hr from Big Sur)  \n     – Hearst Castle tour.  \n     – Elephant Seal Vista Point just north of San Simeon.  \n     – Cambria’s Moonstone Beach Boardwalk and quaint Main Street.  \n\n   • Morro Bay (25 mi / 35 min from Cambria)  \n     – Morro Rock, waterfront restaurants, kayaking and bird-watching.  \n\n   • San Luis Obispo (30 mi / 35 min from Morro Bay)  \n     – Mission San Luis Obispo de Tolosa.  \n     – Bubblegum Alley and bustling Higuera Street for dinner or a brew.  \n     Overnight option: downtown SLO.  \n\n   • Pismo Beach & Solvang (option)  \n     – Pismo: pier, ATV dunes at nearby Oceano Dunes.  \n     – Solvang: Danish-style village and bakeries (20 mi inland from Pismo).  \n\n   • Santa Barbara (100 mi / 2 hrs from SLO)  \n     – State Street shopping, Stearns Wharf, Mission Santa Barbara.  \n     – Wine tasting in the nearby Funk Zone or Santa Ynez Valley.  \n\n   • Malibu & Santa Monica (90 mi / 1½–2 hrs from SB)  \n     – Malibu’s Zuma Beach or Point Dume.  \n     – Santa Monica Pier, Third Street Promenade.  \n\n   • Los Angeles (20 mi / 30 min from Santa Monica)  \n     – Welcome to LA!  \n\n2. Faster Inland Route (I-5)  \n   Total driving time: ~6 hrs, 380 miles  \n   Good if you’re pressed for time;  fewer scenic overlooks but easier mileage.  \n\n   Key stops along I-5:  \n   • Gilroy (40 mi / 45 min from SF) – Home of the Garlic Festival; farm stands.  \n   • Kettleman City (160 mi / 2½ hrs from Gilroy) – Bravo Farms for ice cream and picnic.  \n   • Harris Ranch (80 mi / 1 hr from Kettleman) – Large steakhouse, deli and wine shop.  \n   • Grapevine / Tejon Pass (65 mi / 1 hr from Harris) – Decent rest-stop restaurants and views as you descend into Southern California.  \n   • Valencia / Santa Clarita (30 mi / 30 min from Grapevine) – Valencia Town Center for shops.  \n   • Los Angeles (35 mi / 40 min from Valencia)  \n\n—  \nTips:  \n• Plan fuel and rest stops in Big Sur — services are sparse.  \n• Book lodging early if traveling weekends or holidays (Big Sur, SLO, Santa Barbara are popular).  \n• Allow extra time for traffic, especially near Malibu, Santa Barbara, and LA.  \n\nEnjoy your trip! Let me know if you need more detail on any stop or lodging suggestions.",
        "refusal": null,
        "role": "assistant"
      }
    }
  ],
  "created": 1776470989,
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "id": "chatcmpl-DVnXph5iAItZ049bKX3IMVRStv3NL",
  "model": "o4-mini-2025-04-16",
  "object": "chat.completion",
  "service_tier": "default",
  "system_fingerprint": null,
  "usage": {
    "completion_tokens": 1331,
    "completion_tokens_details": {
      "accepted_prediction_tokens": 0,
      "audio_tokens": 0,
      "reasoning_tokens": 320,
      "rejected_prediction_tokens": 0
    },
    "prompt_tokens": 76,
    "prompt_tokens_details": {
      "audio_tokens": 0,
      "cached_tokens": 0
    },
    "total_tokens": 1407
  }
}

</details>

<details>

<summary>Creative Writing — Longer completion for creative output</summary>

const response = await env.AI.run(
  'openai/o4-mini',
  {
    max_completion_tokens: 8192,
    messages: [
      {
        content: 'Write a short story opening about a detective finding an unusual clue.',
        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/o4-mini",
  "max_completion_tokens": 8192,
  "messages": [
    {
      "content": "Write a short story opening about a detective finding an unusual clue.",
      "role": "user"
    }
  ]
}'
Detective Mara Ellington crouched in the alley’s muted glow, rain dripping from her brimmed hat. The city’s midnight hush was deafening, broken only by distant sirens and the scurry of rats. She’d come to inspect the scene of a daring daylight burglary at the old Currier estate, expecting shattered glass and empty safes. Instead, on the damp cobblestones, she found a single porcelain doll’s head—its cheek chipped, one glass eye staring blankly at the moon.

Heat prickled her neck. No burglar would leave such a thing behind. She reached for it, careful of the spider-web crack snaking from its temple. The doll’s painted lips were twisted into an unnatural grin, and tucked beneath its chin was a scrap of yellowed paper, edges singed. Mara unfolded it, breath catching as she read the single word scrawled in crimson ink: “Found.”
{
  "choices": [
    {
      "finish_reason": "stop",
      "index": 0,
      "message": {
        "annotations": [],
        "content": "Detective Mara Ellington crouched in the alley’s muted glow, rain dripping from her brimmed hat. The city’s midnight hush was deafening, broken only by distant sirens and the scurry of rats. She’d come to inspect the scene of a daring daylight burglary at the old Currier estate, expecting shattered glass and empty safes. Instead, on the damp cobblestones, she found a single porcelain doll’s head—its cheek chipped, one glass eye staring blankly at the moon. \n\nHeat prickled her neck. No burglar would leave such a thing behind. She reached for it, careful of the spider-web crack snaking from its temple. The doll’s painted lips were twisted into an unnatural grin, and tucked beneath its chin was a scrap of yellowed paper, edges singed. Mara unfolded it, breath catching as she read the single word scrawled in crimson ink: “Found.”",
        "refusal": null,
        "role": "assistant"
      }
    }
  ],
  "created": 1776470989,
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "id": "chatcmpl-DVnXpXvTKSGQ5iGgAj5ky00Ve4KC2",
  "model": "o4-mini-2025-04-16",
  "object": "chat.completion",
  "service_tier": "default",
  "system_fingerprint": null,
  "usage": {
    "completion_tokens": 269,
    "completion_tokens_details": {
      "accepted_prediction_tokens": 0,
      "audio_tokens": 0,
      "reasoning_tokens": 64,
      "rejected_prediction_tokens": 0
    },
    "prompt_tokens": 19,
    "prompt_tokens_details": {
      "audio_tokens": 0,
      "cached_tokens": 0
    },
    "total_tokens": 288
  }
}

</details>

<details>

<summary>Streaming Response — Enable streaming for real-time output</summary>

const response = await env.AI.run(
  'openai/o4-mini',
  {
    messages: [{ content: 'Explain the concept of recursion with a simple example.', role: 'user' }],
    stream: true,
    stream_options: { include_usage: true },
  },
)
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/o4-mini",
  "messages": [
    {
      "content": "Explain the concept of recursion with a simple example.",
      "role": "user"
    }
  ],
  "stream": true,
  "stream_options": {
    "include_usage": true
  }
}'