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! ````

{
  "choices": [
    {
      "finish_reason": "stop",
      "index": 0,
      "message": {
        "annotations": [],
        "content": "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.\n\n────────────────────────\n1. Quick start (basic usage)\n────────────────────────\n```python\nimport json\n\nwith open(\"data.json\", \"r\", encoding=\"utf-8\") as f:\n    data = json.load(f)      # `data` is now a Python dict or list\n```\n• json.load() converts the JSON in the file to native Python objects (dict, list, int, float, str, bool, None).  \n• encoding=\"utf-8\" is often optional but safest—especially on Windows.\n\n────────────────────────────────────────────────\n2. Using pathlib (cleaner path handling, cross-platform)\n───────────────────────────────────────────────────────\n```python\nfrom pathlib import Path\nimport json\n\njson_path = Path(\"path\") / \"to\" / \"data.json\"\n\nwith json_path.open(encoding=\"utf-8\") as f:\n    data = json.load(f)\n```\n\n──────────────────────────────────────────────\n3. Adding error handling / validation\n──────────────────────────────────────────────\n```python\nimport json\nfrom pathlib import Path\n\ndef read_json(path):\n    try:\n        with Path(path).open(encoding=\"utf-8\") as f:\n            return json.load(f)\n    except FileNotFoundError:\n        print(f\"File not found: {path}\")\n    except json.JSONDecodeError as exc:\n        print(f\"Invalid JSON in {path}: {exc}\")\n    return None\n\ndata = read_json(\"data.json\")\n```\n\n──────────────────────────────────────────────────────\n4. Loading a JSON lines (NDJSON) file (one JSON per line)\n──────────────────────────────────────────────────────\n```python\nimport json\n\nrecords = []\nwith open(\"data.ndjson\", encoding=\"utf-8\") as f:\n    for line in f:\n        records.append(json.loads(line))\n```\n\n──────────────────────────────────────\n5. Directly into a pandas DataFrame\n──────────────────────────────────────\nIf your JSON is an array of objects (list of dicts) or NDJSON:\n```python\nimport pandas as pd\n\ndf = pd.read_json(\"data.json\")          # Works for many cases\n# For NDJSON:\ndf = pd.read_json(\"data.ndjson\", lines=True)\n```\n\n────────────────────────\n6. Writing JSON back out\n────────────────────────\n```python\nwith open(\"output.json\", \"w\", encoding=\"utf-8\") as f:\n    json.dump(data, f, indent=2, ensure_ascii=False)\n```\n• indent adds pretty-printing.  \n• ensure_ascii=False keeps non-ASCII characters intact.\n\nThat’s all you need to read (and write) JSON in Python!",
        "refusal": null,
        "role": "assistant"
      }
    }
  ],
  "created": 1777319516,
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "id": "chatcmpl-DZMHkoogfY6tsXPCpST3p05XLwgi6",
  "model": "o3-2025-04-16",
  "object": "chat.completion",
  "service_tier": "default",
  "system_fingerprint": null,
  "usage": {
    "completion_tokens": 599,
    "completion_tokens_details": {
      "accepted_prediction_tokens": 0,
      "audio_tokens": 0,
      "reasoning_tokens": 0,
      "rejected_prediction_tokens": 0
    },
    "prompt_tokens": 30,
    "prompt_tokens_details": {
      "audio_tokens": 0,
      "cached_tokens": 0
    },
    "total_tokens": 629
  }
}

</details>

<details>

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

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)
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/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"
    }
  ]
}'
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!