Now you can use 'data' like a normal Python dictionary

print(data)


### Breakdown of the code:
1. **`import json`**: Imports Python's built-in JSON library.
2. **`with open(...) as file:`**: This is the best practice for opening files. The `with` statement ensures that the file is automatically closed as soon as the block of code finishes, even if an error occurs.
3. **`encoding='utf-8'`**: It is highly recommended to specify the encoding, especially if your JSON file contains special characters or emojis.
4. **`json.load(file)`**: This function reads the file and converts the JSON data into the corresponding Python object (usually a dictionary or a list).

---

### Best Practice: Adding Error Handling
If there is a chance the file might not exist or the JSON is formatted incorrectly, it's a good idea to use a `try-except` block:

```python
import json

try:
    with open('data.json', 'r', encoding='utf-8') as file:
        data = json.load(file)
        print("File loaded successfully!")

except FileNotFoundError:
    print("Error: The file was not found.")
except json.JSONDecodeError:
    print("Error: The file does not contain valid JSON.")

Bonus Tip: json.load() vs json.loads()

  • Use json.load() (no 's') when reading directly from a file.
  • Use json.loads() (with an 's' for string) if you already have JSON data saved as a Python string variable. ````
{
  "candidates": [
    {
      "content": {
        "role": "model",
        "parts": [
          {
            "text": "To read a JSON file in Python, you can use the built-in **`json`** module. \n\nHere is the most standard and recommended way to do it:\n\n```python\nimport json\n\n# Open the file in read mode\nwith open('data.json', 'r', encoding='utf-8') as file:\n    # Load the JSON data into a Python dictionary\n    data = json.load(file)\n\n# Now you can use 'data' like a normal Python dictionary\nprint(data)\n```\n\n### Breakdown of the code:\n1. **`import json`**: Imports Python's built-in JSON library.\n2. **`with open(...) as file:`**: This is the best practice for opening files. The `with` statement ensures that the file is automatically closed as soon as the block of code finishes, even if an error occurs.\n3. **`encoding='utf-8'`**: It is highly recommended to specify the encoding, especially if your JSON file contains special characters or emojis.\n4. **`json.load(file)`**: This function reads the file and converts the JSON data into the corresponding Python object (usually a dictionary or a list).\n\n---\n\n### Best Practice: Adding Error Handling\nIf there is a chance the file might not exist or the JSON is formatted incorrectly, it's a good idea to use a `try-except` block:\n\n```python\nimport json\n\ntry:\n    with open('data.json', 'r', encoding='utf-8') as file:\n        data = json.load(file)\n        print(\"File loaded successfully!\")\n        \nexcept FileNotFoundError:\n    print(\"Error: The file was not found.\")\nexcept json.JSONDecodeError:\n    print(\"Error: The file does not contain valid JSON.\")\n```\n\n### Bonus Tip: `json.load()` vs `json.loads()`\n* Use **`json.load()`** (no 's') when reading directly from a **file**.\n* Use **`json.loads()`** (with an 's' for string) if you already have JSON data saved as a Python **string** variable.",
            "thoughtSignature": "AY89a1/WVQVfP8X81xtbe/Y3eP4vwcFwMmemlaAcD6N/8fTRHsROrZr1DG00bINwygCw86NfVtlJCMVVj2WSJgOjnpj5HOLNxpzdsZXEQnAMyZ5R46j2XVXo5k9Ak/qlbbR4gT5YjEMTge1zojUzgH0vlOr4tqfGP5DgFgalGKt4Oy1Xf+7nnsQUwEFqpPpGNpCXCB1piwk/QpeQkywhmrLvtRvKbmpqyND8NiQOok38MchvygH4Yhq66zy+LUHV1awSmVeydrRBpWckgI9n3BmFZC8woyqHYyXqqj8X8sFzz7QA1Ohp5dbvOUKb9Jv02CgWXxjrkCYXYaDIgGf9b2UwFYzb56L7bwGj9qHnUuIaUIM4SvnW970wNgNHTDjVO9y1or8PCY/3L9MI5RPKZyTx18/UhxQkhDBUfMk72RHhlgQRZcw2zOyaX8AQfthY+qB4PKs61MTvNt2N+PuEArTaHSn8f00hGniQ0S+yRFD0zAb1iOhrsOAG38jCnH2TzeVc8+TN0Gx6paG7FEMC9iUVLucMPS5GHgi68r9n0bCY+dawK8o3x6fkvrl/97mNhOey015/w2RUGz1S45Ga3cTFh8/YoVrDVrn1KIRTWqLRBtv5re8x0Q/rfMEgYLasoyRnR45gINNKz6XpD5iYv9NxksoL7HTXJzSwsiKyEMKx/x4cntCsY2eAuiiXTnFWl28O/0TFOJyNjSdif9XTpaTP9FsQ5EvQ/uEHPQy3h6BiHkE/ektGC0AtuXLEKPLONyBTHln6RILmfsr9fIgJ7BJaarCLE+biY87/ArDpRj7xF/hyIe/wqmAZYQtI2GxssOKdQ9bpje86x3XD0t+KD0RniuLEFknMH6MIF7iaCJT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dVpWE6Q6aBsxbCsy5nTTNlMEMx8QvZQpXlchdCd3jbcH63e6BfHrKs3tMjhpE7987x2jywpZj1ALWI/l8OZNYxsMdqcpxtaTyfSjsWcplSwI4fUs="
          }
        ]
      },
      "finishReason": "STOP"
    }
  ],
  "usageMetadata": {
    "promptTokenCount": 20,
    "candidatesTokenCount": 461,
    "totalTokenCount": 1079,
    "trafficType": "ON_DEMAND",
    "promptTokensDetails": [
      {
        "modality": "TEXT",
        "tokenCount": 20
      }
    ],
    "candidatesTokensDetails": [
      {
        "modality": "TEXT",
        "tokenCount": 461
      }
    ],
    "thoughtsTokenCount": 598
  },
  "modelVersion": "gemini-3.1-pro-preview",
  "createTime": "2026-07-24T21:53:04.959579Z",
  "responseId": "wN5jatvIOs27u-gP-sKs4Ao",
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}

