Test (3)

print(fib(40)) # Returns 102334155 instantly


---

### Why this fixes the issue:
* **Naive recursion:** Time complexity is $O(2^n)$ because it recomputes identical values millions of times.
* **Memoized recursion:** Time complexity drops to $O(n)$ because each Fibonacci number from $0$ to $n$ is calculated only once. Space complexity is $O(n)$ to store the cache and recursion stack.
````

```json
{
  "candidates": [
    {
      "content": {
        "role": "model",
        "parts": [
          {
            "text": "Here is how to memoize the recursive Fibonacci function.\n\n### 1. Using a Dictionary / Cache (Explicit)\n\nYou store results of previous calculations in a dictionary and look them up before computing:\n\n```python\ndef fib(n, memo=None):\n    if memo is None:\n        memo = {}\n\n    # Check if already computed\n    if n in memo:\n        return memo[n]\n\n    # Base cases\n    if n <= 0:\n        return 0\n    elif n == 1:\n        return 1\n\n    # Store result in memo dictionary\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---\n\n### 2. Using Python's Built-in `@lru_cache` (Idiomatic Python)\n\nPython has a built-in decorator that handles memoization automatically:\n\n```python\nfrom functools import lru_cache\n\n\n@lru_cache(maxsize=None)\ndef fib(n):\n    if n <= 0:\n        return 0\n    elif n == 1:\n        return 1\n    return fib(n - 1) + fib(n - 2)\n\n\n# Test\nprint(fib(40))  # Returns 102334155 instantly\n```\n\n---\n\n### Why this fixes the issue:\n* **Naive recursion:** Time complexity is $O(2^n)$ because it recomputes identical values millions of times.\n* **Memoized recursion:** Time complexity drops to $O(n)$ because each Fibonacci number from $0$ to $n$ is calculated only once. Space complexity is $O(n)$ to store the cache and recursion stack.",
            "thoughtSignature": "AY89a1+Wv/04SFz0MKQY8n+tFyT0cfnQ+6x5+vRQu2MbyVYQqMErpr6OvgnpAYufyK3yG/BXeedOilTz9V1KgVD1QWF0fywd6r7Yw6Hbfwl+RaCf+zGlEOeM7ZuqPAIjIrQEsfaYbR+THgipFCCvNuP//K5ObnatV7hRrDMt7pqltYwg5NWm/O+0H3YvLp55UZlztXf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Metadata": {
    "promptTokenCount": 62,
    "candidatesTokenCount": 412,
    "totalTokenCount": 698,
    "trafficType": "ON_DEMAND",
    "promptTokensDetails": [
      {
        "modality": "TEXT",
        "tokenCount": 62
      }
    ],
    "candidatesTokensDetails": [
      {
        "modality": "TEXT",
        "tokenCount": 412
      }
    ],
    "thoughtsTokenCount": 224
  },
  "modelVersion": "gemini-3.7-flash",
  "createTime": "2026-08-13T19:07:41.574572Z",
  "responseId": "_RV-auyII6ip3dAP16iw4Qw"
}

</details>

<details>

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

const response = await env.AI.run(
  'google/gemini-3.7-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.7-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
    }
  }
}'
To find the number of smaller cubes with **exactly two red faces**, we can analyze how the $3 \times 3 \times 3$ cube is structured:

1. **Corner cubes (3 painted faces):** There are **8** corners in a cube.
2. **Edge cubes (excluding corners, 2 painted faces):** A cube has 12 edges. With a $3 \times 3 \times 3$ cut, each edge has 1 middle cube with 2 painted faces:
   $$\text{Number of cubes} = 12 \times (3 - 2) = 12$$
3. **Face-center cubes (1 painted face):** There is 1 in the center of each of the 6 faces = **6**.
4. **Interior cube (0 painted faces):** There is **1** cube completely inside.

*(Check: $8 + 12 + 6 + 1 = 27$ total cubes)*

