}

print(data["name"]) # Alice print(data["age"]) # 30 print(data["hobbies"][0]) # reading


## Handling Errors

```python
import json

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

Type Conversions

JSON Python
object dict
array list
string str
number int / float
true / false True / False
null None

That's all you need for most use cases. For very large files, consider streaming libraries like ijson. ````

{
  "id": "msg_013oB35i6D6cJW17UoavzSEs",
  "type": "message",
  "role": "assistant",
  "content": [
    {
      "type": "thinking",
      "thinking": "",
      "signature": "CAIS9wEKYggOGAIqQFeZ1YZ5RyQ9EbHCqt5fSx9vMAMrhvdbZ+CLKMjT6OXEkD0ktq1p+6St3xTcEVpxkyLpemCD799ZbfCwYd+hJ8wyDmNsYXVkZS1mYWJsZS01OAFCCHRoaW5raW5nEgzx2jYo+ujge2+SskIaDHjgiplZQMyTmf+LNyIwXid3ttbHyXFgieCEovuD3vs0EsVznHmbkYlIY9NyF+a/dx04UlNIrelymYxnEZX7KkPe1UpvY5zXlRmwx3hSBIEFA9FHalSXG7jipEwzoJeyxon8+/rF/zkHacZuq8melq/TmwNzVE4jNU6rDEuvJO0C4l9dGAE="
    },
    {
      "type": "text",
      "text": "# Reading a JSON File in Python\n\nUse the built-in `json` module with the `json.load()` function:\n\n```python\nimport json\n\nwith open(\"data.json\", \"r\", encoding=\"utf-8\") as file:\n    data = json.load(file)\n\nprint(data)\n```\n\n## Key Points\n\n- **`json.load(file)`** — reads JSON from a *file object*\n- **`json.loads(string)`** — parses JSON from a *string* (note the \"s\")\n- The `with` statement automatically closes the file when done\n\n## Accessing the Data\n\nJSON objects become Python dictionaries, and JSON arrays become lists:\n\n```python\n# Given data.json:\n# {\n#   \"name\": \"Alice\",\n#   \"age\": 30,\n#   \"hobbies\": [\"reading\", \"coding\"]\n# }\n\nprint(data[\"name\"])        # Alice\nprint(data[\"age\"])         # 30\nprint(data[\"hobbies\"][0])  # reading\n```\n\n## Handling Errors\n\n```python\nimport json\n\ntry:\n    with open(\"data.json\", \"r\", encoding=\"utf-8\") as file:\n        data = json.load(file)\nexcept FileNotFoundError:\n    print(\"File not found.\")\nexcept json.JSONDecodeError as e:\n    print(f\"Invalid JSON: {e}\")\n```\n\n## Type Conversions\n\n| JSON | Python |\n|------|--------|\n| object | `dict` |\n| array | `list` |\n| string | `str` |\n| number | `int` / `float` |\n| `true` / `false` | `True` / `False` |\n| `null` | `None` |\n\nThat's all you need for most use cases. For very large files, consider streaming libraries like `ijson`."
    }
  ],
  "model": "claude-fable-5",
  "stop_reason": "end_turn",
  "usage": {
    "input_tokens": 38,
    "output_tokens": 537
  },
  "stop_sequence": null,
  "stop_details": null,
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}

</details>

<details>

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

