From 769812afd2bc69ad2dd67c2a2c0f6ecedc6bf172 Mon Sep 17 00:00:00 2001 From: A Vertex SDK engineer Date: Mon, 4 May 2026 12:00:05 -0700 Subject: [PATCH] feat: Add Create Skill method for Vertex AI Skill Registry SDK PiperOrigin-RevId: 910161153 --- .../genai/replays/test_skills_create.py | 78 ++ .../vertexai/genai/replays/test_skills_get.py | 33 + .../unit/vertexai/genai/test_genai_skills.py | 44 ++ vertexai/_genai/_skills_utils.py | 116 +++ vertexai/_genai/client.py | 21 + vertexai/_genai/skills.py | 695 ++++++++++++++++++ vertexai/_genai/types/__init__.py | 38 + vertexai/_genai/types/common.py | 311 ++++++++ 8 files changed, 1336 insertions(+) create mode 100644 tests/unit/vertexai/genai/replays/test_skills_create.py create mode 100644 tests/unit/vertexai/genai/replays/test_skills_get.py create mode 100644 tests/unit/vertexai/genai/test_genai_skills.py create mode 100644 vertexai/_genai/_skills_utils.py create mode 100644 vertexai/_genai/skills.py diff --git a/tests/unit/vertexai/genai/replays/test_skills_create.py b/tests/unit/vertexai/genai/replays/test_skills_create.py new file mode 100644 index 0000000000..1cb002b499 --- /dev/null +++ b/tests/unit/vertexai/genai/replays/test_skills_create.py @@ -0,0 +1,78 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +"""Tests the skills.create() method against the Vertex AI endpoint using replays.""" + +import io +import os +import tempfile +import zipfile + +from tests.unit.vertexai.genai.replays import pytest_helper +from vertexai._genai import types + +# MANDATORY: Initialize the replay test framework for this module +pytestmark = pytest_helper.setup( + file=__file__, + globals_for_file=globals(), +) + + +def test_create_skill(client): + """Tests the creation of a skill using `client.skills.create()`.""" + # Target the autopush sandbox endpoint for the Skill Registry API + client._api_client._http_options.base_url = ( + "https://us-central1-autopush-aiplatform.sandbox.googleapis.com" + ) + + with tempfile.TemporaryDirectory() as tmpdir: + # Create a dummy skill structure (SKILL.md is required by the spec) + with open(os.path.join(tmpdir, "SKILL.md"), "w") as f: + f.write("# My Replay Skill\nThis is a test skill for replay tests.") + + skill = client.skills.create( + display_name="My Replay Skill", + description="My Replay Skill Description", + config=types.CreateSkillConfig(local_path=tmpdir, wait_for_completion=True), + ) + + assert skill.name is not None + assert skill.display_name == "My Replay Skill" + assert skill.description == "My Replay Skill Description" + + +def test_create_skill_with_prezipped_bytes(client): + """Tests the creation of a skill with pre-zipped bytes.""" + # Target the autopush sandbox endpoint for the Skill Registry API + client._api_client._http_options.base_url = ( + "https://us-central1-autopush-aiplatform.sandbox.googleapis.com" + ) + + zip_buffer = io.BytesIO() + zinfo = zipfile.ZipInfo("SKILL.md", date_time=(1980, 1, 1, 0, 0, 0)) + with zipfile.ZipFile(zip_buffer, "w") as zip_file: + zip_file.writestr(zinfo, "# My Zipped Replay Skill\nThis is a test.") + zipped_bytes = zip_buffer.getvalue() + + skill = client.skills.create( + display_name="My Zipped Replay Skill", + description="My Zipped Replay Skill Description", + config=types.CreateSkillConfig( + zipped_filesystem=zipped_bytes, wait_for_completion=True + ), + ) + + assert skill.name is not None + assert skill.display_name == "My Zipped Replay Skill" + assert skill.description == "My Zipped Replay Skill Description" diff --git a/tests/unit/vertexai/genai/replays/test_skills_get.py b/tests/unit/vertexai/genai/replays/test_skills_get.py new file mode 100644 index 0000000000..824c0921f1 --- /dev/null +++ b/tests/unit/vertexai/genai/replays/test_skills_get.py @@ -0,0 +1,33 @@ +"""Tests the skills.get() method against the autopush endpoint.""" + +from google.api_core import exceptions +from tests.unit.vertexai.genai.replays import pytest_helper +import pytest + +PROJECT_ID = "demo-project" +REGION = "us-central1" +SKILL_ID = "7184367305562783744" +# target the autopush sandbox endpoint for the Skill Registry API +ENDPOINT = f"{REGION}-autopush-aiplatform.sandbox.googleapis.com" + + +pytestmark = pytest_helper.setup( + file=__file__, + globals_for_file=globals(), +) + + +def test_get_skill(client): # client fixture is injected by pytest_helper.setup + """Tests the skills.get() method against the autopush endpoint.""" + + client._api_client._http_options.base_url = ( + "https://us-central1-autopush-aiplatform.sandbox.googleapis.com" + ) + skill_name = f"projects/{PROJECT_ID}/locations/{REGION}/skills/{SKILL_ID}" + + try: + skill = client.skills.get(name=skill_name) + assert skill.name == skill_name + + except exceptions.GoogleAPIError as e: + pytest.fail(f"Error calling client.skills.get(): {e}") diff --git a/tests/unit/vertexai/genai/test_genai_skills.py b/tests/unit/vertexai/genai/test_genai_skills.py new file mode 100644 index 0000000000..45d83a5fff --- /dev/null +++ b/tests/unit/vertexai/genai/test_genai_skills.py @@ -0,0 +1,44 @@ +# //third_party/py/google/cloud/aiplatform/tests/unit/vertexai/genai/test_genai_skills.py +import json +from unittest import mock +from vertexai import _genai as genai +from vertexai._genai import client as vertexai_client +from google.genai import types as genai_types +import pytest + + +@pytest.fixture +def skills_client(): + creds = mock.MagicMock() + creds.token = "test_token" + client = vertexai_client.Client( + project="test-project", location="test-location", credentials=creds + ) + return client.skills + + +class TestGenaiSkills: + mock_get_skill_response = { + "name": "projects/test-project/locations/test-location/skills/test-skill", + "displayName": "My Test Skill", + } + + def test_get_skill(self, skills_client): + """Tests the get_skill method.""" + with mock.patch.object(skills_client._api_client, "request") as request_mock: + request_mock.return_value = genai_types.HttpResponse( + body=json.dumps(self.mock_get_skill_response) + ) + skill_name = ( + "projects/test-project/locations/test-location/skills/test-skill" + ) + skill = skills_client.get(name=skill_name) + request_mock.assert_called_with( + "get", + skill_name, + {"_url": {"name": skill_name}}, + None, + ) + assert isinstance(skill, genai.types.Skill) + assert skill.name == skill_name + assert skill.display_name == "My Test Skill" diff --git a/vertexai/_genai/_skills_utils.py b/vertexai/_genai/_skills_utils.py new file mode 100644 index 0000000000..6798584ef9 --- /dev/null +++ b/vertexai/_genai/_skills_utils.py @@ -0,0 +1,116 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +"""Utility functions for Skills.""" + +import asyncio +import base64 +import io +import os +import time +from typing import Any, Awaitable, Callable +import zipfile + + +def zip_directory(directory_path: str) -> bytes: + """Zips a directory into memory and returns the bytes. + + Args: + directory_path (str): Required. The local path to the directory. + + Returns: + bytes: The zipped directory content. + """ + if not os.path.isdir(directory_path): + raise ValueError(f"Path is not a directory: {directory_path}") + + zip_buffer = io.BytesIO() + with zipfile.ZipFile(zip_buffer, "w", zipfile.ZIP_DEFLATED) as zip_file: + for root, _, files in os.walk(directory_path): + for file in files: + file_path = os.path.join(root, file) + arcname = os.path.relpath(file_path, directory_path) + + # Read actual file data + with open(file_path, "rb") as f: + file_data = f.read() + + # Use deterministic ZipInfo (mtime: 1980-01-01 00:00:00) + zinfo = zipfile.ZipInfo(arcname, date_time=(1980, 1, 1, 0, 0, 0)) + zinfo.compress_type = zipfile.ZIP_DEFLATED + zinfo.external_attr = 0o644 << 16 # Constant file permissions + + zip_file.writestr(zinfo, file_data) + return zip_buffer.getvalue() + + +def get_zipped_filesystem_payload(directory_path: str) -> str: + """Zips a directory and base64-encodes the result to a UTF-8 string. + + Args: + directory_path (str): Required. The local path to the directory. + + Returns: + str: The base64-encoded zipped directory. + """ + zip_bytes = zip_directory(directory_path) + return base64.b64encode(zip_bytes).decode("utf-8") + + +def await_operation( + *, + operation_name: str, + get_operation_fn: Callable[..., Any], + poll_interval_seconds: float = 10.0, +) -> Any: + """Waits for a long running operation to complete. + + Args: + operation_name (str): Required. The name of the operation. + get_operation_fn (Callable): Required. Function to get the operation + status. + poll_interval_seconds (float): The interval between polls in seconds. + + Returns: + Any: The completed operation. + """ + operation = get_operation_fn(operation_name=operation_name) + while not operation.done: + time.sleep(poll_interval_seconds) + operation = get_operation_fn(operation_name=operation.name) + return operation + + +async def await_operation_async( + *, + operation_name: str, + get_operation_fn: Callable[..., Awaitable[Any]], + poll_interval_seconds: float = 10.0, +) -> Any: + """Waits for a long running operation to complete asynchronously. + + Args: + operation_name (str): Required. The name of the operation. + get_operation_fn (Callable): Required. Async function to get the operation + status. + poll_interval_seconds (float): The interval between polls in seconds. + + Returns: + Any: The completed operation. + """ + operation = await get_operation_fn(operation_name=operation_name) + while not operation.done: + await asyncio.sleep(poll_interval_seconds) + operation = await get_operation_fn(operation_name=operation.name) + return operation diff --git a/vertexai/_genai/client.py b/vertexai/_genai/client.py index 2e43782554..77d8a9aadc 100644 --- a/vertexai/_genai/client.py +++ b/vertexai/_genai/client.py @@ -35,6 +35,7 @@ prompt_optimizer as prompt_optimizer_module, ) from vertexai._genai import prompts as prompts_module + from vertexai._genai import skills as skills_module from vertexai._genai import live as live_module @@ -52,6 +53,7 @@ def __init__(self, api_client: genai_client.BaseApiClient): # type: ignore[name self._prompt_optimizer: Optional[ModuleType] = None self._prompts: Optional[ModuleType] = None self._datasets: Optional[ModuleType] = None + self._skills: Optional[ModuleType] = None @property @_common.experimental_warning( @@ -124,6 +126,15 @@ def datasets(self) -> "datasets_module.AsyncDatasets": ) return self._datasets.AsyncDatasets(self._api_client) # type: ignore[no-any-return] + @property + def skills(self) -> "skills_module.AsyncSkills": + if self._skills is None: + self._skills = importlib.import_module( + ".skills", + __package__, + ) + return self._skills.AsyncSkills(self._api_client) # type: ignore[no-any-return] + async def aclose(self) -> None: """Closes the async client explicitly. @@ -239,6 +250,7 @@ def __init__( self._agent_engines: Optional[ModuleType] = None self._prompts: Optional[ModuleType] = None self._datasets: Optional[ModuleType] = None + self._skills: Optional[ModuleType] = None @property def evals(self) -> "evals_module.Evals": @@ -335,3 +347,12 @@ def datasets(self) -> "datasets_module.Datasets": __package__, ) return self._datasets.Datasets(self._api_client) # type: ignore[no-any-return] + + @property + def skills(self) -> "skills_module.Skills": + if self._skills is None: + self._skills = importlib.import_module( + ".skills", + __package__, + ) + return self._skills.Skills(self._api_client) # type: ignore[no-any-return] diff --git a/vertexai/_genai/skills.py b/vertexai/_genai/skills.py new file mode 100644 index 0000000000..28bac438ee --- /dev/null +++ b/vertexai/_genai/skills.py @@ -0,0 +1,695 @@ +# Copyright 2025 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +# Code generated by the Google Gen AI SDK generator DO NOT EDIT. + +import asyncio +import base64 +import json +import logging +from typing import Any, Optional, Union +from urllib.parse import urlencode + +from google.genai import _api_module +from google.genai import _common +from google.genai._common import get_value_by_path as getv +from google.genai._common import set_value_by_path as setv + +from . import _skills_utils +from . import types + +logger = logging.getLogger("vertexai_genai.skills") + + +def _CreateSkillConfig_to_vertex( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + + if getv(from_object, ["zipped_filesystem"]) is not None: + setv( + parent_object, + ["zippedFilesystem"], + getv(from_object, ["zipped_filesystem"]), + ) + + if getv(from_object, ["skill_id"]) is not None: + setv(parent_object, ["_query", "skillId"], getv(from_object, ["skill_id"])) + + return to_object + + +def _CreateSkillRequestParameters_to_vertex( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ["display_name"]) is not None: + setv(to_object, ["displayName"], getv(from_object, ["display_name"])) + + if getv(from_object, ["description"]) is not None: + setv(to_object, ["description"], getv(from_object, ["description"])) + + if getv(from_object, ["config"]) is not None: + _CreateSkillConfig_to_vertex(getv(from_object, ["config"]), to_object) + + return to_object + + +def _GetSkillOperationParameters_to_vertex( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ["operation_name"]) is not None: + setv( + to_object, ["_url", "operationName"], getv(from_object, ["operation_name"]) + ) + + return to_object + + +def _GetSkillRequestParameters_to_vertex( + from_object: Union[dict[str, Any], object], + parent_object: Optional[dict[str, Any]] = None, +) -> dict[str, Any]: + to_object: dict[str, Any] = {} + if getv(from_object, ["name"]) is not None: + setv(to_object, ["_url", "name"], getv(from_object, ["name"])) + + if getv(from_object, ["config"]) is not None: + setv(to_object, ["config"], getv(from_object, ["config"])) + + return to_object + + +class Skills(_api_module.BaseModule): + """Class for managing Skills in the Skill Registry.""" + + def get( + self, *, name: str, config: Optional[types.GetSkillConfigOrDict] = None + ) -> types.Skill: + """ + Gets a Skill. + """ + + parameter_model = types._GetSkillRequestParameters( + name=name, + config=config, + ) + + request_url_dict: Optional[dict[str, str]] + if not self._api_client.vertexai: + raise ValueError( + "This method is only supported in the Gemini Enterprise Agent Platform (previously known as Vertex AI) client." + ) + else: + request_dict = _GetSkillRequestParameters_to_vertex(parameter_model) + request_url_dict = request_dict.get("_url") + if request_url_dict: + path = "{name}".format_map(request_url_dict) + else: + path = "{name}" + + query_params = request_dict.get("_query") + if query_params: + path = f"{path}?{urlencode(query_params)}" + # TODO: remove the hack that pops config. + request_dict.pop("config", None) + + http_options: Optional[types.HttpOptions] = None + if ( + parameter_model.config is not None + and parameter_model.config.http_options is not None + ): + http_options = parameter_model.config.http_options + + request_dict = _common.convert_to_dict(request_dict) + request_dict = _common.encode_unserializable_types(request_dict) + + response = self._api_client.request("get", path, request_dict, http_options) + + response_dict = {} if not response.body else json.loads(response.body) + + return_value = types.Skill._from_response( + response=response_dict, + kwargs=( + { + "config": { + "response_schema": getattr( + parameter_model.config, "response_schema", None + ), + "response_json_schema": getattr( + parameter_model.config, "response_json_schema", None + ), + "include_all_fields": getattr( + parameter_model.config, "include_all_fields", None + ), + } + } + if getattr(parameter_model, "config", None) + else {} + ), + ) + + self._api_client._verify_response(return_value) + return return_value + + def _create( + self, + *, + display_name: str, + description: str, + config: Optional[types.CreateSkillConfigOrDict] = None, + ) -> types.SkillOperation: + """ + Creates a new Skill. + """ + + parameter_model = types._CreateSkillRequestParameters( + display_name=display_name, + description=description, + config=config, + ) + + request_url_dict: Optional[dict[str, str]] + if not self._api_client.vertexai: + raise ValueError( + "This method is only supported in the Gemini Enterprise Agent Platform (previously known as Vertex AI) client." + ) + else: + request_dict = _CreateSkillRequestParameters_to_vertex(parameter_model) + request_url_dict = request_dict.get("_url") + if request_url_dict: + path = "skills".format_map(request_url_dict) + else: + path = "skills" + + query_params = request_dict.get("_query") + if query_params: + path = f"{path}?{urlencode(query_params)}" + # TODO: remove the hack that pops config. + request_dict.pop("config", None) + + http_options: Optional[types.HttpOptions] = None + if ( + parameter_model.config is not None + and parameter_model.config.http_options is not None + ): + http_options = parameter_model.config.http_options + + request_dict = _common.convert_to_dict(request_dict) + request_dict = _common.encode_unserializable_types(request_dict) + + response = self._api_client.request("post", path, request_dict, http_options) + + response_dict = {} if not response.body else json.loads(response.body) + + return_value = types.SkillOperation._from_response( + response=response_dict, + kwargs=( + { + "config": { + "response_schema": getattr( + parameter_model.config, "response_schema", None + ), + "response_json_schema": getattr( + parameter_model.config, "response_json_schema", None + ), + "include_all_fields": getattr( + parameter_model.config, "include_all_fields", None + ), + } + } + if getattr(parameter_model, "config", None) + else {} + ), + ) + + self._api_client._verify_response(return_value) + return return_value + + def _get_skill_operation( + self, + *, + operation_name: str, + config: Optional[types.GetSkillOperationConfigOrDict] = None, + ) -> types.SkillOperation: + parameter_model = types._GetSkillOperationParameters( + operation_name=operation_name, + config=config, + ) + + request_url_dict: Optional[dict[str, str]] + if not self._api_client.vertexai: + raise ValueError( + "This method is only supported in the Gemini Enterprise Agent Platform (previously known as Vertex AI) client." + ) + else: + request_dict = _GetSkillOperationParameters_to_vertex(parameter_model) + request_url_dict = request_dict.get("_url") + if request_url_dict: + path = "{operationName}".format_map(request_url_dict) + else: + path = "{operationName}" + + query_params = request_dict.get("_query") + if query_params: + path = f"{path}?{urlencode(query_params)}" + # TODO: remove the hack that pops config. + request_dict.pop("config", None) + + http_options: Optional[types.HttpOptions] = None + if ( + parameter_model.config is not None + and parameter_model.config.http_options is not None + ): + http_options = parameter_model.config.http_options + + request_dict = _common.convert_to_dict(request_dict) + request_dict = _common.encode_unserializable_types(request_dict) + + response = self._api_client.request("get", path, request_dict, http_options) + + response_dict = {} if not response.body else json.loads(response.body) + + return_value = types.SkillOperation._from_response( + response=response_dict, + kwargs=( + { + "config": { + "response_schema": getattr( + parameter_model.config, "response_schema", None + ), + "response_json_schema": getattr( + parameter_model.config, "response_json_schema", None + ), + "include_all_fields": getattr( + parameter_model.config, "include_all_fields", None + ), + } + } + if getattr(parameter_model, "config", None) + else {} + ), + ) + + self._api_client._verify_response(return_value) + return return_value + + def create( + self, + *, + display_name: str, + description: str, + config: Optional[types.CreateSkillConfigOrDict] = None, + ) -> Union[types.Skill, types.SkillOperation]: + """Creates a new Skill. + + Args: + display_name (str): + Required. The display name of the Skill. + description (str): + Required. The description of the Skill. + config (CreateSkillConfigOrDict): + Optional. The configuration for creating the Skill. + + Returns: + Skill: The created Skill if wait_for_completion is True. + SkillOperation: The operation for creating the Skill if + wait_for_completion is False. + """ + if config is None: + config = types.CreateSkillConfig() + elif isinstance(config, dict): + config = types.CreateSkillConfig.model_validate(config) + elif not isinstance(config, types.CreateSkillConfig): + raise TypeError( + f"config must be a dict or CreateSkillConfig, but got {type(config)}." + ) + + local_path = config.local_path + zipped_filesystem = config.zipped_filesystem + + if local_path and zipped_filesystem: + raise ValueError( + "Only one of `local_path` or `zipped_filesystem` can be provided in config." + ) + if not local_path and not zipped_filesystem: + raise ValueError( + "Either `local_path` or `zipped_filesystem` must be provided in config." + ) + + if local_path: + zipped_filesystem_payload = _skills_utils.get_zipped_filesystem_payload( + local_path + ) + else: + # Narrow type for mypy + if zipped_filesystem is None: + raise ValueError( + "zipped_filesystem is required if local_path is not provided." + ) + if isinstance(zipped_filesystem, bytes): + zipped_filesystem_payload = base64.b64encode(zipped_filesystem).decode( + "utf-8" + ) + else: + zipped_filesystem_payload = zipped_filesystem + + # Mutate the config object to populate the zipped_filesystem payload + config.zipped_filesystem = zipped_filesystem_payload + + operation = self._create( + display_name=display_name, + description=description, + config=config, + ) + + if config.wait_for_completion: + operation = _skills_utils.await_operation( + operation_name=operation.name, + get_operation_fn=self._get_skill_operation, + ) + if operation.error: + raise RuntimeError(f"Failed to create Skill: {operation.error}") + # Fetch the fully populated Skill resource from the server + return self.get(name=operation.response.name) + + return operation + + +class AsyncSkills(_api_module.BaseModule): + """Class for managing Skills in the Skill Registry.""" + + async def get( + self, *, name: str, config: Optional[types.GetSkillConfigOrDict] = None + ) -> types.Skill: + """ + Gets a Skill. + """ + + parameter_model = types._GetSkillRequestParameters( + name=name, + config=config, + ) + + request_url_dict: Optional[dict[str, str]] + if not self._api_client.vertexai: + raise ValueError( + "This method is only supported in the Gemini Enterprise Agent Platform (previously known as Vertex AI) client." + ) + else: + request_dict = _GetSkillRequestParameters_to_vertex(parameter_model) + request_url_dict = request_dict.get("_url") + if request_url_dict: + path = "{name}".format_map(request_url_dict) + else: + path = "{name}" + + query_params = request_dict.get("_query") + if query_params: + path = f"{path}?{urlencode(query_params)}" + # TODO: remove the hack that pops config. + request_dict.pop("config", None) + + http_options: Optional[types.HttpOptions] = None + if ( + parameter_model.config is not None + and parameter_model.config.http_options is not None + ): + http_options = parameter_model.config.http_options + + request_dict = _common.convert_to_dict(request_dict) + request_dict = _common.encode_unserializable_types(request_dict) + + response = await self._api_client.async_request( + "get", path, request_dict, http_options + ) + + response_dict = {} if not response.body else json.loads(response.body) + + return_value = types.Skill._from_response( + response=response_dict, + kwargs=( + { + "config": { + "response_schema": getattr( + parameter_model.config, "response_schema", None + ), + "response_json_schema": getattr( + parameter_model.config, "response_json_schema", None + ), + "include_all_fields": getattr( + parameter_model.config, "include_all_fields", None + ), + } + } + if getattr(parameter_model, "config", None) + else {} + ), + ) + + self._api_client._verify_response(return_value) + return return_value + + async def _create( + self, + *, + display_name: str, + description: str, + config: Optional[types.CreateSkillConfigOrDict] = None, + ) -> types.SkillOperation: + """ + Creates a new Skill. + """ + + parameter_model = types._CreateSkillRequestParameters( + display_name=display_name, + description=description, + config=config, + ) + + request_url_dict: Optional[dict[str, str]] + if not self._api_client.vertexai: + raise ValueError( + "This method is only supported in the Gemini Enterprise Agent Platform (previously known as Vertex AI) client." + ) + else: + request_dict = _CreateSkillRequestParameters_to_vertex(parameter_model) + request_url_dict = request_dict.get("_url") + if request_url_dict: + path = "skills".format_map(request_url_dict) + else: + path = "skills" + + query_params = request_dict.get("_query") + if query_params: + path = f"{path}?{urlencode(query_params)}" + # TODO: remove the hack that pops config. + request_dict.pop("config", None) + + http_options: Optional[types.HttpOptions] = None + if ( + parameter_model.config is not None + and parameter_model.config.http_options is not None + ): + http_options = parameter_model.config.http_options + + request_dict = _common.convert_to_dict(request_dict) + request_dict = _common.encode_unserializable_types(request_dict) + + response = await self._api_client.async_request( + "post", path, request_dict, http_options + ) + + response_dict = {} if not response.body else json.loads(response.body) + + return_value = types.SkillOperation._from_response( + response=response_dict, + kwargs=( + { + "config": { + "response_schema": getattr( + parameter_model.config, "response_schema", None + ), + "response_json_schema": getattr( + parameter_model.config, "response_json_schema", None + ), + "include_all_fields": getattr( + parameter_model.config, "include_all_fields", None + ), + } + } + if getattr(parameter_model, "config", None) + else {} + ), + ) + + self._api_client._verify_response(return_value) + return return_value + + async def _get_skill_operation( + self, + *, + operation_name: str, + config: Optional[types.GetSkillOperationConfigOrDict] = None, + ) -> types.SkillOperation: + parameter_model = types._GetSkillOperationParameters( + operation_name=operation_name, + config=config, + ) + + request_url_dict: Optional[dict[str, str]] + if not self._api_client.vertexai: + raise ValueError( + "This method is only supported in the Gemini Enterprise Agent Platform (previously known as Vertex AI) client." + ) + else: + request_dict = _GetSkillOperationParameters_to_vertex(parameter_model) + request_url_dict = request_dict.get("_url") + if request_url_dict: + path = "{operationName}".format_map(request_url_dict) + else: + path = "{operationName}" + + query_params = request_dict.get("_query") + if query_params: + path = f"{path}?{urlencode(query_params)}" + # TODO: remove the hack that pops config. + request_dict.pop("config", None) + + http_options: Optional[types.HttpOptions] = None + if ( + parameter_model.config is not None + and parameter_model.config.http_options is not None + ): + http_options = parameter_model.config.http_options + + request_dict = _common.convert_to_dict(request_dict) + request_dict = _common.encode_unserializable_types(request_dict) + + response = await self._api_client.async_request( + "get", path, request_dict, http_options + ) + + response_dict = {} if not response.body else json.loads(response.body) + + return_value = types.SkillOperation._from_response( + response=response_dict, + kwargs=( + { + "config": { + "response_schema": getattr( + parameter_model.config, "response_schema", None + ), + "response_json_schema": getattr( + parameter_model.config, "response_json_schema", None + ), + "include_all_fields": getattr( + parameter_model.config, "include_all_fields", None + ), + } + } + if getattr(parameter_model, "config", None) + else {} + ), + ) + + self._api_client._verify_response(return_value) + return return_value + + async def create( + self, + *, + display_name: str, + description: str, + config: Optional[types.CreateSkillConfigOrDict] = None, + ) -> Union[types.Skill, types.SkillOperation]: + """Creates a new Skill asynchronously. + + Args: + display_name (str): + Required. The display name of the Skill. + description (str): + Required. The description of the Skill. + config (CreateSkillConfigOrDict): + Optional. The configuration for creating the Skill. + + Returns: + Skill: The created Skill if wait_for_completion is True. + SkillOperation: The operation for creating the Skill if + wait_for_completion is False. + """ + if config is None: + config = types.CreateSkillConfig() + elif isinstance(config, dict): + config = types.CreateSkillConfig.model_validate(config) + elif not isinstance(config, types.CreateSkillConfig): + raise TypeError( + f"config must be a dict or CreateSkillConfig, but got {type(config)}." + ) + + local_path = config.local_path + zipped_filesystem = config.zipped_filesystem + + if local_path and zipped_filesystem: + raise ValueError( + "Only one of `local_path` or `zipped_filesystem` can be provided in config." + ) + if not local_path and not zipped_filesystem: + raise ValueError( + "Either `local_path` or `zipped_filesystem` must be provided in config." + ) + + if local_path: + loop = asyncio.get_running_loop() + zipped_filesystem_payload = await loop.run_in_executor( + None, _skills_utils.get_zipped_filesystem_payload, local_path + ) + else: + # Narrow type for mypy + if zipped_filesystem is None: + raise ValueError( + "zipped_filesystem is required if local_path is not provided." + ) + if isinstance(zipped_filesystem, bytes): + zipped_filesystem_payload = base64.b64encode(zipped_filesystem).decode( + "utf-8" + ) + else: + zipped_filesystem_payload = zipped_filesystem + + # Mutate the config object to populate the zipped_filesystem payload + config.zipped_filesystem = zipped_filesystem_payload + + operation = await self._create( + display_name=display_name, + description=description, + config=config, + ) + + if config.wait_for_completion: + operation = await _skills_utils.await_operation_async( + operation_name=operation.name, + get_operation_fn=self._get_skill_operation, + ) + if operation.error: + raise RuntimeError(f"Failed to create Skill: {operation.error}") + # Fetch the fully populated Skill resource asynchronously + return await self.get(name=operation.response.name) + + return operation diff --git a/vertexai/_genai/types/__init__.py b/vertexai/_genai/types/__init__.py index 8ed8e6df4a..62275a9fe3 100644 --- a/vertexai/_genai/types/__init__.py +++ b/vertexai/_genai/types/__init__.py @@ -42,6 +42,7 @@ from .common import _CreateMultimodalDatasetParameters from .common import _CreateSandboxEnvironmentSnapshotRequestParameters from .common import _CreateSandboxEnvironmentTemplateRequestParameters +from .common import _CreateSkillRequestParameters from .common import _CustomJobParameters from .common import _CustomJobParameters from .common import _DeleteAgentEngineMemoryRequestParameters @@ -90,6 +91,8 @@ from .common import _GetSandboxEnvironmentSnapshotRequestParameters from .common import _GetSandboxEnvironmentTemplateOperationParameters from .common import _GetSandboxEnvironmentTemplateRequestParameters +from .common import _GetSkillOperationParameters +from .common import _GetSkillRequestParameters from .common import _IngestEventsRequestParameters from .common import _ListAgentEngineMemoryRequestParameters from .common import _ListAgentEngineMemoryRevisionsRequestParameters @@ -298,6 +301,9 @@ from .common import CreateSandboxEnvironmentTemplateConfig from .common import CreateSandboxEnvironmentTemplateConfigDict from .common import CreateSandboxEnvironmentTemplateConfigOrDict +from .common import CreateSkillConfig +from .common import CreateSkillConfigDict +from .common import CreateSkillConfigOrDict from .common import CustomCodeExecutionSpec from .common import CustomCodeExecutionSpecDict from .common import CustomCodeExecutionSpecOrDict @@ -608,6 +614,12 @@ from .common import GetSandboxEnvironmentTemplateConfig from .common import GetSandboxEnvironmentTemplateConfigDict from .common import GetSandboxEnvironmentTemplateConfigOrDict +from .common import GetSkillConfig +from .common import GetSkillConfigDict +from .common import GetSkillConfigOrDict +from .common import GetSkillOperationConfig +from .common import GetSkillOperationConfigDict +from .common import GetSkillOperationConfigOrDict from .common import IdentityType from .common import Importance from .common import IngestEventsConfig @@ -1243,6 +1255,13 @@ from .common import SessionEventDict from .common import SessionEventOrDict from .common import SessionOrDict +from .common import Skill +from .common import SkillDict +from .common import SkillOperation +from .common import SkillOperationDict +from .common import SkillOperationOrDict +from .common import SkillOrDict +from .common import SkillState from .common import State from .common import Strategy from .common import StructuredMemoryConfig @@ -2478,6 +2497,21 @@ "UpdatePromptConfig", "UpdatePromptConfigDict", "UpdatePromptConfigOrDict", + "GetSkillConfig", + "GetSkillConfigDict", + "GetSkillConfigOrDict", + "Skill", + "SkillDict", + "SkillOrDict", + "CreateSkillConfig", + "CreateSkillConfigDict", + "CreateSkillConfigOrDict", + "SkillOperation", + "SkillOperationDict", + "SkillOperationOrDict", + "GetSkillOperationConfig", + "GetSkillOperationConfigDict", + "GetSkillOperationConfigOrDict", "PromptOptimizerConfig", "PromptOptimizerConfigDict", "PromptOptimizerConfigOrDict", @@ -2591,6 +2625,7 @@ "OptimizeTarget", "MemoryMetadataMergeStrategy", "GenerateMemoriesResponseGeneratedMemoryAction", + "SkillState", "PromptOptimizerMethod", "OptimizationMethod", "PromptData", @@ -2714,6 +2749,9 @@ "_CustomJobParameters", "_GetCustomJobParameters", "_OptimizeRequestParameters", + "_GetSkillRequestParameters", + "_CreateSkillRequestParameters", + "_GetSkillOperationParameters", "evals", "agent_engines", "prompts", diff --git a/vertexai/_genai/types/common.py b/vertexai/_genai/types/common.py index 82fe71fe98..51c8f59709 100644 --- a/vertexai/_genai/types/common.py +++ b/vertexai/_genai/types/common.py @@ -446,6 +446,21 @@ class GenerateMemoriesResponseGeneratedMemoryAction(_common.CaseInSensitiveEnum) """The memory was deleted.""" +class SkillState(_common.CaseInSensitiveEnum): + """State of the Skill.""" + + STATE_UNSPECIFIED = "STATE_UNSPECIFIED" + """The state of the Skill is unspecified.""" + ACTIVE = "ACTIVE" + """The Skill is active.""" + CREATING = "CREATING" + """The Skill is being created.""" + FAILED = "FAILED" + """The Skill was created, but failed to process.""" + DELETING = "DELETING" + """The Skill is being deleted.""" + + class PromptOptimizerMethod(_common.CaseInSensitiveEnum): """The method for data driven prompt optimization.""" @@ -17795,6 +17810,302 @@ class _UpdateDatasetParametersDict(TypedDict, total=False): ] +class GetSkillConfig(_common.BaseModel): + """Config for getting a skill.""" + + http_options: Optional[genai_types.HttpOptions] = Field( + default=None, description="""Used to override HTTP request options.""" + ) + + +class GetSkillConfigDict(TypedDict, total=False): + """Config for getting a skill.""" + + http_options: Optional[genai_types.HttpOptionsDict] + """Used to override HTTP request options.""" + + +GetSkillConfigOrDict = Union[GetSkillConfig, GetSkillConfigDict] + + +class _GetSkillRequestParameters(_common.BaseModel): + """Parameters for GetSkillRequest.""" + + name: Optional[str] = Field( + default=None, + description="""The resource name of the Skill to retrieve. Format: projects/{project}/locations/{location}/skills/{skill}""", + ) + config: Optional[GetSkillConfig] = Field(default=None, description="""""") + + +class _GetSkillRequestParametersDict(TypedDict, total=False): + """Parameters for GetSkillRequest.""" + + name: Optional[str] + """The resource name of the Skill to retrieve. Format: projects/{project}/locations/{location}/skills/{skill}""" + + config: Optional[GetSkillConfigDict] + """""" + + +_GetSkillRequestParametersOrDict = Union[ + _GetSkillRequestParameters, _GetSkillRequestParametersDict +] + + +class Skill(_common.BaseModel): + """Represents a Skill resource. + + Patches the type from the discovery document. + """ + + name: Optional[str] = Field( + default=None, + description="""Identifier. The resource name of the Skill. Format: `projects/{project}/locations/{location}/skills/{skill}`""", + ) + create_time: Optional[datetime.datetime] = Field( + default=None, + description="""Output only. Timestamp when this Skill was created.""", + ) + update_time: Optional[datetime.datetime] = Field( + default=None, + description="""Output only. Timestamp when this Skill was most recently updated.""", + ) + display_name: Optional[str] = Field( + default=None, + description="""Required. Provides the display name of the Skill. This should align with `name` in the `SKILL.md` file.""", + ) + description: Optional[str] = Field( + default=None, + description="""Required. Describes the Skill. Should describe both what the skill does and when to use it. Should include specific keywords that help agents identify relevant tasks. This should align with `description` in the `SKILL.md` file.""", + ) + license: Optional[str] = Field( + default=None, + description="""Optional. Specifies the license of the Skill. This should be an SPDX license identifier (e.g., "MIT", "Apache-2.0"). See https://spdx.org/licenses/. This should align with `license` in the `SKILL.md` file.""", + ) + compatibility: Optional[str] = Field( + default=None, + description="""Optional. Specifies the compatibility of the Skill. Indicates environment requirements (intended product, system packages, network access, etc.). This should align with `compatibility` in the `SKILL.md` file.""", + ) + zipped_filesystem: Optional[str] = Field( + default=None, + description="""Required. Provides the zipped filesystem of the Skill. This should contain the `SKILL.md` file at the root of the zip and optional directories for scripts, references, and assets. Directory should align with the directory structure specified at https://agentskills.io/specification#directory-structure.""", + ) + state: Optional[SkillState] = Field( + default=None, description="""Output only. The state of the Skill.""" + ) + + +class SkillDict(TypedDict, total=False): + """Represents a Skill resource. + + Patches the type from the discovery document. + """ + + name: Optional[str] + """Identifier. The resource name of the Skill. Format: `projects/{project}/locations/{location}/skills/{skill}`""" + + create_time: Optional[datetime.datetime] + """Output only. Timestamp when this Skill was created.""" + + update_time: Optional[datetime.datetime] + """Output only. Timestamp when this Skill was most recently updated.""" + + display_name: Optional[str] + """Required. Provides the display name of the Skill. This should align with `name` in the `SKILL.md` file.""" + + description: Optional[str] + """Required. Describes the Skill. Should describe both what the skill does and when to use it. Should include specific keywords that help agents identify relevant tasks. This should align with `description` in the `SKILL.md` file.""" + + license: Optional[str] + """Optional. Specifies the license of the Skill. This should be an SPDX license identifier (e.g., "MIT", "Apache-2.0"). See https://spdx.org/licenses/. This should align with `license` in the `SKILL.md` file.""" + + compatibility: Optional[str] + """Optional. Specifies the compatibility of the Skill. Indicates environment requirements (intended product, system packages, network access, etc.). This should align with `compatibility` in the `SKILL.md` file.""" + + zipped_filesystem: Optional[str] + """Required. Provides the zipped filesystem of the Skill. This should contain the `SKILL.md` file at the root of the zip and optional directories for scripts, references, and assets. Directory should align with the directory structure specified at https://agentskills.io/specification#directory-structure.""" + + state: Optional[SkillState] + """Output only. The state of the Skill.""" + + +SkillOrDict = Union[Skill, SkillDict] + + +class CreateSkillConfig(_common.BaseModel): + """Config for creating a skill.""" + + http_options: Optional[genai_types.HttpOptions] = Field( + default=None, description="""Used to override HTTP request options.""" + ) + wait_for_completion: Optional[bool] = Field( + default=True, + description="""Whether to wait for the long running operation to complete.""", + ) + local_path: Optional[str] = Field( + default=None, + description="""Optional. The local path to the directory containing the Skill to + be zipped and uploaded. + """, + ) + zipped_filesystem: Optional[Any] = Field( + default=None, description="""Optional. The zipped filesystem of the Skill.""" + ) + skill_id: Optional[str] = Field( + default=None, + description="""Optional. The ID to use for the Skill, which will become the final + component of the Skill's resource name. + """, + ) + + +class CreateSkillConfigDict(TypedDict, total=False): + """Config for creating a skill.""" + + http_options: Optional[genai_types.HttpOptionsDict] + """Used to override HTTP request options.""" + + wait_for_completion: Optional[bool] + """Whether to wait for the long running operation to complete.""" + + local_path: Optional[str] + """Optional. The local path to the directory containing the Skill to + be zipped and uploaded. + """ + + zipped_filesystem: Optional[Any] + """Optional. The zipped filesystem of the Skill.""" + + skill_id: Optional[str] + """Optional. The ID to use for the Skill, which will become the final + component of the Skill's resource name. + """ + + +CreateSkillConfigOrDict = Union[CreateSkillConfig, CreateSkillConfigDict] + + +class _CreateSkillRequestParameters(_common.BaseModel): + """Parameters for creating a skill.""" + + display_name: Optional[str] = Field( + default=None, description="""Required. The display name of the Skill.""" + ) + description: Optional[str] = Field( + default=None, description="""Required. The description of the Skill.""" + ) + config: Optional[CreateSkillConfig] = Field(default=None, description="""""") + + +class _CreateSkillRequestParametersDict(TypedDict, total=False): + """Parameters for creating a skill.""" + + display_name: Optional[str] + """Required. The display name of the Skill.""" + + description: Optional[str] + """Required. The description of the Skill.""" + + config: Optional[CreateSkillConfigDict] + """""" + + +_CreateSkillRequestParametersOrDict = Union[ + _CreateSkillRequestParameters, _CreateSkillRequestParametersDict +] + + +class SkillOperation(_common.BaseModel): + """Operation that has a skill as a response.""" + + name: Optional[str] = Field( + default=None, + description="""The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`.""", + ) + metadata: Optional[dict[str, Any]] = Field( + default=None, + description="""Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any.""", + ) + done: Optional[bool] = Field( + default=None, + description="""If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available.""", + ) + error: Optional[dict[str, Any]] = Field( + default=None, + description="""The error result of the operation in case of failure or cancellation.""", + ) + response: Optional[Skill] = Field( + default=None, description="""The created Skill.""" + ) + + +class SkillOperationDict(TypedDict, total=False): + """Operation that has a skill as a response.""" + + name: Optional[str] + """The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`.""" + + metadata: Optional[dict[str, Any]] + """Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any.""" + + done: Optional[bool] + """If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available.""" + + error: Optional[dict[str, Any]] + """The error result of the operation in case of failure or cancellation.""" + + response: Optional[SkillDict] + """The created Skill.""" + + +SkillOperationOrDict = Union[SkillOperation, SkillOperationDict] + + +class GetSkillOperationConfig(_common.BaseModel): + + http_options: Optional[genai_types.HttpOptions] = Field( + default=None, description="""Used to override HTTP request options.""" + ) + + +class GetSkillOperationConfigDict(TypedDict, total=False): + + http_options: Optional[genai_types.HttpOptionsDict] + """Used to override HTTP request options.""" + + +GetSkillOperationConfigOrDict = Union[ + GetSkillOperationConfig, GetSkillOperationConfigDict +] + + +class _GetSkillOperationParameters(_common.BaseModel): + """Parameters for getting an operation.""" + + operation_name: Optional[str] = Field( + default=None, description="""The server-assigned name for the operation.""" + ) + config: Optional[GetSkillOperationConfig] = Field( + default=None, description="""Used to override the default configuration.""" + ) + + +class _GetSkillOperationParametersDict(TypedDict, total=False): + """Parameters for getting an operation.""" + + operation_name: Optional[str] + """The server-assigned name for the operation.""" + + config: Optional[GetSkillOperationConfigDict] + """Used to override the default configuration.""" + + +_GetSkillOperationParametersOrDict = Union[ + _GetSkillOperationParameters, _GetSkillOperationParametersDict +] + + class PromptOptimizerConfig(_common.BaseModel): """VAPO Prompt Optimizer Config."""