Caching

Zapisywanie kontekstu w pamięci podręcznej umożliwia zapisywanie i ponowne wykorzystywanie wstępnie obliczonych tokenów wejściowych, których chcesz używać wielokrotnie, np. gdy zadajesz różne pytania dotyczące tego samego pliku multimedialnego. W zależności od sposobu użycia może to przynieść oszczędności kosztów i czasu. Szczegółowe wprowadzenie znajdziesz w przewodniku Buforowanie kontekstu.

Metoda: cachedContents.create

Tworzy zasób CachedContent.

Punkt końcowy

post https://generativelanguage.googleapis.com/v1beta/cachedContents

Treść żądania

Treść żądania zawiera wystąpienie elementu CachedContent.

Pola
contents[] object (Content)

Opcjonalnie. Tylko dane wejściowe. Niezmienne. Treść do zapisania w pamięci podręcznej.

tools[] object (Tool)

Opcjonalnie. Tylko dane wejściowe. Niezmienne. Lista Tools, których model może użyć do wygenerowania następnej odpowiedzi.

expiration Union type
Określa, kiedy ten zasób wygaśnie. Pole expiration może mieć tylko jedną z tych wartości:
expireTime string (Timestamp format)

Sygnatura czasowa UTC wskazująca, kiedy zasób jest uznawany za nieaktualny. Jest zawsze podawana na wyjściu niezależnie od tego, co zostało wysłane na wejściu.

Korzysta ze standardu RFC 3339, w którym wygenerowane dane wyjściowe są zawsze znormalizowane do formatu Z i zawierają 0, 3, 6 lub 9 cyfr po przecinku. Akceptowane są też przesunięcia inne niż „Z”. Przykłady: "2014-10-02T15:01:23Z", "2014-10-02T15:01:23.045123456Z" lub "2014-10-02T15:01:23+05:30".

ttl string (Duration format)

Tylko dane wejściowe. Nowy czas życia tego zasobu (tylko dane wejściowe).

Czas trwania w sekundach z maksymalnie 9 miejscami po przecinku, zakończony znakiem „s”. Przykład: "3.5s".

displayName string

Opcjonalnie. Niezmienne. Wygenerowana przez użytkownika nazwa wyświetlana zapisanych w pamięci podręcznej treści. Maksymalnie 128 znaków Unicode.

model string

Wymagane. Niezmienne. Nazwa Model, która ma być używana w przypadku treści w pamięci podręcznej. Format: models/{model}

systemInstruction object (Content)

Opcjonalnie. Tylko dane wejściowe. Niezmienne. Instrukcja systemowa ustawiona przez dewelopera. Obecnie tylko tekst.

toolConfig object (ToolConfig)

Opcjonalnie. Tylko dane wejściowe. Niezmienne. Konfiguracja narzędzia Ta konfiguracja jest udostępniana wszystkim narzędziom.

Przykładowe żądanie

Podstawowe

Python

from google import genai
from google.genai import types

client = genai.Client()
document = client.files.upload(file=media / "a11.txt")
model_name = "gemini-3.7-flash"

cache = client.caches.create(
    model=model_name,
    config=types.CreateCachedContentConfig(
        contents=[document],
        system_instruction="You are an expert analyzing transcripts.",
    ),
)
print(cache)

response = client.models.generate_content(
    model=model_name,
    contents="Please summarize this transcript",
    config=types.GenerateContentConfig(cached_content=cache.name),
)
print(response.text)

Node.js

// Make sure to include the following import:
// import {GoogleGenAI} from '@google/genai';
const ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });
const filePath = path.join(media, "a11.txt");
const document = await ai.files.upload({
  file: filePath,
  config: { mimeType: "text/plain" },
});
console.log("Uploaded file name:", document.name);
const modelName = "gemini-3.7-flash";

const contents = [
  createUserContent(createPartFromUri(document.uri, document.mimeType)),
];

const cache = await ai.caches.create({
  model: modelName,
  config: {
    contents: contents,
    systemInstruction: "You are an expert analyzing transcripts.",
  },
});
console.log("Cache created:", cache);

const response = await ai.models.generateContent({
  model: modelName,
  contents: "Please summarize this transcript",
  config: { cachedContent: cache.name },
});
console.log("Response text:", response.text);

Go

ctx := context.Background()
client, err := genai.NewClient(ctx, &genai.ClientConfig{
	APIKey:  os.Getenv("GEMINI_API_KEY"), 
	Backend: genai.BackendGeminiAPI,
})
if err != nil {
	log.Fatal(err)
}

