Skip to content
Google logo

Gemini 4 Hydrogen

Text Generation • Google

View as MarkdownAgent setup

Model ID

Use with the Workers AI binding, the AI Gateway REST API, or the Unified API.

Calling the provider directly? Use the provider's model name instead, including with provider-native endpoints or the provider's own SDK. For example, Anthropic's name for anthropic/claude-opus-4.8 is claude-opus-4-8.

  • Third-party

Gemini 4 Hydrogen brings Gemini 4 agent and coding quality at Flash speed.

Model Info
Context Window ↗1,048,576 tokens
Terms and Licenselink ↗
More informationlink ↗
Request formatsChat Completions
Pricing
  • Input (per 1M tokens)$1.50
  • Output (per 1M tokens)$7.50
  • Cached input (per 1M tokens)$0.075

Usage

const response = await env.AI.run(
  'google/gemini-4-hydrogen',
  {
    contents: [
      {
        parts: [
          {
            text: 'What are the key differences between optimistic and pessimistic concurrency control in distributed systems?',
          },
        ],
        role: 'user',
      },
    ],
  },
)
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-4-hydrogen",
  "input": {
    "contents": [
      {
        "parts": [
          {
            "text": "What are the key differences between optimistic and pessimistic concurrency control in distributed systems?"
          }
        ],
        "role": "user"
      }
    ]
  }
}'
In distributed systems, concurrency control ensures that multiple nodes or clients accessing shared data do not leave it in an inconsistent state. Because nodes communicate over an unreliable network with non-zero latency, the choice between **Pessimistic Concurrency Control (PCC)** and **Optimistic Concurrency Control (OCC)** has significant implications for performance, fault tolerance, and scalability.

---

### 1. Core Philosophy & Execution Flow

* **Pessimistic Concurrency Control (PCC):** Assumes conflicts are **likely**. A transaction must acquire locks (shared for reads, exclusive for writes) on data items across the relevant nodes *before* reading or modifying them. Other transactions trying to access the same data are blocked until the locks are released.
  * *Flow:* Acquire Locks → Read/Compute → Write → Commit & Release Locks.
* **Optimistic Concurrency Control (OCC):** Assumes conflicts are **rare**. Transactions read data and perform computations locally without acquiring locks. Before committing, the system validates whether any data read by the transaction was modified by another transaction in the meantime. If a conflict is detected, the transaction aborts and retries.
  * *Flow:* Read/Compute (with versions/timestamps) → Validate → Write & Commit (or Abort & Retry).

---

### 2. Impact of Distributed Network Latency

* **PCC (High Lock-Hold Duration):** In a distributed system, acquiring locks across multiple shards or replicas requires network round trips (e.g., Distributed Two-Phase Locking combined with Two-Phase Commit). While waiting for network responses or client computation, locks remain held, stalling other nodes and severely limiting throughput—especially across wide-area networks (WANs).
* **OCC (Reduced Blocking):** Because no locks are held during the read and compute phases, slow clients or high network latency during execution do not block other transactions. Network coordination is concentrated at the commit/validation phase (often via Compare-And-Swap, version checks, or distributed consensus).

---

### 3. Failure Modes & Fault Tolerance

* **PCC (Deadlocks & Orphaned Locks):**
  * **Distributed Deadlocks:** Transaction A on Node 1 holds Lock X and waits for Lock Y on Node 2, while Transaction B holds Lock Y and waits for Lock X. Detecting cycles across nodes requires expensive global wait-for graphs or conservative lock timeouts.
  * **Node/Client Crashes:** If a client acquires a distributed lock and crashes (or gets partitioned), the resource remains locked indefinitely unless the system uses **leases** (time-bounded locks), which introduce clock-skew risks.
