GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — feat: GenAI SDK client - add zero-shot prompt optimizer: an option to… · googleapis/python-aiplatform@bc2e8f4

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • tests/unit/vertexai/genai
    • replays
      • conftest.py
      • test_prompt_optimizer_async_optimize_prompt_return_type.py
      • test_prompt_optimizer_optimize_prompt_return_type.py
    • test_prompt_optimizer.py
  • vertexai/_genai
    • _prompt_optimizer_utils.py
    • prompt_optimizer.py
    • types.py
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎tests/unit/vertexai/genai/replays/conftest.py‎

Copy file name to clipboardExpand all lines: tests/unit/vertexai/genai/replays/conftest.py
+43Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,49 @@
2929
from vertexai._genai import prompt_optimizer
3030
import pytest
3131

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+
3275
IS_KOKORO = os.getenv("KOKORO_BUILD_NUMBER") is not None
3376

3477

Collapse file

‎tests/unit/vertexai/genai/replays/test_prompt_optimizer_async_optimize_prompt_return_type.py‎

Copy file name to clipboard
+38Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
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

‎tests/unit/vertexai/genai/replays/test_prompt_optimizer_optimize_prompt_return_type.py‎

Copy file name to clipboard
+33Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
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

‎tests/unit/vertexai/genai/test_prompt_optimizer.py‎

Copy file name to clipboardExpand all lines: tests/unit/vertexai/genai/test_prompt_optimizer.py
+11Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,4 +64,15 @@ def test_prompt_optimizer_optimize(self, mock_custom_job, mock_client):
6464
mock_client.assert_called_once()
6565
mock_custom_job.assert_called_once()
6666

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+
6778
# TODO(b/415060797): add more tests for prompt_optimizer.optimize
Collapse file

‎vertexai/_genai/_prompt_optimizer_utils.py‎

Copy file name to clipboardExpand all lines: vertexai/_genai/_prompt_optimizer_utils.py
+37Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,8 @@
1414
#
1515
"""Utility functions for prompt optimizer."""
1616

17+
import json
18+
from google.genai import errors
1719
from . import types
1820

1921

@@ -37,3 +39,38 @@ def _get_service_account(
3739
raise ValueError(
3840
"Either service_account or service_account_project_number " "is required."
3941
)
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)

0 commit comments

Comments
0 (0)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.