modelName := "gemini-3.7-flash"
document, err := client.Files.UploadFromPath(
	ctx, 
	filepath.Join(getMedia(), "a11.txt"), 
	&genai.UploadFileConfig{
		MIMEType : "text/plain",
	},
)
if err != nil {
	log.Fatal(err)
}
parts := []*genai.Part{
	genai.NewPartFromURI(document.URI, document.MIMEType),
}
contents := []*genai.Content{
	genai.NewContentFromParts(parts, genai.RoleUser),
}
cache, err := client.Caches.Create(ctx, modelName, &genai.CreateCachedContentConfig{
	Contents: contents,
	SystemInstruction: genai.NewContentFromText(
		"You are an expert analyzing transcripts.", genai.RoleUser,
	),
})
if err != nil {
	log.Fatal(err)
}
fmt.Println("Cache created:")
fmt.Println(cache)

// Use the cache for generating content.
response, err := client.Models.GenerateContent(
	ctx,
	modelName,
	genai.Text("Please summarize this transcript"),
	&genai.GenerateContentConfig{
		CachedContent: cache.Name,
	},
)
if err != nil {
	log.Fatal(err)
}
printResponse(response)

Muszla

wget https://storage.googleapis.com/generativeai-downloads/data/a11.txt
echo '{
  "model": "models/gemini-1.5-flash-001",
  "contents":[
    {
      "parts":[
        {
          "inline_data": {
            "mime_type":"text/plain",
            "data": "'$(base64 $B64FLAGS a11.txt)'"
          }
        }
      ],
    "role": "user"
    }
  ],
  "systemInstruction": {
    "parts": [
      {
        "text": "You are an expert at analyzing transcripts."
      }
    ]
  },
  "ttl": "300s"
}' > request.json

curl -X POST "https://generativelanguage.googleapis.com/v1beta/cachedContents?key=$GEMINI_API_KEY" \
 -H 'Content-Type: application/json' \
 -d @request.json \
 > cache.json

CACHE_NAME=$(cat cache.json | grep '"name":' | cut -d '"' -f 4 | head -n 1)

curl -X POST "https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash-001:generateContent?key=$GEMINI_API_KEY" \
-H 'Content-Type: application/json' \
-d '{
      "contents": [
        {
          "parts":[{
            "text": "Please summarize this transcript"
          }],
          "role": "user"
        },
      ],
      "cachedContent": "'$CACHE_NAME'"
    }'

Nazwa nadawcy

Python

from google import genai
from google.genai import types

client = genai.Client()
document = client.files.upload(file=media / "a11.txt")
model_name = "gemini-3.7-flash"

cache = client.caches.create(
    model=model_name,
    config=types.CreateCachedContentConfig(
        contents=[document],
        system_instruction="You are an expert analyzing transcripts.",
    ),
)
cache_name = cache.name  # Save the name for later

# Later retrieve the cache
cache = client.caches.get(name=cache_name)
response = client.models.generate_content(
    model=model_name,
    contents="Find a lighthearted moment from this transcript",
    config=types.GenerateContentConfig(cached_content=cache.name),
)
print(response.text)

Node.js

// Make sure to include the following import:
// import {GoogleGenAI} from '@google/genai';
const ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });
const filePath = path.join(media, "a11.txt");
const document = await ai.files.upload({
  file: filePath,
  config: { mimeType: "text/plain" },
});
console.log("Uploaded file name:", document.name);
const modelName = "gemini-3.7-flash";

const contents = [
  createUserContent(createPartFromUri(document.uri, document.mimeType)),
];

const cache = await ai.caches.create({
  model: modelName,
  config: {
    contents: contents,
    systemInstruction: "You are an expert analyzing transcripts.",
  },
});
const cacheName = cache.name; // Save the name for later

// Later retrieve the cache
const retrievedCache = await ai.caches.get({ name: cacheName });
const response = await ai.models.generateContent({
  model: modelName,
  contents: "Find a lighthearted moment from this transcript",
  config: { cachedContent: retrievedCache.name },
});
console.log("Response text:", response.text);

Go

ctx := context.Background()
client, err := genai.NewClient(ctx, &genai.ClientConfig{
	APIKey:  os.Getenv("GEMINI_API_KEY"),
	Backend: genai.BackendGeminiAPI,
})
if err != nil {
	log.Fatal(err)
}

modelName := "gemini-3.7-flash"
document, err := client.Files.UploadFromPath(
	ctx, 
	filepath.Join(getMedia(), "a11.txt"), 
	&genai.UploadFileConfig{
		MIMEType : "text/plain",
	},
)
if err != nil {
	log.Fatal(err)
}
parts := []*genai.Part{
	genai.NewPartFromURI(document.URI, document.MIMEType),
}
contents := []*genai.Content{
	genai.NewContentFromParts(parts, genai.RoleUser),
}
cache, err := client.Caches.Create(ctx, modelName, &genai.CreateCachedContentConfig{
	Contents:          contents,
	SystemInstruction: genai.NewContentFromText(
		"You are an expert analyzing transcripts.", genai.RoleUser,
	),
})
if err != nil {
	log.Fatal(err)
}
cacheName := cache.Name

