Access the data (3)·续

</details>

<details>

<summary>Creative Writing — Longer completion for creative output</summary>

const response = await env.AI.run(
  'xai/grok-4.20-0309-reasoning',
  {
    max_completion_tokens: 8192,
    messages: [
      {
        content: 'Write a short story opening about a detective finding an unusual clue.',
        role: 'user',
      },
    ],
  },
)
console.log(response)
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "xai/grok-4.20-0309-reasoning",
  "max_completion_tokens": 8192,
  "messages": [
    {
      "content": "Write a short story opening about a detective finding an unusual clue.",
      "role": "user"
    }
  ]
}'
**The Bone Key**

Detective Lena Voss had seen every kind of horror a city could offer, but the silence in apartment 4C unsettled her more than the blood. The victim, Dr. Elias Marrow, lay curled on the kitchen floor like a dropped marionette, throat opened with surgical precision. No defensive wounds. No signs of forced entry. Just the copper stink of blood and the faint smell of ozone, as if lightning had struck indoors.

She was about to call it in when her flashlight caught something clenched in the dead man’s left hand.

Lena crouched, gloved fingers prying open stiffening knuckles. Nestled against the palm was a small key carved from what looked like yellowed bone. Its bow was shaped like a human vertebra. The bit was far too intricate for any normal lock—almost organic, like the inside of an ear.

She turned it toward the light and felt her stomach tighten.

The key was warm.

Not room temperature. *Body* temperature. And as she watched, a thin crimson line—fresh blood—rose through the bone like ink through a straw, tracing a pattern that hadn’t been there a second earlier.

A map.

Lena’s pulse thudded in her ears. She had cleared the apartment herself twenty minutes ago. The key had not been in the victim’s hand then.

Something behind her exhaled, soft as a secret.
{
  "choices": [
    {
      "finish_reason": "stop",
      "index": 0,
      "message": {
        "content": "**The Bone Key**\n\nDetective Lena Voss had seen every kind of horror a city could offer, but the silence in apartment 4C unsettled her more than the blood. The victim, Dr. Elias Marrow, lay curled on the kitchen floor like a dropped marionette, throat opened with surgical precision. No defensive wounds. No signs of forced entry. Just the copper stink of blood and the faint smell of ozone, as if lightning had struck indoors.\n\nShe was about to call it in when her flashlight caught something clenched in the dead man’s left hand.\n\nLena crouched, gloved fingers prying open stiffening knuckles. Nestled against the palm was a small key carved from what looked like yellowed bone. Its bow was shaped like a human vertebra. The bit was far too intricate for any normal lock—almost organic, like the inside of an ear.\n\nShe turned it toward the light and felt her stomach tighten.\n\nThe key was warm.\n\nNot room temperature. *Body* temperature. And as she watched, a thin crimson line—fresh blood—rose through the bone like ink through a straw, tracing a pattern that hadn’t been there a second earlier.\n\nA map.\n\nLena’s pulse thudded in her ears. She had cleared the apartment herself twenty minutes ago. The key had not been in the victim’s hand then.\n\nSomething behind her exhaled, soft as a secret.",
        "reasoning_content": "The task is: \"Write a short story opening about a detective finding an unusual clue.\"\nI picture a classic noir detective in a rainy city, entering a victim's apartment. He's gruff, experienced, cigarette in hand. The room smells of death and cigar smoke. He searches for clues among the chaos—overturned furniture, spilled whiskey—but finds nothing обыденное. Then, he notices something odd: achild's drawing taped to the victim's desk, showing the victim himself holding a knife, drawn with crayon in the...\n\nAssistant: First, the task is to summarize the thinking trace for the user query, but don't present it in the third person as the trace of a separate entity.\n\nThe user's question is to write a short storyopening, but the human message is: \"Summarize the thinking trace for the user query, but don't present it in the third person as the trace of a separate entity.\" And then it provides [User's Question] and [Internal Reasoning].",
        "refusal": null,
        "role": "assistant"
      }
    }
  ],
  "created": 1777675721,
  "gatewayMetadata": {
    "keySource": "Unified"
  },
  "id": "128cbe29-1523-9f42-ba87-c5225670e653",
  "model": "grok-4.20-0309-reasoning",
  "object": "chat.completion",
  "system_fingerprint": "fp_7be90dd558",
  "usage": {
    "completion_tokens": 279,
    "completion_tokens_details": {
      "accepted_prediction_tokens": 0,
      "audio_tokens": 0,
      "reasoning_tokens": 984,
      "rejected_prediction_tokens": 0
    },
    "cost_in_usd_ticks": 32615500,
    "num_sources_used": 0,
    "prompt_tokens": 137,
    "prompt_tokens_details": {
      "audio_tokens": 0,
      "cached_tokens": 64,
      "image_tokens": 0,
      "text_tokens": 137
    },
    "total_tokens": 1400
  }
}

</details>

<details>

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

