# -----------------------------------------------------------------------------------------# (C) Copyright IBM Corp. 2024-2025.# https://opensource.org/licenses/BSD-3-Clause# -----------------------------------------------------------------------------------------from__future__importannotationsimportjsonimportbase64importloggingfromtypingimportTYPE_CHECKINGfromwarningsimportwarnfromibm_watsonx_ai.href_definitionsimportHrefDefinitionsfromibm_watsonx_ai.utils.authimportget_auth_methodfromibm_watsonx_ai.wml_client_errorimport(WMLClientError,ApiRequestFailure,NoWMLCredentialsProvided,)ifTYPE_CHECKING:fromibm_watsonx_aiimportAPIClient
[docs]classServiceInstance:"""Connect, get details, and check usage of a Watson Machine Learning service instance."""def__init__(self,client:APIClient)->None:self._logger=logging.getLogger(__name__)self._client=clientself._credentials=client.credentialsself._instance_id=self._client.credentials.instance_id# This is used in connections.pyself._href_definitions=HrefDefinitions(self._client,self._client.CLOUD_PLATFORM_SPACES,self._client.PLATFORM_URL,self._client.ICP_PLATFORM_SPACES,)# ml_repository_client is initialized in repoself._details=Noneself._refresh_details=Falsedef_get_token(self)->str:"""Get token. .. deprecated:: v1.2.3 This protected function is deprecated since v1.2.3. Use ``APIClient.token`` instead. """get_token_method_deprecated_warning=("`APIClient.service_instance._get_token()` is deprecated since v1.2.3. ""Use ``APIClient.token`` instead.")warn(get_token_method_deprecated_warning,category=DeprecationWarning)returnself._client.token@propertydefinstance_id(self):ifself._instance_idisNone:raiseWMLClientError(("instance_id for this plan is picked up from the space or project with which ""this instance_id is associated with. Set the space or project with associated ""instance_id to be able to use this function"))returnself._instance_id@propertydefdetails(self):details_attribute_deprecated_warning=("Attribute `details` is deprecated. ""Please use method `get_details()` instead.")warn(details_attribute_deprecated_warning,category=DeprecationWarning)ifself._detailsisNoneorself._refresh_details:self._details=self.get_details()self._refresh_details=Falsereturnself._details@details.setterdefdetails(self,value:dict|None):self._details=value
[docs]defget_instance_id(self)->str:"""Get the instance ID of a Watson Machine Learning service. :return: ID of the instance :rtype: str **Example:** .. code-block:: python instance_details = client.service_instance.get_instance_id() """ifself._instance_idisNone:raiseWMLClientError("instance_id for this plan is picked up from the space or project with which ""this instance_id is associated with. Set the space or project with associated ""instance_id to be able to use this function")returnself.instance_id
[docs]defget_api_key(self)->str:"""Get the API key of a Watson Machine Learning service. :return: API key :rtype: str **Example:** .. code-block:: python instance_details = client.service_instance.get_api_key() """returnself._credentials.api_key
[docs]defget_url(self)->str:"""Get the instance URL of a Watson Machine Learning service. :return: URL of the instance :rtype: str **Example:** .. code-block:: python instance_details = client.service_instance.get_url() """returnself._credentials.url
[docs]defget_username(self)->str:"""Get the username for the Watson Machine Learning service. Applicable only for IBM Cloud PakĀ® for Data. :return: username :rtype: str **Example:** .. code-block:: python instance_details = client.service_instance.get_username() """ifself._client.ICP_PLATFORM_SPACES:ifself._credentials.usernameisnotNone:returnself._credentials.usernameelse:raiseWMLClientError("`username` missing in credentials.")else:raiseWMLClientError("Not applicable for Cloud")
[docs]defget_password(self)->str:"""Get the password for the Watson Machine Learning service. Applicable only for IBM Cloud PakĀ® for Data. :return: password :rtype: str **Example:** .. code-block:: python instance_details = client.service_instance.get_password() """ifself._client.ICP_PLATFORM_SPACES:ifself._credentials.passwordisnotNone:returnself._credentials.passwordelse:raiseWMLClientError("`password` missing in credentials.")else:raiseWMLClientError("Not applicable for Cloud")
[docs]defget_details(self)->dict:"""Get information about the Watson Machine Learning instance. :return: metadata of the service instance :rtype: dict **Example:** .. code-block:: python instance_details = client.service_instance.get_details() """ifself._client.CLOUD_PLATFORM_SPACES:ifself._credentialsisnotNone:ifself._instance_idisNone:raiseWMLClientError("instance_id for this plan is picked up from the space or project with which ""this instance_id is associated with. Set the space or project with associated ""instance_id to be able to use this function")# /ml/v4/instances will need either space_id or project_id as mandatory params# We will enable this service instance class only during create space or# set space/project. So, space_id/project_id would have been populated at this pointheaders=self._client._get_headers()delheaders["User-Agent"]if"ML-Instance-ID"inheaders:headers.pop("ML-Instance-ID")response_get_instance=self._client._session.get(self._href_definitions.get_v4_instance_id_href(self.instance_id),params=self._client._params(skip_space_project_chk=True),headers=headers,)ifresponse_get_instance.status_code==200:returnresponse_get_instance.json()else:raiseApiRequestFailure("Getting instance details failed.",response_get_instance)else:raiseNoWMLCredentialsProvidedelse:return{}