const response = await env.AI.run(
  'anthropic/claude-fable-5',
  {
    max_tokens: 1024,
    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/messages \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "anthropic/claude-fable-5",
  "max_tokens": 1024,
  "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! Your stops depend a lot on which route you take, so let me break it down:

## Highway 1 / Pacific Coast Highway (Scenic Route)
This adds significant time (10+ hours of driving) but is one of the most beautiful drives in the world:

- **Half Moon Bay** – Charming coastal town, great for breakfast
- **Santa Cruz** – Beach boardwalk and surf culture
- **Monterey & Carmel** – World-class aquarium, scenic 17-Mile Drive
- **Big Sur** – Stunning cliffs, Bixby Bridge, McWay Falls, redwood hikes
- **San Simeon** – Hearst Castle and elephant seal viewing at Piedras Blancas
- **Morro Bay** – Iconic Morro Rock
- **Pismo Beach** – Classic beach town vibes
- **Santa Barbara** – Beautiful Spanish architecture, wine country nearby
- **Malibu** – Beaches and a great way to roll into LA

## Highway 101 (Balanced Option, ~7-8 hours)
- **San Jose** – Winchester Mystery House
- **Gilroy** – Garlic capital (and outlet shopping)
- **Paso Robles** – Excellent wine region
- **San Luis Obispo** – Cute college town, Bubblegum Alley
- **Solvang** – Quirky Danish village with bakeries and windmills
- **Santa Barbara** – Same as above

## I-5 (Fastest, ~5-6 hours)
Honestly, not much to see—mostly farmland. Best stop is **Harris Ranch** in Coalinga for a famous steak lunch.

**My suggestion:** If you have 2+ days, take Highway 1 and stay overnight in Monterey, Big Sur, or San Luis Obispo. If you only have one day, 101 gives you a nice mix of speed and scenery.

How much time do you have for the trip? That'll help narrow down the best plan!
{
  "id": "msg_01JoMwDGJCvYbHtRYpMaaVCp",
  "type": "message",
  "role": "assistant",
  "content": [
    {
      "type": "thinking",
      "thinking": "",
      "signature": "CAISnQIKYggOGAIqQK/zBQqMA66bUkZi524Lt0j+w8Eutw4fEZezWpC3T8DkRpnoqnfcGJL1WYXiD+kMGT1/gHSAjBTaezw2E8x5XM8yDmNsYXVkZS1mYWJsZS01OAFCCHRoaW5raW5nEgzQCE8UtUZmIwbubiUaDJd3PUdinhPnsMTDyCIwM6zPNTJBliPRjAxg0rXfsMOgkpBJ2f4PsQF8Qx1/OOnBTzzeThC3LqMxwIvRLQNpKmnrVhJc59urfrUjH5w+2LZJMmRg0KiCqdpSRx65zmj0us3grXlxJ5+5KQkaZMILR038gQ1uVGAQ6IhEzj2LaC5fGMRuo9onFlGkksp3s+gb1jaNoo7hEgxzzD+1GPmhtahCBIrXsJUBctAYAQ=="
    },
    {
      "type": "text",
      "text": "Great question! Your stops depend a lot on which route you take, so let me break it down:\n\n## Highway 1 / Pacific Coast Highway (Scenic Route)\nThis adds significant time (10+ hours of driving) but is one of the most beautiful drives in the world:\n\n- **Half Moon Bay** – Charming coastal town, great for breakfast\n- **Santa Cruz** – Beach boardwalk and surf culture\n- **Monterey & Carmel** – World-class aquarium, scenic 17-Mile Drive\n- **Big Sur** – Stunning cliffs, Bixby Bridge, McWay Falls, redwood hikes\n- **San Simeon** – Hearst Castle and elephant seal viewing at Piedras Blancas\n- **Morro Bay** – Iconic Morro Rock\n- **Pismo Beach** – Classic beach town vibes\n- **Santa Barbara** – Beautiful Spanish architecture, wine country nearby\n- **Malibu** – Beaches and a great way to roll into LA\n\n## Highway 101 (Balanced Option, ~7-8 hours)\n- **San Jose** – Winchester Mystery House\n- **Gilroy** – Garlic capital (and outlet shopping)\n- **Paso Robles** – Excellent wine region\n- **San Luis Obispo** – Cute college town, Bubblegum Alley\n- **Solvang** – Quirky Danish village with bakeries and windmills\n- **Santa Barbara** – Same as above\n\n## I-5 (Fastest, ~5-6 hours)\nHonestly, not much to see—mostly farmland. Best stop is **Harris Ranch** in Coalinga for a famous steak lunch.\n\n**My suggestion:** If you have 2+ days, take Highway 1 and stay overnight in Monterey, Big Sur, or San Luis Obispo. If you only have one day, 101 gives you a nice mix of speed and scenery.\n\nHow much time do you have for the trip? That'll help narrow down the best plan!"
    }
  ],
  "model": "claude-fable-5",
  "stop_reason": "end_turn",
  "usage": {
    "input_tokens": 103,
    "output_tokens": 706
  },
  "stop_sequence": null,
  "stop_details": null,
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}

</details>

<details>

<summary>Creative Writing with Adaptive Thinking — Use adaptive thinking with high effort to steer creative output. Adaptive thinking is always on for Claude Fable 5; use the effort parameter to control depth.</summary>

const response = await env.AI.run(
  'anthropic/claude-fable-5',
  {
    max_tokens: 2048,
    messages: [
      {
        content: 'Write a short story opening about a detective finding an unusual clue.',
        role: 'user',
      },
    ],
    output_config: { effort: 'high' },
    thinking: { type: 'adaptive' },
  },
)
console.log(response)
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/messages \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "anthropic/claude-fable-5",
  "max_tokens": 2048,
  "messages": [
    {
      "content": "Write a short story opening about a detective finding an unusual clue.",
      "role": "user"
    }
  ],
  "output_config": {
    "effort": "high"
  },
  "thinking": {
    "type": "adaptive"
  }
}'

```

The Paper Bird

Detective Mara Voss had worked homicide for eleven years, and in that time she'd catalogued every variety of crime scene debris: shell casings, cigarette butts, the sad confetti of torn receipts. But she had never found an origami crane perched in a dead man's open palm.