|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | +# Copyright 2024 Google LLC |
| 3 | +# |
| 4 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +# you may not use this file except in compliance with the License. |
| 6 | +# You may obtain a copy of the License at |
| 7 | +# |
| 8 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +# |
| 10 | +# Unless required by applicable law or agreed to in writing, software |
| 11 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +# See the License for the specific language governing permissions and |
| 14 | +# limitations under the License. |
| 15 | +from __future__ import annotations |
| 16 | + |
| 17 | +import dataclasses |
| 18 | +import datetime |
| 19 | +from typing import Any, Iterable, Optional |
| 20 | + |
| 21 | +from google.generativeai import protos |
| 22 | +from google.generativeai.types.model_types import idecode_time |
| 23 | +from google.generativeai.types import caching_types |
| 24 | +from google.generativeai.types import content_types |
| 25 | +from google.generativeai.utils import flatten_update_paths |
| 26 | +from google.generativeai.client import get_default_cache_client |
| 27 | + |
| 28 | +from google.protobuf import field_mask_pb2 |
| 29 | +import google.ai.generativelanguage as glm |
| 30 | + |
| 31 | + |
| 32 | +@dataclasses.dataclass |
| 33 | +class CachedContent: |
| 34 | + """Cached content resource.""" |
| 35 | + |
| 36 | + name: str |
| 37 | + model: str |
| 38 | + create_time: datetime.datetime |
| 39 | + update_time: datetime.datetime |
| 40 | + expire_time: datetime.datetime |
| 41 | + |
| 42 | + # NOTE: Automatic CachedContent deletion using contextmanager is not P0(P1+). |
| 43 | + # Adding basic support for now. |
| 44 | + def __enter__(self): |
| 45 | + return self |
| 46 | + |
| 47 | + def __exit__(self, exc_type, exc_value, exc_tb): |
| 48 | + self.delete() |
| 49 | + |
| 50 | + def _to_dict(self) -> protos.CachedContent: |
| 51 | + proto_paths = { |
| 52 | + "name": self.name, |
| 53 | + "model": self.model, |
| 54 | + } |
| 55 | + return protos.CachedContent(**proto_paths) |
| 56 | + |
| 57 | + def _apply_update(self, path, value): |
| 58 | + parts = path.split(".") |
| 59 | + for part in parts[:-1]: |
| 60 | + self = getattr(self, part) |
| 61 | + if parts[-1] == "ttl": |
| 62 | + value = self.expire_time + datetime.timedelta(seconds=value["seconds"]) |
| 63 | + parts[-1] = "expire_time" |
| 64 | + setattr(self, parts[-1], value) |
| 65 | + |
| 66 | + @classmethod |
| 67 | + def _decode_cached_content(cls, cached_content: protos.CachedContent) -> CachedContent: |
| 68 | + # not supposed to get INPUT_ONLY repeated fields, but local gapic lib build |
| 69 | + # is returning these, hence setting including_default_value_fields to False |
| 70 | + cached_content = type(cached_content).to_dict( |
| 71 | + cached_content, including_default_value_fields=False |
| 72 | + ) |
| 73 | + |
| 74 | + idecode_time(cached_content, "create_time") |
| 75 | + idecode_time(cached_content, "update_time") |
| 76 | + # always decode `expire_time` as Timestamp is returned |
| 77 | + # regardless of what was sent on input |
| 78 | + idecode_time(cached_content, "expire_time") |
| 79 | + return cls(**cached_content) |
| 80 | + |
| 81 | + @staticmethod |
| 82 | + def _prepare_create_request( |
| 83 | + model: str, |
| 84 | + name: str | None = None, |
| 85 | + system_instruction: Optional[content_types.ContentType] = None, |
| 86 | + contents: Optional[content_types.ContentsType] = None, |
| 87 | + tools: Optional[content_types.FunctionLibraryType] = None, |
| 88 | + tool_config: Optional[content_types.ToolConfigType] = None, |
| 89 | + ttl: Optional[caching_types.ExpirationTypes] = datetime.timedelta(hours=1), |
| 90 | + ) -> protos.CreateCachedContentRequest: |
| 91 | + """Prepares a CreateCachedContentRequest.""" |
| 92 | + if name is not None: |
| 93 | + if not caching_types.valid_cached_content_name(name): |
| 94 | + raise ValueError(caching_types.NAME_ERROR_MESSAGE.format(name=name)) |
| 95 | + |
| 96 | + name = "cachedContents/" + name |
| 97 | + |
| 98 | + if "/" not in model: |
| 99 | + model = "models/" + model |
| 100 | + |
| 101 | + if system_instruction: |
| 102 | + system_instruction = content_types.to_content(system_instruction) |
| 103 | + |
| 104 | + tools_lib = content_types.to_function_library(tools) |
| 105 | + if tools_lib: |
| 106 | + tools_lib = tools_lib.to_proto() |
| 107 | + |
| 108 | + if tool_config: |
| 109 | + tool_config = content_types.to_tool_config(tool_config) |
| 110 | + |
| 111 | + if contents: |
| 112 | + contents = content_types.to_contents(contents) |
| 113 | + |
| 114 | + if ttl: |
| 115 | + ttl = caching_types.to_ttl(ttl) |
| 116 | + |
| 117 | + cached_content = protos.CachedContent( |
| 118 | + name=name, |
| 119 | + model=model, |
| 120 | + system_instruction=system_instruction, |
| 121 | + contents=contents, |
| 122 | + tools=tools_lib, |
| 123 | + tool_config=tool_config, |
| 124 | + ttl=ttl, |
| 125 | + ) |
| 126 | + |
| 127 | + return protos.CreateCachedContentRequest(cached_content=cached_content) |
| 128 | + |
| 129 | + @classmethod |
| 130 | + def create( |
| 131 | + cls, |
| 132 | + model: str, |
| 133 | + name: str | None = None, |
| 134 | + system_instruction: Optional[content_types.ContentType] = None, |
| 135 | + contents: Optional[content_types.ContentsType] = None, |
| 136 | + tools: Optional[content_types.FunctionLibraryType] = None, |
| 137 | + tool_config: Optional[content_types.ToolConfigType] = None, |
| 138 | + ttl: Optional[caching_types.ExpirationTypes] = datetime.timedelta(hours=1), |
| 139 | + client: glm.CacheServiceClient | None = None, |
| 140 | + ) -> CachedContent: |
| 141 | + """Creates `CachedContent` resource. |
| 142 | +
|
| 143 | + Args: |
| 144 | + model: The name of the `model` to use for cached content creation. |
| 145 | + Any `CachedContent` resource can be only used with the |
| 146 | + `model` it was created for. |
| 147 | + name: The resource name referring to the cached content. |
| 148 | + system_instruction: Developer set system instruction. |
| 149 | + contents: Contents to cache. |
| 150 | + tools: A list of `Tools` the model may use to generate response. |
| 151 | + tool_config: Config to apply to all tools. |
| 152 | + ttl: TTL for cached resource (in seconds). Defaults to 1 hour. |
| 153 | +
|
| 154 | + Returns: |
| 155 | + `CachedContent` resource with specified name. |
| 156 | + """ |
| 157 | + if client is None: |
| 158 | + client = get_default_cache_client() |
| 159 | + |
| 160 | + request = cls._prepare_create_request( |
| 161 | + model=model, |
| 162 | + name=name, |
| 163 | + system_instruction=system_instruction, |
| 164 | + contents=contents, |
| 165 | + tools=tools, |
| 166 | + tool_config=tool_config, |
| 167 | + ttl=ttl, |
| 168 | + ) |
| 169 | + |
| 170 | + response = client.create_cached_content(request) |
| 171 | + return cls._decode_cached_content(response) |
| 172 | + |
| 173 | + @classmethod |
| 174 | + def get(cls, name: str, client: glm.CacheServiceClient | None = None) -> CachedContent: |
| 175 | + """Fetches required `CachedContent` resource. |
| 176 | +
|
| 177 | + Args: |
| 178 | + name: The resource name referring to the cached content. |
| 179 | +
|
| 180 | + Returns: |
| 181 | + `CachedContent` resource with specified `name`. |
| 182 | + """ |
| 183 | + if client is None: |
| 184 | + client = get_default_cache_client() |
| 185 | + |
| 186 | + if "cachedContents/" not in name: |
| 187 | + name = "cachedContents/" + name |
| 188 | + |
| 189 | + request = protos.GetCachedContentRequest(name=name) |
| 190 | + response = client.get_cached_content(request) |
| 191 | + return cls._decode_cached_content(response) |
| 192 | + |
| 193 | + @classmethod |
| 194 | + def list( |
| 195 | + cls, page_size: Optional[int] = 1, client: glm.CacheServiceClient | None = None |
| 196 | + ) -> Iterable[CachedContent]: |
| 197 | + """Lists `CachedContent` objects associated with the project. |
| 198 | +
|
| 199 | + Args: |
| 200 | + page_size: The maximum number of permissions to return (per page). |
| 201 | + The service may return fewer `CachedContent` objects. |
| 202 | +
|
| 203 | + Returns: |
| 204 | + A paginated list of `CachedContent` objects. |
| 205 | + """ |
| 206 | + if client is None: |
| 207 | + client = get_default_cache_client() |
| 208 | + |
| 209 | + request = protos.ListCachedContentsRequest(page_size=page_size) |
| 210 | + for cached_content in client.list_cached_contents(request): |
| 211 | + yield cls._decode_cached_content(cached_content) |
| 212 | + |
| 213 | + def delete(self, client: glm.CachedServiceClient | None = None) -> None: |
| 214 | + """Deletes `CachedContent` resource.""" |
| 215 | + if client is None: |
| 216 | + client = get_default_cache_client() |
| 217 | + |
| 218 | + request = protos.DeleteCachedContentRequest(name=self.name) |
| 219 | + client.delete_cached_content(request) |
| 220 | + return |
| 221 | + |
| 222 | + def update( |
| 223 | + self, |
| 224 | + updates: dict[str, Any], |
| 225 | + client: glm.CacheServiceClient | None = None, |
| 226 | + ) -> CachedContent: |
| 227 | + """Updates requested `CachedContent` resource. |
| 228 | +
|
| 229 | + Args: |
| 230 | + updates: The list of fields to update. Currently only |
| 231 | + `ttl/expire_time` is supported as an update path. |
| 232 | +
|
| 233 | + Returns: |
| 234 | + `CachedContent` object with specified updates. |
| 235 | + """ |
| 236 | + if client is None: |
| 237 | + client = get_default_cache_client() |
| 238 | + |
| 239 | + updates = flatten_update_paths(updates) |
| 240 | + for update_path in updates: |
| 241 | + if update_path == "ttl": |
| 242 | + updates = updates.copy() |
| 243 | + update_path_val = updates.get(update_path) |
| 244 | + updates[update_path] = caching_types.to_ttl(update_path_val) |
| 245 | + else: |
| 246 | + raise ValueError( |
| 247 | + f"As of now, only `ttl` can be updated for `CachedContent`. Got: `{update_path}` instead." |
| 248 | + ) |
| 249 | + field_mask = field_mask_pb2.FieldMask() |
| 250 | + |
| 251 | + for path in updates.keys(): |
| 252 | + field_mask.paths.append(path) |
| 253 | + for path, value in updates.items(): |
| 254 | + self._apply_update(path, value) |
| 255 | + |
| 256 | + request = protos.UpdateCachedContentRequest( |
| 257 | + cached_content=self._to_dict(), update_mask=field_mask |
| 258 | + ) |
| 259 | + client.update_cached_content(request) |
| 260 | + return self |
0 commit comments