maxsize=None allows the cache to grow indefinitely

@lru_cache(maxsize=None) def fib(n): if n <= 0: return 0 if n == 1: return 1

return fib(n - 1) + fib(n - 2)

print(fib(40)) # Instantly computes


---

### JavaScript Example

```javascript
function fib(n, memo = {}) {
    // 1. Check cache
    if (n in memo) return memo[n];

    // 2. Base cases
    if (n <= 0) return 0;
    if (n === 1) return 1;

    // 3. Compute and store
    memo[n] = fib(n - 1, memo) + fib(n - 2, memo);
    return memo[n];
}

console.log(fib(40)); // 102334155

What changed?

  • Without Memoization ($n=40$): Takes roughly 1.1 trillion function calls, taking minutes or hours to finish.
  • With Memoization ($n=40$): Takes only 40 function calls, finishing in less than a millisecond.

(Let me know if you need this written in a different programming language like C++, Java, or Rust!) ````

{
  "candidates": [
    {
      "content": {
        "role": "model",
        "parts": [
          {
            "text": "Here is how to optimize your recursive Fibonacci function using **memoization**. \n\nMemoization stores the results of expensive function calls in a cache (like a dictionary or map) so you don't recompute the same values over and over. This reduces the time complexity from **$O(2^n)$** (exponential) to **$O(n)$** (linear).\n\n---\n\n### Python Example\n\n#### Option 1: Manual Cache (Shows how it works under the hood)\n```python\ndef fib(n, memo={}):\n    # 1. Check if the result is already in the cache\n    if n in memo:\n        return memo[n]\n\n    # 2. Base cases\n    if n <= 0:\n        return 0\n    if n == 1:\n        return 1\n\n    # 3. Compute and store in cache before returning\n    memo[n] = fib(n - 1, memo) + fib(n - 2, memo)\n    return memo[n]\n\n\n# Test\nprint(fib(40))  # Returns 102334155 instantly\n```\n\n#### Option 2: Python's Built-in `@lru_cache` (Cleanest)\nIf you are using Python, you don't even need to modify your function logic—just add a decorator:\n\n```python\nfrom functools import lru_cache\n\n\n# maxsize=None allows the cache to grow indefinitely\n@lru_cache(maxsize=None)\ndef fib(n):\n    if n <= 0:\n        return 0\n    if n == 1:\n        return 1\n\n    return fib(n - 1) + fib(n - 2)\n\n\nprint(fib(40))  # Instantly computes\n```\n\n---\n\n### JavaScript Example\n\n```javascript\nfunction fib(n, memo = {}) {\n    // 1. Check cache\n    if (n in memo) return memo[n];\n    \n    // 2. Base cases\n    if (n <= 0) return 0;\n    if (n === 1) return 1;\n\n    // 3. Compute and store\n    memo[n] = fib(n - 1, memo) + fib(n - 2, memo);\n    return memo[n];\n}\n\nconsole.log(fib(40)); // 102334155\n```\n\n---\n\n### What changed?\n* **Without Memoization ($n=40$):** Takes roughly **1.1 trillion function calls**, taking minutes or hours to finish.\n* **With Memoization ($n=40$):** Takes only **40 function calls**, finishing in less than a millisecond.\n\n*(Let me know if you need this written in a different programming language like C++, Java, or Rust!)*",
            "thoughtSignature": "AY89a1+ctnO9pFN+e7hgW0eZao5X3ew4AhkhyjLFp8H/8277YIUwpU9afhv8Sqb+P9/tYhd+SuWIOyutodLO4F8akA+FkY8qD1Ib3js3+4tcLU9L1gxGKG+/EBA6Hdgh5EBtyf4/1KqsMTAsnPwV0UTF/HRo64vqoyXoX8FBnKiXYLsYDmnBXNMPSudVsSDuuPUOdQM9Siig8F7jLArxYFvDSeQcEgKw3PnAXMLFD3rHiNsAglqZvtsue/04p6JG/LwAswI0GOCXvt9T1iknzVFIAISWkGymKs+jSNF9uwRzcbmDcndEntX4pbKlOBztkB5Eo0m2zw+VecVXy/cScmGCQYUNONikvTWU7MeUlYWRYbLbN/v5GHpFn5nbgVtHzpQpdPhUJEJP6z8fVuRtx3UQOxGSHmpG3xNCDaWDuJEvk2qjBqW8lguRpFZIDO516CV8etHYCi53MkDMZPv8JGWy1+wkqu4/6TyKtG+O3q3NUx2OBQwsUYzfIl+487pmJ/2XtF3mq4eoL4HaXJ+lXBNfjDzJRuj8NyQuG/5yUFpzpAEllh3RoqplDYexbO9LhelfudqAUSiqsRS9yxHZZBMSEoVjpKBlLp5j5wCq5gNDR3MvdqOps4GR91jDiKfF1BWEh3m2x7XV6+L2NNi9KPP1hZBmTExR3W1OXeKpUJLr8t5ROT0650xPAj3Ch2cDzHAEBo67ScwwVUEt8zXRx67p5nmT8GT8IMuzqulPj33Kk/XGmBJ6xoHwgivUPhs2ZPjlV0oDVRRcXUdQkb3yBQMgPmrTK/yE96TIzLaY02f2X7RIpeG+aNi+WSd6DNHGadLXPV2+UbP6mE+0eGj/1eZiyHdH4uANyjIZ5vRQYrsq4R6WC4LWS2a7ClFIcEQOXNTe5YcdqgFc4D+XLubk7SwIGlaIvAAN3UgaPxphDcw0ci0GLKN5NWikEj5y05JnAP0k70I7eNDcvwC8utNX9nNYRdzvJm5tEVjhNhYFmLjtpi3ca8w0wlE+WK1qA+ILYaO5qrvjNm2jFllqRKdBE1i2glFTNZO+dNL43bTgydtXjjrWpFqFFTnx9mP8NLWV/6nA4XdE+JfQA4CQ3JHy6vJAJPbh5cEmS/FRreFwNfS8U6wGaNx3VioqLDnVf9aI0edEEI4m0f7XWsT9dkdWxThfycC95HSFkX9jvUpv5e4dqzNo8bccenbE++4M4qhiqFL9SP5Ov6arYpl33P4rTEDGOHWHIlzupvM5EJ1IkppuSjh2UQm/PtAgHxxuE68riJ3YgbVvY5J7BekLtQMOzvLuEGFU3VGa2ArMs/dtHsfYygv3Nlrzs4IwOKuMo4V0mXYpsKxDckn/Yu3eSxgZzALRcU3Vytm+g6Mutzc5fvZCi4kDVKlW2yDrGFtTk1v116ggtQDPwREyI4+DzO7Cl8NqIZPgvM0NLnuZgNAgF4mABtf6FaTe/C8I9sHYzYVFOft3h1BN993hcAUpJW2aJHYaIChCNKUKBbX7f5nCUtgZ93NhUedLiDnOasVZB9xeR30wWglInifB77Q2Ue1QGXrBlPWyolODYjOcg4ZG42eI80sb5lAojzh3dtfGcf7AUfnNnHWV5dlSVa4uvZw1FF+RyEJuV+UcnSa3Kgjr2YPvD0GxecqBnIP7R7Weahl+mvLx362MYqfOu7+0+l02BCUcyMjWCymfBc+I5O1ILCUxQMnVf/CQZLUKziWrXwXESxeZqkAFqkzYQltrtxwjBddq"
          }
        ]
      },
      "finishReason": "STOP"
    }
  ],
  "usageMetadata": {
    "promptTokenCount": 62,
    "candidatesTokenCount": 631,
    "totalTokenCount": 1031,
    "trafficType": "ON_DEMAND",
    "promptTokensDetails": [
      {
        "modality": "TEXT",
        "tokenCount": 62
      }
    ],
    "candidatesTokensDetails": [
      {
        "modality": "TEXT",
        "tokenCount": 631
      }
    ],
    "thoughtsTokenCount": 338
  },
  "modelVersion": "gemini-3.6-flash",
  "createTime": "2026-07-21T16:21:27.790920Z",
  "responseId": "h5xfaoijMIWq8sYPycj20Q0"
}

