יצירת מטמון הקשר

כדי להשתמש במטמון ההקשר, צריך ליצור אותו. מטמון ההקשר שיוצרים מכיל כמות גדולה של נתונים שאפשר להשתמש בהם בכמה בקשות למודל Gemini. התוכן שנשמר במטמון מאוחסן באזור שבו נשלחת הבקשה ליצירת המטמון.

תוכן שמור במטמון יכול להיות כל אחד מסוגי ה-MIME שנתמכים על ידי מודלים מולטי-מודאליים של Gemini. לדוגמה, אפשר לשמור במטמון כמות גדולה של טקסט, אודיו או וידאו. אפשר לציין יותר מקובץ אחד לשמירה במטמון. למידע נוסף, אפשר לעיין בדרישות המדיה הבאות:

מציינים את התוכן שרוצים לשמור במטמון באמצעות blob, טקסט או נתיב לקובץ שמאוחסן בקטגוריה של Cloud Storage. אם גודל התוכן שאתם שומרים במטמון גדול מ-10MB, אתם צריכים לציין אותו באמצעות ה-URI של קובץ שמאוחסן בקטגוריה של Cloud Storage. הוראות ליצירת קטגוריה של Cloud Storage לאירוח הקובץ מפורטות במאמר יצירת קטגוריות.

תוכן שמור במטמון נשמר לזמן מוגבל. זמן התפוגה שמוגדר כברירת מחדל למטמון הקשר הוא 60 דקות אחרי שהוא נוצר. אם רוצים להגדיר זמן תפוגה אחר, אפשר לציין אותו באמצעות המאפיין ttl או expire_time כשיוצרים מטמון הקשר. אפשר גם לעדכן את מועד התפוגה של מטמון הקשר שלא פג תוקפו. מידע על הגדרת ttl ו-expire_time זמין במאמר עדכון זמן התפוגה.

אחרי שתוקף של מטמון הקשר פג, הוא כבר לא זמין. אם רוצים להתייחס לתוכן במטמון הקשר שפג התוקף שלו בבקשות להנחיות בעתיד, צריך ליצור מחדש את מטמון ההקשר.

תמיכה במיקום

אין תמיכה בשמירת מטמון של הקשר באזור סידני, אוסטרליה (australia-southeast1).

שמירת הקשר במטמון תומכת בנקודת הקצה הגלובלית.

תמיכה במפתח הצפנה

השימוש במטמון הקשר תומך במפתחות הצפנה בניהול הלקוח (CMEK), ומאפשר לכם לשלוט בהצפנה של הנתונים שנשמרים במטמון ולהגן על המידע הרגיש באמצעות מפתחות הצפנה שאתם מנהלים ובבעלותכם. כך אתם מקבלים שכבת אבטחה ותאימות נוספת.

פרטים נוספים זמינים בדוגמה.

אי אפשר להשתמש ב-CMEK כשמשתמשים בנקודת הקצה הגלובלית.

תמיכה ב-Access Transparency

שמירת מטמון של הקשר תומכת ב-Access Transparency.

דוגמה ליצירת מטמון הקשר

בדוגמאות הבאות מוסבר איך ליצור מטמון הקשר.

Python

התקנה

pip install --upgrade google-genai

מידע נוסף מופיע ב מאמרי העזרה בנושא SDK.

מגדירים משתני סביבה כדי להשתמש ב-Gen AI SDK עם Vertex AI:

# 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=us-central1
export GOOGLE_GENAI_USE_ENTERPRISE=True

from google import genai
from google.genai.types import Content, CreateCachedContentConfig, HttpOptions, Part

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

system_instruction = """
You are an expert researcher. You always stick to the facts in the sources provided, and never make up new facts.
Now look at these research papers, and answer the following questions.
"""

contents = [
    Content(
        role="user",
        parts=[
            Part.from_uri(
                file_uri="gs://cloud-samples-data/generative-ai/pdf/2312.11805v3.pdf",
                mime_type="application/pdf",
            ),
            Part.from_uri(
                file_uri="gs://cloud-samples-data/generative-ai/pdf/2403.05530.pdf",
                mime_type="application/pdf",
            ),
        ],
    )
]

content_cache = client.caches.create(
    model="gemini-2.5-flash",
    config=CreateCachedContentConfig(
        contents=contents,
        system_instruction=system_instruction,
        # (Optional) For enhanced security, the content cache can be encrypted using a Cloud KMS key
        # kms_key_name = "projects/.../locations/.../keyRings/.../cryptoKeys/..."
        display_name="example-cache",
        ttl="86400s",
    ),
)

