|
| 1 | +# Copyright 2025 Google LLC |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# https://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | + |
| 16 | +def update_content_cache(cache_name: str) -> str: |
| 17 | + # [START googlegenaisdk_contentcache_update] |
| 18 | + from datetime import datetime as dt |
| 19 | + from datetime import timezone as tz |
| 20 | + from datetime import timedelta |
| 21 | + |
| 22 | + from google import genai |
| 23 | + from google.genai.types import HttpOptions, UpdateCachedContentConfig |
| 24 | + |
| 25 | + client = genai.Client(http_options=HttpOptions(api_version="v1beta1")) |
| 26 | + |
| 27 | + # Get content cache by name |
| 28 | + # cache_name = "projects/111111111111/locations/us-central1/cachedContents/1111111111111111111" |
| 29 | + content_cache = client.caches.get(name=cache_name) |
| 30 | + print("Expire time", content_cache.expire_time) |
| 31 | + # Example response |
| 32 | + # Expire time 2025-02-20 15:50:18.434482+00:00 |
| 33 | + |
| 34 | + # Update expire time using TTL |
| 35 | + content_cache = client.caches.update( |
| 36 | + name=cache_name, config=UpdateCachedContentConfig(ttl="36000s") |
| 37 | + ) |
| 38 | + time_diff = content_cache.expire_time - dt.now(tz.utc) |
| 39 | + print("Expire time(after update):", content_cache.expire_time) |
| 40 | + print("Expire time(in seconds):", time_diff.seconds) |
| 41 | + # Example response |
| 42 | + # Expire time(after update): 2025-02-14 01:51:42.571696+00:00 |
| 43 | + # Expire time(in seconds): 35999 |
| 44 | + |
| 45 | + # Update expire time using specific time stamp |
| 46 | + next_week_utc = dt.now(tz.utc) + timedelta(days=7) |
| 47 | + content_cache = client.caches.update( |
| 48 | + name=cache_name, config=UpdateCachedContentConfig(expireTime=next_week_utc) |
| 49 | + ) |
| 50 | + print("Expire time(after update):", content_cache.expire_time) |
| 51 | + # Example response |
| 52 | + # Expire time(after update): 2025-02-20 15:51:42.614968+00:00 |
| 53 | + # [END googlegenaisdk_contentcache_update] |
| 54 | + return cache_name |
| 55 | + |
| 56 | + |
| 57 | +if __name__ == "__main__": |
| 58 | + cache_name = input("Cache Name: ") |
| 59 | + update_content_cache(cache_name) |
0 commit comments