Access values
print(data['name']) print(data['age'])
**2. Read JSON string manually**
```python
import json
with open('data.json', 'r') as file:
content = file.read() # Read as string
data = json.loads(content) # Parse the string (note the 's')
3. Handle encoding (for special characters)
import json
with open('data.json', 'r', encoding='utf-8') as file:
data = json.load(file)
Error Handling (Recommended)
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")
Key Differences
| Function | Use Case |
|---|---|
json.load(file) |
Read directly from a file object |
json.loads(string) |
Parse a JSON string |
Example JSON file (data.json)
{
"name": "Alice",
"age": 30,
"hobbies": ["reading", "coding"]
}
Output:
data['name'] # → "Alice"
data['age'] # → 30
data['hobbies'] # → ["reading", "coding"]
Tip: Use
with open()to ensure the file is automatically closed after reading.
```json
{
"id": "msg_015vWQKd15N4szFzUuNwum2W",
"type": "message",
"role": "assistant",
"content": [
{
"type": "text",
"text": "## Reading a JSON File in Python\n\n### Basic Method using `json` module\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### Common Approaches\n\n**1. Read as a dictionary/list (most common)**\n```python\nimport json\n\nwith open('data.json', 'r') as file:\n data = json.load(file) # Returns a Python dict or list\n\n# Access values\nprint(data['name'])\nprint(data['age'])\n```\n\n**2. Read JSON string manually**\n```python\nimport json\n\nwith open('data.json', 'r') as file:\n content = file.read() # Read as string\n data = json.loads(content) # Parse the string (note the 's')\n```\n\n**3. Handle encoding (for special characters)**\n```python\nimport json\n\nwith open('data.json', 'r', encoding='utf-8') as file:\n data = json.load(file)\n```\n\n### Error Handling (Recommended)\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### Key Differences\n\n| Function | Use Case |\n|----------|----------|\n| `json.load(file)` | Read directly from a **file object** |\n| `json.loads(string)` | Parse a **JSON string** |\n\n### Example JSON file (`data.json`)\n```json\n{\n \"name\": \"Alice\",\n \"age\": 30,\n \"hobbies\": [\"reading\", \"coding\"]\n}\n```\n\n**Output:**\n```python\ndata['name'] # → \"Alice\"\ndata['age'] # → 30\ndata['hobbies'] # → [\"reading\", \"coding\"]\n```\n\n> **Tip:** Use `with open()` to ensure the file is automatically closed after reading."
}
],
"model": "claude-sonnet-4-6",
"stop_reason": "end_turn",
"usage": {
"input_tokens": 29,
"output_tokens": 508
},
"stop_sequence": null,
"stop_details": null,
"gatewayMetadata": {
"keySource": "Unified"
}
}
```
</details>
<details>
<summary>**Multi-turn Conversation** — Continuing a conversation with context</summary>
```ts
const response = await env.AI.run(
'anthropic/claude-sonnet-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-sonnet-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"
}
]
}'
```
```
Here are some great stops depending on which route you take:
**Pacific Coast Highway (Highway 1) - Scenic Route**
- **Santa Cruz** - Fun boardwalk and beach town
- **Monterey** - Great aquarium and Cannery Row
- **Big Sur** - Stunning coastal views and hiking
- **San Simeon** - Hearst Castle tours
- **Morro Bay** - Charming harbor town
- **Santa Barbara** - Beautiful city with great food and beaches
**Highway 101 - Middle Route**
- **San Jose** - Tech museums and good food
- **Paso Robles** - Wine country and wineries
- **San Luis Obispo** - Charming college town
- **Santa Barbara** - connects with PCH route
**Interstate 5 - Fastest Route**
- This is the most direct but least scenic
- Good if you just want to get there quickly
**Some Tips:**
- The PCH route adds several hours but is worth it for the views
- Big Sur can have road closures, so check conditions ahead of time
- Santa Barbara is a great overnight stop
- Try to drive Big Sur during daylight for the best views
Would you like more details about any specific stop or help planning an overnight itinerary?
```
```json
{
"id": "msg_015gJCs45CLVWFpG9swxLY1h",
"type": "message",
"role": "assistant",
"content": [
{
"type": "text",
"text": "Here are some great stops depending on which route you take:\n\n**Pacific Coast Highway (Highway 1) - Scenic Route**\n- **Santa Cruz** - Fun boardwalk and beach town\n- **Monterey** - Great aquarium and Cannery Row\n- **Big Sur** - Stunning coastal views and hiking\n- **San Simeon** - Hearst Castle tours\n- **Morro Bay** - Charming harbor town\n- **Santa Barbara** - Beautiful city with great food and beaches\n\n**Highway 101 - Middle Route**\n- **San Jose** - Tech museums and good food\n- **Paso Robles** - Wine country and wineries\n- **San Luis Obispo** - Charming college town\n- **Santa Barbara** - connects with PCH route\n\n**Interstate 5 - Fastest Route**\n- This is the most direct but least scenic\n- Good if you just want to get there quickly\n\n**Some Tips:**\n- The PCH route adds several hours but is worth it for the views\n- Big Sur can have road closures, so check conditions ahead of time\n- Santa Barbara is a great overnight stop\n- Try to drive Big Sur during daylight for the best views\n\nWould you like more details about any specific stop or help planning an overnight itinerary?"
}
],
"model": "claude-sonnet-4-6",
"stop_reason": "end_turn",
"usage": {
"input_tokens": 76,
"output_tokens": 290
},
"stop_sequence": null,
"stop_details": null,
"gatewayMetadata": {
"keySource": "Unified"
}
}
```
</details>
<details>
<summary>**Creative Writing** — Higher temperature for creative output</summary>
```ts
const response = await env.AI.run(
'anthropic/claude-sonnet-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-sonnet-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 Weight of Paper
Detective Mara Osei had seen plenty of strange things in fourteen years on the job. She had once found a murder weapon wrapped in a birthday cake. She had once interviewed a parrot that knew the killer's name.
But this was different.
The victim's apartment was ordinary enough — takeout containers, a dying fern, furniture that looked purchased in a single defeated afternoon at a discount store. Nothing about Leonard Voss suggested a man with enemies. Nothing suggested a man with much of anything.
Except the paper.
Mara crouched beside the coffee table and studied it without touching it. A single sheet, handwritten, covered edge to edge in the same two words repeated hundreds of times in shrinking letters, spiraling inward like a drain.
*I remember. I remember. I remember.*
The handwriting started bold and confident at the outer edge. By the center, the letters were barely visible, scratched by what must have been a nearly dead pen — or a nearly dead hand.
The medical examiner appeared in the doorway. "No signs of struggle. No forced entry." He paused. "Honestly, Mara, it looks like he just *stopped*."
She stood up slowly, slipping her hands into her pockets.
"Then what," she said quietly, "was he trying so hard not to forget?"
---
*The fern, she noticed, had been recently watered.*
```
```json
{
"id": "msg_01BfiLNfgBobjw33wuZDP9as",
"type": "message",
"role": "assistant",
"content": [
{
"type": "text",
"text": "# The Weight of Paper\n\nDetective Mara Osei had seen plenty of strange things in fourteen years on the job. She had once found a murder weapon wrapped in a birthday cake. She had once interviewed a parrot that knew the killer's name.\n\nBut this was different.\n\nThe victim's apartment was ordinary enough — takeout containers, a dying fern, furniture that looked purchased in a single defeated afternoon at a discount store. Nothing about Leonard Voss suggested a man with enemies. Nothing suggested a man with much of anything.\n\nExcept the paper.\n\nMara crouched beside the coffee table and studied it without touching it. A single sheet, handwritten, covered edge to edge in the same two words repeated hundreds of times in shrinking letters, spiraling inward like a drain.\n\n*I remember. I remember. I remember.*\n\nThe handwriting started bold and confident at the outer edge. By the center, the letters were barely visible, scratched by what must have been a nearly dead pen — or a nearly dead hand.\n\nThe medical examiner appeared in the doorway. \"No signs of struggle. No forced entry.\" He paused. \"Honestly, Mara, it looks like he just *stopped*.\"\n\nShe stood up slowly, slipping her hands into her pockets.\n\n\"Then what,\" she said quietly, \"was he trying so hard not to forget?\"\n\n---\n\n*The fern, she noticed, had been recently watered.*"
}
],
"model": "claude-sonnet-4-6",
"stop_reason": "end_turn",
"usage": {
"input_tokens": 21,
"output_tokens": 317
},
"stop_sequence": null,
"stop_details": null,
"gatewayMetadata": {
"keySource": "Unified"
}
}
```
</details>
<details>
<summary>**Streaming Response** — Enable streaming for real-time output</summary>
```ts
const response = await env.AI.run(
'anthropic/claude-sonnet-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-sonnet-4.6",
"max_tokens": 1024,
"messages": [
{
"content": "Explain the concept of recursion with a simple example.",
"role": "user"
}
],
"stream": true
}'
```
Recursion
Core Concept
Recursion is when a function calls itself to solve a smaller version of the same problem, until it reaches a simple base case it can solve directly.
Think of it like Russian nesting dolls — each doll contains a smaller version of itself, until you reach the smallest one.
Two Essential Parts
| Part | Purpose |
|---|---|
| Base Case | Stops the recursion (prevents infinite loop) |
| Recursive Case | Breaks the problem into a smaller version |
Simple Example: Countdown
def countdown(n):
# Base case — stop here
if n == 0:
print("Go!")
return
# Recursive case — call itself with a smaller value
print(n)
countdown(n - 1) # ← calls itself
countdown(3)
Output:
3
2
1
Go!
How It Executes Step by Step
countdown(3)
→ prints 3, calls countdown(2)
→ prints 2, calls countdown(1)
→ prints 1, calls countdown(0)
→ prints "Go!", returns ✓ BASE CASE
Classic Example: Factorial
def factorial(n):
if n == 0: # base case
return 1
return n * factorial(n - 1) # recursive case
print(factorial(4)) # → 24
Why it works:
factorial(4)
= 4 × factorial(3)
= 4 × 3 × factorial(2)
= 4 × 3 × 2 × factorial(1)
= 4 × 3 × 2 × 1 × factorial(0)
= 4 × 3 × 2 × 1 × 1
= 24
⚠️ Common Mistake: Missing Base Case
def broken(n):
print(n)
broken(n - 1) # never stops → stack overflow!
When to Use Recursion
✅ Good fit for: - Tree/folder traversal - Sorting algorithms (merge sort) - Problems naturally defined recursively (Fibonacci, factorials)