// Later retrieve the cache.
cache, err = client.Caches.Get(ctx, cacheName, &genai.GetCachedContentConfig{})
if err != nil {
	log.Fatal(err)
}

response, err := client.Models.GenerateContent(
	ctx,
	modelName,
	genai.Text("Find a lighthearted moment from this transcript"),
	&genai.GenerateContentConfig{
		CachedContent: cache.Name,
	},
)
if err != nil {
	log.Fatal(err)
}
fmt.Println("Response from cache (create from name):")
printResponse(response)

Z czatu

Python

from google import genai
from google.genai import types

client = genai.Client()
model_name = "gemini-3.7-flash"
system_instruction = "You are an expert analyzing transcripts."

# Create a chat session with the given system instruction.
chat = client.chats.create(
    model=model_name,
    config=types.GenerateContentConfig(system_instruction=system_instruction),
)
document = client.files.upload(file=media / "a11.txt")

response = chat.send_message(
    message=["Hi, could you summarize this transcript?", document]
)
print("\n\nmodel:  ", response.text)
response = chat.send_message(
    message=["Okay, could you tell me more about the trans-lunar injection"]
)
print("\n\nmodel:  ", response.text)

# To cache the conversation so far, pass the chat history as the list of contents.
cache = client.caches.create(
    model=model_name,
    config={
        "contents": chat.get_history(),
        "system_instruction": system_instruction,
    },
)
# Continue the conversation using the cached content.
chat = client.chats.create(
    model=model_name,
    config=types.GenerateContentConfig(cached_content=cache.name),
)
response = chat.send_message(
    message="I didn't understand that last part, could you explain it in simpler language?"
)
print("\n\nmodel:  ", response.text)

Node.js

// Make sure to include the following import:
// import {GoogleGenAI} from '@google/genai';
const ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });
const modelName = "gemini-3.7-flash";
const systemInstruction = "You are an expert analyzing transcripts.";

// Create a chat session with the system instruction.
const chat = ai.chats.create({
  model: modelName,
  config: { systemInstruction: systemInstruction },
});
const filePath = path.join(media, "a11.txt");
const document = await ai.files.upload({
  file: filePath,
  config: { mimeType: "text/plain" },
});
console.log("Uploaded file name:", document.name);

let response = await chat.sendMessage({
  message: createUserContent([
    "Hi, could you summarize this transcript?",
    createPartFromUri(document.uri, document.mimeType),
  ]),
});
console.log("\n\nmodel:", response.text);

response = await chat.sendMessage({
  message: "Okay, could you tell me more about the trans-lunar injection",
});
console.log("\n\nmodel:", response.text);

// To cache the conversation so far, pass the chat history as the list of contents.
const chatHistory = chat.getHistory();
const cache = await ai.caches.create({
  model: modelName,
  config: {
    contents: chatHistory,
    systemInstruction: systemInstruction,
  },
});

// Continue the conversation using the cached content.
const chatWithCache = ai.chats.create({
  model: modelName,
  config: { cachedContent: cache.name },
});
response = await chatWithCache.sendMessage({
  message:
    "I didn't understand that last part, could you explain it in simpler language?",
});
console.log("\n\nmodel:", response.text);

Go

ctx := context.Background()
client, err := genai.NewClient(ctx, &genai.ClientConfig{
	APIKey:  os.Getenv("GEMINI_API_KEY"),
	Backend: genai.BackendGeminiAPI,
})
if err != nil {
	log.Fatal(err)
}

modelName := "gemini-3.7-flash"
systemInstruction := "You are an expert analyzing transcripts."

// Create initial chat with a system instruction.
chat, err := client.Chats.Create(ctx, modelName, &genai.GenerateContentConfig{
	SystemInstruction: genai.NewContentFromText(systemInstruction, genai.RoleUser),
}, nil)
if err != nil {
	log.Fatal(err)
}

document, err := client.Files.UploadFromPath(
	ctx, 
	filepath.Join(getMedia(), "a11.txt"), 
	&genai.UploadFileConfig{
		MIMEType : "text/plain",
	},
)
if err != nil {
	log.Fatal(err)
}

// Send first message with the transcript.
parts := make([]genai.Part, 2)
parts[0] = genai.Part{Text: "Hi, could you summarize this transcript?"}
parts[1] = genai.Part{
	FileData: &genai.FileData{
		FileURI :      document.URI,
		MIMEType: document.MIMEType,
	},
}

// Send chat message.
resp, err := chat.SendMessage(ctx, parts...)
if err != nil {
	log.Fatal(err)
}
fmt.Println("\n\nmodel: ", resp.Text())

