コンテキスト キャッシュを更新する

コンテキスト キャッシュが期限切れになる時期は更新できます。コンテキスト キャッシュのデフォルトの有効期限は、作成時刻から 60 分後です。コンテキスト キャッシュは、期限切れになるとガベージ コレクションで削除されるため、使用することも更新することもできなくなります。期限切れになっていないコンテキスト キャッシュの有効期限を更新するには、次のいずれかのプロパティを更新します。

  • ttl - キャッシュの作成、または ttl の更新からキャッシュが期限切れになるまでの時間を秒単位およびナノ秒単位で指定します。ttl を設定すると、キャッシュの expireTime が更新されます。

  • expire_time - コンテキスト キャッシュが期限切れになる絶対日時を Timestamp で指定します。

ttl パラメータを使用してコンテキスト キャッシュを更新する

有効期限を 3,600 秒更新する curl コマンドの例を次に示します。

Python

インストール

pip install --upgrade google-genai

詳しくは、SDK リファレンス ドキュメントをご覧ください。

Vertex AI で Gen AI SDK を使用するための環境変数を設定します。

# Replace the `GOOGLE_CLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION` values
# with appropriate values for your project.
export GOOGLE_CLOUD_PROJECT=GOOGLE_CLOUD_PROJECT
export GOOGLE_CLOUD_LOCATION=global
export GOOGLE_GENAI_USE_VERTEXAI=True

from datetime import datetime as dt
from datetime import timezone as tz
from datetime import timedelta

from google import genai
from google.genai.types import HttpOptions, UpdateCachedContentConfig

client = genai.Client(http_options=HttpOptions(api_version="v1"))

# Get content cache by name
# cache_name = "projects/.../locations/.../cachedContents/1111111111111111111"
content_cache = client.caches.get(name=cache_name)
print("Expire time", content_cache.expire_time)
# Example response
#   Expire time 2025-02-20 15:50:18.434482+00:00

# Update expire time using TTL
content_cache = client.caches.update(
    name=cache_name, config=UpdateCachedContentConfig(ttl="36000s")
)
time_diff = content_cache.expire_time - dt.now(tz.utc)
print("Expire time(after update):", content_cache.expire_time)
print("Expire time(in seconds):", time_diff.seconds)
# Example response
#   Expire time(after update): 2025-02-14 01:51:42.571696+00:00
#   Expire time(in seconds): 35999

# Update expire time using specific time stamp
next_week_utc = dt.now(tz.utc) + timedelta(days=7)
content_cache = client.caches.update(
    name=cache_name, config=UpdateCachedContentConfig(expireTime=next_week_utc)
)
print("Expire time(after update):", content_cache.expire_time)
# Example response
#   Expire time(after update): 2025-02-20 15:51:42.614968+00:00

Go

Go をインストールまたは更新する方法について学びます。

詳しくは、SDK リファレンス ドキュメントをご覧ください。

Vertex AI で Gen AI SDK を使用するための環境変数を設定します。

# Replace the `GOOGLE_CLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION` values
# with appropriate values for your project.
export GOOGLE_CLOUD_PROJECT=GOOGLE_CLOUD_PROJECT
export GOOGLE_CLOUD_LOCATION=global
export GOOGLE_GENAI_USE_VERTEXAI=True

import (
	"context"
	"fmt"
	"io"
	"time"

	genai "google.golang.org/genai"
)

// updateContentCache shows how to update content cache expiration time.
func updateContentCache(w io.Writer, cacheName string) error {
	ctx := context.Background()

	client, err := genai.NewClient(ctx, &genai.ClientConfig{
		HTTPOptions: genai.HTTPOptions{APIVersion: "v1"},
	})
	if err != nil {
		return fmt.Errorf("failed to create genai client: %w", err)
	}

	// Update expire time using TTL
	resp, err := client.Caches.Update(ctx, cacheName, &genai.UpdateCachedContentConfig{
		TTL: time.Duration(time.Duration.Seconds(36000)),
	})
	if err != nil {
		return fmt.Errorf("failed to update content cache exp. time with TTL: %w", err)
	}

	fmt.Fprintf(w, "Cache expires in: %s\n", time.Until(resp.ExpireTime))
	// Example response:
	// Cache expires in: 10h0m0.005875s

	// Update expire time using specific time stamp
	inSevenDays := time.Now().Add(7 * 24 * time.Hour)
	resp, err = client.Caches.Update(ctx, cacheName, &genai.UpdateCachedContentConfig{
		ExpireTime: inSevenDays,
	})
	if err != nil {
		return fmt.Errorf("failed to update content cache expire time: %w", err)
	}

	fmt.Fprintf(w, "Cache expires in: %s\n", time.Until(resp.ExpireTime))
	// Example response:
	// Cache expires in: 167h59m59.80327s

	return nil
}

