Caching

컨텍스트 캐싱을 사용하면 동일한 미디어 파일에 대해 다양한 질문을 할 때와 같이 반복적으로 사용하려는 사전 계산된 입력 토큰을 저장하고 재사용할 수 있습니다. 이를 통해 사용량에 따라 비용과 속도를 절약할 수 있습니다. 자세한 내용은 컨텍스트 캐싱 가이드를 참고하세요.

메서드: cachedContents.create

CachedContent 리소스를 만듭니다.

엔드포인트

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

요청 본문

요청 본문에 CachedContent의 인스턴스가 포함됩니다.

필드
contents[] object (Content)

선택사항입니다. 입력 전용입니다. 변경할 수 없습니다. 캐시할 콘텐츠입니다.

tools[] object (Tool)

선택사항입니다. 입력 전용입니다. 변경할 수 없습니다. 모델이 다음 응답을 생성하는 데 사용할 수 있는 Tools 목록입니다.

expiration Union type
이 리소스가 만료되는 시점을 지정합니다. expiration는 다음 중 하나여야 합니다.
expireTime string (Timestamp format)

이 리소스가 만료된 것으로 간주되는 시간의 타임스탬프(UTC)입니다. 이 필드는 입력으로 전송된 항목에 관계없이 항상 출력으로 제공됩니다

생성된 출력은 항상 Z-정규화되고 소수점 이하 0, 3, 6 또는 9자리인 RFC 3339를 사용합니다. 'Z' 이외의 오프셋도 허용됩니다. 예를 들면 "2014-10-02T15:01:23Z", "2014-10-02T15:01:23.045123456Z" 또는 "2014-10-02T15:01:23+05:30"입니다.

ttl string (Duration format)

입력 전용입니다. 이 리소스의 새 TTL입니다(입력 전용).

소수점 아래가 최대 9자리까지이고 's'로 끝나는 초 단위 기간입니다. 예를 들면 "3.5s"입니다.

displayName string

선택사항입니다. 변경할 수 없습니다. 캐시된 콘텐츠의 사용자 생성 의미 있는 표시 이름입니다. 최대 128개의 유니코드 문자

model string

필수 항목입니다. 변경할 수 없습니다. 캐시된 콘텐츠에 사용할 Model의 이름입니다. 형식: models/{model}

systemInstruction object (Content)

선택사항입니다. 입력 전용입니다. 변경할 수 없습니다. 개발자가 설정한 시스템 요청 사항입니다. 현재는 텍스트만 지원됩니다.

toolConfig object (ToolConfig)

선택사항입니다. 입력 전용입니다. 변경할 수 없습니다. 도구 구성 이 구성은 모든 도구에 공유됩니다.

요청 예시

기본

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)

Shell

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'"
    }'

보낸사람 이름

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)

채팅에서

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())

응답 본문

성공한 경우 응답 본문에 새로 생성된 CachedContent의 인스턴스가 포함됩니다.

메서드: cachedContents.list

CachedContents를 나열합니다.

엔드포인트

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

쿼리 매개변수

pageSize integer

선택사항입니다. 반환할 최대 캐시 콘텐츠 수입니다. 서비스가 이 값보다 더 적게 반환할 수 있습니다. 지정하지 않으면 최대 개수 미만의 기본 항목이 반환됩니다. 최댓값은 1,000이며, 1,000을 초과하는 값은 1,000으로 변환됩니다.

pageToken string

선택사항입니다. 이전 cachedContents.list 호출에서 받은 페이지 토큰입니다. 후속 페이지를 검색하려면 이를 입력합니다.

페이지를 매길 때 cachedContents.list에 제공된 다른 모든 매개 변수는 페이지 토큰을 제공한 호출과 일치해야 합니다.

요청 본문

요청 본문은 비어 있어야 합니다.

응답 본문

CachedContents 목록이 포함된 응답입니다.

성공한 경우 응답 본문은 다음과 같은 구조의 데이터를 포함합니다.

필드
cachedContents[] object (CachedContent)

캐시된 콘텐츠 목록입니다.

nextPageToken string

다음 페이지를 검색하기 위해 pageToken으로 전송할 수 있는 토큰입니다. 이 필드를 생략하면 후속 페이지가 표시되지 않습니다.

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

메서드: cachedContents.get

CachedContent 리소스를 읽습니다.

엔드포인트

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

경로 매개변수

name string

필수 항목입니다. 콘텐츠 캐시 항목을 참조하는 리소스 이름입니다. 형식: cachedContents/{id} cachedContents/{cachedcontent} 형식이 사용됩니다.

요청 본문

요청 본문은 비어 있어야 합니다.

요청 예시

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)

Shell

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

응답 본문

성공한 경우 응답 본문에 CachedContent의 인스턴스가 포함됩니다.

메서드: cachedContents.patch