resp, err = chat.SendMessage(
	ctx, 
	genai.Part{
		Text: "Okay, could you tell me more about the trans-lunar injection",
	},
)
if err != nil {
	log.Fatal(err)
}
fmt.Println("\n\nmodel: ", resp.Text())

// To cache the conversation so far, pass the chat history as the list of contents.
cache, err := client.Caches.Create(ctx, modelName, &genai.CreateCachedContentConfig{
	Contents:          chat.History(false),
	SystemInstruction: genai.NewContentFromText(systemInstruction, genai.RoleUser),
})
if err != nil {
	log.Fatal(err)
}

// Continue the conversation using the cached history.
chat, err = client.Chats.Create(ctx, modelName, &genai.GenerateContentConfig{
	CachedContent: cache.Name,
}, nil)
if err != nil {
	log.Fatal(err)
}

resp, err = chat.SendMessage(
	ctx, 
	genai.Part{
		Text: "I didn't understand that last part, could you explain it in simpler language?",
	},
)
if err != nil {
	log.Fatal(err)
}
fmt.Println("\n\nmodel: ", resp.Text())

Treść odpowiedzi

Jeśli operacja się uda, treść odpowiedzi będzie zawierała nowo utworzoną instancję CachedContent.

Metoda: cachedContents.list

Wyświetla listę CachedContents.

Punkt końcowy

get https://generativelanguage.googleapis.com/v1beta/cachedContents

Parametry zapytania

pageSize integer

Opcjonalnie. Maksymalna liczba treści z pamięci podręcznej do zwrócenia. Usługa może zwrócić mniej niż ta wartość. Jeśli nie podasz tej wartości, zostanie zwrócona domyślna (poniżej maksymalnej) liczba produktów. Maksymalna wartość to 1000. Wartości powyżej 1000 zostaną zmienione na 1000.

pageToken string

Opcjonalnie. Token strony otrzymany z poprzedniego wywołania cachedContents.list. Podaj ten token, aby pobrać kolejną stronę.

Podczas paginacji wszystkie inne parametry przekazane do funkcji cachedContents.list muszą być zgodne z wywołaniem, które dostarczyło token strony.

Treść żądania

Treść żądania musi być pusta.

Treść odpowiedzi

Odpowiedź z listą CachedContents.

W przypadku powodzenia treść żądania zawiera dane o następującej strukturze:

Pola
cachedContents[] object (CachedContent)

Lista treści z pamięci podręcznej.

nextPageToken string

Token, który można wysłać jako pageToken, aby pobrać następną stronę. Jeśli pominiesz to pole, nie będzie kolejnych stron.

Zapis JSON
{
  "cachedContents": [
    {
      object (CachedContent)
    }
  ],
  "nextPageToken": string
}

Metoda: cachedContents.get

Odczytuje zasób CachedContent.

Punkt końcowy

get https://generativelanguage.googleapis.com/v1beta/{name=cachedContents/*}

Parametry ścieżki

name string

Wymagane. Nazwa zasobu odnosząca się do wpisu w pamięci podręcznej treści. Format: cachedContents/{id}. Ma postać cachedContents/{cachedcontent}.

Treść żądania

Treść żądania musi być pusta.

Przykładowe żądanie

Python

from google import genai

client = genai.Client()
document = client.files.upload(file=media / "a11.txt")
model_name = "gemini-3.7-flash"

cache = client.caches.create(
    model=model_name,
    config={
        "contents": [document],
        "system_instruction": "You are an expert analyzing transcripts.",
    },
)
print(client.caches.get(name=cache.name))

Node.js

// Make sure to include the following import:
// import {GoogleGenAI} from '@google/genai';
const ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });
const filePath = path.join(media, "a11.txt");
const document = await ai.files.upload({
  file: filePath,
  config: { mimeType: "text/plain" },
});
console.log("Uploaded file name:", document.name);
const modelName = "gemini-3.7-flash";

const contents = [
  createUserContent(createPartFromUri(document.uri, document.mimeType)),
];

const cache = await ai.caches.create({
  model: modelName,
  config: {
    contents: contents,
    systemInstruction: "You are an expert analyzing transcripts.",
  },
});
const retrievedCache = await ai.caches.get({ name: cache.name });
console.log("Retrieved Cache:", retrievedCache);

Go

ctx := context.Background()
client, err := genai.NewClient(ctx, &genai.ClientConfig{
	APIKey:  os.Getenv("GEMINI_API_KEY"),
	Backend: genai.BackendGeminiAPI,
})
if err != nil {
	log.Fatal(err)
}