print(content_cache.name)
print(content_cache.usage_metadata)
# Example response:
#   projects/111111111111/locations/.../cachedContents/1111111111111111111
#   CachedContentUsageMetadata(audio_duration_seconds=None, image_count=167,
#       text_count=153, total_token_count=43130, video_duration_seconds=None)

Go

כך מתקינים או מעדכנים את Go.

מידע נוסף מופיע ב מאמרי העזרה בנושא SDK.

מגדירים משתני סביבה כדי להשתמש ב-Gen AI SDK עם Vertex AI:

# 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=us-central1
export GOOGLE_GENAI_USE_ENTERPRISE=True

import (
	"context"
	"encoding/json"
	"fmt"
	"io"
	"time"

	genai "google.golang.org/genai"
)

// createContentCache shows how to create a content cache with an expiration parameter.
func createContentCache(w io.Writer) (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)
	}

	modelName := "gemini-2.5-flash"

	systemInstruction := "You are an expert researcher. You always stick to the facts " +
		"in the sources provided, and never make up new facts. " +
		"Now look at these research papers, and answer the following questions."

	cacheContents := []*genai.Content{
		{
			Parts: []*genai.Part{
				{FileData: &genai.FileData{
					FileURI:  "gs://cloud-samples-data/generative-ai/pdf/2312.11805v3.pdf",
					MIMEType: "application/pdf",
				}},
				{FileData: &genai.FileData{
					FileURI:  "gs://cloud-samples-data/generative-ai/pdf/2403.05530.pdf",
					MIMEType: "application/pdf",
				}},
			},
			Role: genai.RoleUser,
		},
	}
	config := &genai.CreateCachedContentConfig{
		Contents: cacheContents,
		SystemInstruction: &genai.Content{
			Parts: []*genai.Part{
				{Text: systemInstruction},
			},
		},
		DisplayName: "example-cache",
		TTL:         time.Duration(time.Duration.Seconds(86400)),
	}

	res, err := client.Caches.Create(ctx, modelName, config)
	if err != nil {
		return "", fmt.Errorf("failed to create content cache: %w", err)
	}

	cachedContent, err := json.MarshalIndent(res, "", "  ")
	if err != nil {
		return "", fmt.Errorf("failed to marshal cache info: %w", err)
	}

	// See the documentation: https://pkg.go.dev/google.golang.org/genai#CachedContent
	fmt.Fprintln(w, string(cachedContent))

	// Example response:
	// {
	//   "name": "projects/111111111111/locations/us-central1/cachedContents/1111111111111111111",
	//   "displayName": "example-cache",
	//   "model": "projects/111111111111/locations/us-central1/publishers/google/models/gemini-2.5-flash",
	//   "createTime": "2025-02-18T15:05:08.29468Z",
	//   "updateTime": "2025-02-18T15:05:08.29468Z",
	//   "expireTime": "2025-02-19T15:05:08.280828Z",
	//   "usageMetadata": {
	//     "imageCount": 167,
	//     "textCount": 153,
	//     "totalTokenCount": 43125
	//   }
	// }

	return res.Name, nil
}

Java

כך מתקינים או מעדכנים את Java.

מידע נוסף מופיע ב מאמרי העזרה בנושא SDK.

מגדירים משתני סביבה כדי להשתמש ב-Gen AI SDK עם Vertex AI:

# 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=us-central1
export GOOGLE_GENAI_USE_ENTERPRISE=True


import com.google.genai.Client;
import com.google.genai.types.CachedContent;
import com.google.genai.types.Content;
import com.google.genai.types.CreateCachedContentConfig;
import com.google.genai.types.HttpOptions;
import com.google.genai.types.Part;
import java.time.Duration;
import java.util.Optional;

public class ContentCacheCreateWithTextGcsPdf {

  public static void main(String[] args) {
    // TODO(developer): Replace these variables before running the sample.
    String modelId = "gemini-2.5-flash";
    contentCacheCreateWithTextGcsPdf(modelId);
  }