CachedContent 리소스를 업데이트합니다 (만료만 업데이트 가능).

엔드포인트

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

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

경로 매개변수

cachedContent.name string

출력 전용입니다. 식별자. 캐시된 콘텐츠를 참조하는 리소스 이름입니다. 형식: cachedContents/{id} cachedContents/{cachedcontent} 형식이 사용됩니다.

쿼리 매개변수

updateMask string (FieldMask format)

업데이트할 필드 목록입니다.

정규화된 필드 이름의 쉼표로 구분된 목록입니다. 예: "user.displayName,photo"

요청 본문

요청 본문에 CachedContent의 인스턴스가 포함됩니다.

필드
expiration Union type
이 리소스가 만료되는 시점을 지정합니다. expiration는 다음 중 하나여야 합니다.
expireTime string (Timestamp format)

이 리소스가 만료된 것으로 간주되는 시간의 타임스탬프(UTC)입니다. 이 필드는 입력으로 전송된 항목에 관계없이 항상 출력으로 제공됩니다

생성된 출력은 항상 Z-정규화되고 소수점 이하 0, 3, 6 또는 9자리인 RFC 3339를 사용합니다. 'Z' 이외의 오프셋도 허용됩니다. 예를 들면 "2014-10-02T15:01:23Z", "2014-10-02T15:01:23.045123456Z" 또는 "2014-10-02T15:01:23+05:30"입니다.

ttl string (Duration format)

입력 전용입니다. 이 리소스의 새 TTL입니다(입력 전용).

소수점 아래가 최대 9자리까지이고 's'로 끝나는 초 단위 기간입니다. 예를 들면 "3.5s"입니다.

요청 예시

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)

Shell

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

응답 본문

성공한 경우 응답 본문에 CachedContent의 인스턴스가 포함됩니다.

메서드: cachedContents.delete

CachedContent 리소스를 삭제합니다.

엔드포인트

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

경로 매개변수

name string

필수 항목입니다. 콘텐츠 캐시 항목을 참조하는 리소스 이름입니다. 형식: cachedContents/{id} cachedContents/{cachedcontent} 형식을 사용합니다.

요청 본문

요청 본문은 비어 있어야 합니다.

요청 예시

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)

Shell

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

응답 본문

성공하면 응답 본문은 빈 JSON 객체입니다.

REST 리소스: cachedContents

리소스: CachedContent

사전 처리되었으며 GenerativeService에 대한 후속 요청에서 사용할 수 있는 콘텐츠입니다.

캐시된 콘텐츠는 콘텐츠가 생성된 모델에서만 사용할 수 있습니다.

필드
contents[] object (Content)

선택사항입니다. 입력 전용입니다. 변경할 수 없습니다. 캐시할 콘텐츠입니다.

tools[] object (Tool)

선택사항입니다. 입력 전용입니다. 변경할 수 없습니다. 모델이 다음 응답을 생성하는 데 사용할 수 있는 Tools 목록입니다.

createTime string (Timestamp format)

출력 전용입니다. 캐시 항목의 생성 시간입니다.

생성된 출력은 항상 Z-정규화되고 소수점 이하 0, 3, 6 또는 9자리인 RFC 3339를 사용합니다. 'Z' 이외의 오프셋도 허용됩니다. 예를 들면 "2014-10-02T15:01:23Z", "2014-10-02T15:01:23.045123456Z" 또는 "2014-10-02T15:01:23+05:30"입니다.

updateTime string (Timestamp format)

출력 전용입니다. 캐시 항목이 마지막으로 업데이트된 시간(UTC)입니다.

생성된 출력은 항상 Z-정규화되고 소수점 이하 0, 3, 6 또는 9자리인 RFC 3339를 사용합니다. 'Z' 이외의 오프셋도 허용됩니다. 예를 들면 "2014-10-02T15:01:23Z", "2014-10-02T15:01:23.045123456Z" 또는 "2014-10-02T15:01:23+05:30"입니다.

usageMetadata object (UsageMetadata)

출력 전용입니다. 캐시된 콘텐츠 사용에 관한 메타데이터입니다.

expiration Union type
이 리소스가 만료되는 시점을 지정합니다. expiration는 다음 중 하나여야 합니다.
expireTime string (Timestamp format)

이 리소스가 만료된 것으로 간주되는 시간의 타임스탬프(UTC)입니다. 이 필드는 입력으로 전송된 항목에 관계없이 항상 출력으로 제공됩니다

생성된 출력은 항상 Z-정규화되고 소수점 이하 0, 3, 6 또는 9자리인 RFC 3339를 사용합니다. 'Z' 이외의 오프셋도 허용됩니다. 예를 들면 "2014-10-02T15:01:23Z", "2014-10-02T15:01:23.045123456Z" 또는 "2014-10-02T15:01:23+05:30"입니다.

