Claude Sonnet 5·续

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-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"
  }
}'
Detective Mara Voss crouched beside the overturned chair, careful not to let her coat brush the chalk outline still drying on the hardwood floor. The apartment smelled of lavender and something underneath it—copper, sharp and unmistakable.

"You seeing this?" she called to her partner, Reyes, who was photographing the bookshelf.

He crossed the room, careful of the evidence markers scattered like yellow teeth across the carpet. Mara pointed at the small object resting in the dead man's open palm: a single playing card, the seven of diamonds, except where the diamonds should have been, someone had drawn seven tiny, perfect spirals in red ink.

"Could be nothing," Reyes said, though his voice suggested he didn't believe it.

"Could be." Mara pulled an evidence bag from her pocket but didn't reach for the card yet. Something about it held her still. The spirals weren't random—she'd seen that pattern before, scratched into the doorframe of a cold case file she'd inherited three years ago. A case that had never made sense, that had kept her awake on more nights than she cared to admit.

"Mara?"

She blinked, realized she'd been staring. "This isn't our first body with this signature," she said quietly. "I just didn't know there'd be a second."

Outside, rain began to tap against the window, and somewhere in the building, a door clicked shut—soft, deliberate, like someone had been listening.
{
  "id": "msg_01DACMFVHe3JbaQREntjsDuc",
  "type": "message",
  "role": "assistant",
  "content": [
    {
      "type": "text",
      "text": "Detective Mara Voss crouched beside the overturned chair, careful not to let her coat brush the chalk outline still drying on the hardwood floor. The apartment smelled of lavender and something underneath it—copper, sharp and unmistakable.\n\n\"You seeing this?\" she called to her partner, Reyes, who was photographing the bookshelf.\n\nHe crossed the room, careful of the evidence markers scattered like yellow teeth across the carpet. Mara pointed at the small object resting in the dead man's open palm: a single playing card, the seven of diamonds, except where the diamonds should have been, someone had drawn seven tiny, perfect spirals in red ink.\n\n\"Could be nothing,\" Reyes said, though his voice suggested he didn't believe it.\n\n\"Could be.\" Mara pulled an evidence bag from her pocket but didn't reach for the card yet. Something about it held her still. The spirals weren't random—she'd seen that pattern before, scratched into the doorframe of a cold case file she'd inherited three years ago. A case that had never made sense, that had kept her awake on more nights than she cared to admit.\n\n\"Mara?\"\n\nShe blinked, realized she'd been staring. \"This isn't our first body with this signature,\" she said quietly. \"I just didn't know there'd be a second.\"\n\nOutside, rain began to tap against the window, and somewhere in the building, a door clicked shut—soft, deliberate, like someone had been listening."
    }
  ],
  "model": "claude-sonnet-5",
  "stop_reason": "end_turn",
  "usage": {
    "input_tokens": 26,
    "output_tokens": 469
  },
  "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-sonnet-5',
  {
    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-sonnet-5",
  "max_tokens": 1024,
  "messages": [
    {
      "content": "Explain the concept of recursion with a simple example.",
      "role": "user"
    }
  ],
  "stream": true
}'
# Recursion

**Recursion** is a programming technique where a function calls itself to solve a problem by breaking it down into smaller, similar subproblems.

## Key Components

Every recursive function needs:
1. **Base case** – a condition that stops the recursion (prevents infinite loops)
2. **Recursive case** – where the function calls itself with a smaller/simpler input

## Simple Example: Factorial

The factorial of a number `n` (written `n!`) is the product of all positive integers up to `n`.

Mathematically: `5! = 5 × 4 × 3 × 2 × 1 = 120`

This can be defined recursively as:
```
n! = n × (n-1)!
0! = 1  (base case)
```

### Code Example (Python)

```python
def factorial(n):
    # Base case
    if n == 0:
        return 1
    # Recursive case
    else:
        return n * factorial(n - 1)

print(factorial(5))  # Output: 120
```

### How It Works (Step-by-Step)

```
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 * factorial(0)))))
= 5 * (4 * (3 * (2 * (1 * 1))))
= 120
```

The function keeps calling itself with smaller values until it hits the **base case** (`n == 0`), then the results "unwind" back up, multiplying together to produce the final answer.

## Why Use Recursion?

- Makes code **cleaner** for problems that are naturally recursive (trees, fractals, divide-and-conquer algorithms)
- Mirrors **mathematical definitions** closely
- Useful for problems like: tree traversal, sorting algorithms (quicksort, mergesort), the Fibonacci sequence, and navigating file systems

## Caution ⚠️
Without a proper base case, recursion leads to **infinite recursion** and a stack overflow error!
[
  {
    "type": "message_start",
    "message": {
      "model": "claude-sonnet-5",
      "id": "msg_0188koTEnwXJD4cbqRcEfaCT",
      "type": "message",
      "role": "assistant",
      "content": [],
      "stop_reason": null,
      "stop_sequence": null,
      "stop_details": null,
      "usage": {
        "input_tokens": 22,
        "cache_creation_input_tokens": 0,
        "cache_read_input_tokens": 0,
        "cache_creation": {
          "ephemeral_5m_input_tokens": 0,
          "ephemeral_1h_input_tokens": 0
        },
        "output_tokens": 6,
        "service_tier": "standard",
        "inference_geo": "global"
      }
    }
  },
  {
    "type": "content_block_start",
    "index": 0,
    "content_block": {
      "type": "text",
      "text": ""
    }
  },
  "... 20 more chunks omitted ...",
  {
    "type": "message_stop"
  }
]

</details>

Parameters

▶messages[]

arrayrequired

max_tokens

numberrequiredexclusiveMinimum: 0

system

string

stream

boolean

▶metadata{}

object

id

string

type

stringconst: message

role

stringconst: assistant

▶content[]

array

model

string

stop_reason

string

▶usage{}

object

API Schemas (Raw)

Input Open Download

Output Open Download

Was this helpful?

YesNo

On this page

Claude Sonnet 5·续 - 图1Docs

{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/anthropic/claude-sonnet-5/#page","headline":"Claude Sonnet 5","description":"Claude Sonnet 5 is Anthropic's most agentic Sonnet model yet, built for coding, tool use, reasoning, and long-horizon professional work at lower cost than Opus-class models.","url":"https://developers.cloudflare.com/ai/models/anthropic/claude-sonnet-5/","inLanguage":"en","image":"https://developers.cloudflare.com/og-docs.png","publisher":{"@type":"Organization","name":"Cloudflare","description":"One platform for your apps, agents, and workforce. Build, secure, and scale without managing infrastructure","url":"https://www.cloudflare.com/","sameAs":["https://github.com/cloudflare","https://www.linkedin.com/company/cloudflare","https://x.com/cloudflare"],"logo":{"@type":"ImageObject","url":"https://developers.cloudflare.com/logo.svg"},"address":{"@type":"PostalAddress","streetAddress":"101 Townsend St","addressLocality":"San Francisco","addressRegion":"CA","postalCode":"94107","addressCountry":"US"},"contactPoint":[{"@type":"ContactPoint","contactType":"Customer Support","url":"https://support.cloudflare.com/","availableLanguage":["English"]},{"@type":"ContactPoint","contactType":"Sales","url":"https://www.cloudflare.com/contact/","availableLanguage":["English"]}]},"isPartOf":{"@type":"WebSite","@id":"https://developers.cloudflare.com/#website","name":"Cloudflare Docs","url":"https://developers.cloudflare.com/"}}


description: Claude Sonnet 5.5 offers the best combination of speed and intelligence, with adaptive thinking for coding, tool use, reasoning, and long-horizon work. title: Claude Sonnet 5.5 image: https://developers.cloudflare.com/og-docs.png


Skip to content

Documentation Index
Fetch the complete documentation index at: https://developers.cloudflare.com/llms.txt
Use this file to discover all available pages before exploring further.

Anthropic logo