Java

Java をインストールまたは更新します。

詳しくは、SDK リファレンス ドキュメントをご覧ください。

Vertex AI で Gen AI SDK を使用するための環境変数を設定します。

# Replace the `GOOGLE_CLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION` values
# with appropriate values for your project.
export GOOGLE_CLOUD_PROJECT=GOOGLE_CLOUD_PROJECT
export GOOGLE_CLOUD_LOCATION=global
export GOOGLE_GENAI_USE_VERTEXAI=True


import com.google.genai.Client;
import com.google.genai.types.CachedContent;
import com.google.genai.types.HttpOptions;
import com.google.genai.types.UpdateCachedContentConfig;
import java.time.Duration;
import java.time.Instant;
import java.time.temporal.ChronoUnit;

public class ContentCacheUpdate {

  public static void main(String[] args) {
    // TODO(developer): Replace these variables before running the sample.
    // E.g cacheName = "projects/111111111111/locations/global/cachedContents/1111111111111111111"
    String cacheName = "your-cache-name";
    contentCacheUpdate(cacheName);
  }

  // Updates the cache using the specified cache resource name
  public static void contentCacheUpdate(String cacheName) {

    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests.
    try (Client client =
        Client.builder()
            .location("global")
            .vertexAI(true)
            .httpOptions(HttpOptions.builder().apiVersion("v1").build())
            .build()) {

      // Get info of the cached content
      CachedContent cachedContent = client.caches.get(cacheName, null);

      cachedContent.expireTime()
          .ifPresent(expireTime -> System.out.println("Expire time: " + expireTime));
      // Example response
      // Expire time: 2025-07-29T23:39:49.227291Z

      // Update expire time using TTL
      CachedContent updatedCachedContent =
          client.caches.update(
              cacheName,
              UpdateCachedContentConfig.builder().ttl(Duration.ofSeconds(36000)).build());

      updatedCachedContent.expireTime()
          .ifPresent(expireTime -> System.out.println("Expire time after update: " + expireTime));
      // Example response
      // Expire time after update: 2025-07-30T08:40:33.537205Z

      // Update expire time using specific time stamp
      Instant nextWeek = Instant.now().plus(7, ChronoUnit.DAYS);
      updatedCachedContent =
          client.caches.update(
              cacheName, UpdateCachedContentConfig.builder().expireTime(nextWeek).build());

      updatedCachedContent
          .expireTime()
          .ifPresent(expireTime -> System.out.println("Expire time after update: " + expireTime));
      // Example response
      // Expire time after update: 2025-08-05T22:40:33.713988900Z

      System.out.println("Updated cache: " + cacheName);
    }
  }
}

Node.js

インストール

npm install @google/genai

詳しくは、SDK リファレンス ドキュメントをご覧ください。

Vertex AI で Gen AI SDK を使用するための環境変数を設定します。

# Replace the `GOOGLE_CLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION` values
# with appropriate values for your project.
export GOOGLE_CLOUD_PROJECT=GOOGLE_CLOUD_PROJECT
export GOOGLE_CLOUD_LOCATION=global
export GOOGLE_GENAI_USE_VERTEXAI=True

const {GoogleGenAI} = require('@google/genai');
const {DateTime} = require('luxon');

const GOOGLE_CLOUD_PROJECT = process.env.GOOGLE_CLOUD_PROJECT;
const GOOGLE_CLOUD_LOCATION = process.env.GOOGLE_CLOUD_LOCATION || 'global';