</details>

<details>

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

const response = await env.AI.run(
  'google/gemini-3.1-pro',
  {
    contents: [
      {
        parts: [{ text: 'I need help planning a road trip from San Francisco to Los Angeles.' }],
        role: 'user',
      },
      {
        parts: [
          {
            text: "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: 'model',
      },
      { parts: [{ text: 'Yes, what are some good places to stop?' }], role: 'user' },
    ],
    generationConfig: { maxOutputTokens: 2048 },
  },
)
console.log(response)
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "google/gemini-3.1-pro",
  "input": {
    "contents": [
      {
        "parts": [
          {
            "text": "I need help planning a road trip from San Francisco to Los Angeles."
          }
        ],
        "role": "user"
      },
      {
        "parts": [
          {
            "text": "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": "model"
      },
      {
        "parts": [
          {
            "text": "Yes, what are some good places to stop?"
          }
        ],
        "role": "user"
      }
    ],
    "generationConfig": {
      "maxOutputTokens": 2048
    }
  }
}'

``` The stops you make will depend heavily on which route you decide to take.

If you want to do the drive in 5-6 hours, you'll take Interstate 5 (I-5), which is the fast, inland route. If you have a full day (or even better, two days), you can take the Pacific Coast Highway (Highway 1 / US-101), which is one of the most famous and scenic drives in the world.

Here are the best stops for both options, listed in order from North to South:

🌊 The Scenic Coastal Route (Highway 1 / US-101)

This route takes 9+ hours of pure driving, so it’s best if you have a whole day or plan to stay somewhere overnight.

  • Santa Cruz: A classic California surf town. You can stretch your legs at the famous Santa Cruz Beach Boardwalk or grab a coffee downtown.
  • Monterey & Carmel-by-the-Sea: Monterey is home to the world-renowned Monterey Bay Aquarium and Cannery Row. Right next door is Carmel, a charming, fairytale-like village with boutique shops and a beautiful white-sand beach.
  • Big Sur: This is the most dramatic, cliff-hugging part of the drive. Must-sees include the iconic Bixby Creek Bridge and McWay Falls (an 80-foot waterfall that drops right onto the beach). Note: Always check Caltrans before your trip, as Highway 1 frequently experiences closures due to landslides.
  • San Simeon: Stop here to see Hearst Castle (a magnificent historic mansion on a hill—book tickets in advance!) and the Piedras Blancas Elephant Seal Rookery, where you can see hundreds of massive elephant seals lounging on the beach.
  • San Luis Obispo (SLO): A great halfway point. It has a fantastic, walkable downtown area. If you like quirky stops, check out Bubblegum Alley or grab a slice of cake at the wildly eccentric, pink-themed Madonna Inn.
  • Santa Barbara: Known as the "American Riviera." It features stunning Spanish colonial architecture, great wine tasting, beautiful beaches, and a vibrant downtown street (State Street).

🚗 The Fast Inland Route (I-5)

This route is mostly flat agricultural land. The stops here are less about sightseeing and more about unique places to grab food and stretch your legs.

  • Casa de Fruta (Pacheco Pass): If you take Highway 152 to connect to I-5, this massive roadside fruit stand/theme park is a legendary California pit stop. Great for snacks, dried fruit, and a quick break.
  • Harris Ranch (Coalinga): A massive, famous steakhouse and inn sitting right on I-5. It's a very popular spot to stop for a nice sit-down lunch or dinner.
  • Kettleman City / Bravo Farms: Kettleman City is the classic halfway point. It has a massive In-N-Out Burger, but the real star is Bravo Farms—a quirky, western-themed roadside attraction with a cheese factory, ice cream, a petting zoo, and lots of souvenirs.
  • Tejon Ranch (The Grapevine): Right before you climb the mountains to drop down into Los Angeles, there are the Outlets at Tejon if you want to do a little shopping or need a final coffee/food break.