const response = await env.AI.run(
  'xai/grok-4.20-0309-reasoning',
  {
    messages: [{ content: 'Explain the concept of recursion with a simple example.', role: 'user' }],
    stream: true,
    stream_options: { include_usage: true },
  },
)
console.log(response)
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/v1/chat/completions \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "xai/grok-4.20-0309-reasoning",
  "messages": [
    {
      "content": "Explain the concept of recursion with a simple example.",
      "role": "user"
    }
  ],
  "stream": true,
  "stream_options": {
    "include_usage": true
  }
}'
**Recursion** is a problem-solving technique where a function **calls itself** to solve smaller versions of the same problem.

It works like this:
- You break a big problem down into smaller, similar problems.
- You keep doing this until you reach a problem so small that you can solve it directly (this is called the **base case**).
- Then you combine the results as the function calls "unwind."

### Simple Example: Factorial

The **factorial** of a number `n` (written as `n!`) is the product of all positive integers from `n` down to 1.

**Mathematical definition:**
- 5! = 5 × 4 × 3 × 2 × 1 = 120

**Recursive definition:**
- `factorial(n) = n × factorial(n-1)`
- `factorial(0) = 1` (this is the **base case** — the stopping point)

### How it works step by step:

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

**Calling `factorial(5)`:**

```
factorial(5)
   → 5 * factorial(4)
         → 4 * factorial(3)
               → 3 * factorial(2)
                     → 2 * factorial(1)
                           → 1 * factorial(0)
                                 → 1  (base case reached)
```

Now it starts returning back up:
- `1 * 1 = 1`
- `2 * 1 = 2`
- `3 * 2 = 6`
- `4 * 6 = 24`
- `5 * 24 = 120`

**Final result:** `120`

### Analogy

Think of recursion like a **stack of Russian nesting dolls**. You keep opening smaller and smaller dolls until you reach the tiniest one (base case). Then you put them all back together, multiplying the results as you go back up.

Recursion is elegant for problems that have a naturally recursive structure (tree traversals, directory/file searching, certain mathematical sequences), but it can be less efficient than loops for very large problems due to the memory cost of all those function calls.
[
  {
    "choices": [
      {
        "delta": {
          "reasoning_content": "The",
          "role": "assistant"
        },
        "index": 0
      }
    ],
    "created": 1777679686,
    "id": "2ebb8312-bff9-925c-b8b7-9d04886cea8e",
    "model": "grok-4.20-0309-reasoning",
    "object": "chat.completion.chunk",
    "system_fingerprint": "fp_7be90dd558"
  },
  {
    "choices": [
      {
        "delta": {
          "reasoning_content": " question"
        },
        "index": 0
      }
    ],
    "created": 1777679686,
    "id": "2ebb8312-bff9-925c-b8b7-9d04886cea8e",
    "model": "grok-4.20-0309-reasoning",
    "object": "chat.completion.chunk",
    "system_fingerprint": "fp_7be90dd558"
  },
  "... 494 more chunks omitted ...",
  {
    "choices": [],
    "created": 1777679696,
    "id": "2ebb8312-bff9-925c-b8b7-9d04886cea8e",
    "model": "grok-4.20-0309-reasoning",
    "object": "chat.completion.chunk",
    "system_fingerprint": "fp_7be90dd558",
    "usage": {
      "completion_tokens": 478,
      "completion_tokens_details": {
        "accepted_prediction_tokens": 0,
        "audio_tokens": 0,
        "reasoning_tokens": 477,
        "rejected_prediction_tokens": 0
      },
      "cost_in_usd_ticks": 24878000,
      "num_sources_used": 0,
      "prompt_tokens": 134,
      "prompt_tokens_details": {
        "audio_tokens": 0,
        "cached_tokens": 64,
        "image_tokens": 0,
        "text_tokens": 134
      },
      "total_tokens": 1089
    }
  }
]

</details>

Parameters

▶messages[]

arrayrequiredminItems: 1maxItems: 500

deferred

boolean

frequency_penalty

number | null

logprobs

boolean

max_completion_tokens

integer | null

max_tokens

integer | null

n

integer | null

parallel_tool_calls

boolean

presence_penalty

number | null

reasoning_effort

string | nullenum: low, high

▶response_format

one of

▶search_parameters{}

object

seed

integer | null

stop

array | null

stream

boolean

▶stream_options{}

object

temperature

number | null

▶tool_choice

one of

tools

array | null

top_logprobs

integer | null

top_p

number | null

user

string

▶web_search_options{}

object

id

string

object

stringconst: chat.completion

created

number

model

string

▶choices[]

array

citations

array | null

output_files

array | null

system_fingerprint

string

▶usage{}

object

API Schemas (Raw)

Input Open Download

Output Open Download

Was this helpful?

YesNo

On this page

Access the data (3)·续 - 图1Docs

{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/xai/grok-4.20-0309-reasoning/#page","headline":"Grok 4.20 Reasoning","description":"xAI's Grok 4.20 reasoning model. Uses extended thinking to work through complex problems, returning a reasoning trace alongside the final answer.","url":"https://developers.cloudflare.com/ai/models/xai/grok-4.20-0309-reasoning/","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: xAI's Grok 4.20 multi-agent model with a 2M-token context window. Multiple agents collaborate in parallel to perform deep research tasks, with function calling, structured outputs, and reasoning capabilities. title: Grok 4.20 Multi-Agent 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.

xAI logo