ttl string (Duration format)

입력 전용입니다. 이 리소스의 새 TTL입니다(입력 전용).

소수점 아래가 최대 9자리까지이고 's'로 끝나는 초 단위 기간입니다. 예를 들면 "3.5s"입니다.

name string

출력 전용입니다. 식별자. 캐시된 콘텐츠를 참조하는 리소스 이름입니다. 형식: cachedContents/{id}

displayName string

선택사항입니다. 변경할 수 없습니다. 캐시된 콘텐츠의 사용자 생성 의미 있는 표시 이름입니다. 최대 128개의 유니코드 문자

model string

필수 항목입니다. 변경할 수 없습니다. 캐시된 콘텐츠에 사용할 Model의 이름입니다. 형식: models/{model}

systemInstruction object (Content)

선택사항입니다. 입력 전용입니다. 변경할 수 없습니다. 개발자가 설정한 시스템 요청 사항입니다. 현재는 텍스트만 지원됩니다.

toolConfig object (ToolConfig)

선택사항입니다. 입력 전용입니다. 변경할 수 없습니다. 도구 구성 이 구성은 모든 도구에 공유됩니다.

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

요청에서 Tool 사용을 지정하는 매개변수가 포함된 도구 구성입니다.

필드
functionCallingConfig object (FunctionCallingConfig)

선택사항입니다. 함수 호출 구성입니다.

retrievalConfig object (RetrievalConfig)

선택사항입니다. 검색 구성입니다.

includeServerSideToolInvocations boolean

선택사항입니다. true인 경우 API 응답에 Content 메시지 내의 서버 측 도구 호출 및 응답이 포함됩니다. 이를 통해 클라이언트는 서버의 도구 상호작용을 관찰할 수 있습니다.

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

FunctionCallingConfig

함수 호출 동작을 지정하기 위한 구성입니다.

필드
mode enum (Mode)

선택사항입니다. 함수 호출이 실행되어야 하는 모드를 지정합니다. 지정하지 않으면 기본값이 AUTO로 설정됩니다.

allowedFunctionNames[] string

선택사항입니다. 제공되는 경우 모델이 호출할 함수를 제한하는 함수 이름 세트입니다.

모드가 ANY 또는 VALIDATED인 경우에만 설정해야 합니다. 함수 이름은 [FunctionDeclaration.name]과 일치해야 합니다. 설정되면 모델이 허용된 함수 이름에서만 함수 호출을 예측합니다.

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

모드

실행 모드를 정의하여 함수 호출의 실행 동작을 정의합니다.

열거형
MODE_UNSPECIFIED 지정되지 않은 함수 호출 모드입니다. 이 값을 사용하면 안 됩니다.
AUTO 기본 모델 동작으로, 모델이 함수 호출 또는 자연어 응답을 예측하도록 결정합니다.
ANY 모델이 항상 함수 호출만 예측하도록 제한됩니다. 'allowedFunctionNames'가 설정되면 예측 함수 호출이 'allowedFunctionNames' 중 하나로 제한되고, 그렇지 않으면 예측 함수 호출이 제공된 'functionDeclarations' 중 하나가 됩니다.
NONE 모델이 함수 호출을 예측하지 않습니다. 모델 동작은 함수 선언을 전달하지 않는 경우와 동일합니다.
VALIDATED 모델이 함수 호출 또는 자연어 응답을 예측하도록 결정하지만 제한된 디코딩으로 함수 호출을 검증합니다. 'allowedFunctionNames'가 설정되면 예측 함수 호출이 'allowedFunctionNames' 중 하나로 제한되고, 그렇지 않으면 예측 함수 호출이 제공된 'functionDeclarations' 중 하나가 됩니다.

RetrievalConfig

검색 구성입니다.

필드
latLng object (LatLng)

선택사항입니다. 사용자의 위치입니다.

languageCode string

선택사항입니다. 사용자의 언어 코드입니다. 콘텐츠의 언어 코드입니다. BCP47에 정의된 언어 태그를 사용합니다.

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

LatLng

위도/경도 쌍을 나타내는 객체로 위도와 경도를 나타내는 복식 쌍으로 표현됩니다. 달리 명시되지 않는 한 이 객체는 WGS84 표준을 준수해야 합니다. 값은 정규화된 범위 내에 있어야 합니다.

필드
latitude number

위도(도)입니다. 범위는 [-90.0, +90.0]입니다.

longitude number

경도입니다. 범위는 [-180.0, +180.0]입니다.

JSON 표현
{
  "latitude": number,
  "longitude": number
}

UsageMetadata

캐시된 콘텐츠 사용에 관한 메타데이터입니다.

필드
totalTokenCount integer

캐시된 콘텐츠가 사용하는 총 토큰 수입니다.

JSON 표현
{
  "totalTokenCount": integer
}