</details>

<details>

<summary>Spatial Reasoning — Higher thinking budget for a spatial reasoning task</summary>

const response = await env.AI.run(
  'google/gemini-3.6-flash',
  {
    contents: [
      {
        parts: [
          {
            text: 'A cube is painted red on all faces, then cut into 27 equal smaller cubes. How many of the smaller cubes have exactly two red faces?',
          },
        ],
        role: 'user',
      },
    ],
    generationConfig: { maxOutputTokens: 4096 },
  },
)
console.log(response)
curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/ai/run \
  --header "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  --header "Content-Type: application/json" \
  --data '{
  "model": "google/gemini-3.6-flash",
  "input": {
    "contents": [
      {
        "parts": [
          {
            "text": "A cube is painted red on all faces, then cut into 27 equal smaller cubes. How many of the smaller cubes have exactly two red faces?"
          }
        ],
        "role": "user"
      }
    ],
    "generationConfig": {
      "maxOutputTokens": 4096
    }
  }
}'
There are **12** smaller cubes that have exactly two red faces.

### Breakdown of the solution:

When a cube is cut into 27 equal smaller cubes, it forms a **$3 \times 3 \times 3$ grid**. The location of a small cube determines how many of its faces are painted red:

1. **Corner cubes (3 painted faces):** There are **8** corners on a cube, so 8 small cubes have 3 red faces.
2. **Edge cubes (2 painted faces):** These are the cubes along the edges, excluding the corners. A cube has **12 edges**, and with a $3 \times 3 \times 3$ grid, there is exactly 1 such cube per edge ($12 \times 1 = \mathbf{12}$).
3. **Face-center cubes (1 painted face):** There are **6** faces on a cube, and each face has 1 center cube ($6 \times 1 = 6$).
4. **Inside/Core cube (0 painted faces):** There is **1** cube hidden completely in the center.