  // Creates a cached content using text and gcs pdfs files
  public static Optional<String> contentCacheCreateWithTextGcsPdf(String modelId) {
    // 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()) {

      // Set the system instruction
      Content systemInstruction =
          Content.fromParts(
              Part.fromText(
                  "You are an expert researcher. You always stick to the facts"
                      + " in the sources provided, and never make up new facts.\n"
                      + "Now look at these research papers, and answer the following questions."));

      // Set pdf files
      Content contents =
          Content.fromParts(
              Part.fromUri(
                  "gs://cloud-samples-data/generative-ai/pdf/2312.11805v3.pdf", "application/pdf"),
              Part.fromUri(
                  "gs://cloud-samples-data/generative-ai/pdf/2403.05530.pdf", "application/pdf"));

      // Configuration for cached content using pdfs files and text
      CreateCachedContentConfig config =
          CreateCachedContentConfig.builder()
              .systemInstruction(systemInstruction)
              .contents(contents)
              .displayName("example-cache")
              .ttl(Duration.ofSeconds(86400))
              .build();

      CachedContent cachedContent = client.caches.create(modelId, config);
      cachedContent.name().ifPresent(System.out::println);
      cachedContent.usageMetadata().ifPresent(System.out::println);
      // Example response:
      // projects/111111111111/locations/global/cachedContents/1111111111111111111
      // CachedContentUsageMetadata{audioDurationSeconds=Optional.empty, imageCount=Optional[167],
      // textCount=Optional[153], totalTokenCount=Optional[43125],
      // videoDurationSeconds=Optional.empty}
      return cachedContent.name();
    }
  }
}

Node.js

התקנה

npm install @google/genai

מידע נוסף מופיע ב מאמרי העזרה בנושא SDK.

מגדירים משתני סביבה כדי להשתמש ב-Gen AI SDK עם Vertex AI:

# 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=us-central1
export GOOGLE_GENAI_USE_ENTERPRISE=True


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

const GOOGLE_CLOUD_PROJECT = process.env.GOOGLE_CLOUD_PROJECT;
const GOOGLE_CLOUD_LOCATION = process.env.GOOGLE_CLOUD_LOCATION || 'global';
async function generateContentCache(
  projectId = GOOGLE_CLOUD_PROJECT,
  location = GOOGLE_CLOUD_LOCATION
) {
  const client = new GoogleGenAI({
    vertexai: true,
    project: projectId,
    location: location,
    httpOptions: {
      apiVersion: 'v1',
    },
  });

  const systemInstruction = `
  You are an expert researcher. You always stick to the facts in the sources provided, and never make up new facts.
  Now look at these research papers, and answer the following questions.
  `;

  const contents = [
    {
      role: 'user',
      parts: [
        {
          fileData: {
            fileUri:
              'gs://cloud-samples-data/generative-ai/pdf/2312.11805v3.pdf',
            mimeType: 'application/pdf',
          },
        },
        {
          fileData: {
            fileUri: 'gs://cloud-samples-data/generative-ai/pdf/2403.05530.pdf',
            mimeType: 'application/pdf',
          },
        },
      ],
    },
  ];

  const contentCache = await client.caches.create({
    model: 'gemini-2.5-flash',
    config: {
      contents: contents,
      systemInstruction: systemInstruction,
      displayName: 'example-cache',
      ttl: '86400s',
    },
  });

  console.log(contentCache);
  console.log(contentCache.name);

  // Example response:
  //  projects/111111111111/locations/us-central1/cachedContents/1111111111111111111
  //  CachedContentUsageMetadata(audio_duration_seconds=None, image_count=167,
  //  text_count=153, total_token_count=43130, video_duration_seconds=None)

  return contentCache.name;
}

REST

אפשר להשתמש ב-REST כדי ליצור מטמון הקשר באמצעות Agent Platform API לשליחת בקשת POST לנקודת הקצה של מודל בעל תוכן שיווקי. בדוגמה הבאה מוצג אופן היצירה של מטמון הקשר באמצעות קובץ שמאוחסן בקטגוריה של Cloud Storage.

