Skip to main content
Creates a cached content resource that stores context (like documents, conversation history, or system instructions) for reuse across multiple requests. This reduces latency and costs for repeated queries against the same content.

Method Signature

Parameters

string
required
The model to use for this cached content.Example: 'gemini-2.0-flash' or 'gemini-1.5-pro'
CreateCachedContentConfig
Configuration for the cached content.Available options:
  • contents: The content to cache (documents, conversation history, etc.)
  • system_instruction: System instructions to cache
  • tools: Tools configuration to cache
  • tool_config: Tool configuration settings
  • ttl: Time-to-live as a duration string (e.g., "3600s" for 1 hour)
  • expire_time: Specific expiration timestamp
  • display_name: Human-readable name for the cache
  • kms_key_name: KMS encryption key (Vertex AI only)

Returns

CachedContent
A CachedContent object containing:
  • name: The resource name (e.g., "cachedContents/abc123")
  • model: The model name
  • display_name: Human-readable name
  • create_time: When the cache was created
  • update_time: Last update time
  • expire_time: When the cache will expire
  • usage_metadata: Token usage information

Examples

Basic Cache Creation

Cache with Document

Cache with System Instructions

Use Cached Content in Generation

Cache Multiple Documents

Set Specific Expiration Time

Cache with Tools

Async Cache Creation

Cache Conversation History

Cost Optimization

Caching is cost-effective when:
  • You make multiple requests with the same large context
  • The cached content is reused more than once
  • The context is large (thousands of tokens)
Cached tokens are typically cheaper than regular input tokens, and subsequent requests using the cache only pay for new tokens.

TTL vs Expire Time

You can specify expiration using either:
  • ttl: Duration from now (e.g., "3600s" for 1 hour)
  • expire_time: Specific timestamp
Use ttl for relative expiration, expire_time for absolute expiration. Don’t specify both.

Error Handling

API Availability

This method is available in both Gemini API and Vertex AI.Vertex AI differences:
  • Supports kms_key_name for encryption
  • Some tool options may differ