Skip to main content

gemini_genai_rs/caches/
mod.rs

1//! Caches API — create, list, get, update, delete cached content.
2//!
3//! Feature-gated behind `caches`.
4
5use serde::{Deserialize, Serialize};
6
7use crate::client::Client;
8use crate::client::http::HttpError;
9use crate::protocol::types::Content;
10use crate::transport::auth::ServiceEndpoint;
11
12/// Cached content resource.
13#[derive(Debug, Clone, Serialize, Deserialize)]
14#[serde(rename_all = "camelCase")]
15pub struct CachedContent {
16    /// Resource name (e.g., `cachedContents/abc123`).
17    #[serde(default)]
18    pub name: String,
19    /// Display name.
20    #[serde(default)]
21    pub display_name: Option<String>,
22    /// The model used for this cached content.
23    #[serde(default)]
24    pub model: Option<String>,
25    /// System instruction.
26    #[serde(default)]
27    pub system_instruction: Option<Content>,
28    /// Cached content items.
29    #[serde(default)]
30    pub contents: Option<Vec<Content>>,
31    /// Expiration time (RFC3339).
32    #[serde(default)]
33    pub expire_time: Option<String>,
34    /// TTL duration string (e.g., "3600s").
35    #[serde(default)]
36    pub ttl: Option<String>,
37    /// Usage metadata.
38    #[serde(default)]
39    pub usage_metadata: Option<CachedContentUsageMetadata>,
40    /// Creation time (RFC3339).
41    #[serde(default)]
42    pub create_time: Option<String>,
43    /// Update time (RFC3339).
44    #[serde(default)]
45    pub update_time: Option<String>,
46}
47
48/// Usage metadata for cached content.
49#[derive(Debug, Clone, Serialize, Deserialize)]
50#[serde(rename_all = "camelCase")]
51pub struct CachedContentUsageMetadata {
52    /// Total token count of the cached content.
53    #[serde(default)]
54    pub total_token_count: u64,
55}
56
57/// Configuration for creating cached content.
58#[derive(Debug, Clone)]
59pub struct CreateCachedContentConfig {
60    /// Model to use for caching.
61    pub model: String,
62    /// Display name.
63    pub display_name: Option<String>,
64    /// System instruction to cache.
65    pub system_instruction: Option<Content>,
66    /// Content to cache.
67    pub contents: Vec<Content>,
68    /// TTL duration string (e.g., "3600s").
69    pub ttl: Option<String>,
70}
71
72/// Updates to apply to a cached content resource.
73#[derive(Debug, Clone, Serialize, Deserialize)]
74#[serde(rename_all = "camelCase")]
75pub struct UpdateCachedContentRequest {
76    /// New TTL duration string.
77    #[serde(skip_serializing_if = "Option::is_none")]
78    pub ttl: Option<String>,
79    /// New expiration time (RFC3339).
80    #[serde(skip_serializing_if = "Option::is_none")]
81    pub expire_time: Option<String>,
82}
83
84/// Response from listCachedContents.
85#[derive(Debug, Clone, Serialize, Deserialize)]
86#[serde(rename_all = "camelCase")]
87pub struct ListCachedContentsResponse {
88    /// List of cached contents.
89    #[serde(default)]
90    pub cached_contents: Vec<CachedContent>,
91    /// Pagination token for the next page.
92    #[serde(default)]
93    pub next_page_token: Option<String>,
94}
95
96/// Errors from the Caches API.
97#[derive(Debug, thiserror::Error)]
98pub enum CachesError {
99    #[error(transparent)]
100    /// Transport-level HTTP failure.
101    Http(#[from] HttpError),
102    #[error("Failed to parse response: {0}")]
103    /// Response body failed to parse.
104    Parse(#[from] serde_json::Error),
105    #[error("Failed to serialize request: {0}")]
106    /// A request field failed to serialize to JSON.
107    Serialize(#[source] serde_json::Error),
108    #[error("Auth error: {0}")]
109    /// Authentication/authorization failure.
110    Auth(#[from] crate::session::AuthError),
111}
112
113impl Client {
114    /// List cached contents.
115    pub async fn list_cached_contents(&self) -> Result<ListCachedContentsResponse, CachesError> {
116        let url = self.rest_url(ServiceEndpoint::CachedContents);
117        let headers = self.auth_headers().await?;
118        let json = self.http_client().get_json(&url, headers).await?;
119        if json.is_null() {
120            return Ok(ListCachedContentsResponse {
121                cached_contents: vec![],
122                next_page_token: None,
123            });
124        }
125        Ok(serde_json::from_value(json)?)
126    }
127
128    /// Create a new cached content.
129    pub async fn create_cached_content(
130        &self,
131        config: CreateCachedContentConfig,
132    ) -> Result<CachedContent, CachesError> {
133        let url = self.rest_url(ServiceEndpoint::CachedContents);
134        let headers = self.auth_headers().await?;
135
136        let mut body = serde_json::json!({
137            "model": config.model,
138            "contents": config.contents,
139        });
140
141        if let Some(name) = config.display_name {
142            body["displayName"] = serde_json::Value::String(name);
143        }
144        if let Some(instruction) = &config.system_instruction {
145            body["systemInstruction"] =
146                serde_json::to_value(instruction).map_err(CachesError::Serialize)?;
147        }
148        if let Some(ttl) = config.ttl {
149            body["ttl"] = serde_json::Value::String(ttl);
150        }
151
152        let json = self.http_client().post_json(&url, headers, &body).await?;
153        Ok(serde_json::from_value(json)?)
154    }
155
156    /// Get a cached content by name.
157    pub async fn get_cached_content(&self, name: &str) -> Result<CachedContent, CachesError> {
158        let base_url = self.rest_url(ServiceEndpoint::CachedContents);
159        let url = format!("{base_url}/{name}");
160        let headers = self.auth_headers().await?;
161        let json = self.http_client().get_json(&url, headers).await?;
162        Ok(serde_json::from_value(json)?)
163    }
164
165    /// Update a cached content (TTL or expiration time).
166    pub async fn update_cached_content(
167        &self,
168        name: &str,
169        updates: UpdateCachedContentRequest,
170    ) -> Result<CachedContent, CachesError> {
171        let base_url = self.rest_url(ServiceEndpoint::CachedContents);
172        let url = format!("{base_url}/{name}");
173        let headers = self.auth_headers().await?;
174        let json = self
175            .http_client()
176            .patch_json(&url, headers, &updates)
177            .await?;
178        Ok(serde_json::from_value(json)?)
179    }
180
181    /// Delete a cached content by name.
182    pub async fn delete_cached_content(&self, name: &str) -> Result<(), CachesError> {
183        let base_url = self.rest_url(ServiceEndpoint::CachedContents);
184        let url = format!("{base_url}/{name}");
185        let headers = self.auth_headers().await?;
186        self.http_client().delete(&url, headers).await?;
187        Ok(())
188    }
189}
190
191#[cfg(test)]
192mod tests {
193    use super::*;
194
195    #[test]
196    fn parse_cached_content() {
197        let json = serde_json::json!({
198            "name": "cachedContents/abc123",
199            "displayName": "my-cache",
200            "model": "models/gemini-1.5-flash",
201            "expireTime": "2026-03-02T12:00:00Z",
202            "usageMetadata": {
203                "totalTokenCount": 5000
204            },
205            "createTime": "2026-03-01T12:00:00Z",
206            "updateTime": "2026-03-01T12:00:00Z"
207        });
208        let cached: CachedContent = serde_json::from_value(json).unwrap();
209        assert_eq!(cached.name, "cachedContents/abc123");
210        assert_eq!(cached.display_name, Some("my-cache".to_string()));
211        assert_eq!(cached.model, Some("models/gemini-1.5-flash".to_string()));
212        assert_eq!(cached.usage_metadata.unwrap().total_token_count, 5000);
213    }
214
215    #[test]
216    fn parse_list_cached_contents_response() {
217        let json = serde_json::json!({
218            "cachedContents": [
219                {"name": "cachedContents/a", "model": "models/gemini-1.5-flash"},
220                {"name": "cachedContents/b", "model": "models/gemini-1.5-pro"}
221            ],
222            "nextPageToken": "token123"
223        });
224        let resp: ListCachedContentsResponse = serde_json::from_value(json).unwrap();
225        assert_eq!(resp.cached_contents.len(), 2);
226        assert_eq!(resp.next_page_token, Some("token123".to_string()));
227    }
228
229    #[test]
230    fn update_request_serialization() {
231        let update = UpdateCachedContentRequest {
232            ttl: Some("7200s".to_string()),
233            expire_time: None,
234        };
235        let json = serde_json::to_value(&update).unwrap();
236        assert_eq!(json["ttl"], "7200s");
237        assert!(json.get("expireTime").is_none());
238    }
239
240    #[test]
241    fn usage_metadata_serialization() {
242        let meta = CachedContentUsageMetadata {
243            total_token_count: 12345,
244        };
245        let json = serde_json::to_value(&meta).unwrap();
246        assert_eq!(json["totalTokenCount"], 12345);
247    }
248
249    #[test]
250    fn empty_list_response() {
251        let json = serde_json::json!({"cachedContents": []});
252        let resp: ListCachedContentsResponse = serde_json::from_value(json).unwrap();
253        assert!(resp.cached_contents.is_empty());
254        assert!(resp.next_page_token.is_none());
255    }
256}