Therefore, there are **12** smaller cubes with exactly two red faces.
{
  "candidates": [
    {
      "content": {
        "role": "model",
        "parts": [
          {
            "text": "To find the number of smaller cubes with **exactly two red faces**, we can analyze how the $3 \\times 3 \\times 3$ cube is structured:\n\n1. **Corner cubes (3 painted faces):** There are **8** corners in a cube.\n2. **Edge cubes (excluding corners, 2 painted faces):** A cube has 12 edges. With a $3 \\times 3 \\times 3$ cut, each edge has 1 middle cube with 2 painted faces:\n   $$\\text{Number of cubes} = 12 \\times (3 - 2) = 12$$\n3. **Face-center cubes (1 painted face):** There is 1 in the center of each of the 6 faces = **6**.\n4. **Interior cube (0 painted faces):** There is **1** cube completely inside.\n\n*(Check: $8 + 12 + 6 + 1 = 27$ total cubes)*\n\nTherefore, there are **12** smaller cubes with exactly two red faces.",
            "thoughtSignature": "AY89a18GhPrAzwD4+OG6wmLOGj2YZE0gv9PY76IqT4vccoHQerNJubk8VCyX0atC0qHPy/28tlQG5WlMvbqfovvGqrSJeNHSVC6RoyKD7SMGVnSOw83d5XDYxirhMa5XgVbtEF6O5t03QYpIyB/ice00yWw9US/osp4NOYRDYTPA6uekMJkCjFH8lNuYP4RnEFmEXHyxBtnlrcXvB2fy9bWxZEw3ck69faKWfJF/Ia0oy27SOdIaQTzcczJum9F+AnjliMkpY4EdIm+5KvOwrZCgcz+QWfNGQBu9SOK9qalhHHiI7diBhU8f4Dans3S1a1A9jKV8mOelXtaNDOXOKSk45muOSxds5JF/wb/2XAdTpgLt2cLE/vOuF4c4WBA+vpV9lvwlHKGMklvwFz7kSwnVOLnxglQwQl9ykyfdcInHzlaWAzfzEu7tq/Zkmp67DBtN7ZeG/teVlPIqm63uwBrQT8MOWVB27Ah59QI57TzclfNs0scwjmTlzFIzrzEKx+uz4Z4ekistTu8yGW12Gk8ypl5HEwZnOS8JpRR/ln20XV95oMb27LA6qnnW71S5SUva8+PdQsRw3NmeIp1FDmjxmuLE43UBcsGn/rj8KymrDRHkC1PHyOU+6je4J+/fma44zwfp4G2YJOit3f8btPUVsjrXH011krTONlK47hfKp08WJO7nCVaw7+gphzRrUMugxl8g7D3kVd5uym1c+lQstrs+FaaXj1VZwM5UUX3p/6ex+gso45qJ+h1OFhmZeOHKF8KTUw86RMdtFC+r1ULthumOSJHmb0nkQKnBqqV7qXdzNVep0rwZHk6rfULTPUQ0XaKAy9dtk8YOeeX7ULaTOHRe044Q9EcZk5eFCF5ktauTBwOG4+7B3R84/TS6DYOKQZSdYukuAQpq9SzlNnZaa1DHc9YLPP0CyPkEJ6yyZjEN78TiLvb+eXW06pPNC/wXVUdx47dq6w8MI16w4CiA8e8r/C7sqKSkD2j0Ksufr+mAq5gwSgOMRQx8vR+SfWp+3i1RvkRHpONZGftNyBuXfPLq1t/Hk6Wci4xkE8k8grwopKdghzHBpknmkz9783YjkeIFQMcoruEgfvzpElGERWmXKg7UqrMaOhY/HNcZ4auUoj8mUMBj+ejiCV/v+YrO6y3TAifJPYJEn4tiV3smbXTIA+UpilF4POrVSoeJkNhb6EVOrDK/UsjP2NNKNclL6F19JurykzmBrQZZs8vVn5KWLxkBXkdkdGMAjtPRdtX9ggfr+hhTNjBYSpo2sxVDjNhOs977Aie8wsRBejfR3a+OUVwyK9PptIaRqpJVQ9YTu0iUe3PcWUSo6YH+6gsOVSRjFrqj+1Ayq0SXfKisu9hF2HOp/vC03Bx0Weqw6XqYMnNvDSjIKEWTImfuGJyx0MK0VS4bvQm/T7T3OmbGnSsqHPx83n10xw=="
          }
        ]
      },
      "finishReason": "STOP"
    }
  ],
  "usageMetadata": {
    "promptTokenCount": 31,
    "candidatesTokenCount": 228,
    "totalTokenCount": 602,
    "trafficType": "ON_DEMAND",
    "promptTokensDetails": [
      {
        "modality": "TEXT",
        "tokenCount": 31
      }
    ],
    "candidatesTokensDetails": [
      {
        "modality": "TEXT",
        "tokenCount": 228
      }
    ],
    "thoughtsTokenCount": 343
  },
  "modelVersion": "gemini-3.7-flash",
  "createTime": "2026-08-13T19:07:45.456897Z",
  "responseId": "ARZ-asHxG6mp3dAP9fHcoQ0"
}

</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

Test (3) - 图1Docs

{"@context":"https://schema.org","@type":"TechArticle","@id":"https://developers.cloudflare.com/ai/models/google/gemini-3.7-flash/#page","headline":"Gemini 3.7 Flash","description":"Gemini 3.7 Flash is a highly capable, natively multimodal reasoning model optimized for agentic workflows and real-world tasks.","url":"https://developers.cloudflare.com/ai/models/google/gemini-3.7-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: Our most intelligent Flash model, engineered for long-horizon software engineering, autonomous agents, and complex enterprise workflows. title: Gemini 3.8 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