Access values like a normal dictionary
print(config['name']) print(config['settings']['theme'])
### Reading a JSON String (not a file)
```python
import json
json_string = '{"name": "Alice", "age": 30}'
data = json.loads(json_string) # Note: loads() with an 's'
print(data['name']) # Output: Alice
Handling Errors
import json
try:
with open('data.json', 'r') as file:
data = json.load(file)
except FileNotFoundError:
print("File not found!")
except json.JSONDecodeError:
print("Invalid JSON format!")
Specifying Encoding
import json
with open('data.json', 'r', encoding='utf-8') as file:
data = json.load(file)
Key Differences
| Method | Input | Use Case |
|---|---|---|
json.load(file) |
File object | Reading from a .json file |
json.loads(string) |
String | Parsing a JSON-formatted string |
JSON → Python Type Mapping
| JSON Type | Python Type |
|---|---|
object |
dict |
array |
list |
string |
str |
number |
int/float |
true/false |
True/False |
null |
None |
Tip: Always use the
withstatement when opening files — it ensures the file is properly closed, even if an error occurs.
```json
{
"content": [
{
"text": "# Reading a JSON File in Python\n\nPython has a built-in `json` module that makes it easy to read JSON files. Here are the most common approaches:\n\n## Basic Example\n\n```python\nimport json\n\n# Open and read the JSON file\nwith open('data.json', 'r') as file:\n data = json.load(file)\n\nprint(data)\n```\n\n## Step-by-Step Breakdown\n\n| Step | Code | Description |\n|------|------|-------------|\n| 1 | `import json` | Import the built-in JSON module |\n| 2 | `open('data.json', 'r')` | Open the file in **read** mode |\n| 3 | `json.load(file)` | Parse the JSON into a Python object |\n\n## Common Scenarios\n\n### Reading into a Dictionary\n```python\nimport json\n\nwith open('config.json', 'r') as file:\n config = json.load(file)\n\n# Access values like a normal dictionary\nprint(config['name'])\nprint(config['settings']['theme'])\n```\n\n### Reading a JSON String (not a file)\n```python\nimport json\n\njson_string = '{\"name\": \"Alice\", \"age\": 30}'\ndata = json.loads(json_string) # Note: loads() with an 's'\n\nprint(data['name']) # Output: Alice\n```\n\n### Handling Errors\n```python\nimport json\n\ntry:\n with open('data.json', 'r') as file:\n data = json.load(file)\nexcept FileNotFoundError:\n print(\"File not found!\")\nexcept json.JSONDecodeError:\n print(\"Invalid JSON format!\")\n```\n\n### Specifying Encoding\n```python\nimport json\n\nwith open('data.json', 'r', encoding='utf-8') as file:\n data = json.load(file)\n```\n\n## Key Differences\n\n| Method | Input | Use Case |\n|--------|-------|----------|\n| `json.load(file)` | **File object** | Reading from a `.json` file |\n| `json.loads(string)` | **String** | Parsing a JSON-formatted string |\n\n## JSON → Python Type Mapping\n\n| JSON Type | Python Type |\n|-----------|-------------|\n| `object` | `dict` |\n| `array` | `list` |\n| `string` | `str` |\n| `number` | `int`/`float` |\n| `true/false` | `True`/`False` |\n| `null` | `None` |\n\n> **Tip:** Always use the `with` statement when opening files — it ensures the file is properly closed, even if an error occurs.",
"type": "text"
}
],
"gatewayMetadata": {
"keySource": "BYOK"
},
"id": "msg_01XBD4XMEahrUEnEVbu4gPwV",
"model": "claude-opus-4-6",
"role": "assistant",
"stop_details": null,
"stop_reason": "end_turn",
"stop_sequence": null,
"type": "message",
"usage": {
"input_tokens": 29,
"output_tokens": 643
}
}
```
</details>
<details>
<summary>**Multi-turn Conversation** — Continuing a conversation with context</summary>
```ts
const response = await env.AI.run(
'anthropic/claude-opus-4.6',
{
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)
```
```bash
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.6",
"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 Stops Between SF & LA
Here are some popular options depending on your route:
## Coastal Route (Highway 1) 🌊
This is the scenic route (~8-10 hours with stops):
- **Half Moon Bay** – Beautiful coastal town, great seafood
- **Santa Cruz** – Boardwalk, surfing, laid-back vibe
- **Monterey/Carmel** – Monterey Bay Aquarium, 17-Mile Drive
- **Big Sur** – Stunning cliffs, Bixby Bridge, McWay Falls
- **San Simeon** – Hearst Castle, elephant seal colony
- **San Luis Obispo** – Charming college town, great food
- **Santa Barbara** – "American Riviera," wine country, beaches
- **Solvang** – Danish-style village with bakeries & windmills
## Inland Route (I-5) 🚗
This is the fastest route (~5-6 hours):
- **Harris Ranch** – Popular rest stop with a restaurant
- **Bakersfield** – Buck Owens' Crystal Palace (country music)
- Not as scenic, but efficient!
## Tips:
- ⛽ Fill up before Big Sur (limited gas stations)
- 📸 Start early for the best light on Highway 1
- 🏨 Consider an overnight stop if taking the coastal route
**Which route interests you more – scenic or fast?**
```
```json
{
"content": [
{
"text": "# Great Stops Between SF & LA\n\nHere are some popular options depending on your route:\n\n## Coastal Route (Highway 1) 🌊\nThis is the scenic route (~8-10 hours with stops):\n- **Half Moon Bay** – Beautiful coastal town, great seafood\n- **Santa Cruz** – Boardwalk, surfing, laid-back vibe\n- **Monterey/Carmel** – Monterey Bay Aquarium, 17-Mile Drive\n- **Big Sur** – Stunning cliffs, Bixby Bridge, McWay Falls\n- **San Simeon** – Hearst Castle, elephant seal colony\n- **San Luis Obispo** – Charming college town, great food\n- **Santa Barbara** – \"American Riviera,\" wine country, beaches\n- **Solvang** – Danish-style village with bakeries & windmills\n\n## Inland Route (I-5) 🚗\nThis is the fastest route (~5-6 hours):\n- **Harris Ranch** – Popular rest stop with a restaurant\n- **Bakersfield** – Buck Owens' Crystal Palace (country music)\n- Not as scenic, but efficient!\n\n## Tips:\n- ⛽ Fill up before Big Sur (limited gas stations)\n- 📸 Start early for the best light on Highway 1\n- 🏨 Consider an overnight stop if taking the coastal route\n\n**Which route interests you more – scenic or fast?**",
"type": "text"
}
],
"gatewayMetadata": {
"keySource": "BYOK"
},
"id": "msg_019VVbDba57acjUFWYzMdWQV",
"model": "claude-opus-4-6",
"role": "assistant",
"stop_details": null,
"stop_reason": "end_turn",
"stop_sequence": null,
"type": "message",
"usage": {
"input_tokens": 76,
"output_tokens": 340
}
}
```
</details>
<details>
<summary>**Creative Writing** — Higher temperature for creative output</summary>
```ts
const response = await env.AI.run(
'anthropic/claude-opus-4.6',
{
max_tokens: 512,
messages: [
{
content: 'Write a short story opening about a detective finding an unusual clue.',
role: 'user',
},
],
temperature: 0.8,
},
)
console.log(response)
```
```bash
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.6",
"max_tokens": 512,
"messages": [
{
"content": "Write a short story opening about a detective finding an unusual clue.",
"role": "user"
}
],
"temperature": 0.8
}'
```
```
# The Orchid on the Windowsill
Detective Mara Solis had seen her share of crime scenes—enough to know when something didn't belong.
The apartment was almost aggressively ordinary. Beige carpet, IKEA furniture, a stack of unopened mail on the kitchen counter. The victim, Gerald Pryce, age fifty-two, accountant, had lived the kind of life that left barely a thumbprint on the world. Even in death, slumped against his recliner with a single stab wound beneath the ribs, he seemed to be trying not to make a fuss.
But there, on the windowsill above the kitchen sink, sat a black orchid.
Not dark purple. Not deep burgundy masquerading as black under bad lighting. Mara leaned closer, pulling on a fresh glove, and tilted the pot toward the gray morning light filtering through the blinds. The petals were the pure, liquid black of a moonless lake—a color that shouldn't exist in nature.
And as far as the department's botanist would confirm six hours later, it didn't.
"No soil," Mara murmured, peering into the ceramic pot. The orchid's roots wrapped around nothing but a small, folded piece of vellum paper, yellowed at the edges. She extracted it with tweezers and opened it carefully.
A single line, handwritten in red ink:
*He was not the first, and you already know me.*
Mara set the note down. Her hands were steady. Her pulse was not.
She read it again—not because she needed to, but because some part of her recognized the handwriting.
```
```json
{
"content": [
{
"text": "# The Orchid on the Windowsill\n\nDetective Mara Solis had seen her share of crime scenes—enough to know when something didn't belong.\n\nThe apartment was almost aggressively ordinary. Beige carpet, IKEA furniture, a stack of unopened mail on the kitchen counter. The victim, Gerald Pryce, age fifty-two, accountant, had lived the kind of life that left barely a thumbprint on the world. Even in death, slumped against his recliner with a single stab wound beneath the ribs, he seemed to be trying not to make a fuss.\n\nBut there, on the windowsill above the kitchen sink, sat a black orchid.\n\nNot dark purple. Not deep burgundy masquerading as black under bad lighting. Mara leaned closer, pulling on a fresh glove, and tilted the pot toward the gray morning light filtering through the blinds. The petals were the pure, liquid black of a moonless lake—a color that shouldn't exist in nature.\n\nAnd as far as the department's botanist would confirm six hours later, it didn't.\n\n\"No soil,\" Mara murmured, peering into the ceramic pot. The orchid's roots wrapped around nothing but a small, folded piece of vellum paper, yellowed at the edges. She extracted it with tweezers and opened it carefully.\n\nA single line, handwritten in red ink:\n\n*He was not the first, and you already know me.*\n\nMara set the note down. Her hands were steady. Her pulse was not.\n\nShe read it again—not because she needed to, but because some part of her recognized the handwriting.",
"type": "text"
}
],
"gatewayMetadata": {
"keySource": "BYOK"
},
"id": "msg_01Q6DJ95CWj3L7QbCZ7onQHq",
"model": "claude-opus-4-6",
"role": "assistant",
"stop_details": null,
"stop_reason": "end_turn",
"stop_sequence": null,
"type": "message",
"usage": {
"input_tokens": 21,
"output_tokens": 374
}
}
```
</details>
<details>
<summary>**Streaming Response** — Enable streaming for real-time output</summary>
```ts
const response = await env.AI.run(
'anthropic/claude-opus-4.6',
{
max_tokens: 1024,
messages: [{ content: 'Explain the concept of recursion with a simple example.', role: 'user' }],
stream: true,
},
)
console.log(response)
```
```bash
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.6",
"max_tokens": 1024,
"messages": [
{
"content": "Explain the concept of recursion with a simple example.",
"role": "user"
}
],
"stream": true
}'
```
Understanding Recursion
The Concept
Recursion is a programming technique where a function calls itself to solve a problem by breaking it down into smaller, simpler sub-problems. Every recursive function needs:
- Base Case – A condition that stops the recursion (prevents infinite loops).
- Recursive Case – The function calling itself with a smaller or simpler input.
Think of it like Russian nesting dolls 🪆 — you keep opening a smaller doll until you reach the tiniest one (the base case).
Simple Example: Factorial
The factorial of n (written n!) is:
5! = 5 × 4 × 3 × 2 × 1 = 120
def factorial(n):
# Base case: stop when n is 0 or 1
if n <= 1:
return 1
# Recursive case: n * factorial of (n-1)
return n * factorial(n - 1)
print(factorial(5)) # Output: 120
How It Works (Call Stack)
factorial(5)
│
├─ 5 * factorial(4)
│ ├─ 4 * factorial(3)
│ │ ├─ 3 * factorial(2)
│ │ │ ├─ 2 * factorial(1)
│ │ │ │ └─ returns 1 ← Base case hit!
│ │ │ └─ returns 2 × 1 = 2
│ │ └─ returns 3 × 2 = 6
│ └─ returns 4 × 6 = 24
└─ returns 5 × 24 = 120 ✅