modelName := "gemini-3.7-flash"
document, err := client.Files.UploadFromPath(
	ctx, 
	filepath.Join(getMedia(), "a11.txt"), 
	&genai.UploadFileConfig{
		MIMEType : "text/plain",
	},
)
if err != nil {
	log.Fatal(err)
}
parts := []*genai.Part{
	genai.NewPartFromURI(document.URI, document.MIMEType),
}
contents := []*genai.Content{
	genai.NewContentFromParts(parts, genai.RoleUser),
}

cache, err := client.Caches.Create(ctx, modelName, &genai.CreateCachedContentConfig{
	Contents:          contents,
	SystemInstruction: genai.NewContentFromText(
		"You are an expert analyzing transcripts.", genai.RoleUser,
	),
})
if err != nil {
	log.Fatal(err)
}

cache, err = client.Caches.Get(ctx, cache.Name, &genai.GetCachedContentConfig{})
if err != nil {
	log.Fatal(err)
}
fmt.Println("Retrieved cache:")
fmt.Println(cache)

Muszla

curl "https://generativelanguage.googleapis.com/v1beta/$CACHE_NAME?key=$GEMINI_API_KEY"

Treść odpowiedzi

W przypadku powodzenia treść odpowiedzi obejmuje wystąpienie elementu CachedContent.

Metoda: cachedContents.patch

Aktualizuje zasób CachedContent (można aktualizować tylko datę wygaśnięcia).

Punkt końcowy

patch https://generativelanguage.googleapis.com/v1beta/{cachedContent.name=cachedContents/*}

PATCH https://generativelanguage.googleapis.com/v1beta/{cachedContent.name=cachedContents/*}

Parametry ścieżki

cachedContent.name string

Tylko dane wyjściowe. Identyfikator. Nazwa zasobu odnosząca się do treści z pamięci podręcznej. Format: cachedContents/{id}. Ma postać cachedContents/{cachedcontent}.

Parametry zapytania

updateMask string (FieldMask format)

Lista pól do zaktualizowania.

Jest to lista w pełni kwalifikowanych nazw pól rozdzielonych przecinkami. Przykład: "user.displayName,photo".

Treść żądania

Treść żądania zawiera wystąpienie elementu CachedContent.

Pola
expiration Union type
Określa, kiedy ten zasób wygaśnie. Pole expiration może mieć tylko jedną z tych wartości:
expireTime string (Timestamp format)

Sygnatura czasowa UTC wskazująca, kiedy zasób jest uznawany za nieaktualny. Jest zawsze podawana na wyjściu niezależnie od tego, co zostało wysłane na wejściu.

Korzysta ze standardu RFC 3339, w którym wygenerowane dane wyjściowe są zawsze znormalizowane do formatu Z i zawierają 0, 3, 6 lub 9 cyfr po przecinku. Akceptowane są też przesunięcia inne niż „Z”. Przykłady: "2014-10-02T15:01:23Z", "2014-10-02T15:01:23.045123456Z" lub "2014-10-02T15:01:23+05:30".

ttl string (Duration format)

Tylko dane wejściowe. Nowy czas życia tego zasobu (tylko dane wejściowe).

Czas trwania w sekundach z maksymalnie 9 miejscami po przecinku, zakończony znakiem „s”. Przykład: "3.5s".

Przykładowe żądanie

Python

from google import genai
from google.genai import types
import datetime

client = genai.Client()
document = client.files.upload(file=media / "a11.txt")
model_name = "gemini-3.7-flash"

cache = client.caches.create(
    model=model_name,
    config={
        "contents": [document],
        "system_instruction": "You are an expert analyzing transcripts.",
    },
)

# Update the cache's time-to-live (ttl)
ttl = f"{int(datetime.timedelta(hours=2).total_seconds())}s"
client.caches.update(
    name=cache.name, config=types.UpdateCachedContentConfig(ttl=ttl)
)
print(f"After update:\n {cache}")

# Alternatively, update the expire_time directly
# Update the expire_time directly in valid RFC 3339 format (UTC with a "Z" suffix)
expire_time = (
    (
        datetime.datetime.now(datetime.timezone.utc)
        + datetime.timedelta(minutes=15)
    )
    .isoformat()
    .replace("+00:00", "Z")
)
client.caches.update(
    name=cache.name,
    config=types.UpdateCachedContentConfig(expire_time=expire_time),
)

Node.js

// Make sure to include the following import:
// import {GoogleGenAI} from '@google/genai';
const ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });
const filePath = path.join(media, "a11.txt");
const document = await ai.files.upload({
  file: filePath,
  config: { mimeType: "text/plain" },
});
console.log("Uploaded file name:", document.name);
const modelName = "gemini-3.7-flash";

const contents = [
  createUserContent(createPartFromUri(document.uri, document.mimeType)),
];

let cache = await ai.caches.create({
  model: modelName,
  config: {
    contents: contents,
    systemInstruction: "You are an expert analyzing transcripts.",
  },
});