לפני שמשתמשים בנתוני הבקשה, צריך להחליף את הנתונים הבאים:

  • PROJECT_ID: [מזהה הפרויקט](/resource-manager/docs/creating-managing-projects#identifiers). .
  • LOCATION: האזור שבו הבקשה תעובד ושבו התוכן ששמור במטמון מאוחסן. רשימת האזורים הנתמכים מופיעה כאן.
  • CACHE_DISPLAY_NAME: שם תצוגה בעל משמעות שיעזור לכם לתאר ולזהות כל מטמון הקשר.
  • MIME_TYPE: סוג ה-MIME של התוכן שרוצים לשמור במטמון.
  • CONTENT_TO_CACHE_URI: ה-URI של Cloud Storage של התוכן שרוצים לשמור במטמון.
  • MODEL_ID: המודל שמשמש לשמירת נתונים במטמון.

ה-method של ה-HTTP וכתובת ה-URL:

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

גוף בקשת JSON:

{
  "model": "projects/PROJECT_ID/locations/LOCATION/publishers/google/models/MODEL_ID",
  "displayName": "CACHE_DISPLAY_NAME",
  "contents": [{
    "role": "user",
      "parts": [{
        "fileData": {
          "mimeType": "MIME_TYPE",
          "fileUri": "CONTENT_TO_CACHE_URI"
        }
      }]
  },
  {
    "role": "model",
      "parts": [{
        "text": "This is sample text to demonstrate explicit caching."
      }]
  }]
}

כדי לשלוח את הבקשה עליכם לבחור אחת מהאפשרויות הבאות:

curl

שומרים את גוף הבקשה בקובץ בשם request.json ומריצים את הפקודה הבאה:

curl -X POST \
-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"

PowerShell

שומרים את גוף הבקשה בקובץ בשם request.json ומריצים את הפקודה הבאה:

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

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

אתם אמורים לקבל תגובת JSON שדומה לזו:

פקודת curl לדוגמה

LOCATION="us-central1"
MODEL_ID="gemini-2.5-flash"
PROJECT_ID="test-project"
MIME_TYPE="video/mp4"
CACHED_CONTENT_URI="gs://path-to-bucket/video-file-name.mp4"

curl -X POST \
-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 -d \
'{
  "model":"projects/${PROJECT_ID}/locations/${LOCATION}/publishers/google/models/${MODEL_ID}",
  "contents": [
    {
      "role": "user",
      "parts": [
        {
          "fileData": {
            "mimeType": "${MIME_TYPE}",
            "fileUri": "${CACHED_CONTENT_URI}"
          }
        }
      ]
    }
  ]
}'

יצירת מטמון הקשר עם CMEK

כדי להטמיע שמירת נתונים במטמון בהקשר של CMEK, צריך ליצור CMEK לפי ההוראות ולוודא שלחשבון השירות (P4SA) של Gemini Enterprise Agent Platform לכל מוצר ולכל פרויקט יש את ההרשאות הדרושות של Cloud Key Management Service CryptoKey Encrypter/Decrypter במפתח. האפשרות הזו מאפשרת ליצור ולנהל תוכן במטמון בצורה מאובטחת, וגם לבצע קריאות אחרות כמו {List, Update, Delete, Get} CachedContent(s) בלי לציין שוב ושוב מפתח KMS.

REST

אפשר להשתמש ב-REST כדי ליצור מטמון הקשר באמצעות Agent Platform API לשליחת בקשת POST לנקודת הקצה של מודל בעל תוכן שיווקי. בדוגמה הבאה מוצג אופן היצירה של מטמון הקשר באמצעות קובץ שמאוחסן בקטגוריה של Cloud Storage.

לפני שמשתמשים בנתוני הבקשה, צריך להחליף את הנתונים הבאים:

  • PROJECT_ID: .
  • LOCATION: האזור שבו הבקשה תעובד ושבו התוכן ששמור במטמון מאוחסן. רשימת האזורים הנתמכים מופיעה כאן.
  • MODEL_ID: gemini-2.0-flash-001.
  • CACHE_DISPLAY_NAME: שם תצוגה בעל משמעות שיעזור לכם לתאר ולזהות כל מטמון הקשר.
  • MIME_TYPE: סוג ה-MIME של התוכן שרוצים לשמור במטמון.
  • CACHED_CONTENT_URI: ה-URI של Cloud Storage של התוכן שרוצים לשמור במטמון.
  • KMS_KEY_NAME: שם מפתח Cloud KMS.

ה-method של ה-HTTP וכתובת ה-URL:

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

גוף בקשת JSON:

{
  "model": "projects/PROJECT_ID/locations/LOCATION/publishers/google/models/gemini-2.0-flash-001",
  "displayName": "CACHE_DISPLAY_NAME",
  "contents": [{
    "role": "user",
      "parts": [{
        "fileData": {
          "mimeType": "MIME_TYPE",
          "fileUri": "CONTENT_TO_CACHE_URI"
        }
      }]}],
    "encryptionSpec": {
      "kmsKeyName": "KMS_KEY_NAME"
    }
}

כדי לשלוח את הבקשה עליכם לבחור אחת מהאפשרויות הבאות:

curl

שומרים את גוף הבקשה בקובץ בשם request.json ומריצים את הפקודה הבאה:

curl -X POST \
-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"

PowerShell

שומרים את גוף הבקשה בקובץ בשם request.json ומריצים את הפקודה הבאה:

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

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

אתם אמורים לקבל תגובת JSON שדומה לזו:

פקודת curl לדוגמה

LOCATION="us-central1"
MODEL_ID="gemini-2.5-flash"
PROJECT_ID="test-project"
MIME_TYPE="video/mp4"
CACHED_CONTENT_URI="gs://path-to-bucket/video-file-name.mp4"
KMS_KEY_NAME="projects/${PROJECT_ID}/locations/{LOCATION}/keyRings/your-key-ring/cryptoKeys/your-key"

