|
| 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 | +# http://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 | +from __future__ import annotations |
| 16 | + |
| 17 | +import logging |
| 18 | +import os |
| 19 | +import re |
| 20 | + |
| 21 | +from google.cloud import exceptions as cloud_exceptions |
| 22 | +from google.cloud import storage |
| 23 | + |
| 24 | +from .eval_set import EvalSet |
| 25 | +from .eval_sets_manager import EvalSetStorageManager |
| 26 | + |
| 27 | +logger = logging.getLogger("google_adk." + __name__) |
| 28 | + |
| 29 | +_EVAL_SETS_DIR = "evals/eval_sets" |
| 30 | +_EVAL_SET_FILE_EXTENSION = ".evalset.json" |
| 31 | + |
| 32 | + |
| 33 | +class GcsEvalSetStorageManager(EvalSetStorageManager): |
| 34 | + """An EvalSetStorageManager that stores eval sets in a GCS bucket.""" |
| 35 | + |
| 36 | + def __init__(self, bucket_name: str, **kwargs): |
| 37 | + """Initializes the GcsEvalSetStorageManager. |
| 38 | +
|
| 39 | + Args: |
| 40 | + bucket_name: The name of the bucket to use. |
| 41 | + **kwargs: Keyword arguments to pass to the Google Cloud Storage client. |
| 42 | + """ |
| 43 | + self.bucket_name = bucket_name |
| 44 | + self.storage_client = storage.Client(**kwargs) |
| 45 | + self.bucket = self.storage_client.bucket(self.bucket_name) |
| 46 | + # Check if the bucket exists. |
| 47 | + if not self.bucket.exists(): |
| 48 | + raise ValueError( |
| 49 | + f"Bucket `{self.bucket_name}` does not exist. Please create it before" |
| 50 | + " using the GcsEvalSetStorageManager." |
| 51 | + ) |
| 52 | + |
| 53 | + def _get_eval_sets_dir(self, app_name: str) -> str: |
| 54 | + return f"{app_name}/{_EVAL_SETS_DIR}" |
| 55 | + |
| 56 | + def _validate_id(self, id_name: str, id_value: str): |
| 57 | + pattern = r"^[a-zA-Z0-9_]+$" |
| 58 | + if not bool(re.fullmatch(pattern, id_value)): |
| 59 | + raise ValueError( |
| 60 | + f"Invalid {id_name}. {id_name} should have the `{pattern}` format", |
| 61 | + ) |
| 62 | + |
| 63 | + def get_eval_set_path(self, app_name: str, eval_set_id: str) -> str: |
| 64 | + """Gets the path to the EvalSet identified by app_name and eval_set_id.""" |
| 65 | + eval_sets_dir = self._get_eval_sets_dir(app_name) |
| 66 | + return f"{eval_sets_dir}/{eval_set_id}{_EVAL_SET_FILE_EXTENSION}" |
| 67 | + |
| 68 | + def list_eval_sets(self, app_name: str) -> list[str]: |
| 69 | + """Gets the EvalSet id from the given path.""" |
| 70 | + eval_sets_dir = self._get_eval_sets_dir(app_name) |
| 71 | + eval_sets = [] |
| 72 | + try: |
| 73 | + for blob in self.bucket.list_blobs(prefix=eval_sets_dir): |
| 74 | + eval_set_id = blob.name.split("/")[-1].removesuffix( |
| 75 | + _EVAL_SET_FILE_EXTENSION |
| 76 | + ) |
| 77 | + eval_sets.append(eval_set_id) |
| 78 | + return sorted(eval_sets) |
| 79 | + |
| 80 | + except cloud_exceptions.NotFound as e: |
| 81 | + raise ValueError( |
| 82 | + f"App `{app_name}` not found in GCS bucket `{self.bucket_name}`." |
| 83 | + ) from e |
| 84 | + |
| 85 | + def save_eval_set(self, path: str, eval_set: EvalSet): |
| 86 | + """Writes the EvalSet to the given path.""" |
| 87 | + blob = self.bucket.blob(path) |
| 88 | + blob.upload_from_string( |
| 89 | + eval_set.model_dump_json(indent=2), |
| 90 | + content_type="application/json", |
| 91 | + ) |
| 92 | + |
| 93 | + def load_eval_set(self, path: str) -> EvalSet | None: |
| 94 | + """Loads the EvalSet from the given path.""" |
| 95 | + try: |
| 96 | + blob = self.bucket.blob(path) |
| 97 | + eval_set_data = blob.download_as_text() |
| 98 | + return EvalSet.model_validate_json(eval_set_data) |
| 99 | + except cloud_exceptions.NotFound: |
| 100 | + return None |
0 commit comments