GeezerVison is showing github.com — feat: GenAI SDK client - add zero-shot prompt optimizer: an option to… · googleapis/python-aiplatform@bc2e8f4
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/replays/conftest.py +43Lines changed: 43 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
| 29 | 29 | from vertexai._genai import prompt_optimizer | 30 | 30 | import pytest | 31 | 31 |
| | 32 | + | | 33 | +from typing import Any, Optional, Union | | 34 | +import pydantic | | 35 | + | | 36 | + | | 37 | +def pop_undeterministic_headers(headers: dict[str, str]) -> None: | | 38 | + """Remove headers that are not deterministic.""" | | 39 | + headers.pop("Date", None) # pytype: disable=attribute-error | | 40 | + headers.pop("Server-Timing", None) # pytype: disable=attribute-error | | 41 | + | | 42 | + | | 43 | +class PatchedReplayResponse(pydantic.BaseModel): | | 44 | + """Represents a single response in a replay.""" | | 45 | + | | 46 | + status_code: int = 200 | | 47 | + headers: dict[str, str] | | 48 | + body_segments: list[Union[list[dict[str, object]], dict[str, object]]] | | 49 | + byte_segments: Optional[list[bytes]] = None | | 50 | + sdk_response_segments: list[dict[str, object]] | | 51 | + | | 52 | + def model_post_init(self, __context: Any) -> None: | | 53 | + pop_undeterministic_headers(self.headers) | | 54 | + | | 55 | + | | 56 | +class PatchedReplayInteraction(pydantic.BaseModel): | | 57 | + """Represents a single interaction, request and response in a replay.""" | | 58 | + | | 59 | + request: _replay_api_client.ReplayRequest | | 60 | + response: PatchedReplayResponse | | 61 | + | | 62 | + | | 63 | +class PatchedReplayFile(pydantic.BaseModel): | | 64 | + """Represents a recorded session.""" | | 65 | + | | 66 | + replay_id: str | | 67 | + interactions: list[PatchedReplayInteraction] | | 68 | + | | 69 | + | | 70 | +_replay_api_client.ReplayResponse = PatchedReplayResponse | | 71 | +_replay_api_client.ReplayInteraction = PatchedReplayInteraction | | 72 | +_replay_api_client.ReplayFile = PatchedReplayFile | | 73 | + | | 74 | + | 32 | 75 | IS_KOKORO = os.getenv("KOKORO_BUILD_NUMBER") is not None | 33 | 76 |
| 34 | 77 |
| |
Collapse file Copy file name to clipboard +38Lines changed: 38 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
| | 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 | +# pylint: disable=protected-access,bad-continuation,missing-function-docstring | | 16 | + | | 17 | +from tests.unit.vertexai.genai.replays import pytest_helper | | 18 | +from vertexai._genai import types | | 19 | +import pytest | | 20 | + | | 21 | + | | 22 | +pytest_plugins = ("pytest_asyncio",) | | 23 | + | | 24 | + | | 25 | +@pytest.mark.asyncio | | 26 | +async def test_optimize_prompt(client): | | 27 | + """Tests the optimize request parameters method.""" | | 28 | + | | 29 | + test_prompt = "Generate system instructions for analyzing medical articles" | | 30 | + response = await client.aio.prompt_optimizer.optimize_prompt(prompt=test_prompt) | | 31 | + assert isinstance(response, types.OptimizeResponse) | | 32 | + | | 33 | + | | 34 | +pytestmark = pytest_helper.setup( | | 35 | + file=__file__, | | 36 | + globals_for_file=globals(), | | 37 | + test_method="prompt_optimizer.optimize_prompt", | | 38 | +) |
Collapse file Copy file name to clipboard +33Lines changed: 33 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
| | 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 | +# pylint: disable=protected-access,bad-continuation,missing-function-docstring | | 16 | + | | 17 | +from tests.unit.vertexai.genai.replays import pytest_helper | | 18 | +from vertexai._genai import types | | 19 | + | | 20 | + | | 21 | +def test_optimize_prompt(client): | | 22 | + """Tests the optimize request parameters method.""" | | 23 | + | | 24 | + test_prompt = "Generate system instructions for analyzing medical articles" | | 25 | + response = client.prompt_optimizer.optimize_prompt(prompt=test_prompt) | | 26 | + assert isinstance(response, types.OptimizeResponse) | | 27 | + | | 28 | + | | 29 | +pytestmark = pytest_helper.setup( | | 30 | + file=__file__, | | 31 | + globals_for_file=globals(), | | 32 | + test_method="prompt_optimizer.optimize_prompt", | | 33 | +) |
Collapse file Copy file name to clipboardExpand all lines: tests/unit/vertexai/genai/test_prompt_optimizer.py +11Lines changed: 11 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -64,4 +64,15 @@ def test_prompt_optimizer_optimize(self, mock_custom_job, mock_client): | 64 | 64 | mock_client.assert_called_once() | 65 | 65 | mock_custom_job.assert_called_once() | 66 | 66 |
| | 67 | + @mock.patch.object(client.Client, "_get_api_client") | | 68 | + @mock.patch.object(prompt_optimizer.PromptOptimizer, "_custom_optimize_prompt") | | 69 | + def test_prompt_optimizer_optimize_prompt( | | 70 | + self, mock_custom_optimize_prompt, mock_client | | 71 | + ): | | 72 | + """Test that prompt_optimizer.optimize method creates a custom job.""" | | 73 | + test_client = vertexai.Client(project=_TEST_PROJECT, location=_TEST_LOCATION) | | 74 | + test_client.prompt_optimizer.optimize_prompt(prompt="test_prompt") | | 75 | + mock_client.assert_called_once() | | 76 | + mock_custom_optimize_prompt.assert_called_once() | | 77 | + | 67 | 78 | # TODO(b/415060797): add more tests for prompt_optimizer.optimize |
Collapse file Copy file name to clipboardExpand all lines: vertexai/_genai/_prompt_optimizer_utils.py +37Lines changed: 37 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
| 14 | 14 | # | 15 | 15 | """Utility functions for prompt optimizer.""" | 16 | 16 |
| | 17 | +import json | | 18 | +from google.genai import errors | 17 | 19 | from . import types | 18 | 20 |
| 19 | 21 |
| @@ -37,3 +39,38 @@ def _get_service_account( | 37 | 39 | raise ValueError( | 38 | 40 | "Either service_account or service_account_project_number " "is required." | 39 | 41 | ) | | 42 | + | | 43 | + | | 44 | +def _clean_and_parse_optimized_prompt(output_str: str): | | 45 | + """Cleans a string response returned from the prompt optimizer endpoint. | | 46 | +
| | 47 | + Args: | | 48 | + output_str: The optimized prompt string containing the JSON data, | | 49 | + potentially with markdown formatting like ```json ... ```. | | 50 | +
| | 51 | + Returns: | | 52 | + The parsed JSON data, or None if parsing fails. | | 53 | + """ | | 54 | + lines = output_str.strip().split("\n") | | 55 | + # Remove markdown delimiters | | 56 | + if lines and lines[0].strip().startswith("```"): | | 57 | + cleaned_string = "\n".join(lines[1:-1]) | | 58 | + else: | | 59 | + cleaned_string = output_str | | 60 | + | | 61 | + # remove any 'json' labels if they exist on the first line. | | 62 | + if cleaned_string.strip().startswith("json"): | | 63 | + cleaned_string = cleaned_string.strip()[4:].strip() | | 64 | + | | 65 | + try: | | 66 | + return json.loads(cleaned_string) | | 67 | + except json.JSONDecodeError as e: | | 68 | + raise errors.ClinentError( | | 69 | + f"Failed to parse the response from prompt optimizer endpoint. {e}" | | 70 | + ) from e | | 71 | + | | 72 | + | | 73 | +def _parse(output_str: str) -> types.OptimizeResponse: | | 74 | + """Parses the output string from the prompt optimizer endpoint.""" | | 75 | + parsed_out = _clean_and_parse_optimized_prompt(output_str) | | 76 | + return types.OptimizeResponse(**parsed_out) |
|