// Update the cache's time-to-live (ttl)
const ttl = `${2 * 3600}s`; // 2 hours in seconds
cache = await ai.caches.update({
  name: cache.name,
  config: { ttl },
});
console.log("After update (TTL):", cache);

// Alternatively, update the expire_time directly (in RFC 3339 format with a "Z" suffix)
const expireTime = new Date(Date.now() + 15 * 60000)
  .toISOString()
  .replace(/\.\d{3}Z$/, "Z");
cache = await ai.caches.update({
  name: cache.name,
  config: { expireTime: expireTime },
});
console.log("After update (expire_time):", cache);

Go

ctx := context.Background()
client, err := genai.NewClient(ctx, &genai.ClientConfig{
	APIKey:  os.Getenv("GEMINI_API_KEY"),
	Backend: genai.BackendGeminiAPI,
})
if err != nil {
	log.Fatal(err)
}

modelName := "gemini-3.7-flash"
document, err := client.Files.UploadFromPath(
	ctx, 
	filepath.Join(getMedia(), "a11.txt"), 
	&genai.UploadFileConfig{
		MIMEType : "text/plain",
	},
)
if err != nil {
	log.Fatal(err)
}
parts := []*genai.Part{
	genai.NewPartFromURI(document.URI, document.MIMEType),
}
contents := []*genai.Content{
	genai.NewContentFromParts(parts, genai.RoleUser),
}

cache, err := client.Caches.Create(ctx, modelName, &genai.CreateCachedContentConfig{
	Contents:          contents,
	SystemInstruction: genai.NewContentFromText(
		"You are an expert analyzing transcripts.", genai.RoleUser,
	),
})
if err != nil {
	log.Fatal(err)
}

_, err = client.Caches.Delete(ctx, cache.Name, &genai.DeleteCachedContentConfig{})
if err != nil {
	log.Fatal(err)
}
fmt.Println("Cache deleted:", cache.Name)

Muszla

curl -X PATCH "https://generativelanguage.googleapis.com/v1beta/$CACHE_NAME?key=$GEMINI_API_KEY" \
 -H 'Content-Type: application/json' \
 -d '{"ttl": "600s"}'

Treść odpowiedzi

W przypadku powodzenia treść odpowiedzi obejmuje wystąpienie elementu CachedContent.

Metoda: cachedContents.delete

Usuwa zasób CachedContent.

Punkt końcowy

delete https://generativelanguage.googleapis.com/v1beta/{name=cachedContents/*}

Parametry ścieżki

name string

Wymagane. Nazwa zasobu odnosząca się do wpisu w pamięci podręcznej treści. Format: cachedContents/{id}. Ma postać cachedContents/{cachedcontent}.

Treść żądania

Treść żądania musi być pusta.

Przykładowe żądanie

Python

from google import genai

client = genai.Client()
document = client.files.upload(file=media / "a11.txt")
model_name = "gemini-3.7-flash"

cache = client.caches.create(
    model=model_name,
    config={
        "contents": [document],
        "system_instruction": "You are an expert analyzing transcripts.",
    },
)
client.caches.delete(name=cache.name)

Node.js

// Make sure to include the following import:
// import {GoogleGenAI} from '@google/genai';
const ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });
const filePath = path.join(media, "a11.txt");
const document = await ai.files.upload({
  file: filePath,
  config: { mimeType: "text/plain" },
});
console.log("Uploaded file name:", document.name);
const modelName = "gemini-3.7-flash";

const contents = [
  createUserContent(createPartFromUri(document.uri, document.mimeType)),
];

const cache = await ai.caches.create({
  model: modelName,
  config: {
    contents: contents,
    systemInstruction: "You are an expert analyzing transcripts.",
  },
});
await ai.caches.delete({ name: cache.name });
console.log("Cache deleted:", cache.name);

Go

ctx := context.Background()
client, err := genai.NewClient(ctx, &genai.ClientConfig{
	APIKey:  os.Getenv("GEMINI_API_KEY"),
	Backend: genai.BackendGeminiAPI,
})
if err != nil {
	log.Fatal(err)
}

modelName := "gemini-3.7-flash"
document, err := client.Files.UploadFromPath(
	ctx, 
	filepath.Join(getMedia(), "a11.txt"), 
	&genai.UploadFileConfig{
		MIMEType : "text/plain",
	},
)
if err != nil {
	log.Fatal(err)
}
parts := []*genai.Part{
	genai.NewPartFromURI(document.URI, document.MIMEType),
}
contents := []*genai.Content{
	genai.NewContentFromParts(parts, genai.RoleUser),
}

cache, err := client.Caches.Create(ctx, modelName, &genai.CreateCachedContentConfig{
	Contents:          contents,
	SystemInstruction: genai.NewContentFromText(
		"You are an expert analyzing transcripts.", genai.RoleUser,
	),
})
if err != nil {
	log.Fatal(err)
}