**Total check:** $8 + 12 + 6 + 1 = 27$ cubes.
{
  "candidates": [
    {
      "content": {
        "role": "model",
        "parts": [
          {
            "text": "There are **12** smaller cubes that have exactly two red faces.\n\n### Breakdown of the solution:\n\nWhen a cube is cut into 27 equal smaller cubes, it forms a **$3 \\times 3 \\times 3$ grid**. The location of a small cube determines how many of its faces are painted red:\n\n1. **Corner cubes (3 painted faces):** There are **8** corners on a cube, so 8 small cubes have 3 red faces.\n2. **Edge cubes (2 painted faces):** These are the cubes along the edges, excluding the corners. A cube has **12 edges**, and with a $3 \\times 3 \\times 3$ grid, there is exactly 1 such cube per edge ($12 \\times 1 = \\mathbf{12}$).\n3. **Face-center cubes (1 painted face):** There are **6** faces on a cube, and each face has 1 center cube ($6 \\times 1 = 6$).\n4. **Inside/Core cube (0 painted faces):** There is **1** cube hidden completely in the center.\n\n**Total check:** $8 + 12 + 6 + 1 = 27$ cubes.",
            "thoughtSignature": "AY89a19pbjpH5K2G+uQep8Sf+P3G1IbQZffTYG3H42VJAG+qKUF6Kp3D7aoC5i33ePiT+Qyh6qAVi9f5n1QPEpDkGiAAqvk7cLOd8Tl8YGOIg2AAFqqBfnALSkK7bk++ViADaeJllbJTz0Mwnn0TLDDxhy7Lylqu0fNR5QMQDf6GNNka+DOufFA3PsiGt3byDrkkEA9hU2ACYq4vgaICecMAR0fR8voH8Y5qY46fZ4Ul1wvaMqLL6KEtKkQyR/TBVbAIGsRk/wwjE+11qwOgOm18MhfdcLC9UmNCQrjqVF9EaFOp1I2oL/nIj4M0bmpiDfrtYCLUYZFdoxrOECAdyR4tcds8c0FZi9KgZfVj2MoTPsYGIc1kzAkRBTIHVC5RAjPXuS5MowtUoniRaW6BVkv8FaDGi+VjSWP9cb72PHmdMY60r6b4f3kc15rji8IiiPy2DYXtxSjXwFHwIE52j4zQ7L8cUBbCeQC4VFL17h6H9ZPpa/qc6PFNqnX0zarqMl3RL9hJOu4Viqy7uxNZOleE0BtyTGGQBNKM5WZSAgF5V7kxLNivxPK5ZGk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3fvvyQkMqIvV8XS4GjKCqNf+NA2YKMsxr/coupSXKwIBw5JjWdz0bcF/hiYVD0gTfvgVXqTQrTXcmUm7NbpHxRSzhs+lW7n5miyVjEt5WmsYTM7mWIdIWXN4DpRQSwJCz0Sq407VRkvPbHGdA2+UcQtZqQm5zNBCbgKkzSQvI7HjrZpRtWfp8N0rL1cEB6iKO/TIOms3T3MweSU/Xqw4IqIkgc4ef/EULrLui8vb0lVV9U+84mjpw7pGXsQxZoAmFm9KZbifjMwH3XXCWgkspES1HaTOfMhjl47e39pqYVPYz2Jx33I/XIvvd/QCedD+TAAU34cd/DMm8BWClbE4bp3u+zi/Gl3vQgTlotQwucxPf3N9W6FBUjaYsYWti40FqFDnxV932A8SuWdu4n51lSk1xL/2suhVOzGxAiO+sN27QZV6+t5I7SBouU4i3myqOPK86RwQ6PAJIb4dU00dleexfmPOEB9kNCyFF6/JRgoF/6sAfN5S/DBe3C7zUb1F58QhXgVSrYEjUOam86SDgj1BGwgGRDL4K++TrBISun3HoOLriVKL0YfF2Mv5qgfnxDQbLdV5QbnaBY8LUiBX29XO3I4+O+Qje5F8iVy8zLMn1nI38sZ5Crsl9kZEIX+xFDMr2eP8mMghV5OLQx02j88ZUI5vwrtH95VZcomG/4+t6Jr3FYdhbiTcakp6dpccYlbeDJ9n6i+DTbhAM40J"
          }
        ]
      },
      "finishReason": "STOP"
    }
  ],
  "usageMetadata": {
    "promptTokenCount": 31,
    "candidatesTokenCount": 265,
    "totalTokenCount": 1089,
    "trafficType": "ON_DEMAND",
    "promptTokensDetails": [
      {
        "modality": "TEXT",
        "tokenCount": 31
      }
    ],
    "candidatesTokensDetails": [
      {
        "modality": "TEXT",
        "tokenCount": 265
      }
    ],
    "thoughtsTokenCount": 793
  },
  "modelVersion": "gemini-3.6-flash",
  "createTime": "2026-07-21T16:21:32.579668Z",
  "responseId": "jJxfatSwI9jY8sYPgtSd8Ag"
}

