GeezerVison is showing github.com — feat: GenAI Client(evals) - Add location override parameter to run_in… · silverdev/python-aiplatform@b867043
File treeExpand file treeCollapse file tree Open diff view settings tests/unit/vertexai/genai
Expand file treeCollapse file tree Open diff view settings Collapse file Copy file name to clipboardExpand all lines: tests/unit/vertexai/genai/test_evals.py +44-2Lines changed: 44 additions & 2 deletions | Original file line number | Diff line number | Diff line change |
|---|
| 12 | 12 | # See the License for the specific language governing permissions and | 13 | 13 | # limitations under the License. | 14 | 14 | # | | 15 | +# pylint: disable=protected-access,bad-continuation, | 15 | 16 | import importlib | 16 | 17 | import json | 17 | 18 | import os | @@ -69,6 +70,7 @@ def mock_api_client_fixture(): | 69 | 70 | ) | 70 | 71 | mock_client._credentials.universe_domain = "googleapis.com" | 71 | 72 | mock_client._evals_client = mock.Mock(spec=evals.Evals) | | 73 | + mock_client._http_options = None | 72 | 74 | return mock_client | 73 | 75 |
| 74 | 76 |
| @@ -139,6 +141,46 @@ def mock_evaluate_instances_side_effect(*args, **kwargs): | 139 | 141 | } | 140 | 142 |
| 141 | 143 |
| | 144 | +class TestGetApiClientWithLocation: | | 145 | + @mock.patch("vertexai._genai._evals_common.vertexai.Client") | | 146 | + def test_get_api_client_with_location_override( | | 147 | + self, mock_vertexai_client, mock_api_client_fixture | | 148 | + ): | | 149 | + mock_api_client_fixture.location = "us-central1" | | 150 | + new_location = "europe-west1" | | 151 | + _evals_common._get_api_client_with_location( | | 152 | + mock_api_client_fixture, new_location | | 153 | + ) | | 154 | + mock_vertexai_client.assert_called_once_with( | | 155 | + project=mock_api_client_fixture.project, | | 156 | + location=new_location, | | 157 | + credentials=mock_api_client_fixture._credentials, | | 158 | + http_options=mock_api_client_fixture._http_options, | | 159 | + ) | | 160 | + | | 161 | + @mock.patch("vertexai._genai._evals_common.vertexai.Client") | | 162 | + def test_get_api_client_with_same_location( | | 163 | + self, mock_vertexai_client, mock_api_client_fixture | | 164 | + ): | | 165 | + mock_api_client_fixture.location = "us-central1" | | 166 | + new_location = "us-central1" | | 167 | + _evals_common._get_api_client_with_location( | | 168 | + mock_api_client_fixture, new_location | | 169 | + ) | | 170 | + mock_vertexai_client.assert_not_called() | | 171 | + | | 172 | + @mock.patch("vertexai._genai._evals_common.vertexai.Client") | | 173 | + def test_get_api_client_with_none_location( | | 174 | + self, mock_vertexai_client, mock_api_client_fixture | | 175 | + ): | | 176 | + mock_api_client_fixture.location = "us-central1" | | 177 | + new_location = None | | 178 | + _evals_common._get_api_client_with_location( | | 179 | + mock_api_client_fixture, new_location | | 180 | + ) | | 181 | + mock_vertexai_client.assert_not_called() | | 182 | + | | 183 | + | 142 | 184 | class TestEvals: | 143 | 185 | """Unit tests for the GenAI client.""" | 144 | 186 |
| @@ -4984,7 +5026,7 @@ def test_execute_evaluation_adds_creation_timestamp( | 4984 | 5026 | frozenset(["summarization_quality"]), | 4985 | 5027 | ) | 4986 | 5028 | @mock.patch("time.sleep", return_value=None) | 4987 | | - @mock.patch("vertexai._genai.evals.Evals._evaluate_instances") | | 5029 | + @mock.patch("vertexai._genai.evals.Evals._evaluate_instances") # fmt: skip | 4988 | 5030 | def test_predefined_metric_retry_on_resource_exhausted( | 4989 | 5031 | self, | 4990 | 5032 | mock_private_evaluate_instances, | @@ -5037,7 +5079,7 @@ def test_predefined_metric_retry_on_resource_exhausted( | 5037 | 5079 | frozenset(["summarization_quality"]), | 5038 | 5080 | ) | 5039 | 5081 | @mock.patch("time.sleep", return_value=None) | 5040 | | - @mock.patch("vertexai._genai.evals.Evals._evaluate_instances") | | 5082 | + @mock.patch("vertexai._genai.evals.Evals._evaluate_instances") # fmt: skip | 5041 | 5083 | def test_predefined_metric_retry_fail_on_resource_exhausted( | 5042 | 5084 | self, | 5043 | 5085 | mock_private_evaluate_instances, | |
Collapse file Copy file name to clipboardExpand all lines: vertexai/_genai/_evals_common.py +33Lines changed: 33 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
| 56 | 56 | AGENT_MAX_WORKERS = 10 | 57 | 57 |
| 58 | 58 |
| | 59 | +def _get_api_client_with_location( | | 60 | + api_client: BaseApiClient, location: Optional[str] | | 61 | +) -> BaseApiClient: | | 62 | + """Returns a new API client with the specified location.""" | | 63 | + if not location or location == api_client.location: | | 64 | + return api_client | | 65 | + | | 66 | + logger.info( | | 67 | + "Model endpoint location set to %s, overriding client location %s for this API call.", | | 68 | + location, | | 69 | + api_client.location, | | 70 | + ) | | 71 | + return vertexai.Client( | | 72 | + project=api_client.project, | | 73 | + location=location, | | 74 | + credentials=api_client._credentials, | | 75 | + http_options=api_client._http_options, | | 76 | + )._api_client | | 77 | + | | 78 | + | 59 | 79 | def _get_agent_engine_instance( | 60 | 80 | agent_name: str, api_client: BaseApiClient | 61 | 81 | ) -> Union[types.AgentEngine, Any]: | @@ -715,6 +735,7 @@ def _execute_inference( | 715 | 735 | dest: Optional[str] = None, | 716 | 736 | config: Optional[genai_types.GenerateContentConfig] = None, | 717 | 737 | prompt_template: Optional[Union[str, types.PromptTemplateOrDict]] = None, | | 738 | + location: Optional[str] = None, | 718 | 739 | ) -> pd.DataFrame: | 719 | 740 | """Executes inference on a given dataset using the specified model. | 720 | 741 |
| @@ -730,12 +751,18 @@ def _execute_inference( | 730 | 751 | representing a file path or a GCS URI. | 731 | 752 | config: The generation configuration for the model. | 732 | 753 | prompt_template: The prompt template to use for inference. | | 754 | + location: The location to use for the inference. If not specified, the | | 755 | + location configured in the client will be used. | 733 | 756 |
| 734 | 757 | Returns: | 735 | 758 | A pandas DataFrame containing the inference results. | 736 | 759 | """ | 737 | 760 | if not api_client: | 738 | 761 | raise ValueError("'api_client' instance must be provided.") | | 762 | + | | 763 | + if location: | | 764 | + api_client = _get_api_client_with_location(api_client, location) | | 765 | + | 739 | 766 | prompt_dataset = _load_dataframe(api_client, src) | 740 | 767 | if prompt_template: | 741 | 768 | logger.info("Applying prompt template...") | @@ -1056,6 +1083,7 @@ def _execute_evaluation( # type: ignore[no-untyped-def] | 1056 | 1083 | metrics: list[types.Metric], | 1057 | 1084 | dataset_schema: Optional[Literal["GEMINI", "FLATTEN", "OPENAI"]] = None, | 1058 | 1085 | dest: Optional[str] = None, | | 1086 | + location: Optional[str] = None, | 1059 | 1087 | **kwargs, | 1060 | 1088 | ) -> types.EvaluationResult: | 1061 | 1089 | """Evaluates a dataset using the provided metrics. | @@ -1066,12 +1094,17 @@ def _execute_evaluation( # type: ignore[no-untyped-def] | 1066 | 1094 | metrics: The metrics to evaluate the dataset against. | 1067 | 1095 | dataset_schema: The schema of the dataset. | 1068 | 1096 | dest: The destination to save the evaluation results. | | 1097 | + location: The location to use for the evaluation. If not specified, the | | 1098 | + location configured in the client will be used. | 1069 | 1099 | **kwargs: Extra arguments to pass to evaluation, such as `agent_info`. | 1070 | 1100 |
| 1071 | 1101 | Returns: | 1072 | 1102 | The evaluation result. | 1073 | 1103 | """ | 1074 | 1104 |
| | 1105 | + if location: | | 1106 | + api_client = _get_api_client_with_location(api_client, location) | | 1107 | + | 1075 | 1108 | logger.info("Preparing dataset(s) and metrics...") | 1076 | 1109 | if isinstance(dataset, types.EvaluationDataset): | 1077 | 1110 | dataset_list = [dataset] | |
Collapse file Copy file name to clipboardExpand all lines: vertexai/_genai/evals.py +13-1Lines changed: 13 additions & 1 deletion | Original file line number | Diff line number | Diff line change |
|---|
@@ -904,6 +904,7 @@ def run_inference( | 904 | 904 | src: Union[str, pd.DataFrame, types.EvaluationDataset], | 905 | 905 | model: Optional[Union[str, Callable[[Any], Any]]] = None, | 906 | 906 | agent: Optional[Union[str, types.AgentEngine]] = None, | | 907 | + location: Optional[str] = None, | 907 | 908 | config: Optional[types.EvalRunInferenceConfigOrDict] = None, | 908 | 909 | ) -> types.EvaluationDataset: | 909 | 910 | """Runs inference on a dataset for evaluation. | @@ -928,6 +929,10 @@ def run_inference( | 928 | 929 | `projects/{project}/locations/{location}/reasoningEngines/{reasoning_engine_id}`, | 929 | 930 | run_inference will fetch the agent engine from the resource name. | 930 | 931 | - Or `types.AgentEngine` object. | | 932 | + location: The location to use for the inference. If not specified, the | | 933 | + location configured in the client will be used. If specified, | | 934 | + this will override the location set in `vertexai.Client` only | | 935 | + for this API call. | 931 | 936 | config: The optional configuration for the inference run. Must be a dict or | 932 | 937 | `types.EvalRunInferenceConfig` type. | 933 | 938 | - dest: The destination path for storage of the inference results. | @@ -955,8 +960,9 @@ def run_inference( | 955 | 960 | agent_engine=agent, | 956 | 961 | src=src, | 957 | 962 | dest=config.dest, | 958 | | - config=config.generate_content_config, | 959 | 963 | prompt_template=config.prompt_template, | | 964 | + location=location, | | 965 | + config=config.generate_content_config, | 960 | 966 | ) | 961 | 967 |
| 962 | 968 | def evaluate( | @@ -968,6 +974,7 @@ def evaluate( | 968 | 974 | list[types.EvaluationDatasetOrDict], | 969 | 975 | ], | 970 | 976 | metrics: list[types.MetricOrDict] = None, | | 977 | + location: Optional[str] = None, | 971 | 978 | config: Optional[types.EvaluateMethodConfigOrDict] = None, | 972 | 979 | **kwargs, | 973 | 980 | ) -> types.EvaluationResult: | @@ -977,6 +984,10 @@ def evaluate( | 977 | 984 | dataset: The dataset(s) to evaluate. Can be a pandas DataFrame, a single | 978 | 985 | `types.EvaluationDataset` or a list of `types.EvaluationDataset`. | 979 | 986 | metrics: The list of metrics to use for evaluation. | | 987 | + location: The location to use for the evaluation service. If not specified, | | 988 | + the location configured in the client will be used. If specified, | | 989 | + this will override the location set in `vertexai.Client` only for | | 990 | + this API call. | 980 | 991 | config: Optional configuration for the evaluation. Can be a dictionary or a | 981 | 992 | `types.EvaluateMethodConfig` object. | 982 | 993 | - dataset_schema: Schema to use for the dataset. If not specified, the | @@ -1022,6 +1033,7 @@ def evaluate( | 1022 | 1033 | metrics=metrics, | 1023 | 1034 | dataset_schema=config.dataset_schema, | 1024 | 1035 | dest=config.dest, | | 1036 | + location=location, | 1025 | 1037 | **kwargs, | 1026 | 1038 | ) | 1027 | 1039 |
| |
|