async function updateContentCache(
  projectId = GOOGLE_CLOUD_PROJECT,
  location = GOOGLE_CLOUD_LOCATION,
  cacheName = 'example-cache'
) {
  const client = new GoogleGenAI({
    vertexai: true,
    project: projectId,
    location: location,
    httpOptions: {
      apiVersion: 'v1',
    },
  });

  let contentCache = await client.caches.get({
    name: cacheName,
  });

  console.log('Expire time', contentCache.expireTime);

  contentCache = await client.caches.update({
    name: cacheName,
    config: {
      ttl: '36000s',
    },
  });

  const expireTime = DateTime.fromISO(contentCache.expireTime, {zone: 'utc'});
  const now = DateTime.utc();
  const timeDiff = expireTime.diff(now, ['seconds']);

  console.log('Expire time (after update):', expireTime.toISO());
  console.log('Expire time (in seconds):', Math.floor(timeDiff.seconds));

  const nextWeekUtc = DateTime.utc().plus({days: 7});
  console.log('Next week (UTC):', nextWeekUtc.toISO());

  contentCache = await client.caches.update({
    name: cacheName,
    config: {
      expireTime: nextWeekUtc,
    },
  });

  console.log('Expire time (after update):', contentCache.expireTime);
  return contentCache;
}
// Example response
//    Expire time(after update): 2025-02-20 15:51:42.614968+00:00

REST

REST を使用してコンテキスト キャッシュを作成または更新するには、Vertex AI API を使用してパブリッシャー モデル エンドポイントに PATCH リクエストを送信します。次の例は、ttl パラメータを使用して有効期限を更新する方法を示しています。

リクエストのデータを使用する前に、次のように置き換えます。

HTTP メソッドと URL:

PATCH https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/cachedContents/CACHE_ID

リクエストの本文(JSON):

{
  "seconds":"SECONDS",
  "nanos":"NANOSECONDS"
}

リクエストを送信するには、次のいずれかのオプションを選択します。

curl

リクエスト本文を request.json という名前のファイルに保存して、次のコマンドを実行します。

curl -X PATCH \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/cachedContents/CACHE_ID"

PowerShell

リクエスト本文を request.json という名前のファイルに保存して、次のコマンドを実行します。

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method PATCH `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/cachedContents/CACHE_ID" | Select-Object -Expand Content

次のような JSON レスポンスが返されます。

curl コマンドの例

PROJECT_ID="PROJECT_ID"
LOCATION="us-central1"
CACHE_ID="CACHE_ID"

curl \
-X PATCH \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json"\
"https://${LOCATION}-aiplatform.googleapis.com/v1/projects/${PROJECT_ID}/locations/${LOCATION}/cachedContents/${CACHE_ID}" -d \
'{
   "ttl": {"seconds":"3600","nanos":"0"}
}'

expire_time パラメータを使用してコンテキスト キャッシュを更新する

expire_time パラメータを使用して有効期限を 2024 年 6 月 30 日午前 9 時に更新する curl コマンドの例を次に示します。

REST

REST を使用してコンテキスト キャッシュを作成または更新するには、Vertex AI API を使用してパブリッシャー モデル エンドポイントに PATCH リクエストを送信します。次の例は、expire_time パラメータを使用して有効期限を更新する方法を示しています。

リクエストのデータを使用する前に、次のように置き換えます。

HTTP メソッドと URL:

PATCH https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/cachedContents/CACHE_ID

リクエストの本文(JSON):

{
   "expire_time":"EXPIRE_TIME"
}

リクエストを送信するには、次のいずれかのオプションを選択します。

curl

リクエスト本文を request.json という名前のファイルに保存して、次のコマンドを実行します。

curl -X PATCH \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/cachedContents/CACHE_ID"

PowerShell

リクエスト本文を request.json という名前のファイルに保存して、次のコマンドを実行します。

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method PATCH `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/cachedContents/CACHE_ID" | Select-Object -Expand Content

次のような JSON レスポンスが返されます。

curl コマンドの例

PROJECT_ID="PROJECT_ID"
LOCATION="us-central1"
CACHE_ID="CACHE_ID"

curl \
-X PATCH \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json"\
"https://${LOCATION}-aiplatform.googleapis.com/v1/projects/${PROJECT_ID}/locations/${LOCATION}/cachedContents/${CACHE_ID}" -d \
'{
   "expire_time":"2024-06-30T09:00:00.000000Z"
}'

次のステップ