> ## AI Agent Context
> - Full documentation index: https://aistudio.google.com/llms.txt
> - Gemini Docs MCP server (consistent live info): https://gemini-api-docs-mcp.dev
> - Coding agent skills & setup guide: https://aistudio.google.com/docs/coding-agents.md

# Context caching

AI workflows often send the same tool schemas, instructions, documents, or history on every request. Implicit context caching reuses matching prompt prefixes with no setup calls or storage fees. Cached input tokens cost 95% less on Gemini 4 models and up to 90% less on Gemini 3 and 2.5 models.

{% callout type="note" %}
  The Interactions API and all Gemini 4 models support implicit caching only. To create explicit caches on Gemini 3 or Gemini 2.5 models, use the [GenerateContent API](/docs/caching?generate-content=true#explicit-caching).

{% /callout %}

To confirm that implicit caching is active and discounting your input tokens, check the usage metadata in the response. This example sends two consecutive requests asking different questions about the same policy manual, which exceeds Gemini 4's 4,096-token minimum. The first call populates the cache automatically. The second reuses the shared prefix and reads `usage.total_cached_tokens` to report the cache hit rate:

{% tabs %}
  {% tab label="Python" %}
  ```python
  from google import genai
  
  client = genai.Client()
  
  # Build a shared prefix above the 4,096-token minimum for Gemini 4.
  shared_manual = "\n".join(
      f"Policy {i}: Standard SLA response time is 4 hours for tier {i % 3 + 1} "
      "accounts. Escalate billing disputes above $5,000 to regional finance."
      for i in range(1, 351)
  )
  
  system_instruction = "Answer policy questions concisely using only the manual."
  
  # First call populates the implicit cache.
  client.interactions.create(
      model="gemini-4-neon",
      system_instruction=system_instruction,
      input=f"{shared_manual}\n\nQuestion: What is the SLA response time?",
  )
  
  # Second call reuses the identical prefix.
  second = client.interactions.create(
      model="gemini-4-neon",
      system_instruction=system_instruction,
      input=f"{shared_manual}\n\nQuestion: Where do billing disputes above $5,000 go?",
  )
  
  cached = second.usage.total_cached_tokens or 0
  total_in = second.usage.total_input_tokens or 1
  print(f"Answer: {second.output_text}")
  print(f"Cached tokens: {cached} / {total_in} ({cached / total_in:.1%})")
  ```

  {% /tab %}

  {% tab label="JavaScript" %}
  ```javascript
  import { GoogleGenAI } from "@google/genai";
  
  const ai = new GoogleGenAI({});
  
  // Build a shared prefix above the 4,096-token minimum for Gemini 4.
  const sharedManual = Array.from(
    { length: 350 },
    (_, idx) =>
      `Policy ${idx + 1}: Standard SLA response time is 4 hours for tier ${(idx % 3) + 1} accounts. Escalate billing disputes above $5,000 to regional finance.`
  ).join("\n");
  
  const systemInstruction = "Answer policy questions concisely using only the manual.";
  
  async function main() {
    // First call populates the implicit cache.
    await ai.interactions.create({
      model: "gemini-4-neon",
      system_instruction: systemInstruction,
      input: `${sharedManual}\n\nQuestion: What is the SLA response time?`,
    });
  
    // Second call reuses the identical prefix.
    const second = await ai.interactions.create({
      model: "gemini-4-neon",
      system_instruction: systemInstruction,
      input: `${sharedManual}\n\nQuestion: Where do billing disputes above $5,000 go?`,
    });
  
    const cached = second.usage?.total_cached_tokens ?? 0;
    const totalIn = second.usage?.total_input_tokens ?? 0;
    const hitRate = totalIn > 0 ? ((cached / totalIn) * 100).toFixed(1) : "0.0";
    console.log("Answer:", second.output_text);
    console.log(`Cached tokens: ${cached} / ${totalIn} (${hitRate}%)`);
  }
  
  await main();
  ```

  {% /tab %}

  {% tab label="REST" %}
  ```bash
  # Build a shared prefix above the 4,096-token minimum for Gemini 4.
  SHARED_MANUAL=$(awk 'BEGIN {
    for (i = 1; i <= 350; i++) {
      printf "Policy %d: Standard SLA response time is 4 hours for tier %d accounts. Escalate billing disputes above $5,000 to regional finance.\n", i, (i % 3) + 1
    }
  }')
  SYSTEM_INSTRUCTION="Answer policy questions concisely using only the manual."
  INPUT_1="${SHARED_MANUAL}"$'\n\n''Question: What is the SLA response time?'
  INPUT_2="${SHARED_MANUAL}"$'\n\n''Question: Where do billing disputes above $5,000 go?'
  
  # First call populates the implicit cache.
  jq -n \
    --arg sys "$SYSTEM_INSTRUCTION" \
    --arg input "$INPUT_1" \
    '{model: "gemini-4-neon", system_instruction: $sys, input: $input}' \
  | curl -s -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
      -H "x-goog-api-key: $GEMINI_API_KEY" \
      -H "Content-Type: application/json" \
      -d @- > /dev/null
  
  # Second call reuses the identical prefix.
  RESPONSE=$(jq -n \
    --arg sys "$SYSTEM_INSTRUCTION" \
    --arg input "$INPUT_2" \
    '{model: "gemini-4-neon", system_instruction: $sys, input: $input}' \
  | curl -s -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
      -H "x-goog-api-key: $GEMINI_API_KEY" \
      -H "Content-Type: application/json" \
      -d @-)
  
  echo "$RESPONSE" | jq '{
    cached_tokens: (.usage.total_cached_tokens // 0),
    total_input_tokens: (.usage.total_input_tokens // 0),
    hit_rate_pct: (if (.usage.total_input_tokens // 0) > 0 then (((.usage.total_cached_tokens // 0) / .usage.total_input_tokens) * 100 | round) else 0 end)
  }'
  ```

  {% /tab %}

{% /tabs %}

## Implicit caching  {% id="implicit-caching" %}

Implicit caching is enabled by default on all Gemini 2.5 and newer models. When a request matches a cached prefix above the model's token floor, the API bills those tokens at the cached input rate. You pay no storage fees and no cache-write surcharges.

| Model | Minimum input tokens | Cache discount | Storage fee |
| :--- | :--- | :--- | :--- |
| Gemini 4 Neon (`gemini-4-neon`) | 4,096 | 95% (all tiers) | None |
| Gemini 4 Carbon (`gemini-4-carbon`) | 4,096 | 95% (all tiers) | None |
| Gemini 4 Hydrogen (`gemini-4-hydrogen`) | 4,096 | 95% (all tiers) | None |
| Gemini 4 Argon (`gemini-4-argon`) | 4,096 | 95% (all tiers) | None |
| Gemini 3.8 Flash (`gemini-3.8-flash`) | 4,096 | 90% (all tiers) | None |
| Gemini 3.6 Flash (`gemini-3.6-flash`) | 4,096 | 90% (all tiers) | None |
| Gemini 3.1 Pro Preview (`gemini-3.1-pro-preview`) | 4,096 | 90% (Standard, Priority), 80% (Flex, Batch) | None |

Gemini 4, Gemini 3.8 Flash, and Gemini 3.6 Flash apply their full discount across Standard, Flex, Batch, and Priority tiers. On Gemini 3.1 Pro Preview, the 90% discount applies to Standard and Priority tiers. On Flex and Batch tiers, Gemini 3.1 Pro Preview bills cache hits at the Standard cached rate (80% off Flex and Batch input). For per-million-token rates across tiers, see [Pricing](/docs/pricing).

Implicit caching is opportunistic and offers no guaranteed retention window or cost savings. Independent stateless requests that share an identical prefix (such as system instructions, tool definitions, and reference documents followed by different user messages) can share an implicit cache entry on Gemini 4 without extending a full earlier request.

Implicit cache entries stay in memory (RAM), not on disk, and remain isolated to your project. Each entry has a best-effort time to live (TTL) of up to 24 hours, and the server evicts entries dynamically based on capacity and request routing. Because eviction is not predictable, sending priming or periodic keep-alive requests does not guarantee that a prefix stays cached. Send requests with shared prefixes close together in time.

In-memory caching works with [zero data retention (ZDR)](/docs/zdr) because cached prefixes are never stored at rest. On the Interactions API, setting `store=False` opts out of server-side conversation storage while still using implicit caching.

## Prompt-prefix engineering for Gemini 4  {% id="prompt-prefix-engineering" %}

Implicit caching matches your tokenized request from the first token onward. The first token that differs between two requests breaks the cache for everything after it. Knowing how Gemini 4 orders your request lets you keep static fields at the top and volatile fields at the end.

### How Gemini 4 orders your prompt  {% id="prompt-order" %}

Gemini 4 serializes every request in a fixed four-part order from top to bottom:

1. Model configuration and built-in server tools. Your `thinking_level` setting comes first. Generic structured output format instructions (when `response_format` enables JSON mode) and built-in server tools (`code_execution`, `google_search`, `url_context`, and agentic video understanding) follow next. The JSON schema itself is injected later in Step 4.
2. Tools and function declarations, placed before `system_instruction`. Built-in tools (`file_search`, `google_maps`, `computer_use`) come first. Next come `tool_search` and all deferred tools (`defer_loading: true`, including deferred MCP server tools), sorted alphabetically by `name`. Your non-deferred custom `function` declarations follow in array order. Non-deferred MCP server tools always append after all custom `function` declarations in server and tool order, rather than interleaving at their `tools` array position.
3. Developer `system_instruction`. Your system prompt lands after all tool declarations.
4. Conversation history and user `input`. Earlier turns appear oldest first, including uploaded files, model thoughts, tool calls, tool results, and text. Right before the latest user turn, the server injects your `response_format` JSON schema and any grounding context (time and location). Placing them there keeps Steps 1 through 3 and earlier turns cached even when the schema changes.

```none
Request prefix (top to bottom - first change breaks everything below it)
+--------------------------------------------------------------------------+
| 1. Model config and built-in server tools                                |
|    - thinking_level (first item, changing it busts 100% of the cache)    |
|    - Generic structured output format instructions (schema is in Step 4) |
|    - Built-in server tools (code_execution, google_search, url_context)  |
+--------------------------------------------------------------------------+
| 2. Tools and function declarations (serialized BEFORE system_instruction)|
|    - Built-in tools (file_search, google_maps, computer_use)             |
|    - tool_search + deferred tools (including MCP, sorted by name)        |
|    - Non-deferred custom function declarations (your array order)        |
|    - Non-deferred MCP server tools (appended after custom functions)     |
+--------------------------------------------------------------------------+
| 3. system_instruction                                                    |
|    - Static developer prompt (changing it busts turn history below)      |
+--------------------------------------------------------------------------+
| 4. Conversation history and user input                                   |
|    - Prior turns, oldest first (files, thoughts, tool calls/results)     |
|    - Injected response_format JSON schema (before latest user turn)      |
|    - Server-injected grounding context (before latest user turn)         |
|    - Latest user message (place volatile timestamps and IDs here)        |
+--------------------------------------------------------------------------+
```

Because `tools` serialize before `system_instruction`, adding, removing, or reordering non-deferred tools invalidates both `system_instruction` and the entire conversation history. Changing `system_instruction` invalidates the conversation history below it, leaving the tool prefix intact.

### What breaks your cache  {% id="cache-invalidators" %}

Most unexpected cache misses come from one of six avoidable request changes:

| Cache-breaking pattern | What gets invalidated | How to fix it |
| :--- | :--- | :--- |
| Changing `thinking_level` mid-session | 100% of the prompt prefix | Keep one `thinking_level` per session or route different levels to separate workflows. |
| Mutating or reordering non-deferred `tools` | Tools, `system_instruction`, and all turns | Keep the non-deferred `tools` array fixed and ordered, or use [tool retrieval](/docs/caching#tool-retrieval) with `defer_loading: true`. |
| Putting timestamps, UUIDs, or session IDs in `system_instruction` | `system_instruction` and all turns | Keep `system_instruction` static and pass volatile metadata in the final user message. |
| Reordering JSON keys or file arrays across calls | Everything from the first differing key or file onward | Sort JSON keys in a fixed order and keep uploaded files in the same order before the query. |
| Omitting `tools`, `system_instruction`, or `generation_config` on `previous_interaction_id` follow-ups | The prompt prefix changes on every turn | Resend identical `tools`, `system_instruction`, and `generation_config` on every turn. |
| Stripping `thought` or tool `signature` fields in stateless mode | Breaks turn replay and invalidates prefix matching | Append every model step from `interaction.steps` unchanged when `store=False`. |

### Structure a cache-friendly request  {% id="cache-friendly-request" %}

Keep `thinking_level`, `tools`, `system_instruction`, and shared reference text identical across requests. Put volatile fields like timestamps, request IDs, and the current question in the final content block of `input`:

{% tabs %}
  {% tab label="Python" %}
  ```python
  from datetime import datetime, timezone
  import uuid
  from google import genai
  
  client = genai.Client()
  
  # Keep tools, system_instruction, thinking_level, and reference text static.
  tools = [
      {
          "type": "function",
          "name": "lookup_order",
          "description": "Fetch status and shipping details for a customer order.",
          "parameters": {
              "type": "object",
              "properties": {
                  "order_id": {"type": "string"},
              },
              "required": ["order_id"],
          },
      }
  ]
  
  system_instruction = (
      "You are a support assistant. Follow the handbook rules and call lookup_order "
      "when a customer asks about a specific order."
  )
  
  generation_config = {"thinking_level": "high"}
  
  shared_handbook = "\n".join(
      f"Section {i}: Return window is 30 days for standard orders in region {i % 5 + 1}. "
      "Damaged shipments qualify for immediate replacement after order verification."
      for i in range(1, 351)
  )
  
  
  def ask_support(user_id: str, question: str):
      # Place volatile metadata at the end of input so the prefix stays stable.
      volatile_turn = (
          f"Request ID: {uuid.uuid4()}\n"
          f"Timestamp: {datetime.now(timezone.utc).isoformat()}\n"
          f"User ID: {user_id}\n"
          f"Question: {question}"
      )
      return client.interactions.create(
          model="gemini-4-neon",
          tools=tools,
          system_instruction=system_instruction,
          generation_config=generation_config,
          input=[
              {"type": "text", "text": shared_handbook},
              {"type": "text", "text": volatile_turn},
          ],
      )
  
  
  ask_support("user_101", "What is the standard return window?")
  second = ask_support("user_202", "Do damaged shipments get replaced?")
  
  print("Second call cached tokens:", second.usage.total_cached_tokens or 0)
  print("Second call answer:", second.output_text)
  ```

  {% /tab %}

  {% tab label="JavaScript" %}
  ```javascript
  import crypto from "node:crypto";
  import { GoogleGenAI } from "@google/genai";
  
  const ai = new GoogleGenAI({});
  
  // Keep tools, system_instruction, thinking_level, and reference text static.
  const tools = [
    {
      type: "function",
      name: "lookup_order",
      description: "Fetch status and shipping details for a customer order.",
      parameters: {
        type: "object",
        properties: {
          order_id: { type: "string" },
        },
        required: ["order_id"],
      },
    },
  ];
  
  const systemInstruction =
    "You are a support assistant. Follow the handbook rules and call lookup_order when a customer asks about a specific order.";
  
  const generationConfig = { thinking_level: "high" };
  
  const sharedHandbook = Array.from(
    { length: 350 },
    (_, idx) =>
      `Section ${idx + 1}: Return window is 30 days for standard orders in region ${(idx % 5) + 1}. Damaged shipments qualify for immediate replacement after order verification.`
  ).join("\n");
  
  async function askSupport(userId, question) {
    // Place volatile metadata at the end of input so the prefix stays stable.
    const volatileTurn = [
      `Request ID: ${crypto.randomUUID()}`,
      `Timestamp: ${new Date().toISOString()}`,
      `User ID: ${userId}`,
      `Question: ${question}`,
    ].join("\n");
  
    return ai.interactions.create({
      model: "gemini-4-neon",
      tools,
      system_instruction: systemInstruction,
      generation_config: generationConfig,
      input: [
        { type: "text", text: sharedHandbook },
        { type: "text", text: volatileTurn },
      ],
    });
  }
  
  async function main() {
    await askSupport("user_101", "What is the standard return window?");
    const second = await askSupport("user_202", "Do damaged shipments get replaced?");
  
    console.log("Second call cached tokens:", second.usage?.total_cached_tokens ?? 0);
    console.log("Second call answer:", second.output_text);
  }
  
  await main();
  ```

  {% /tab %}

  {% tab label="REST" %}
  ```bash
  SHARED_HANDBOOK=$(awk 'BEGIN {
    for (i = 1; i <= 350; i++) {
      printf "Section %d: Return window is 30 days for standard orders in region %d. Damaged shipments qualify for immediate replacement after order verification.\n", i, (i % 5) + 1
    }
  }')
  
  send_request() {
    local user_id="$1"
    local question="$2"
    local ts
    ts=$(date -u +"%Y-%m-%dT%H:%M:%SZ")
    local volatile_turn
    volatile_turn=$(printf "Timestamp: %s\nUser ID: %s\nQuestion: %s" "$ts" "$user_id" "$question")
  
    jq -n \
      --arg handbook "$SHARED_HANDBOOK" \
      --arg turn "$volatile_turn" \
      '{
        model: "gemini-4-neon",
        tools: [{
          type: "function",
          name: "lookup_order",
          description: "Fetch status and shipping details for a customer order.",
          parameters: {
            type: "object",
            properties: { order_id: { type: "string" } },
            required: ["order_id"]
          }
        }],
        system_instruction: "You are a support assistant. Follow the handbook rules and call lookup_order when a customer asks about a specific order.",
        generation_config: { thinking_level: "high" },
        input: [
          { type: "text", text: $handbook },
          { type: "text", text: $turn }
        ]
      }' \
    | curl -s -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
        -H "x-goog-api-key: $GEMINI_API_KEY" \
        -H "Content-Type: application/json" \
        -d @-
  }
  
  send_request "user_101" "What is the standard return window?" > /dev/null
  SECOND=$(send_request "user_202" "Do damaged shipments get replaced?")
  echo "$SECOND" | jq '{cached_tokens: (.usage.total_cached_tokens // 0), total_input_tokens: .usage.total_input_tokens}'
  ```

  {% /tab %}

{% /tabs %}

## Multi-turn and agent loops  {% id="multi-turn-agent-loops" %}

Long conversations and multi-step agents benefit most from implicit caching because each turn appends to the prior history. Multi-turn cache hit rates depend on how many tokens each follow-up adds and how stateful requests handle parameters.

### How Gemini 4 caches follow-up turns  {% id="multi-turn-delta-rule" %}

On Gemini 4, every request recomputes a trailing 2,050-token window at the standard input rate. Gemini caches the full previous request only when the new turn adds at least 2,050 tokens. Model output, thinking tokens, tool calls, tool results, and the new user message all count toward that 2,050-token threshold.

When a turn adds fewer than 2,050 tokens, cache lookup snaps back. Gemini reprocesses the last 2,050 tokens of the previous turn at the standard input rate. Most agent turns exceed 2,050 tokens through thinking and tool results, so the full prior turn stays cached.

| Scenario | Turn 1 total prefix | Tokens added before turn 2 | Turn 2 cached tokens | Turn 2 billed at standard rate |
| :--- | :--- | :--- | :--- | :--- |
| Short chat follow-up | 10,000 | 400 (short reply and user question) | 7,950 | 2,450 (last 2,050 of turn 1 plus 400 new) |
| Agent tool-use turn | 10,000 | 3,200 (thoughts, tool call, and tool result) | 10,000 | 3,200 (all 10,000 of turn 1 cached) |

### Stateful vs. stateless conversations  {% id="stateful-vs-stateless" %}

Implicit caching works in both [stateful](/docs/text-generation#multi-turn-conversations) (`previous_interaction_id`) and [stateless](/docs/text-generation#stateless-conversations) (`store=False`) modes. Use `previous_interaction_id` when server-side storage fits your privacy requirements, because server-managed state prevents client-side serialization drift.

The `previous_interaction_id` parameter persists conversation turns only. It does not persist `tools`, `system_instruction`, or `generation_config`. You must resend identical `tools`, `system_instruction`, and `generation_config` values on every follow-up turn, or the prompt prefix changes and breaks the cache.

{% tabs %}
  {% tab label="Python" %}
  ```python
  from google import genai
  
  client = genai.Client()
  
  tools = [
      {
          "type": "function",
          "name": "get_account_tier",
          "description": "Return the support tier for an account ID.",
          "parameters": {
              "type": "object",
              "properties": {"account_id": {"type": "string"}},
              "required": ["account_id"],
          },
      }
  ]
  system_instruction = "Answer account questions concisely using the policy handbook."
  generation_config = {"thinking_level": "high"}
  
  shared_handbook = "\n".join(
      f"Rule {i}: Enterprise accounts in group {i % 4 + 1} receive 24/7 phone support "
      "and quarterly architecture reviews."
      for i in range(1, 351)
  )
  
  # Turn 1 establishes the conversation and populates the cache.
  turn1 = client.interactions.create(
      model="gemini-4-neon",
      tools=tools,
      system_instruction=system_instruction,
      generation_config=generation_config,
      input=f"{shared_handbook}\n\nWhat support perks do enterprise accounts receive?",
  )
  
  # Turn 2 chains via previous_interaction_id AND resends identical config.
  turn2 = client.interactions.create(
      model="gemini-4-neon",
      previous_interaction_id=turn1.id,
      tools=tools,
      system_instruction=system_instruction,
      generation_config=generation_config,
      input="Do they also get quarterly architecture reviews?",
  )
  
  print("Turn 2 answer:", turn2.output_text)
  print("Turn 2 cached tokens:", turn2.usage.total_cached_tokens or 0)
  ```

  {% /tab %}

  {% tab label="JavaScript" %}
  ```javascript
  import { GoogleGenAI } from "@google/genai";
  
  const ai = new GoogleGenAI({});
  
  const tools = [
    {
      type: "function",
      name: "get_account_tier",
      description: "Return the support tier for an account ID.",
      parameters: {
        type: "object",
        properties: { account_id: { type: "string" } },
        required: ["account_id"],
      },
    },
  ];
  const systemInstruction = "Answer account questions concisely using the policy handbook.";
  const generationConfig = { thinking_level: "high" };
  
  const sharedHandbook = Array.from(
    { length: 350 },
    (_, idx) =>
      `Rule ${idx + 1}: Enterprise accounts in group ${(idx % 4) + 1} receive 24/7 phone support and quarterly architecture reviews.`
  ).join("\n");
  
  async function main() {
    // Turn 1 establishes the conversation and populates the cache.
    const turn1 = await ai.interactions.create({
      model: "gemini-4-neon",
      tools,
      system_instruction: systemInstruction,
      generation_config: generationConfig,
      input: `${sharedHandbook}\n\nWhat support perks do enterprise accounts receive?`,
    });
  
    // Turn 2 chains via previous_interaction_id AND resends identical config.
    const turn2 = await ai.interactions.create({
      model: "gemini-4-neon",
      previous_interaction_id: turn1.id,
      tools,
      system_instruction: systemInstruction,
      generation_config: generationConfig,
      input: "Do they also get quarterly architecture reviews?",
    });
  
    console.log("Turn 2 answer:", turn2.output_text);
    console.log("Turn 2 cached tokens:", turn2.usage?.total_cached_tokens ?? 0);
  }
  
  await main();
  ```

  {% /tab %}

  {% tab label="REST" %}
  ```bash
  SHARED_HANDBOOK=$(awk 'BEGIN {
    for (i = 1; i <= 350; i++) {
      printf "Rule %d: Enterprise accounts in group %d receive 24/7 phone support and quarterly architecture reviews.\n", i, (i % 4) + 1
    }
  }')
  
  BASE_CONFIG='{
    "model": "gemini-4-neon",
    "tools": [{
      "type": "function",
      "name": "get_account_tier",
      "description": "Return the support tier for an account ID.",
      "parameters": {
        "type": "object",
        "properties": { "account_id": { "type": "string" } },
        "required": ["account_id"]
      }
    }],
    "system_instruction": "Answer account questions concisely using the policy handbook.",
    "generation_config": { "thinking_level": "high" }
  }'
  
  TURN1_INPUT="${SHARED_HANDBOOK}"$'\n\n''What support perks do enterprise accounts receive?'
  
  # Turn 1 establishes the conversation and populates the cache.
  TURN1=$(jq -n --argjson base "$BASE_CONFIG" --arg input "$TURN1_INPUT" '$base + {input: $input}' \
  | curl -s -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
      -H "x-goog-api-key: $GEMINI_API_KEY" \
      -H "Content-Type: application/json" \
      -d @-)
  TURN1_ID=$(echo "$TURN1" | jq -r '.id')
  
  # Turn 2 chains via previous_interaction_id AND resends identical config.
  TURN2=$(jq -n \
    --argjson base "$BASE_CONFIG" \
    --arg prev "$TURN1_ID" \
    --arg input "Do they also get quarterly architecture reviews?" \
    '$base + {previous_interaction_id: $prev, input: $input}' \
  | curl -s -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
      -H "x-goog-api-key: $GEMINI_API_KEY" \
      -H "Content-Type: application/json" \
      -d @-)
  
  echo "$TURN2" | jq '{cached_tokens: (.usage.total_cached_tokens // 0), total_input_tokens: .usage.total_input_tokens}'
  ```

  {% /tab %}

{% /tabs %}

In stateless mode (`store=False`), you manage the turn history on your client and pass it in `input` on every call. Implicit caching still hits as long as every prior step stays byte-for-byte identical. Append every model-generated step from `interaction.steps` verbatim, keeping the `signature` field on `thought`, `tool_search_call`, `tool_search_result`, and `function_call` steps. See [Stateless conversations](/docs/text-generation#stateless-conversations) and [Stateless tool retrieval](/docs/tool-retrieval#stateless).

## Caching with tools, files, and long decode  {% id="feature-interactions" %}

Large agents combine tool retrieval, uploaded files, and long-decode continuations. Each feature interacts with your prompt prefix in a predictable way.

### Tool retrieval  {% id="tool-retrieval" %}

On the Interactions API (`v1beta`), [tool retrieval](/docs/tool-retrieval) lets you add `{"type": "tool_search"}` and mark large libraries of functions or MCP servers with `defer_loading: true`. Deferred tools emit only their `name` and `short_description` (or the first sentence of `description`) in the prefix, sorted alphabetically by `name`. Because the API sorts deferred tools alphabetically, changing their array order in your request does not break the cache.

When Gemini retrieves a deferred tool mid-conversation, the API appends the full schema inline in the conversation steps (`tool_search_call` and `tool_search_result`) instead of editing the top-level tool declaration block. Your earlier prefix stays cached across turns.

Watch out for the 4,096-token floor when adopting tool retrieval. Deferring dozens of verbose tool schemas shrinks your starting prompt, which can drop a medium-sized request below 4,096 tokens until later turns grow past the threshold.

### Files API and multimodal context  {% id="files-api" %}

Upload large documents, videos, audio clips, or images once with the [Files API](/docs/files). Files stay available for 48 hours at no storage cost, with limits of 2 GB per file and 20 GB per project. Use the Files API whenever a request exceeds 100 MB or a PDF exceeds 50 MB.

Place uploaded file references before your variable question text in `input`, and keep multiple files in the same order across requests. For example, send `{"type": "document", "uri": uploaded_file.uri, "mime_type": uploaded_file.mime_type}` before `{"type": "text", "text": question}` so the tokenized file forms a reusable prefix.

### Long decode continuations  {% id="long-decode" %}

When [long decode](/docs/long-decode) (`max_output_tokens > 65,536`) splits generation across multiple hops, each hop resends the prompt plus everything generated so far as input. Implicit caching discounts those repeated hop prefixes by 95% on every continuation hop.

If you manage hops in your own loop with `automatic_continuation=False` or direct REST, send the same `model`, `tools`, `system_instruction`, and `generation_config` on every hop to preserve cache hits.

Because `usage.total_input_tokens` sums input tokens across every hop, do not use it to measure context size or trigger context compaction. Instead, add `usage.initial_input_tokens` to `total_output_tokens` and `total_thought_tokens` (see [Count tokens in long decode](/docs/long-decode#count-tokens)).

## Migrating from explicit caching  {% id="migrating-from-explicit-caching" %}

Gemini 4 models and the Interactions API replace manual cache lifecycle management with implicit caching at a 95% input discount and zero storage cost. Follow this checklist to migrate from explicit `cachedContents` on `generateContent`:

* Remove `caches.create`, `caches.update`, `caches.list`, `caches.delete`, and TTL renewal logic.
* Move your cached `system_instruction`, `tools`, and uploaded file references into `interactions.create`, placing static content before variable queries.
* Switch your model ID to a Gemini 4 model such as `gemini-4-neon` and remove `cached_content=cache.name`.
* Keep `thinking_level`, `tools`, `system_instruction`, and file order identical across calls to maintain cache hits.
* Read `interaction.usage.total_cached_tokens` instead of `response.usage_metadata.cached_content_token_count`.

### Before: explicit caching with `generateContent` {% id="migration-before" %}

{% tabs %}
  {% tab label="Python" %}
  ```python
  from google import genai
  from google.genai import types
  
  client = genai.Client(http_options={"api_version": "v1beta"})
  
  uploaded_file = client.files.upload(file="manual.pdf")
  
  cache = client.caches.create(
      model="gemini-3.8-flash",
      config=types.CreateCachedContentConfig(
          system_instruction="Answer questions concisely using the uploaded manual.",
          contents=[uploaded_file],
          ttl="300s",
      ),
  )
  
  response = client.models.generate_content(
      model="gemini-3.8-flash",
      contents="Summarize the refund policy.",
      config=types.GenerateContentConfig(cached_content=cache.name),
  )
  
  print("Answer:", response.text)
  print("Cached tokens:", response.usage_metadata.cached_content_token_count or 0)
  ```

  {% /tab %}

  {% tab label="JavaScript" %}
  ```javascript
  import {
    GoogleGenAI,
    createPartFromUri,
    createUserContent,
  } from "@google/genai";
  
  const ai = new GoogleGenAI({ httpOptions: { apiVersion: "v1beta" } });
  
  async function main() {
    const uploadedFile = await ai.files.upload({
      file: "manual.pdf",
      config: { mimeType: "application/pdf" },
    });
  
    const cache = await ai.caches.create({
      model: "gemini-3.8-flash",
      config: {
        systemInstruction: "Answer questions concisely using the uploaded manual.",
        contents: createUserContent(
          createPartFromUri(uploadedFile.uri, uploadedFile.mimeType)
        ),
        ttl: "300s",
      },
    });
  
    const response = await ai.models.generateContent({
      model: "gemini-3.8-flash",
      contents: "Summarize the refund policy.",
      config: { cachedContent: cache.name },
    });
  
    console.log("Answer:", response.text);
    console.log("Cached tokens:", response.usageMetadata?.cachedContentTokenCount ?? 0);
  }
  
  await main();
  ```

  {% /tab %}

  {% tab label="REST" %}
  ```bash
  # Assumes manual.pdf was uploaded via the Files API and FILE_URI is set.
  CACHE_NAME=$(jq -n --arg uri "$FILE_URI" '{
    model: "models/gemini-3.8-flash",
    systemInstruction: { parts: [{ text: "Answer questions concisely using the uploaded manual." }] },
    contents: [{ role: "user", parts: [{ fileData: { mimeType: "application/pdf", fileUri: $uri } }] }],
    ttl: "300s"
  }' | curl -s -X POST "https://generativelanguage.googleapis.com/v1beta/cachedContents" \
    -H "x-goog-api-key: $GEMINI_API_KEY" \
    -H "Content-Type: application/json" \
    -d @- | jq -r '.name')
  
  jq -n --arg cache "$CACHE_NAME" '{
    cachedContent: $cache,
    contents: [{ role: "user", parts: [{ text: "Summarize the refund policy." }] }]
  }' | curl -s -X POST "https://generativelanguage.googleapis.com/v1beta/models/gemini-3.8-flash:generateContent" \
    -H "x-goog-api-key: $GEMINI_API_KEY" \
    -H "Content-Type: application/json" \
    -d @- | jq '{cached_tokens: (.usageMetadata.cachedContentTokenCount // 0)}'
  ```

  {% /tab %}

{% /tabs %}

### After: implicit caching on Gemini 4 with the Interactions API  {% id="migration-after" %}

{% tabs %}
  {% tab label="Python" %}
  ```python
  from google import genai
  
  client = genai.Client()
  
  uploaded_file = client.files.upload(file="manual.pdf")
  system_instruction = "Answer questions concisely using the uploaded manual."
  
  # Upload once, place the file URI before the variable query, and skip caches.create.
  for question in [
      "Summarize the refund policy.",
      "List the support escalation tiers.",
  ]:
      interaction = client.interactions.create(
          model="gemini-4-neon",
          system_instruction=system_instruction,
          input=[
              {
                  "type": "document",
                  "uri": uploaded_file.uri,
                  "mime_type": uploaded_file.mime_type,
              },
              {"type": "text", "text": question},
          ],
      )
      print("Answer:", interaction.output_text)
      print("Cached tokens:", interaction.usage.total_cached_tokens or 0)
  ```

  {% /tab %}

  {% tab label="JavaScript" %}
  ```javascript
  import { GoogleGenAI } from "@google/genai";
  
  const ai = new GoogleGenAI({});
  
  async function main() {
    const uploadedFile = await ai.files.upload({
      file: "manual.pdf",
      config: { mimeType: "application/pdf" },
    });
    const systemInstruction = "Answer questions concisely using the uploaded manual.";
  
    // Upload once, place the file URI before the variable query, and skip caches.create.
    const questions = [
      "Summarize the refund policy.",
      "List the support escalation tiers.",
    ];
  
    for (const question of questions) {
      const interaction = await ai.interactions.create({
        model: "gemini-4-neon",
        system_instruction: systemInstruction,
        input: [
          {
            type: "document",
            uri: uploadedFile.uri,
            mime_type: uploadedFile.mimeType,
          },
          { type: "text", text: question },
        ],
      });
      console.log("Answer:", interaction.output_text);
      console.log("Cached tokens:", interaction.usage?.total_cached_tokens ?? 0);
    }
  }
  
  await main();
  ```

  {% /tab %}

  {% tab label="REST" %}
  ```bash
  # Assumes manual.pdf was uploaded via the Files API and FILE_URI is set.
  # Place the file URI before the variable query and skip cachedContents.
  SYSTEM_INSTRUCTION="Answer questions concisely using the uploaded manual."
  
  for QUESTION in "Summarize the refund policy." "List the support escalation tiers."; do
    jq -n \
      --arg sys "$SYSTEM_INSTRUCTION" \
      --arg uri "$FILE_URI" \
      --arg q "$QUESTION" \
      '{
        model: "gemini-4-neon",
        system_instruction: $sys,
        input: [
          { type: "document", uri: $uri, mime_type: "application/pdf" },
          { type: "text", text: $q }
        ]
      }' \
    | curl -s -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
        -H "x-goog-api-key: $GEMINI_API_KEY" \
        -H "Content-Type: application/json" \
        -d @- \
    | jq '{cached_tokens: (.usage.total_cached_tokens // 0)}'
  done
  ```

  {% /tab %}

{% /tabs %}

## Measuring and debugging cache hit rates  {% id="debugging-cache-hits" %}

Track your cache hit ratio across requests by dividing `usage.total_cached_tokens` by `usage.total_input_tokens`. Log both fields on every turn so you catch prefix regressions early:

{% tabs %}
  {% tab label="Python" %}
  ```python
  from google import genai
  
  client = genai.Client()
  
  shared_context = "\n".join(
      f"Entry {i}: Service {i % 10} runs in us-central1 with 99.95% uptime SLA."
      for i in range(1, 401)
  )
  
  
  def log_cache_metrics(label: str, interaction):
      usage = interaction.usage
      total_in = usage.total_input_tokens or 0
      cached = usage.total_cached_tokens or 0
      uncached = total_in - cached
      hit_rate = (cached / total_in * 100) if total_in else 0.0
      print(
          f"{label}: cached={cached}, uncached={uncached}, "
          f"total_in={total_in}, hit_rate={hit_rate:.1f}%"
      )
  
  
  first = client.interactions.create(
      model="gemini-4-neon",
      input=f"{shared_context}\n\nWhich region hosts Service 3?",
  )
  log_cache_metrics("Call 1", first)
  
  second = client.interactions.create(
      model="gemini-4-neon",
      input=f"{shared_context}\n\nWhat is the uptime SLA for Service 7?",
  )
  log_cache_metrics("Call 2", second)
  ```

  {% /tab %}

  {% tab label="JavaScript" %}
  ```javascript
  import { GoogleGenAI } from "@google/genai";
  
  const ai = new GoogleGenAI({});
  
  const sharedContext = Array.from(
    { length: 400 },
    (_, idx) =>
      `Entry ${idx + 1}: Service ${(idx + 1) % 10} runs in us-central1 with 99.95% uptime SLA.`
  ).join("\n");
  
  function logCacheMetrics(label, interaction) {
    const totalIn = interaction.usage?.total_input_tokens ?? 0;
    const cached = interaction.usage?.total_cached_tokens ?? 0;
    const uncached = totalIn - cached;
    const hitRate = totalIn ? (cached / totalIn) * 100 : 0;
    console.log(
      `${label}: cached=${cached}, uncached=${uncached}, total_in=${totalIn}, hit_rate=${hitRate.toFixed(1)}%`
    );
  }
  
  async function main() {
    const first = await ai.interactions.create({
      model: "gemini-4-neon",
      input: `${sharedContext}\n\nWhich region hosts Service 3?`,
    });
    logCacheMetrics("Call 1", first);
  
    const second = await ai.interactions.create({
      model: "gemini-4-neon",
      input: `${sharedContext}\n\nWhat is the uptime SLA for Service 7?`,
    });
    logCacheMetrics("Call 2", second);
  }
  
  await main();
  ```

  {% /tab %}

  {% tab label="REST" %}
  ```bash
  SHARED_CONTEXT=$(awk 'BEGIN {
    for (i = 1; i <= 400; i++) {
      printf "Entry %d: Service %d runs in us-central1 with 99.95%% uptime SLA.\n", i, i % 10
    }
  }')
  
  call_and_measure() {
    local label="$1"
    local question="$2"
    local input="${SHARED_CONTEXT}"$'\n\n'"${question}"
  
    local resp
    resp=$(jq -n --arg input "$input" '{model: "gemini-4-neon", input: $input}' \
    | curl -s -X POST "https://generativelanguage.googleapis.com/v1beta/interactions" \
        -H "x-goog-api-key: $GEMINI_API_KEY" \
        -H "Content-Type: application/json" \
        -d @-)
  
    echo "$resp" | jq -r --arg label "$label" '
      (.usage.total_input_tokens // 0) as $in |
      (.usage.total_cached_tokens // 0) as $cached |
      "\($label): cached=\($cached), uncached=\($in - $cached), total_in=\($in), hit_rate=\((if $in > 0 then ($cached / $in * 1000 | round / 10) else 0 end))%"'
  }
  
  call_and_measure "Call 1" "Which region hosts Service 3?"
  call_and_measure "Call 2" "What is the uptime SLA for Service 7?"
  ```

  {% /tab %}

{% /tabs %}

If `total_cached_tokens` is `0` or lower than expected, check these five causes in order:

1. Input below the minimum token floor: Check `usage.total_input_tokens` or call `count_tokens`. Gemini 4 requires at least 4,096 input tokens before implicit caching activates.
2. Changing `thinking_level` or structured output mode: Changing `thinking_level` invalidates 100% of the prefix because it serializes first. Toggling `response_format` JSON mode (or switching between schema and no-schema output) invalidates the prefix from Step 1 onward. Changing only the JSON schema keeps Steps 1 through 3 and prior turns cached, breaking the prefix right before the latest user turn.
3. Mutating tools or `system_instruction`: Adding, removing, or reordering non-deferred `tools` busts both `system_instruction` and conversation history. Audit `system_instruction` and JSON tool schemas for timestamps, UUIDs, or unstable key order.
4. Missing parameters on `previous_interaction_id` turns: Verify that every stateful follow-up resends the same `tools`, `system_instruction`, and `generation_config`.
5. Short follow-up turns or cold traffic: When a follow-up adds fewer than 2,050 tokens, Gemini reprocesses the trailing 2,050 tokens at standard rates. Sparse requests may also land after in-memory cache eviction.

## Best practices  {% id="best-practices" %}

* Order every request from static to volatile: keep `thinking_level`, non-deferred `tools`, `system_instruction`, and shared files fixed, and put timestamps, request IDs, and user queries in the final message.
* Keep `previous_interaction_id` turns consistent by resending identical `tools`, `system_instruction`, and `generation_config` on every turn.
* Defer large tool libraries with `{"type": "tool_search"}` and `defer_loading: true` so loaded schemas append inline without invalidating your tool prefix.
* Upload reusable documents, audio, and video once with the [Files API](/docs/files) and place file URIs before variable text in a consistent order.
* Group requests that share a prefix close together in time to maximize hits before in-memory eviction.
* Monitor `total_cached_tokens / total_input_tokens` in production logs to catch prompt edits that lower your cache hit rate.

## Limitations  {% id="limitations" %}

* Best-effort retention: Implicit caches live in memory with a 24-hour maximum TTL and no cost-saving guarantee. Entries can evict earlier based on capacity and request routing, and priming or periodic keep-alive requests do not guarantee retention.
* Minimum token floor: Requests need at least 4,096 input tokens on Gemini 4 and Gemini 3 models, or 2,048 tokens on Gemini 2.5 models.
* Trailing 2,050-token window on Gemini 4: Every request recomputes at least a trailing 2,050-token window at standard input rates. When a multi-turn follow-up adds fewer than 2,050 tokens, Gemini reprocesses the last 2,050 tokens of the prior turn at standard input rates.
* No explicit caches on Gemini 4 or the Interactions API: To create explicit cache objects with custom TTLs, use Gemini 3 or Gemini 2.5 models on `generateContent`.
* Standard quotas apply: Cached tokens count 1:1 toward standard tokens per minute (TPM) limits and context window size, and count at the discounted cached token rate toward [spend-based rate limits](/docs/rate-limits#spend-rate-limits).

## What's next  {% id="whats-next" %}

* Compare per-model cached input rates in [Pricing](/docs/pricing).
* Learn how to create explicit caches on Gemini 3 and Gemini 2.5 in [GenerateContent API context caching](/docs/caching?generate-content=true#explicit-caching).
* Shrink large tool catalogs without breaking prefixes with [Tool retrieval](/docs/tool-retrieval).
* Run multi-hop reasoning past 64K tokens with [Long decode](/docs/long-decode).
* Upload reusable media once using the [Files API](/docs/files).
* Review privacy and `store=False` controls in [Zero data retention](/docs/zdr).
* Estimate prompt lengths before sending requests in [Understand and count tokens](/docs/tokens).