* **OCC (Cascading Aborts & Starvation):**
  * **Deadlock-Free:** Because transactions never wait on locks, distributed deadlocks cannot occur.
  * **Wasted Work & Livelock:** If a node crashes mid-transaction, no cleanup of locks is needed. However, under heavy contention, long-running transactions may repeatedly fail validation and restart (starvation), wasting CPU and network bandwidth.

---

### 4. Performance Under Contention

| Workload | Pessimistic (PCC) | Optimistic (OCC) |
| :--- | :--- | :--- |
| **Low Contention** | **Slower.** Pays the network and coordination tax of acquiring/releasing locks even when no conflicts exist. | **Faster.** Minimal coordination overhead; transactions execute unimpeded and usually pass validation. |
| **High Contention** | **More Predictable.** Queues conflicting transactions orderly via locks, avoiding wasted computation and retry storms. | **Degrades Severely.** High abort rates cause retry storms, amplifying network traffic and reducing effective throughput. |

---

### 5. Common Distributed Implementations

* **PCC:**
  * Distributed Lock Managers (e.g., using etcd, ZooKeeper, or Chubby with fencing tokens and leases).
  * Strict Two-Phase Locking (2PL) combined with Two-Phase Commit (2PC) in traditional distributed SQL databases.
* **OCC:**
  * Version numbers / ETags with conditional writes (e.g., DynamoDB `ConditionExpression`, HTTP `If-Match`, S3 conditional puts).
  * Timestamp-based validation and Multi-Version Concurrency Control (MVCC) combined with validation phases (used in systems like Google Percolator or read-write paths of some distributed NewSQL databases).

---

### Summary Table

| Dimension | Pessimistic (PCC) | Optimistic (OCC) |
| :--- | :--- | :--- |
| **Assumption** | Conflicts are frequent | Conflicts are rare |
| **Conflict Detection** | Prevented upfront via locking | Detected at commit time via validation |
| **Conflict Resolution** | Blocking / Waiting | Abort and retry |
| **Deadlock Risk** | Yes (requires detection or timeouts) | No |
| **Crash Impact** | Dangerous if locks aren't lease-based | Benign (uncommitted state is discarded) |
| **Best Suited For** | Hot data, financial ledgers, high-contention writes, expensive rollbacks | Read-heavy workloads, geographically distributed clients, low-contention updates |