_, err = client.Caches.Delete(ctx, cache.Name, &genai.DeleteCachedContentConfig{})
if err != nil {
	log.Fatal(err)
}
fmt.Println("Cache deleted:", cache.Name)

Muszla

curl -X DELETE "https://generativelanguage.googleapis.com/v1beta/$CACHE_NAME?key=$GEMINI_API_KEY"

Treść odpowiedzi

Jeśli operacja się uda, treść odpowiedzi będzie pustym obiektem JSON.

Zasób REST: cachedContents

Zasób: CachedContent

Treści, które zostały wstępnie przetworzone i mogą być używane w kolejnych żądaniach do usługi GenerativeService.

Treści z pamięci podręcznej mogą być używane tylko z modelem, dla którego zostały utworzone.

Pola
contents[] object (Content)

Opcjonalnie. Tylko dane wejściowe. Niezmienne. Treść do zapisania w pamięci podręcznej.

tools[] object (Tool)

Opcjonalnie. Tylko dane wejściowe. Niezmienne. Lista Tools, których model może użyć do wygenerowania następnej odpowiedzi.

createTime string (Timestamp format)

Tylko dane wyjściowe. Czas utworzenia wpisu w pamięci podręcznej.

Korzysta ze standardu RFC 3339, w którym wygenerowane dane wyjściowe są zawsze znormalizowane do formatu Z i zawierają 0, 3, 6 lub 9 cyfr po przecinku. Akceptowane są też przesunięcia inne niż „Z”. Przykłady: "2014-10-02T15:01:23Z", "2014-10-02T15:01:23.045123456Z" lub "2014-10-02T15:01:23+05:30".

updateTime string (Timestamp format)

Tylko dane wyjściowe. Czas ostatniej aktualizacji wpisu w pamięci podręcznej (w strefie czasowej UTC).

Korzysta ze standardu RFC 3339, w którym wygenerowane dane wyjściowe są zawsze znormalizowane do formatu Z i zawierają 0, 3, 6 lub 9 cyfr po przecinku. Akceptowane są też przesunięcia inne niż „Z”. Przykłady: "2014-10-02T15:01:23Z", "2014-10-02T15:01:23.045123456Z" lub "2014-10-02T15:01:23+05:30".

usageMetadata object (UsageMetadata)

Tylko dane wyjściowe. Metadane dotyczące korzystania z treści z pamięci podręcznej.

expiration Union type
Określa, kiedy ten zasób wygaśnie. Pole expiration może mieć tylko jedną z tych wartości:
expireTime string (Timestamp format)

Sygnatura czasowa UTC wskazująca, kiedy zasób jest uznawany za nieaktualny. Jest zawsze podawana na wyjściu niezależnie od tego, co zostało wysłane na wejściu.

Korzysta ze standardu RFC 3339, w którym wygenerowane dane wyjściowe są zawsze znormalizowane do formatu Z i zawierają 0, 3, 6 lub 9 cyfr po przecinku. Akceptowane są też przesunięcia inne niż „Z”. Przykłady: "2014-10-02T15:01:23Z", "2014-10-02T15:01:23.045123456Z" lub "2014-10-02T15:01:23+05:30".

ttl string (Duration format)

Tylko dane wejściowe. Nowy czas życia tego zasobu (tylko dane wejściowe).

Czas trwania w sekundach z maksymalnie 9 miejscami po przecinku, zakończony znakiem „s”. Przykład: "3.5s".

name string

Tylko dane wyjściowe. Identyfikator. Nazwa zasobu odnosząca się do treści z pamięci podręcznej. Format: cachedContents/{id}

displayName string

Opcjonalnie. Niezmienne. Wygenerowana przez użytkownika nazwa wyświetlana zapisanych w pamięci podręcznej treści. Maksymalnie 128 znaków Unicode.

model string

Wymagane. Niezmienne. Nazwa Model, która ma być używana w przypadku treści w pamięci podręcznej. Format: models/{model}

systemInstruction object (Content)

Opcjonalnie. Tylko dane wejściowe. Niezmienne. Instrukcja systemowa ustawiona przez dewelopera. Obecnie tylko tekst.

toolConfig object (ToolConfig)

Opcjonalnie. Tylko dane wejściowe. Niezmienne. Konfiguracja narzędzia Ta konfiguracja jest udostępniana wszystkim narzędziom.

Zapis JSON
{
  "contents": [
    {
      object (Content)
    }
  ],
  "tools": [
    {
      object (Tool)
    }
  ],
  "createTime": string,
  "updateTime": string,
  "usageMetadata": {
    object (UsageMetadata)
  },

  // expiration
  "expireTime": string,
  "ttl": string
  // Union type
  "name": string,
  "displayName": string,
  "model": string,
  "systemInstruction": {
    object (Content)
  },
  "toolConfig": {
    object (ToolConfig)
  }
}

