עליך ליצור שמירת הקשר במטמון לפני שתוכל להשתמש בה. הקשר ששומרים במטמון מכיל כמות גדולה של נתונים שאפשר להשתמש בהם בכמה בקשות למודל Gemini. התוכן נשמר במטמון באזור שבו שלחתם את הבקשה ליצור את המטמון.
התוכן במטמון יכול להיות בכל אחד מסוגי ה-MIME שנתמכים במודלים המולטי-מודאליים של Gemini. לדוגמה, אתם יכולים לשמור במטמון כמות גדולה של טקסט, אודיו או וידאו. אפשר לציין יותר מקובץ אחד לשמירה במטמון. מידע נוסף:
כדי לציין את התוכן שרוצים לשמור במטמון, משתמשים ב-blob, בטקסט או בנתיב לקובץ שמאוחסן בקטגוריה של Cloud Storage. אם גודל התוכן שאתם שומרים במטמון גדול מ-10MB, אתם צריכים לציין אותו באמצעות URI של קובץ שמאוחסן בקטגוריה של Cloud Storage. במאמר יצירת קטגוריות מוסבר איך יוצרים קטגוריה של Cloud Storage לאירוח הקובץ.
לתוכן ששמור במטמון יש משך חיים מוגבל. כברירת מחדל, התוקף של שמירת ההקשר במטמון פג 60 דקות אחרי שהיא נוצרה. אם אתם רוצים זמן תפוגה אחר, אתם יכולים לציין אותו באמצעות המאפיין ttl או expire_time כשאתם יוצרים שמירת הקשר במטמון. אפשר גם לעדכן את זמן התפוגה של שמירת הקשר במטמון שלא פג. בקטע עדכון זמן התפוגה מוסבר איך מציינים את הערכים של ttl ו-expire_time.
אחרי שתוקף שמירת ההקשר במטמון פג, הוא לא זמין יותר. אם אתם רוצים להפנות לתוכן במטמון הקשר שפג תוקפו בבקשות עתידיות להנחיות, אתם צריכים ליצור מחדש את מטמון ההקשר.
תמיכה במיקום
אפשר לשמור הקשר במטמון בנקודת הקצה הגלובלית.
תמיכה במפתחות הצפנה
שמירת הקשר במטמון תומכת במפתחות הצפנה בניהול הלקוח (CMEK), כך שאתם יכולים לשלוט בהצפנה של הנתונים שנשמרו במטמון ולהגן על המידע הרגיש שלכם באמצעות מפתחות הצפנה שאתם מנהלים ובבעלותכם. כך אפשר להוסיף עוד שכבת אבטחה ותאימות.
לפרטים נוספים, עיינו בדוגמה.
אי אפשר להשתמש ב-CMEK כשמשתמשים בנקודת הקצה הגלובלית.
תמיכה ב-Access Transparency
שמירת הקשר במטמון תומכת ב-Access Transparency.
דוגמה ליצירת שמירת הקשר במטמון
בדוגמאות הבאות מוסבר איך ליצור שמירת הקשר במטמון.
Python
התקנה
pip install --upgrade google-genai
מידע נוסף זמין ב מאמרי העזרה של ה-SDK.
מגדירים משתני סביבה כדי להשתמש ב-Google 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
Go
מידע נוסף זמין ב מאמרי העזרה של ה-SDK.
מגדירים משתני סביבה כדי להשתמש ב-Google 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
Java
איך מתקינים או מעדכנים את Java
מידע נוסף זמין ב מאמרי העזרה של ה-SDK.
מגדירים משתני סביבה כדי להשתמש ב-Google 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
Node.js
התקנה
npm install @google/genai
מידע נוסף זמין ב מאמרי העזרה של ה-SDK.
מגדירים משתני סביבה כדי להשתמש ב-Google 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
REST
כדי ליצור שמירת הקשר במטמון באמצעות REST, אתם יכולים להשתמש ב-Agent Platform API כדי לשלוח בקשת POST לנקודת הקצה של המודל של בעל האפליקציה. בדוגמה הבאה מוסבר איך ליצור שמירת הקשר במטמון באמצעות קובץ שמאוחסן בקטגוריה של Cloud Storage.
לפני שמשתמשים בנתוני הבקשה, צריך להחליף את הנתונים הבאים:
- PROJECT_ID: מזהה הפרויקט.
- 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-3.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 בלי לציין שוב ושוב מפתח KMS.
REST
כדי ליצור שמירת הקשר במטמון באמצעות REST, אתם יכולים להשתמש ב-Agent Platform API כדי לשלוח בקשת POST לנקודת הקצה של המודל של בעל האפליקציה. בדוגמה הבאה מוסבר איך ליצור שמירת הקשר במטמון באמצעות קובץ שמאוחסן בקטגוריה של Cloud Storage.
לפני שמשתמשים בנתוני הבקשה, צריך להחליף את הנתונים הבאים:
- PROJECT_ID: .
- LOCATION: האזור שבו הבקשה תעובד והתוכן יישמר במטמון. כאן אפשר לראות את רשימת האזורים הנתמכים.
- MODEL_ID: gemini-3.5-flash.
- 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-3.5-flash",
"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-3.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.
מגדירים משתני סביבה כדי להשתמש ב-Google 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-3.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
איך מתקינים או מעדכנים את Google Gen AI SDK ל-Go
מידע נוסף זמין במאמרי העזרה של ה-SDK.
מגדירים משתני סביבה כדי להשתמש ב-Google 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-3.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
}