*(Note: Many modern distributed databases—such as CockroachDB or Google Spanner—use **hybrid** approaches, combining MVCC so reads don't block writes, alongside locking or timestamp ordering for concurrent writes.)*
{
  "candidates": [
    {
      "content": {
        "role": "model",
        "parts": [
          {
            "text": "In distributed systems, concurrency control ensures that multiple nodes or clients accessing shared data do not leave it in an inconsistent state. Because nodes communicate over an unreliable network with non-zero latency, the choice between **Pessimistic Concurrency Control (PCC)** and **Optimistic Concurrency Control (OCC)** has significant implications for performance, fault tolerance, and scalability.\n\n---\n\n### 1. Core Philosophy & Execution Flow\n\n* **Pessimistic Concurrency Control (PCC):** Assumes conflicts are **likely**. A transaction must acquire locks (shared for reads, exclusive for writes) on data items across the relevant nodes *before* reading or modifying them. Other transactions trying to access the same data are blocked until the locks are released.\n  * *Flow:* Acquire Locks → Read/Compute → Write → Commit & Release Locks.\n* **Optimistic Concurrency Control (OCC):** Assumes conflicts are **rare**. Transactions read data and perform computations locally without acquiring locks. Before committing, the system validates whether any data read by the transaction was modified by another transaction in the meantime. If a conflict is detected, the transaction aborts and retries.\n  * *Flow:* Read/Compute (with versions/timestamps) → Validate → Write & Commit (or Abort & Retry).\n\n---\n\n### 2. Impact of Distributed Network Latency\n\n* **PCC (High Lock-Hold Duration):** In a distributed system, acquiring locks across multiple shards or replicas requires network round trips (e.g., Distributed Two-Phase Locking combined with Two-Phase Commit). While waiting for network responses or client computation, locks remain held, stalling other nodes and severely limiting throughput—especially across wide-area networks (WANs).\n* **OCC (Reduced Blocking):** Because no locks are held during the read and compute phases, slow clients or high network latency during execution do not block other transactions. Network coordination is concentrated at the commit/validation phase (often via Compare-And-Swap, version checks, or distributed consensus).\n\n---\n\n### 3. Failure Modes & Fault Tolerance\n\n* **PCC (Deadlocks & Orphaned Locks):**\n  * **Distributed Deadlocks:** Transaction A on Node 1 holds Lock X and waits for Lock Y on Node 2, while Transaction B holds Lock Y and waits for Lock X. Detecting cycles across nodes requires expensive global wait-for graphs or conservative lock timeouts.\n  * **Node/Client Crashes:** If a client acquires a distributed lock and crashes (or gets partitioned), the resource remains locked indefinitely unless the system uses **leases** (time-bounded locks), which introduce clock-skew risks.\n* **OCC (Cascading Aborts & Starvation):**\n  * **Deadlock-Free:** Because transactions never wait on locks, distributed deadlocks cannot occur.\n  * **Wasted Work & Livelock:** If a node crashes mid-transaction, no cleanup of locks is needed. However, under heavy contention, long-running transactions may repeatedly fail validation and restart (starvation), wasting CPU and network bandwidth.\n\n---\n\n### 4. Performance Under Contention\n\n| Workload | Pessimistic (PCC) | Optimistic (OCC) |\n| :--- | :--- | :--- |\n| **Low Contention** | **Slower.** Pays the network and coordination tax of acquiring/releasing locks even when no conflicts exist. | **Faster.** Minimal coordination overhead; transactions execute unimpeded and usually pass validation. |\n| **High Contention** | **More Predictable.** Queues conflicting transactions orderly via locks, avoiding wasted computation and retry storms. | **Degrades Severely.** High abort rates cause retry storms, amplifying network traffic and reducing effective throughput. |\n\n---\n\n### 5. Common Distributed Implementations\n\n* **PCC:**\n  * Distributed Lock Managers (e.g., using etcd, ZooKeeper, or Chubby with fencing tokens and leases).\n  * Strict Two-Phase Locking (2PL) combined with Two-Phase Commit (2PC) in traditional distributed SQL databases.\n* **OCC:**\n  * Version numbers / ETags with conditional writes (e.g., DynamoDB `ConditionExpression`, HTTP `If-Match`, S3 conditional puts).\n  * Timestamp-based validation and Multi-Version Concurrency Control (MVCC) combined with validation phases (used in systems like Google Percolator or read-write paths of some distributed NewSQL databases).\n\n---\n\n### Summary Table\n\n| Dimension | Pessimistic (PCC) | Optimistic (OCC) |\n| :--- | :--- | :--- |\n| **Assumption** | Conflicts are frequent | Conflicts are rare |\n| **Conflict Detection** | Prevented upfront via locking | Detected at commit time via validation |\n| **Conflict Resolution** | Blocking / Waiting | Abort and retry |\n| **Deadlock Risk** | Yes (requires detection or timeouts) | No |\n| **Crash Impact** | Dangerous if locks aren't lease-based | Benign (uncommitted state is discarded) |\n| **Best Suited For** | Hot data, financial ledgers, high-contention writes, expensive rollbacks | Read-heavy workloads, geographically distributed clients, low-contention updates |\n\n*(Note: Many modern distributed databases—such as CockroachDB or Google Spanner—use **hybrid** approaches, combining MVCC so reads don't block writes, alongside locking or timestamp ordering for concurrent writes.)*",
            "thoughtSignature": "AY89a1/V6+o/UuSQJtg1F89g9uBdMxhm3Dth//Y3tyKexkr3aIzRZNfypQbWdLh/XBiHk+6z4I2lwsmA/g0j/QYAljrP/V6M8He0nPi6Wl60DmCEnkCQAzpFUPFpHk/QFINah4ijg1W5XgtiCCNNHtFcfnLl5Wetn83TGNEPBrum7GFP1gTjcrkvaAk+G6esSpllIl5SfhbOfcOI+BAH4o5ht0WUxpNc4qvkT6FM6gZtv7hQ3rz5nLvBzirjU8/tn/Skx0wrjOiyODse17RPMuUPTzEPB6kpWpgI1/dabDmyWJz+a3tNelWQ9ZC8kyFxwnm6/7OH3XALJEOylPSokOQ5n+r7hSIryYletsruNRl6qxR02j2zHogYWIgq3AbrvXd3TauCwMqBAffBQMitHbaQJCJewLVy/gdvCUEgpPPhvV2Y2uH1oDA8W69L4AMHMgLl0qOQ6w056YOuhDq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s27NoP+rr/nuZwSdZ009hMCSpRYlvsk9/8/ubFTWZWJ4+Z9iHebe/s/vR/eb5xu/JixjnzYNtY9+cr3vvkLlS+HGskh6kcfdAnvozrzIpLm5ahhYj8HnClx4Zpu0MLNDUrafAwLHq4mXciRkTfbqEJum71LbF9JktJTX51Vn12FMjRqLa10z/vms7Ty4sZJUQvvJ2IHzw7GLWbS6Bcf1WHt6t3FsAW9mPDhu0ldMijYz6Tzvmq263syKbEi5rzovOVVMfwxoIAFhx3ZX8EgYGdW3DP1eYQXp4QFrpV/XcrUZmDnyViu/0QJo4t100WpceR6yFRaSrJGI2vR5gWSwbvP/9lu3bvvxL+FaYttAvGX3kvG/GnZaos/Koh5+WhtgZ2NlMqegrzJz4KrmxKrb/rk+T1Cx23SdI4VNsgu5v82DqaBpL5/lJLVMTShxMZb2SQ9u+i49sz44dlx4zQs6k67kYTnRMr+K/Kya6Y+soyrie1cvdRWg69gNFZIR6EwDGpiMvMdVw4f9V7qR7KeZUe+0GD7IYwBkWzjMJ3iq9bSY5pzQAvPHflJ29Zm5ru6lravzbtpW3axCVid397czQWopTHOIy/IhkDRvrWejki9RBVSDF2ReJM2mK3XJu1QDBbcOCpXI3axOOSYCSJPy9u3saCgRJitlUejpi3DjZbBRSUJsihObMp3J/+zvRSuV+hNLPC5WXCUTJixEsOcAHIiwR0zN5IqArPHazv2ICawcpoDvUz+cndHedgyvS5ol9ttbq6rqKPcYgkCCoU1Chu++uRCcwbsIIKtShf3EeoVwWsr0EjqpvBBcVyv/cB7gcoIaWvVgI5orORReWYZkFxGiVmRWioY1q2veG6HJ7Rm0MKZIbqfr2jgleYOfcbAByzb7E9IfUW/KlA+lfDC3yZ7pBNa6rWiBr1npGrKO1rs1shjH5bFPMNNbqNd8UeivKSmFAckQqESnl+c/wJSGG5zHflP/jM2KTyxxJyVxH36T0WHO1+eD0Swlpg+SWHgBHgkJzmdOU9IS78fmHKPTgn14eXww
... response truncated ...

Examples

Agentic Coding — Coding task with a system instruction
const response = await env.AI.run(
  'google/gemini-4-hydrogen',
  {
    contents: [
      {
        parts: [
          { text: 'Write a Python function that merges two sorted lists into one sorted list.' },
        ],
        role: 'user',
      },
    ],
    systemInstruction: {
      parts: [
        {
          text: 'You are an expert software engineering agent. Write concise, correct, well-documented code.',
        },
      ],
    },
  },
)
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-4-hydrogen",
  "input": {
    "contents": [
      {
        "parts": [
          {
            "text": "Write a Python function that merges two sorted lists into one sorted list."
          }
        ],
        "role": "user"
      }
    ],
    "systemInstruction": {
      "parts": [
        {
          "text": "You are an expert software engineering agent. Write concise, correct, well-documented code."
        }
      ]
    }
  }
}'
```python
from typing import TypeVar

T = TypeVar("T")


def merge_sorted_lists(list1: list[T], list2: list[T]) -> list[T]:
    """Merge two sorted lists into a single sorted list.

    Uses a two-pointer approach to combine the lists in linear time
    while preserving the sorted order.

    Args:
        list1: The first sorted list.
        list2: The second sorted list.

    Returns:
        A new sorted list containing all elements from both input lists.
    """
    merged: list[T] = []
    i, j = 0, 0

    while i < len(list1) and j < len(list2):
        if list1[i] <= list2[j]:
            merged.append(list1[i])
            i += 1
        else:
            merged.append(list2[j])
            j += 1

    # Append any remaining elements from either list
    if i < len(list1):
        merged.extend(list1[i:])
    if j < len(list2):
        merged.extend(list2[j:])

    return merged
```

### Example Usage
```python
print(merge_sorted_lists([1, 3, 5], [2, 4, 6]))  # [1, 2, 3, 4, 5, 6]
print(merge_sorted_lists([], [1, 2, 3]))         # [1, 2, 3]
print(merge_sorted_lists([1, 2, 2], [2, 3]))     # [1, 2, 2, 2, 3]
```

### Complexity
- **Time Complexity:** $O(n + m)$, where $n$ and $m$ are the lengths of `list1` and `list2`.
- **Space Complexity:** $O(n + m)$ for the returned merged list.
{
  "candidates": [
    {
      "content": {
        "role": "model",
        "parts": [
          {
            "text": "```python\nfrom typing import TypeVar\n\nT = TypeVar(\"T\")\n\n\ndef merge_sorted_lists(list1: list[T], list2: list[T]) -> list[T]:\n    \"\"\"Merge two sorted lists into a single sorted list.\n\n    Uses a two-pointer approach to combine the lists in linear time\n    while preserving the sorted order.\n\n    Args:\n        list1: The first sorted list.\n        list2: The second sorted list.\n\n    Returns:\n        A new sorted list containing all elements from both input lists.\n    \"\"\"\n    merged: list[T] = []\n    i, j = 0, 0\n\n    while i < len(list1) and j < len(list2):\n        if list1[i] <= list2[j]:\n            merged.append(list1[i])\n            i += 1\n        else:\n            merged.append(list2[j])\n            j += 1\n\n    # Append any remaining elements from either list\n    if i < len(list1):\n        merged.extend(list1[i:])\n    if j < len(list2):\n        merged.extend(list2[j:])\n\n    return merged\n```\n\n### Example Usage\n```python\nprint(merge_sorted_lists([1, 3, 5], [2, 4, 6]))  # [1, 2, 3, 4, 5, 6]\nprint(merge_sorted_lists([], [1, 2, 3]))         # [1, 2, 3]\nprint(merge_sorted_lists([1, 2, 2], [2, 3]))     # [1, 2, 2, 2, 3]\n```\n\n### Complexity\n- **Time Complexity:** $O(n + m)$, where $n$ and $m$ are the lengths of `list1` and `list2`.\n- **Space Complexity:** $O(n + m)$ for the returned merged list.",
            "thoughtSignature": "AY89a18K+RfRuMGvBUZuuFZG6pLQI+YVqxyWyh6wpvNm/eE9rctLkx1fQFCMTwJRBg3sz6yTscGMrryBzRdyrrYZI2P/TSGCiYfBqc9elxTtGcjyI4kTqzL4OVehNMun70VHHMVh1FKbGyVkzqqQ6UPsoqUJdk3EWvN/MkzGdLiGWV7THyACKeP3hhUJ62BfPcRlBVxa33O6/pZMT4qKY6qbDRNL+Imwk1lvwF19/i63DnKor+nhL6PSpURvB50xpgloNsvvbR0OjD5K4JOKHz5TeRoi4ZMLGZsa81/toXHpVOBdCMFSCPH6iYuAjXmewEEh7QrnRh69tx/NWfknGNNnkV1dvnanxDndG5TmJ/ycnnyg9N37l3ormT+sw+ndeRbYpbPU/vfEE/v7ollJ3ZkZ0q2mG/xRsLyyLZatbAhWlvlqPF4Xl4vnLg=="
          }
        ]
      },
      "finishReason": "STOP"
    }
  ],
  "usageMetadata": {
    "promptTokenCount": 68,
    "candidatesTokenCount": 457,
    "totalTokenCount": 577,
    "trafficType": "ON_DEMAND",
    "promptTokensDetails": [
      {
        "modality": "TEXT",
        "tokenCount": 68
      }
    ],
    "candidatesTokensDetails": [
      {
        "modality": "TEXT",
        "tokenCount": 457
      }
    ],
    "thoughtsTokenCount": 52
  },
  "modelVersion": "gemini-4-hydrogen",
  "createTime": "2026-11-13T00:04:02.561753Z",
  "responseId": "8lP2atmkIrqH3dAPlNLEoA0"
}
Multi-turn Conversation — Continuing a multi-step coding conversation, typical of an agentic loop
const response = await env.AI.run(
  'google/gemini-4-hydrogen',
  {
    contents: [
      {
        parts: [{ text: 'I have a bug where my recursive fibonacci function is too slow for n=40.' }],
        role: 'user',
      },
      {
        parts: [
          {
            text: "That's expected with naive recursion since it recomputes overlapping subproblems exponentially. You can fix it with memoization or an iterative approach. Which would you like to see?",
          },
        ],
        role: 'model',
      },
      { parts: [{ text: 'Show me the memoized version.' }], role: 'user' },
    ],
  },
)
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-4-hydrogen",
  "input": {
    "contents": [
      {
        "parts": [
          {
            "text": "I have a bug where my recursive fibonacci function is too slow for n=40."
          }
        ],
        "role": "user"
      },
      {
        "parts": [
          {
            "text": "That'\''s expected with naive recursion since it recomputes overlapping subproblems exponentially. You can fix it with memoization or an iterative approach. Which would you like to see?"
          }
        ],
        "role": "model"
      },
      {
        "parts": [
          {
            "text": "Show me the memoized version."
          }
        ],
        "role": "user"
      }
    ]
  }
}'
Here is the memoized version in Python using a dictionary to store already-computed results:

```python
def fib(n, memo={}):
    if n in memo:
        return memo[n]
    if n <= 1:
        return n
    
    memo[n] = fib(n - 1, memo) + fib(n - 2, memo)
    return memo[n]
```

*(Note: Using a mutable default argument like `memo={}` is fine here since you want the cache to persist across calls, though if you want a fresh cache per top-level call, initialize `memo=None` and set `memo = {}` inside the function or use a wrapper.)*

If you are using Python 3.9+, you can also use the built-in `@cache` decorator to do the exact same thing automatically:

```python
from functools import cache

@cache
def fib(n):
    if n <= 1:
        return n
    return fib(n - 1) + fib(n - 2)
```

This brings the time complexity down from $O(2^n)$ to $O(n)$, so `fib(40)` will run almost instantaneously. Let me know if you need this in a different language.
{
  "candidates": [
    {
      "content": {
        "role": "model",
        "parts": [
          {
            "text": "Here is the memoized version in Python using a dictionary to store already-computed results:\n\n```python\ndef fib(n, memo={}):\n    if n in memo:\n        return memo[n]\n    if n <= 1:\n        return n\n    \n    memo[n] = fib(n - 1, memo) + fib(n - 2, memo)\n    return memo[n]\n```\n\n*(Note: Using a mutable default argument like `memo={}` is fine here since you want the cache to persist across calls, though if you want a fresh cache per top-level call, initialize `memo=None` and set `memo = {}` inside the function or use a wrapper.)*\n\nIf you are using Python 3.9+, you can also use the built-in `@cache` decorator to do the exact same thing automatically:\n\n```python\nfrom functools import cache\n\n@cache\ndef fib(n):\n    if n <= 1:\n        return n\n    return fib(n - 1) + fib(n - 2)\n```\n\nThis brings the time complexity down from $O(2^n)$ to $O(n)$, so `fib(40)` will run almost instantaneously. Let me know if you need this in a different language.",
            "thoughtSignature": "AY89a18H8Khrq9Yj7SsNNS6g4HVYt0H7fZMEL8mmJ7f0YdQSdeRcLw+kRrXLZub+RPHD5I4gGPxjHW09m8RUkuUoo2un+KRqC5VoVbitATuiXaeslC+dUC1G6SOqxm60+3FvyuRkB0rhS+a5sE2sXZkz4RucjXod3GffHCeUekvTyi1lCHbif7auicgE6Qey0+ni1CZbYnHx9cnvAjqMSvCtHvmAo4nRPU2AlAq/68hKL21ap3azNdjOZpR1HZAR3ow6ZIhXbuLFj94WeS+pBbH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S5U2BvFY198+76vSYXOmmfSH63xwK5Fp7yeoAljKvY7+0LXIBmNv/z91gye1No7ucdQ2YvJJDa4J9ad1KulJJLVOHk8cL2NxKhNomCw/e750Eqa7qKpoQKVcHOKaEs5D0zAIkOCAL6aFhMFbEtibWw9r3Hdyiq3M6rx8mwaV4fsS+If8nnamUIx1pu6VHahsAvtksOKw=="
          }
        ]
      },
      "finishReason": "STOP"
    }
  ],
  "usageMetadata": {
    "promptTokenCount": 101,
    "candidatesTokenCount": 284,
    "totalTokenCount": 642,
    "trafficType": "ON_DEMAND",
    "promptTokensDetails": [
      {
        "modality": "TEXT",
        "tokenCount": 101
      }
    ],
    "candidatesTokensDetails": [
      {
        "modality": "TEXT",
        "tokenCount": 284
      }
    ],
    "thoughtsTokenCount": 257
  },
  "modelVersion": "gemini-4-hydrogen",
  "createTime": "2026-11-13T00:04:06.452258Z",
  "responseId": "9lP2aqLNG7KC3dAPxpGXyA8"
}
Spatial Reasoning — A reasoning-heavy puzzle with the thinking level set to HIGH
const response = await env.AI.run(
  'google/gemini-4-hydrogen',
  {
    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: { thinkingConfig: { thinkingLevel: 'HIGH' } },
  },
)
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-4-hydrogen",
  "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": {
      "thinkingConfig": {
        "thinkingLevel": "HIGH"
      }
    }
  }
}'
When a cube is cut into 27 equal smaller cubes ($3 \times 3 \times 3$), the cubes with **exactly two red faces** are the ones located along the edges, excluding the corners. 

* A cube has **12 edges**.
* On each edge of 3 smaller cubes, the 2 corner cubes have three red faces, leaving **1 middle cube** per edge with two red faces.

$12 \text{ edges} \times 1 \text{ cube per edge} = \mathbf{12}$

There are **12** smaller cubes with exactly two red faces.
{
  "candidates": [
    {
      "content": {
        "role": "model",
        "parts": [
          {
            "text": "When a cube is cut into 27 equal smaller cubes ($3 \\times 3 \\times 3$), the cubes with **exactly two red faces** are the ones located along the edges, excluding the corners. \n\n* A cube has **12 edges**.\n* On each edge of 3 smaller cubes, the 2 corner cubes have three red faces, leaving **1 middle cube** per edge with two red faces.\n\n$12 \\text{ edges} \\times 1 \\text{ cube per edge} = \\mathbf{12}$\n\nThere are **12** smaller cubes with exactly two red faces.",
            "thoughtSignature": "AY89a1/jbphySqF95wQbjfNJxFENVKDTW7BFBd53L2yAGu3sMtum5II6q3tt1q52BxQWPQaGcgwJfeAmL42TxNyfiebY0WrWYhycKhTmbDaZoVnEYQsGZnQNu2zl3cNnF9Buwu16oERQBcLT7LNKNiBls7E8VGgECSvSqt8OhVrShx4WqBRL1l/3kTdA2nquXNji24guawQav2KrZgGbnSTe4mzraAZst2O1HEv08mL/ZTQsQZR8aVpenkDkKGoCGX0nnOfqV1n/RmVBTkbteiijDgc1F6xl/S28qB4UINJrPNApxgIgsHOga1K4MtMwFEMJ7BxoNN8r04l/F75i1J/SqwyPE1t4bQaHG4Gr9+QuoZEoLp9O3f3XrVWRTdmIvClXUODHbXN4N4mwW2t2FZ/82qUtDBOX/vjDfRoGIfjmq0k3yyDOM6Y+4io9r3/f0Tn0OPzVW6S4qd2X5gssKIj+Kd7A62M4pADdWAz3doC6xqrddLJI2p1DqR8V7LxPf6dhU6zmiEYdUUckWpC6kTaiT4gcQYjYZqDvqHeJEayqwT2eir8t4yolBIJsnwn+c2kCarmNAnjNl894KNNNsZvlYBshL1ksPvkP9cqzR5tWbQ+5t0AGDmWS3oseL0VmwkP94kP4T6ybOo2cG1YsnV8mQhRAPGNQE4wtSl/GtOfN5asRJuZE+vbxap+Z450C2Hg+Tigw+K0OzYspTxfOsPOu7n26HYFbYqX2/6K1ru4CL9dvrLmW5QMgIjB084xOGnipDrezUhRdbHBP2iQm7zdfpiDBIGI6unAA1BVwNpXqZ60C5W6BocYZpBHpTC7sP2bmglrB0X8GW+dgJae6ag8AESMGfL+NWp6m6tEgcGjRn9hfAqtFw4hfw+YgMev26Uw37LyIytKOwjhaaqK/6LTBmP2+puLSii8cxL/DtnIhX/yNlstAcc8JaVM6FLz5wnTVxpnH+IcuephR5fZIFL9pIyveetiiuX/aFSKQILL1NLhcKqDKhS9okZR4Ft68uTLHuM4ewZ/e02R1m/IEsUlnbBAWjqh4jZPJiFWEMXtTnnVH4X6R371H4oFWWGIdHs1ETEAq/bD3vjkk/Ov4RvHUxHXhuCQ="
          }
        ]
      },
      "finishReason": "STOP"
    }
  ],
  "usageMetadata": {
    "promptTokenCount": 62,
    "candidatesTokenCount": 135,
    "totalTokenCount": 460,
    "trafficType": "ON_DEMAND",
    "promptTokensDetails": [
      {
        "modality": "TEXT",
        "tokenCount": 62
      }
    ],
    "candidatesTokensDetails": [
      {
        "modality": "TEXT",
        "tokenCount": 135
      }
    ],
    "thoughtsTokenCount": 263
  },
  "modelVersion": "gemini-4-hydrogen",
  "createTime": "2026-11-13T00:04:10.338909Z",
  "responseId": "-lP2at3XFMqg3dAP9uPQiA4"
}

Parameters

Schema variant
toolConfig
modelVersion
string

API Schemas (Raw)

Input
Output

Was this helpful?