</details>

Parameters

Schema variant

Generate ContentChat Completions

▶contents[]

arrayrequired

▶systemInstruction{}

object

▶generationConfig{}

object

▶safetySettings[]

array

▶tools[]

array

toolConfig

▶messages[]

arrayrequired

temperature

numberminimum: 0maximum: 2

max_tokens

numberexclusiveMinimum: 0

max_completion_tokens

numberexclusiveMinimum: 0

top_p

numberminimum: 0maximum: 1

frequency_penalty

numberminimum: -2maximum: 2

presence_penalty

numberminimum: -2maximum: 2

stream

boolean

▶stream_options{}

object

▶tools[]

array

tool_choice

response_format

▶modalities[]

array

▶audio{}

object

reasoning_effort

stringOptional reasoning control; availability and accepted values are model-dependent.

▶candidates[]

array

▶usageMetadata{}

object

modelVersion

string

id

string

object

string

created

number

model

string

▶choices[]

array

▶usage{}

object

API Schemas (Raw)

Input Open Download

Output Open Download

Was this helpful?

YesNo

On this page

maxsize=None allows the cache to grow in - 图1Docs

{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/google/gemini-3.6-flash/#page","headline":"Gemini 3.6 Flash","description":"Gemini 3.6 Flash provides sustained frontier-level intelligence optimized for real-world tasks at a higher speed and lower cost, excelling at code generation, agentic execution, and spatial reasoning.","url":"https://developers.cloudflare.com/ai/models/google/gemini-3.6-flash/","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: Gemini 3.7 Flash is a highly capable, natively multimodal reasoning model optimized for agentic workflows and real-world tasks. title: Gemini 3.7 Flash 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.

Google logo