Loop through items

for user in data['users']: print(user['name'])


Let me know if you'd like help with **writing** JSON files or handling more complex structures!
````

```json
{
  "id": "msg_01Vo4yZSkvQT8zgudnTpsjtt",
  "type": "message",
  "role": "assistant",
  "content": [
    {
      "type": "text",
      "text": "# Reading a JSON File in Python\n\nPython's built-in `json` module makes this straightforward.\n\n## Basic Method\n\n```python\nimport json\n\nwith open('data.json', 'r') as file:\n    data = json.load(file)\n\nprint(data)\n```\n\n- `json.load()` reads from a **file object**\n- The `with` statement automatically closes the file\n\n## Reading from a JSON String\n\nIf you have JSON as a string (not a file), use `json.loads()` (note the \"s\" for \"string\"):\n\n```python\nimport json\n\njson_string = '{\"name\": \"Alice\", \"age\": 30}'\ndata = json.loads(json_string)\n\nprint(data['name'])  # Alice\n```\n\n## Example with Error Handling\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(data)\nexcept FileNotFoundError:\n    print(\"The file was not found.\")\nexcept json.JSONDecodeError:\n    print(\"The file contains invalid JSON.\")\n```\n\n## How JSON Maps to Python\n\n| JSON          | Python   |\n|---------------|----------|\n| object        | `dict`   |\n| array         | `list`   |\n| string        | `str`    |\n| number (int)  | `int`    |\n| number (real) | `float`  |\n| true / false  | `True` / `False` |\n| null          | `None`   |\n\n## Accessing the Data\n\n```python\n# Given: {\"users\": [{\"name\": \"Alice\"}, {\"name\": \"Bob\"}]}\n\nprint(data['users'][0]['name'])  # Alice\n\n# Loop through items\nfor user in data['users']:\n    print(user['name'])\n```\n\nLet me know if you'd like help with **writing** JSON files or handling more complex structures!"
    }
  ],
  "model": "claude-opus-4-8",
  "stop_reason": "end_turn",
  "usage": {
    "input_tokens": 38,
    "output_tokens": 555
  },
  "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-opus-4.8',
  {
    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-opus-4.8",
  "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"
    }
  ]
}'
Here are some great stops along the way, depending on which route you take:

## Coastal Route (Highway 1 / Pacific Coast Highway)
*More scenic but slower—adds a few hours*

- **Santa Cruz** – Beach boardwalk and classic seaside vibes
- **Monterey** – Famous aquarium and Cannery Row
- **Carmel-by-the-Sea** – Charming village with art galleries
- **Big Sur** – Stunning coastline, Bixby Bridge, McWay Falls
- **Hearst Castle** (San Simeon) – Historic mansion tours
- **Pismo Beach** – Sand dunes and laid-back beach town

## Inland Route (I-5)
*Fastest but less scenic*

- **Not many highlights**—mostly farmland, but quick gas/food stops
- Good if you're short on time

## Middle Route (Highway 101)
*A nice balance of speed and scenery*

- **Gilroy** – Garlic capital, outlet shopping
- **Paso Robles** – Wine country with great tasting rooms
- **San Luis Obispo** – Cute college town, historic mission
- **Santa Barbara** – Beautiful "American Riviera," beaches and Spanish architecture
- **Solvang** – Quaint Danish-style village

## A Few Questions to Narrow It Down:
1. How much time do you have for the trip?
2. Are you more interested in nature, food/wine, or towns and attractions?
3. Are you doing it one-way or round-trip?

