GeezerVison is showing github.com — fix: GenAI Client(evals) - Treat NaN and array cells as missing in ev… · hamgor/python-aiplatform@b28737e
File treeExpand file treeCollapse file tree Open diff view settings tests/unit/agentplatform/genai
Expand file treeCollapse file tree Open diff view settings Collapse file Copy file name to clipboardExpand all lines: agentplatform/_genai/_evals_common.py +14-7Lines changed: 14 additions & 7 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -123,6 +123,11 @@ def _temp_logger_level(logger_name: str, level: int) -> None: # type: ignore[mi | 123 | 123 | logger_instance.setLevel(original_level) | 124 | 124 |
| 125 | 125 |
| | 126 | +def _is_missing(value: Any) -> bool: | | 127 | + """Returns True for None or a scalar NaN, such as a missing DataFrame cell.""" | | 128 | + return bool(pd.api.types.is_scalar(value) and pd.isna(value)) | | 129 | + | | 130 | + | 126 | 131 | def _get_api_client_with_location( | 127 | 132 | api_client: BaseApiClient, location: Optional[str] | 128 | 133 | ) -> BaseApiClient: | @@ -1585,7 +1590,7 @@ def _build_interaction_id_dataset( | 1585 | 1590 | eval_cases = [] | 1586 | 1591 | for i, row in enumerate(loaded_data): | 1587 | 1592 | interaction = row.get(_evals_constant.INTERACTION_ID) | 1588 | | - if not interaction: | | 1593 | + if _is_missing(interaction) or not interaction: | 1589 | 1594 | raise ValueError(f"Missing `interaction_id` value for row {i}.") | 1590 | 1595 | eval_cases.append( | 1591 | 1596 | types.EvalCase( | @@ -1895,12 +1900,12 @@ def _execute_inference_concurrently( | 1895 | 1900 | max_workers = AGENT_MAX_WORKERS if runtime or agent else MAX_WORKERS | 1896 | 1901 | with tqdm(total=len(prompt_dataset), desc=progress_desc) as pbar: | 1897 | 1902 | with concurrent.futures.ThreadPoolExecutor(max_workers=max_workers) as executor: | 1898 | | - for index, row in prompt_dataset.iterrows(): | | 1903 | + for index, (_, row) in enumerate(prompt_dataset.iterrows()): | 1899 | 1904 | try: | 1900 | 1905 | if ( | 1901 | 1906 | has_agent_data | 1902 | 1907 | and AGENT_DATA in row.index | 1903 | | - and row.get(AGENT_DATA) is not None | | 1908 | + and not _is_missing(row.get(AGENT_DATA)) | 1904 | 1909 | ): | 1905 | 1910 | agent_data_obj = row[AGENT_DATA] | 1906 | 1911 | if isinstance(agent_data_obj, dict): | @@ -2125,7 +2130,7 @@ def _run_litellm_inference( | 2125 | 2130 |
| 2126 | 2131 | with tqdm(total=len(prompt_dataset), desc=f"LiteLLM Inference ({model})") as pbar: | 2127 | 2132 | with concurrent.futures.ThreadPoolExecutor(max_workers=MAX_WORKERS) as executor: | 2128 | | - for index, row in prompt_dataset.iterrows(): | | 2133 | + for index, (_, row) in enumerate(prompt_dataset.iterrows()): | 2129 | 2134 | messages = _convert_prompt_row_to_litellm_messages(row) | 2130 | 2135 | future = executor.submit( | 2131 | 2136 | _call_litellm_completion, model=model, messages=messages | @@ -3866,7 +3871,7 @@ def _drop_empty_columns(df: "pd.DataFrame") -> "pd.DataFrame": | 3866 | 3871 | def is_empty(x: Any) -> bool: | 3867 | 3872 | if isinstance(x, (list, dict)): | 3868 | 3873 | return not x | 3869 | | - return pd.isna(x) # type: ignore[no-any-return] | | 3874 | + return _is_missing(x) | 3870 | 3875 |
| 3871 | 3876 | cols_to_drop = [col for col in df.columns if df[col].apply(is_empty).all()] | 3872 | 3877 | return df.drop(columns=cols_to_drop) | @@ -4165,6 +4170,8 @@ def _create_evaluation_set_from_dataframe( | 4165 | 4170 | if _evals_constant.RESPONSE in row or agent_data_obj or intermediate_events: | 4166 | 4171 | # Resolve the oneof conflict: prioritize agent_data over flat text | 4167 | 4172 | response_text = row.get(_evals_constant.RESPONSE) or None | | 4173 | + if _is_missing(response_text): | | 4174 | + response_text = None | 4168 | 4175 |
| 4169 | 4176 | if agent_data_obj and response_text: | 4170 | 4177 | logger.info( | @@ -4219,15 +4226,15 @@ def _create_evaluation_set_from_dataframe( | 4219 | 4226 | prompt = types.EvaluationPrompt( | 4220 | 4227 | prompt_template_data=types.PromptTemplateData(values=values) | 4221 | 4228 | ) | 4222 | | - elif _evals_constant.PROMPT in row: | | 4229 | + elif not _is_missing(row.get(_evals_constant.PROMPT)): | 4223 | 4230 | prompt = types.EvaluationPrompt(text=row[_evals_constant.PROMPT]) | 4224 | 4231 |
| 4225 | 4232 | eval_item_requests.append( | 4226 | 4233 | types.EvaluationItemRequest( | 4227 | 4234 | prompt=prompt or None, | 4228 | 4235 | golden_response=( | 4229 | 4236 | types.CandidateResponse(text=row[_evals_constant.REFERENCE]) | 4230 | | - if _evals_constant.REFERENCE in row | | 4237 | + if not _is_missing(row.get(_evals_constant.REFERENCE)) | 4231 | 4238 | else None | 4232 | 4239 | ), | 4233 | 4240 | candidate_responses=( | |
Collapse file Copy file name to clipboardExpand all lines: tests/unit/agentplatform/genai/test_evals.py +100Lines changed: 100 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -102,6 +102,16 @@ def test_drop_empty_columns_none_empty(self): | 102 | 102 | result_df = _evals_common._drop_empty_columns(df) | 103 | 103 | assert list(result_df.columns) == ["col1", "col2"] | 104 | 104 |
| | 105 | + def test_drop_empty_columns_with_array_cells(self): | | 106 | + df = pd.DataFrame( | | 107 | + { | | 108 | + "col1": [None, None], | | 109 | + "col2": [pd.Series([1, 2]).to_numpy(), pd.Series([3, 4]).to_numpy()], | | 110 | + } | | 111 | + ) | | 112 | + result_df = _evals_common._drop_empty_columns(df) | | 113 | + assert list(result_df.columns) == ["col2"] | | 114 | + | 105 | 115 |
| 106 | 116 | def _create_content_dump(text: str) -> dict[str, list[genai_types.Content]]: | 107 | 117 | return { | @@ -4816,6 +4826,61 @@ def test_has_tool_call_with_agent_event(self): | 4816 | 4826 | assert _evals_metric_handlers._has_tool_call(events) | 4817 | 4827 |
| 4818 | 4828 |
| | 4829 | +class TestExecuteInferenceConcurrently: | | 4830 | + """Unit tests for row handling in the concurrent inference helpers.""" | | 4831 | + | | 4832 | + def test_missing_agent_data_falls_back_to_prompt(self): | | 4833 | + completed_trace = { | | 4834 | + "turns": [ | | 4835 | + { | | 4836 | + "events": [ | | 4837 | + {"author": "user", "content": {"parts": [{"text": "hi"}]}}, | | 4838 | + {"author": "agent", "content": {"parts": [{"text": "hey"}]}}, | | 4839 | + ] | | 4840 | + } | | 4841 | + ] | | 4842 | + } | | 4843 | + prompt_dataset = pd.DataFrame( | | 4844 | + [{"prompt": "p0", "agent_data": completed_trace}, {"prompt": "p1"}] | | 4845 | + ) | | 4846 | + inference_fn = mock.Mock(return_value={"response": "r1"}) | | 4847 | + | | 4848 | + responses = _evals_common._execute_inference_concurrently( | | 4849 | + api_client=mock.Mock(), | | 4850 | + prompt_dataset=prompt_dataset, | | 4851 | + progress_desc="Agent Run", | | 4852 | + inference_fn=inference_fn, | | 4853 | + runtime=mock.Mock(), | | 4854 | + ) | | 4855 | + | | 4856 | + assert [event["author"] for event in responses[0]] == ["user", "agent"] | | 4857 | + assert responses[1] == {"response": "r1"} | | 4858 | + assert inference_fn.call_args.kwargs["contents"] == "p1" | | 4859 | + | | 4860 | + def test_responses_follow_row_positions(self): | | 4861 | + prompt_dataset = pd.DataFrame({"prompt": ["p0", "p1"]}, index=[1, 0]) | | 4862 | + | | 4863 | + responses = _evals_common._execute_inference_concurrently( | | 4864 | + api_client=None, | | 4865 | + prompt_dataset=prompt_dataset, | | 4866 | + progress_desc="Custom Inference", | | 4867 | + model_or_fn=lambda contents: f"response to {contents}", | | 4868 | + ) | | 4869 | + | | 4870 | + assert responses == ["response to p0", "response to p1"] | | 4871 | + | | 4872 | + @mock.patch.object(_evals_common, "_call_litellm_completion") | | 4873 | + def test_litellm_responses_follow_row_positions(self, mock_call_litellm_completion): | | 4874 | + mock_call_litellm_completion.side_effect = lambda model, messages: { | | 4875 | + "content": messages[0]["content"] | | 4876 | + } | | 4877 | + prompt_dataset = pd.DataFrame({"prompt": ["p0", "p1"]}, index=[1, 0]) | | 4878 | + | | 4879 | + responses = _evals_common._run_litellm_inference("gpt-4o", prompt_dataset) | | 4880 | + | | 4881 | + assert responses == [{"content": "p0"}, {"content": "p1"}] | | 4882 | + | | 4883 | + | 4819 | 4884 | @pytest.mark.usefixtures("google_auth_mock") | 4820 | 4885 | class TestRunAgent: | 4821 | 4886 | """Unit tests for the _run_agent function.""" | @@ -10308,6 +10373,33 @@ def test_create_evaluation_set_with_intermediate_events( | 10308 | 10373 | ] | 10309 | 10374 | assert candidate_response["events"] == expected_events | 10310 | 10375 |
| | 10376 | + @mock.patch.object(_evals_common, "evals") | | 10377 | + @mock.patch.object(_evals_common, "_gcs_utils") | | 10378 | + def test_create_evaluation_set_treats_nan_cells_as_missing( | | 10379 | + self, mock_gcs_utils, mock_evals_module | | 10380 | + ): | | 10381 | + eval_df = pd.DataFrame( | | 10382 | + [{"prompt": "p0", "response": "r0"}, {"reference": "ref1"}] | | 10383 | + ) | | 10384 | + | | 10385 | + _evals_common._create_evaluation_set_from_dataframe( | | 10386 | + api_client=self.mock_api_client, | | 10387 | + gcs_dest_prefix="gs://bucket/prefix", | | 10388 | + eval_df=eval_df, | | 10389 | + candidate_name="test-candidate", | | 10390 | + ) | | 10391 | + | | 10392 | + upload = mock_gcs_utils.GcsUtils.return_value.upload_json_to_prefix | | 10393 | + first, second = (call.kwargs["data"] for call in upload.call_args_list) | | 10394 | + assert first == { | | 10395 | + "prompt": {"text": "p0"}, | | 10396 | + "candidateResponses": [{"candidate": "test-candidate", "text": "r0"}], | | 10397 | + } | | 10398 | + assert second == { | | 10399 | + "goldenResponse": {"text": "ref1"}, | | 10400 | + "candidateResponses": [{"candidate": "test-candidate"}], | | 10401 | + } | | 10402 | + | 10311 | 10403 | @mock.patch.object(_evals_common, "evals") | 10312 | 10404 | @mock.patch.object(_evals_common, "_gcs_utils") | 10313 | 10405 | def test_create_evaluation_set_with_user_scenario( | @@ -11799,6 +11891,14 @@ def test_build_interaction_id_dataset_requires_agent(self): | 11799 | 11891 | [{"interaction_id": "abc123"}], None, "global" | 11800 | 11892 | ) | 11801 | 11893 |
| | 11894 | + def test_build_interaction_id_dataset_rejects_nan_interaction_id(self): | | 11895 | + with pytest.raises(ValueError, match="Missing `interaction_id` value"): | | 11896 | + _evals_common._build_interaction_id_dataset( | | 11897 | + [{"interaction_id": "abc123"}, {"interaction_id": float("nan")}], | | 11898 | + _TEST_GEMINI_AGENT, | | 11899 | + "global", | | 11900 | + ) | | 11901 | + | 11802 | 11902 | def test_build_interaction_id_dataset_rejects_non_gemini_agent(self): | 11803 | 11903 | with pytest.raises(ValueError, match="Gemini Agents API resource name"): | 11804 | 11904 | _evals_common._build_interaction_id_dataset( | |
Collapse file Copy file name to clipboardExpand all lines: vertexai/_genai/_evals_common.py +13-6Lines changed: 13 additions & 6 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -93,6 +93,11 @@ def _temp_logger_level(logger_name: str, level: int) -> None: # type: ignore[mi | 93 | 93 | logger_instance.setLevel(original_level) | 94 | 94 |
| 95 | 95 |
| | 96 | +def _is_missing(value: Any) -> bool: | | 97 | + """Returns True for None or a scalar NaN, such as a missing DataFrame cell.""" | | 98 | + return bool(pd.api.types.is_scalar(value) and pd.isna(value)) | | 99 | + | | 100 | + | 96 | 101 | def _get_api_client_with_location( | 97 | 102 | api_client: BaseApiClient, location: Optional[str] | 98 | 103 | ) -> BaseApiClient: | @@ -684,12 +689,12 @@ def _execute_inference_concurrently( | 684 | 689 | max_workers = AGENT_MAX_WORKERS if agent_engine or agent else MAX_WORKERS | 685 | 690 | with tqdm(total=len(prompt_dataset), desc=progress_desc) as pbar: | 686 | 691 | with concurrent.futures.ThreadPoolExecutor(max_workers=max_workers) as executor: | 687 | | - for index, row in prompt_dataset.iterrows(): | | 692 | + for index, (_, row) in enumerate(prompt_dataset.iterrows()): | 688 | 693 | try: | 689 | 694 | if ( | 690 | 695 | has_agent_data | 691 | 696 | and AGENT_DATA in row.index | 692 | | - and row.get(AGENT_DATA) is not None | | 697 | + and not _is_missing(row.get(AGENT_DATA)) | 693 | 698 | ): | 694 | 699 | agent_data_obj = row[AGENT_DATA] | 695 | 700 | if isinstance(agent_data_obj, dict): | @@ -913,7 +918,7 @@ def _run_litellm_inference( | 913 | 918 |
| 914 | 919 | with tqdm(total=len(prompt_dataset), desc=f"LiteLLM Inference ({model})") as pbar: | 915 | 920 | with concurrent.futures.ThreadPoolExecutor(max_workers=MAX_WORKERS) as executor: | 916 | | - for index, row in prompt_dataset.iterrows(): | | 921 | + for index, (_, row) in enumerate(prompt_dataset.iterrows()): | 917 | 922 | messages = _convert_prompt_row_to_litellm_messages(row) | 918 | 923 | future = executor.submit( | 919 | 924 | _call_litellm_completion, model=model, messages=messages | @@ -2645,7 +2650,7 @@ def _drop_empty_columns(df: "pd.DataFrame") -> "pd.DataFrame": | 2645 | 2650 | def is_empty(x: Any) -> bool: | 2646 | 2651 | if isinstance(x, (list, dict)): | 2647 | 2652 | return not x | 2648 | | - return pd.isna(x) # type: ignore[no-any-return] | | 2653 | + return _is_missing(x) | 2649 | 2654 |
| 2650 | 2655 | cols_to_drop = [col for col in df.columns if df[col].apply(is_empty).all()] | 2651 | 2656 | return df.drop(columns=cols_to_drop) | @@ -2944,6 +2949,8 @@ def _create_evaluation_set_from_dataframe( | 2944 | 2949 | if _evals_constant.RESPONSE in row or agent_data_obj or intermediate_events: | 2945 | 2950 | # Resolve the oneof conflict: prioritize agent_data over flat text | 2946 | 2951 | response_text = row.get(_evals_constant.RESPONSE) or None | | 2952 | + if _is_missing(response_text): | | 2953 | + response_text = None | 2947 | 2954 |
| 2948 | 2955 | if agent_data_obj and response_text: | 2949 | 2956 | logger.info( | @@ -2998,15 +3005,15 @@ def _create_evaluation_set_from_dataframe( | 2998 | 3005 | prompt = types.EvaluationPrompt( | 2999 | 3006 | prompt_template_data=types.PromptTemplateData(values=values) | 3000 | 3007 | ) | 3001 | | - elif _evals_constant.PROMPT in row: | | 3008 | + elif not _is_missing(row.get(_evals_constant.PROMPT)): | 3002 | 3009 | prompt = types.EvaluationPrompt(text=row[_evals_constant.PROMPT]) | 3003 | 3010 |
| 3004 | 3011 | eval_item_requests.append( | 3005 | 3012 | types.EvaluationItemRequest( | 3006 | 3013 | prompt=prompt or None, | 3007 | 3014 | golden_response=( | 3008 | 3015 | types.CandidateResponse(text=row[_evals_constant.REFERENCE]) | 3009 | | - if _evals_constant.REFERENCE in row | | 3016 | + if not _is_missing(row.get(_evals_constant.REFERENCE)) | 3010 | 3017 | else None | 3011 | 3018 | ), | 3012 | 3019 | candidate_responses=( | |
|