ToolConfig

Konfiguracja narzędzia zawierająca parametry określające użycie Tool w żądaniu.

Pola
functionCallingConfig object (FunctionCallingConfig)

Opcjonalnie. Konfiguracja wywoływania funkcji.

retrievalConfig object (RetrievalConfig)

Opcjonalnie. Konfiguracja pobierania.

includeServerSideToolInvocations boolean

Opcjonalnie. Jeśli wartość to „true”, odpowiedź interfejsu API będzie zawierać wywołania narzędzi po stronie serwera i odpowiedzi w wiadomości Content. Umożliwia to klientom obserwowanie interakcji serwera z narzędziami.

Zapis JSON
{
  "functionCallingConfig": {
    object (FunctionCallingConfig)
  },
  "retrievalConfig": {
    object (RetrievalConfig)
  },
  "includeServerSideToolInvocations": boolean
}

FunctionCallingConfig

Konfiguracja określająca działanie wywoływania funkcji.

Pola
mode enum (Mode)

Opcjonalnie. Określa tryb, w którym ma być wykonywane wywoływanie funkcji. Jeśli nie zostanie określona, wartością domyślną będzie AUTO.

allowedFunctionNames[] string

Opcjonalnie. Zbiór nazw funkcji, które po podaniu ograniczają funkcje, które model będzie wywoływać.

Tę wartość należy ustawić tylko wtedy, gdy tryb to ANY lub VALIDATED. Nazwy funkcji powinny być zgodne z [FunctionDeclaration.name]. Gdy ta opcja jest ustawiona, model będzie prognozować wywołanie funkcji tylko na podstawie dozwolonych nazw funkcji.

Zapis JSON
{
  "mode": enum (Mode),
  "allowedFunctionNames": [
    string
  ]
}

Tryb

Określa sposób wykonywania wywołań funkcji przez zdefiniowanie trybu wykonywania.

Wartości w polu enum
MODE_UNSPECIFIED Nieokreślony tryb wywoływania funkcji. Nie należy używać tej wartości.
AUTO Domyślne działanie modelu: model decyduje, czy przewidzieć wywołanie funkcji, czy odpowiedź w języku naturalnym.
ANY Model jest ograniczony do przewidywania tylko wywołań funkcji. Jeśli ustawiono parametr „allowedFunctionNames”, przewidywane wywołanie funkcji będzie ograniczone do dowolnej z funkcji „allowedFunctionNames”. W przeciwnym razie przewidywane wywołanie funkcji będzie dowolną z funkcji „functionDeclarations”.
NONE Model nie będzie prognozować żadnego wywołania funkcji. Działanie modelu jest takie samo jak w przypadku, gdy nie przekazujesz żadnych deklaracji funkcji.
VALIDATED Model decyduje, czy przewidzieć wywołanie funkcji, czy odpowiedź w języku naturalnym, ale będzie weryfikować wywołania funkcji za pomocą dekodowania z ograniczeniami. Jeśli ustawiono parametr „allowedFunctionNames”, przewidywane wywołanie funkcji będzie ograniczone do dowolnej z funkcji „allowedFunctionNames”. W przeciwnym razie przewidywane wywołanie funkcji będzie dowolną z funkcji „functionDeclarations”.

RetrievalConfig

Konfiguracja pobierania.

Pola
latLng object (LatLng)

Opcjonalnie. Lokalizacja użytkownika.

languageCode string

Opcjonalnie. Kod języka użytkownika. Kod języka treści. Używaj tagów języków zdefiniowanych przez BCP47.

Zapis JSON
{
  "latLng": {
    object (LatLng)
  },
  "languageCode": string
}

LatLng

Obiekt reprezentujący parę szerokości i długości geograficznej. Jest to para liczb zmiennoprzecinkowych podwójnej precyzji, które reprezentują stopnie szerokości i długości geograficznej. O ile nie określono inaczej, ten obiekt musi być zgodny ze standardem WGS84. Wartości muszą mieścić się w znormalizowanych zakresach.

Pola
latitude number

Szerokość geograficzna w stopniach. Musi mieścić się w zakresie od –90,0 do +90,0.

longitude number

Długość geograficzna w stopniach. Musi mieścić się w zakresie [-180,0, +180,0].

Zapis JSON
{
  "latitude": number,
  "longitude": number
}

UsageMetadata

Metadane dotyczące korzystania z treści z pamięci podręcznej.

Pola
totalTokenCount integer

Łączna liczba tokenów, które zużywają treści w pamięci podręcznej.

Zapis JSON
{
  "totalTokenCount": integer
}