Let me know and I can help build a more detailed itinerary!
{
  "id": "msg_01La2dbCTcjvDFxNBTcwH4B9",
  "type": "message",
  "role": "assistant",
  "content": [
    {
      "type": "text",
      "text": "Here are some great stops along the way, depending on which route you take:\n\n## Coastal Route (Highway 1 / Pacific Coast Highway)\n*More scenic but slower—adds a few hours*\n\n- **Santa Cruz** – Beach boardwalk and classic seaside vibes\n- **Monterey** – Famous aquarium and Cannery Row\n- **Carmel-by-the-Sea** – Charming village with art galleries\n- **Big Sur** – Stunning coastline, Bixby Bridge, McWay Falls\n- **Hearst Castle** (San Simeon) – Historic mansion tours\n- **Pismo Beach** – Sand dunes and laid-back beach town\n\n## Inland Route (I-5)\n*Fastest but less scenic*\n\n- **Not many highlights**—mostly farmland, but quick gas/food stops\n- Good if you're short on time\n\n## Middle Route (Highway 101)\n*A nice balance of speed and scenery*\n\n- **Gilroy** – Garlic capital, outlet shopping\n- **Paso Robles** – Wine country with great tasting rooms\n- **San Luis Obispo** – Cute college town, historic mission\n- **Santa Barbara** – Beautiful \"American Riviera,\" beaches and Spanish architecture\n- **Solvang** – Quaint Danish-style village\n\n## A Few Questions to Narrow It Down:\n1. How much time do you have for the trip?\n2. Are you more interested in nature, food/wine, or towns and attractions?\n3. Are you doing it one-way or round-trip?\n\nLet me know and I can help build a more detailed itinerary!"
    }
  ],
  "model": "claude-opus-4-8",
  "stop_reason": "end_turn",
  "usage": {
    "input_tokens": 103,
    "output_tokens": 537
  },
  "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 -- the recommended replacement for the deprecated temperature parameter.</summary>

const response = await env.AI.run(
  'anthropic/claude-opus-4.8',
  {
    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-opus-4.8",
  "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"
  }
}'
Detective Mara Voss had seen a thousand crime scenes, but never one this tidy.

The apartment was immaculate—books aligned by height, not a dish in the sink, the dead man arranged on his sofa as if posing for a portrait. No signs of struggle. No forced entry. Just Walter Crane, sixty-three, eyes closed, hands folded across his chest like a man who'd decided to nap forever.

It was the chess set that stopped her.

She crouched beside the small table, careful not to touch. The board was mid-game, pieces scattered in the chaos of a real match—except for one. A black knight, removed from play, stood at the very center of the board where no square could hold it properly. Balanced on the dividing line between two squares, defying the geometry of the game.

Someone had placed it there. Deliberately. The angle was too perfect, the position too impossible to be an accident.

Mara pulled a pen from her jacket and leaned closer. There, etched into the felt base of the knight in letters so small she had to squint, was a single word.

*Soon.*

She felt the cold travel up her spine before her mind caught up to it.

"Detective?" Officer Reyes called from the doorway. "Coroner's saying natural causes. Heart gave out."

Mara didn't look away from the knight. "No," she said quietly. "Somebody wanted us to think that."

She straightened, scanning the too-perfect room with new eyes.

The game wasn't over. It had just begun.
{
  "id": "msg_01D5U1NAjKU24Fq5Q1bsyG9a",
  "type": "message",
  "role": "assistant",
  "content": [
    {
      "type": "text",
      "text": "Detective Mara Voss had seen a thousand crime scenes, but never one this tidy.\n\nThe apartment was immaculate—books aligned by height, not a dish in the sink, the dead man arranged on his sofa as if posing for a portrait. No signs of struggle. No forced entry. Just Walter Crane, sixty-three, eyes closed, hands folded across his chest like a man who'd decided to nap forever.\n\nIt was the chess set that stopped her.\n\nShe crouched beside the small table, careful not to touch. The board was mid-game, pieces scattered in the chaos of a real match—except for one. A black knight, removed from play, stood at the very center of the board where no square could hold it properly. Balanced on the dividing line between two squares, defying the geometry of the game.\n\nSomeone had placed it there. Deliberately. The angle was too perfect, the position too impossible to be an accident.\n\nMara pulled a pen from her jacket and leaned closer. There, etched into the felt base of the knight in letters so small she had to squint, was a single word.\n\n*Soon.*\n\nShe felt the cold travel up her spine before her mind caught up to it.\n\n\"Detective?\" Officer Reyes called from the doorway. \"Coroner's saying natural causes. Heart gave out.\"\n\nMara didn't look away from the knight. \"No,\" she said quietly. \"Somebody wanted us to think that.\"\n\nShe straightened, scanning the too-perfect room with new eyes.\n\nThe game wasn't over. It had just begun."
    }
  ],
  "model": "claude-opus-4-8",
  "stop_reason": "end_turn",
  "usage": {
    "input_tokens": 26,
    "output_tokens": 483
  },
  "stop_sequence": null,
  "stop_details": null,
  "gatewayMetadata": {
    "keySource": "Unified"
  }
}

</details>

<details>

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

const response = await env.AI.run(
  'anthropic/claude-opus-4.8',
  {
    max_tokens: 1024,
    messages: [{ content: 'Explain the concept of recursion with a simple example.', role: 'user' }],
    stream: true,
  },
)
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-opus-4.8",
  "max_tokens": 1024,
  "messages": [
    {
      "content": "Explain the concept of recursion with a simple example.",
      "role": "user"
    }
  ],
  "stream": true
}'

````

Understanding Recursion

Recursion is a programming technique where a function solves a problem by calling itself on a smaller version of the same problem.

The Two Essential Parts

Every recursive function needs:

  1. Base case — the condition that stops the recursion (prevents infinite loops)
  2. Recursive case — where the function calls itself with a simpler input

Simple Example: Factorial

The factorial of a number (written as n!) is the product of all numbers from 1 to n.

5! = 5 × 4 × 3 × 2 × 1 = 120

Notice that 5! = 5 × 4!, which means we can define factorial in terms of itself.

Code Example (Python)

def factorial(n):
    # Base case: stop when we reach 1
    if n == 1:
        return 1
    # Recursive case: n × factorial of (n-1)
    else:
        return n * factorial(n - 1)

print(factorial(5))  # Output: 120

How It Works (Step by Step)

When you call factorial(5), it unfolds like this:

factorial(5) = 5 × factorial(4)
             = 5 × (4 × factorial(3))
             = 5 × (4 × (3 × factorial(2)))
             = 5 × (4 × (3 × (2 × factorial(1))))
             = 5 × (4 × (3 × (2 × 1)))      ← base case reached!
             = 120

The function keeps calling itself until it hits the base case (n == 1), then the results "bubble back up."


A Helpful Analogy 🪆

Think of Russian nesting dolls: - To open the biggest doll, you open the next smaller one, and so on. - Eventually you reach the smallest doll that can't be opened (the base case). - Then you put them all back together.


Key Takeaway

A recursive function breaks a big problem into smaller, identical sub-problems until it reaches a case simple enough to solve directly.

⚠️ Warning: Always include a base case! Without it, the function calls itself forever and crashes (a "stack overflow" error).