curl -X POST \
-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 -d \
'{

"model": "projects/{PROJECT_ID}}/locations/{LOCATION}/publishers/google/models/{MODEL_ID}",
  "contents" : [
    {
      "role": "user",
      "parts": [
        {
          "file_data": {
            "mime_type":"{MIME_TYPE}",
            "file_uri":"{CACHED_CONTENT_URI}"
          }
        }
      ]
    }
  ],
  "encryption_spec" :
  {
    "kms_key_name":"{KMS_KEY_NAME}"
  }
}'

GenAI SDK ל-Python

התקנה

pip install --upgrade google-genai

מידע נוסף מופיע במאמרי העזרה בנושא SDK.

מגדירים משתני סביבה כדי להשתמש ב-Gen AI SDK עם Gemini Enterprise Agent Platform:

# 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=us-central1
export GOOGLE_GENAI_USE_ENTERPRISE=True
import os
from google import genai
from google.genai.types import Content, CreateCachedContentConfig, HttpOptions, Part

os.environ['GOOGLE_CLOUD_PROJECT'] = 'vertexsdk'
os.environ['GOOGLE_CLOUD_LOCATION'] = 'us-central1'
os.environ['GOOGLE_GENAI_USE_ENTERPRISE'] = 'True'

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

system_instruction = """
You are an expert researcher. You always stick to the facts in the sources provided, and never make up new facts.
Now look at these research papers, and answer the following questions.
"""

contents = [
    Content(
        role="user",
        parts=[
            Part.from_uri(
                file_uri="gs://cloud-samples-data/generative-ai/pdf/2312.11805v3.pdf",
                mime_type="application/pdf",
            ),
            Part.from_uri(
                file_uri="gs://cloud-samples-data/generative-ai/pdf/2403.05530.pdf",
                mime_type="application/pdf",
            ),
        ],
    )
]

content_cache = client.caches.create(
    model="gemini-2.5-flash",
    config=CreateCachedContentConfig(
        contents=contents,
        system_instruction=system_instruction,
        display_name="example-cache",
        kms_key_name="projects/vertexsdk/locations/us-central1/keyRings/your-project/cryptoKeys/your-key",
        ttl="86400s",
    ),
)

print(content_cache.name)
print(content_cache.usage_metadata)

GenAI SDK for Go

איך מתקינים או מעדכנים את Gen AI SDK for Go

מידע נוסף מופיע במאמרי העזרה בנושא SDK.

מגדירים משתני סביבה כדי להשתמש ב-Gen AI SDK עם Gemini Enterprise Agent Platform:


import (
    "context"
    "encoding/json"
    "fmt"
    "io"

    genai "google.golang.org/genai"
)

// createContentCache shows how to create a content cache with an expiration parameter.
func createContentCache(w io.Writer) (string, error) {
    ctx := context.Background()

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

    modelName := "gemini-2.5-flash"

    systemInstruction := "You are an expert researcher. You always stick to the facts " +
        "in the sources provided, and never make up new facts. " +
        "Now look at these research papers, and answer the following questions."

    cacheContents := []*genai.Content{
        {
            Parts: []*genai.Part{
                {FileData: &genai.FileData{
                    FileURI:  "gs://cloud-samples-data/generative-ai/pdf/2312.11805v3.pdf",
                    MIMEType: "application/pdf",
                }},
                {FileData: &genai.FileData{
                    FileURI:  "gs://cloud-samples-data/generative-ai/pdf/2403.05530.pdf",
                    MIMEType: "application/pdf",
                }},
            },
            Role: "user",
        },
    }
    config := &genai.CreateCachedContentConfig{
        Contents: cacheContents,
        SystemInstruction: &genai.Content{
            Parts: []*genai.Part{
                {Text: systemInstruction},
            },
        },
        DisplayName: "example-cache",
        KmsKeyName:  "projects/vertexsdk/locations/us-central1/keyRings/your-project/cryptoKeys/your-key",
        TTL:         "86400s",
    }

    res, err := client.Caches.Create(ctx, modelName, config)
    if err != nil {
        return "", fmt.Errorf("failed to create content cache: %w", err)
    }

    cachedContent, err := json.MarshalIndent(res, "", "  ")
    if err != nil {
        return "", fmt.Errorf("failed to marshal cache info: %w", err)
    }

    // See the documentation: https://pkg.go.dev/google.golang.org/genai#CachedContent
    fmt.Fprintln(w, string(cachedContent))

    return res.Name, nil
}

המאמרים הבאים