Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
ibm
GitHub Repository: ibm/watson-machine-learning-samples
Path: blob/master/cloud/notebooks/python_sdk/instance-management/Machine Learning artifacts export and import.ipynb
9203 views
Kernel: .venv_watsonx_ai_samples_py_312

Export/Import assets with ibm-watsonx-ai

This notebook demonstrates an example for exporting/importing assets using watsonx.ai Runtime service. It contains steps and code to work with ibm-watsonx-ai library available in PyPI repository.

Some familiarity with Python is helpful. This notebook uses Python 3.12.

Learning goals

The learning goals of this notebook are:

  • Download an externally trained Keras model.

  • Persist an external model in watsonx.ai Runtime repository.

  • Export the model from the space

  • Import the model to another space and deploy

Contents

This notebook contains the following parts:

  1. Setup

  2. Download externally created Keras model

  3. Persist externally created Keras model

  4. Export the model

  5. Import the model

  6. Deploy and score the imported model

  7. Clean up

  8. Summary and next steps

1. Set up the environment

Before you use the sample code in this notebook, you must perform the following setup tasks:

Install and import the ibm-watsonx-ai and dependecies

Note: ibm-watsonx-ai documentation can be found here.

%pip install wget | tail -n 1 %pip install matplotlib | tail -n 1 %pip install -U ibm-watsonx-ai | tail -n 1
Successfully installed wget-3.2 Successfully installed contourpy-1.3.3 cycler-0.12.1 fonttools-4.61.1 kiwisolver-1.4.9 matplotlib-3.10.8 numpy-2.4.1 pillow-12.1.0 pyparsing-3.3.1 Successfully installed anyio-4.12.1 cachetools-6.2.4 certifi-2026.1.4 charset_normalizer-3.4.4 h11-0.16.0 httpcore-1.0.9 httpx-0.28.1 ibm-cos-sdk-2.14.3 ibm-cos-sdk-core-2.14.3 ibm-cos-sdk-s3transfer-2.14.3 ibm-watsonx-ai-1.5.0 idna-3.11 jmespath-1.0.1 lomond-0.3.3 pandas-2.2.3 pytz-2025.2 requests-2.32.5 tabulate-0.9.0 typing_extensions-4.15.0 tzdata-2025.3 urllib3-2.6.3

Connection to watsonx.ai Runtime

Authenticate the watsonx.ai Runtime service on IBM Cloud. You need to provide platform api_key and instance location.

You can use IBM Cloud CLI to retrieve platform API Key and instance location.

API Key can be generated in the following way:

ibmcloud login ibmcloud iam api-key-create API_KEY_NAME

In result, get the value of api_key from the output.

Location of your watsonx.ai Runtime instance can be retrieved in the following way:

ibmcloud login --apikey API_KEY -a https://cloud.ibm.com ibmcloud resource service-instance INSTANCE_NAME

In result, get the value of location from the output.

Tip: Your Cloud API key can be generated by going to the Users section of the Cloud console. From that page, click your name, scroll down to the API Keys section, and click Create an IBM Cloud API key. Give your key a name and click Create, then copy the created key and paste it below. You can also get a service specific url by going to the Endpoint URLs section of the watsonx.ai Runtime docs. You can check your instance location in your watsonx.ai Runtime Service instance details.

You can also get service specific apikey by going to the Service IDs section of the Cloud Console. From that page, click Create, then copy the created key and paste it below.

Action: Enter your url and api_key in the following cell.

import getpass from ibm_watsonx_ai import Credentials credentials = Credentials( url="https://us-south.ml.cloud.ibm.com", api_key=getpass.getpass("Please enter your watsonx.ai api key (hit enter): "), )
from ibm_watsonx_ai import APIClient client = APIClient(credentials)

Create two spaces. One for export and one for import

Tip: You can refer to details and example for space management apis here.

# Refer to the link in above tip how to find the COS and instance CRNs cos_resource_crn = "PASTE_YOUR_COS_CRN" instance_crn = "PASTE_YOUR_WML_INSTANCE_CRN" name = "PASTE_YOUR_INSTANCE_NAME_HERE"
import uuid space_name = str(uuid.uuid4())
export_space_metadata = { client.spaces.ConfigurationMetaNames.NAME: "client_space_export_" + space_name, client.spaces.ConfigurationMetaNames.DESCRIPTION: space_name + " description", client.spaces.ConfigurationMetaNames.STORAGE: {"resource_crn": cos_resource_crn}, client.spaces.ConfigurationMetaNames.COMPUTE: {"name": name, "crn": instance_crn}, } space = client.spaces.store(meta_props=export_space_metadata, background_mode=False) export_space_id = client.spaces.get_id(space)
################################################################################## Synchronous space creation with id: 'd5ffc00c-837b-402a-839f-450f35ca184f' started ################################################################################## preparing active ------------------------------------------------------------------------------ Creating space 'd5ffc00c-837b-402a-839f-450f35ca184f' finished successfully. ------------------------------------------------------------------------------
import_space_metadata = { client.spaces.ConfigurationMetaNames.NAME: "client_space_import_" + space_name, client.spaces.ConfigurationMetaNames.DESCRIPTION: space_name + " description", client.spaces.ConfigurationMetaNames.STORAGE: {"resource_crn": cos_resource_crn}, client.spaces.ConfigurationMetaNames.COMPUTE: {"name": name, "crn": instance_crn}, } space = client.spaces.store(meta_props=import_space_metadata, background_mode=False) import_space_id = client.spaces.get_id(space)
################################################################################## Synchronous space creation with id: '3d8d02c2-de18-4ad2-8c9c-b4e69be485f6' started ################################################################################## preparing active ------------------------------------------------------------------------------ Creating space '3d8d02c2-de18-4ad2-8c9c-b4e69be485f6' finished successfully. ------------------------------------------------------------------------------

2. Download externally created Keras model and data

In this section, you will download externally created Keras models and data used for training it.

import os import wget model_path = "mnist-keras-model.h5.zip" if not os.path.isfile(model_path): wget.download( "https://github.com/IBM/watsonx-ai-samples/raw/master/cloud/models/keras/mnist-keras-model.h5.zip" )
import os import wget data_dir = "MNIST_DATA" if not os.path.isdir(data_dir): os.mkdir(data_dir) filename = os.path.join(data_dir, "mnist.npz") if not os.path.isfile(filename): wget.download("https://s3.amazonaws.com/img-datasets/mnist.npz", out=data_dir)
import numpy as np dataset = np.load(filename) x_test = dataset["x_test"]

3. Persist externally created Keras model

In this section, you will learn how to store your model in watsonx.ai Runtime repository by using the watsonx.ai Client.

3.1: Publish model

Define model name, type and software specification needed to deploy model later.

software_spec_id = client.software_specifications.get_id_by_name("runtime-25.1-py3.12")
client.set.default_space(export_space_id) metadata = { client.repository.ModelMetaNames.NAME: "External Keras model", client.repository.ModelMetaNames.TYPE: "tensorflow_2.18", client.repository.ModelMetaNames.SOFTWARE_SPEC_ID: software_spec_id, } published_model = client.repository.store_model(model=model_path, meta_props=metadata)

3.2: Get model details

import json published_model_id = client.repository.get_model_id(published_model) model_details = client.repository.get_details(published_model_id) print(json.dumps(model_details, indent=2))
{ "metadata": { "name": "External Keras model", "space_id": "d5ffc00c-837b-402a-839f-450f35ca184f", "resource_key": "4f3dccd1-9d46-49ab-879d-efd8ffa5d8c6", "id": "88d5f6a9-6fce-4046-b1af-94cc05e5201c", "created_at": "2026-01-19T09:35:51Z", "rov": { "member_roles": { "IBMid-696000GJGB": { "user_iam_id": "IBMid-696000GJGB", "roles": [ "OWNER" ] } } }, "owner": "IBMid-696000GJGB" }, "entity": { "software_spec": { "id": "f47ae1c3-198e-5718-b59d-2ea471561e9e" }, "type": "tensorflow_2.18" } }

3.3 Get all models in the space

space_id is automatically picked up from client.set.default_space() api call before

models_details = client.repository.list_models()

4. Export

help(client.export_assets.start)
Help on method start in module ibm_watsonx_ai.export_assets: start(meta_props: 'dict[str, str | bool | list]', space_id: 'str | None' = None, project_id: 'str | None' = None) -> 'dict[str, Any]' method of ibm_watsonx_ai.export_assets.Export instance Start the export. You must provide the space_id or the project_id. ALL_ASSETS is by default False. You don't need to provide it unless it is set to True. You must provide one of the following in the meta_props: ALL_ASSETS, ASSET_TYPES, or ASSET_IDS. Only one of these can be provided. In the `meta_props`: ALL_ASSETS is a boolean. When set to True, it exports all assets in the given space. ASSET_IDS is an array that contains the list of assets IDs to be exported. ASSET_TYPES is used to provide the asset types to be exported. All assets of that asset type will be exported. Eg: wml_model, wml_model_definition, wml_pipeline, wml_function, wml_experiment, software_specification, hardware_specification, package_extension, script :param meta_props: metadata, to see available meta names use ``client.export_assets.ConfigurationMetaNames.get()`` :type meta_props: dict :param space_id: space identifier :type space_id: str, optional :param project_id: project identifier :type project_id: str, optional :return: Response json :rtype: dict **Example:** .. code-block:: python metadata = { client.export_assets.ConfigurationMetaNames.NAME: "export_model", client.export_assets.ConfigurationMetaNames.ASSET_IDS: [ "13a53931-a8c0-4c2f-8319-c793155e7517", "13a53931-a8c0-4c2f-8319-c793155e7518", ], } details = client.export_assets.start( meta_props=metadata, space_id="98a53931-a8c0-4c2f-8319-c793155e4598" ) .. code-block:: python metadata = { client.export_assets.ConfigurationMetaNames.NAME: "export_model", client.export_assets.ConfigurationMetaNames.ASSET_TYPES: [ "wml_model" ], } details = client.export_assets.start( meta_props=metadata, space_id="98a53931-a8c0-4c2f-8319-c793155e4598" ) .. code-block:: python metadata = { client.export_assets.ConfigurationMetaNames.NAME: "export_model", client.export_assets.ConfigurationMetaNames.ALL_ASSETS: True, } details = client.export_assets.start( meta_props=metadata, space_id="98a53931-a8c0-4c2f-8319-c793155e4598" )

client.export_assets has these apis. For any help on these apis, type 'help(api_name)' in your notebook Example: help(client.export_assets.start), help(client.export_assets.get_details)

  1. client.export_assets.start: This starts the export job. export job is asynchronously executed

  2. client.export_assets.get_details: Given export_id and corresponding space_id/project_id, this gives the export job details. Usually used for monitoring the export job submitted with start api

  3. client.export_assets.list: Prints summary of all the export jobs

  4. client.export_assets.get_exported_content: Downloads the exported content. This information will be used by the import process

  5. client.export_assets.delete: Deletes the given export job

  6. client.export_assets.cancel: Cancels the given export job if running

4.1: Start the export process

Start the export process for the model created. Either ASSET_IDS or ASSET_TYPES or ALL_ASSETS can be provided. If you have more than one model ids, you need to provide them as array like client.export_assets.ConfigurationMetaNames.ASSET_IDS: [model_id1, model_id2] Refer to the help api above to see different usages and details

metadata = { client.export_assets.ConfigurationMetaNames.NAME: "export_model", client.export_assets.ConfigurationMetaNames.ASSET_IDS: [published_model_id], } details = client.export_assets.start(meta_props=metadata, space_id=export_space_id) print(json.dumps(details, indent=2)) export_job_id = details["metadata"]["id"]
export job with id 9ae088d7-194b-4d4e-9323-fc3570996821 has started. Monitor status using client.export_assets.get_details api. Check 'help(client.export_assets.get_details)' for details on the api usage { "entity": { "assets": { "all_assets": false, "asset_ids": [ "88d5f6a9-6fce-4046-b1af-94cc05e5201c" ] }, "format": "json", "status": { "state": "pending" } }, "metadata": { "created_at": "2026-01-19T09:36:01.446Z", "creator_id": "IBMid-696000GJGB", "id": "9ae088d7-194b-4d4e-9323-fc3570996821", "name": "export_model", "space_id": "d5ffc00c-837b-402a-839f-450f35ca184f", "url": "/v2/asset_exports/9ae088d7-194b-4d4e-9323-fc3570996821" } }

4.2: Monitor the export process

import time start_time = time.time() diff_time = start_time - start_time while True and diff_time < 10 * 60: time.sleep(3) response = client.export_assets.get_details(export_job_id, space_id=export_space_id) state = response["entity"]["status"]["state"] print(state) if state == "completed" or state == "error" or state == "failed": break diff_time = time.time() - start_time print(json.dumps(response, indent=2))
completed { "entity": { "assets": { "all_assets": false, "asset_ids": [ "88d5f6a9-6fce-4046-b1af-94cc05e5201c" ] }, "format": "json", "status": { "state": "completed" } }, "metadata": { "created_at": "2026-01-19T09:36:01.446Z", "creator_id": "IBMid-696000GJGB", "id": "9ae088d7-194b-4d4e-9323-fc3570996821", "name": "export_model", "space_id": "d5ffc00c-837b-402a-839f-450f35ca184f", "updated_at": "2026-01-19T09:36:04.610Z", "url": "/v2/asset_exports/9ae088d7-194b-4d4e-9323-fc3570996821" } }

4.3: Get the exported content

export_dir = "EXPORT_DATA" if not os.path.isdir(export_dir): os.mkdir(export_dir) export_file_name = "exported_content_" + str(uuid.uuid4()) + ".zip" export_file_path = os.path.join(export_dir, export_file_name) details = client.export_assets.get_exported_content( export_job_id, space_id=export_space_id, file_path=export_file_path ) print(details)
Successfully saved export content to file: 'EXPORT_DATA/exported_content_4a37d2b9-4500-4abf-bbed-c628c8806fed.zip' EXPORT_DATA/exported_content_4a37d2b9-4500-4abf-bbed-c628c8806fed.zip

5. Import

client.import_assets has these apis. For any help on these apis, type 'help(api_name)' in your notebook Example: help(client.import_assets.start), help(client.import_assets.get_details)

  1. client.import_assets.start: This starts the import job. import job is asynchronously executed

  2. client.import_assets.get_details: Given import_id and corresponding space_id/project_id, this gives the import job details. Usually used for monitoring the import job submitted with start api

  3. client.import_assets.list: Prints summary of all the import jobs

  4. client.import_assets.delete: Deletes the given import job

  5. client.import_assets.cancel: Cancels the given import job if running

5.1: Start the import process

details = client.import_assets.start( file_path=export_file_path, space_id=import_space_id ) print(json.dumps(details, indent=2)) import_job_id = details["metadata"]["id"]
import job with id 0d2532f8-d4b9-4008-adae-2c1e51f0a53c has started. Monitor status using client.import_assets.get_details api. Check 'help(client.import_assets.get_details)' for details on the api usage { "entity": { "format": "json", "status": { "state": "pending" } }, "metadata": { "created_at": "2026-01-19T09:36:15.937Z", "creator_id": "IBMid-696000GJGB", "id": "0d2532f8-d4b9-4008-adae-2c1e51f0a53c", "space_id": "3d8d02c2-de18-4ad2-8c9c-b4e69be485f6", "url": "/v2/asset_imports/0d2532f8-d4b9-4008-adae-2c1e51f0a53c" } }

5.2: Monitor the import process

import time start_time = time.time() diff_time = start_time - start_time while True and diff_time < 10 * 60: time.sleep(3) response = client.import_assets.get_details(import_job_id, space_id=import_space_id) state = response["entity"]["status"]["state"] print(state) if state == "completed" or state == "error" or state == "failed": break diff_time = time.time() - start_time print(json.dumps(response, indent=2)) client.set.default_space(import_space_id) print("{}List of models: {}".format("\n", "\n")) client.repository.list_models() details = client.repository.get_model_details() for obj in details["resources"]: if obj["metadata"]["name"] == "External Keras model": model_id_for_deployment = obj["metadata"]["id"] print("{}model id for deployment: {}".format("\n", model_id_for_deployment))
running completed { "entity": { "format": "json", "status": { "state": "completed" } }, "metadata": { "created_at": "2026-01-19T09:36:15.937Z", "creator_id": "IBMid-696000GJGB", "id": "0d2532f8-d4b9-4008-adae-2c1e51f0a53c", "space_id": "3d8d02c2-de18-4ad2-8c9c-b4e69be485f6", "updated_at": "2026-01-19T09:36:21.860Z", "url": "/v2/asset_imports/0d2532f8-d4b9-4008-adae-2c1e51f0a53c" } } List of models: model id for deployment: 502536fc-8cf1-4d76-9da6-34e4c1fbacfc

List the import and export jobs

print("Export jobs: \n") client.export_assets.list(space_id=export_space_id)
Export jobs:
print("\nImport jobs:") client.import_assets.list(space_id=import_space_id)
Import jobs:

6. Deploy and score the imported model

6.1: Create model deployment

Create online deployment for published model

metadata = { client.deployments.ConfigurationMetaNames.NAME: "Deployment of external Keras model", client.deployments.ConfigurationMetaNames.ONLINE: {}, } created_deployment = client.deployments.create( model_id_for_deployment, meta_props=metadata )
###################################################################################### Synchronous deployment creation for id: '502536fc-8cf1-4d76-9da6-34e4c1fbacfc' started ###################################################################################### initializing Note: online_url and serving_urls are deprecated and will be removed in a future release. Use inference instead. ...... ready ----------------------------------------------------------------------------------------------- Successfully finished deployment creation, deployment_id='9819e543-8b53-42b1-8409-a58255a69b63' -----------------------------------------------------------------------------------------------
deployment_id = client.deployments.get_id(created_deployment)

Now you can print an online scoring endpoint.

scoring_endpoint = client.deployments.get_scoring_href(created_deployment) print(scoring_endpoint)

You can also list existing deployments.

client.deployments.list()

6.2: Get deployment details

details = client.deployments.get_details(deployment_id) print(json.dumps(details, indent=2))

6.3: Score

You can use below method to do test scoring request against deployed model.

Let's first visualize two samples from dataset, we'll use for scoring. You must have matplotlib package installed

%matplotlib inline import matplotlib.pyplot as plt
for i, image in enumerate([x_test[0], x_test[1]]): plt.subplot(2, 2, i + 1) plt.axis("off") plt.imshow(image, cmap=plt.cm.gray_r, interpolation="nearest")
Image in a Jupyter notebook

Prepare scoring payload with records to score.

score_0 = x_test[0].reshape(28, 28, 1) score_1 = x_test[1].reshape(28, 28, 1)
scoring_payload = {"input_data": [{"values": [score_0, score_1]}]}

Use client.deployments.score() method to run scoring.

predictions = client.deployments.score(deployment_id, scoring_payload)
print(json.dumps(predictions, indent=2))
{ "predictions": [ { "fields": [ "prediction" ], "id": "y_hat", "values": [ [ 2.1161436052352656e-06, 9.53357170985214e-10, 4.728389346730921e-10, 3.943275572737548e-08, 0.00011951127089560032, 1.438263979025578e-07, 2.1252301252161487e-08, 0.9995545744895935, 8.875564958543691e-07, 0.0003227672423236072 ], [ 0.021077046170830727, 0.1209486722946167, 0.8552001714706421, 0.0012876029359176755, 4.0436454582959414e-05, 0.0004892426659353077, 0.00048998644342646, 9.553693234920502e-05, 0.00018569448729977012, 0.00018568598898127675 ] ] } ] }
for i, prediction in enumerate(predictions["predictions"][0]["values"]): plt.bar(range(10), prediction) plt.title("Digit probability") plt.xlabel("Digit") plt.ylabel("Probability") plt.xticks(range(10)) plt.yscale("log") plt.show()
Image in a Jupyter notebookImage in a Jupyter notebook

7. Clean up

client.export_assets.delete(export_job_id, space_id=export_space_id) client.import_assets.delete(import_job_id, space_id=import_space_id) client.spaces.delete(export_space_id) client.spaces.delete(import_space_id)
Export job deleted Import job deleted
'SUCCESS'

If you want to clean up all created assets:

  • experiments

  • trainings

  • pipelines

  • model definitions

  • models

  • functions

  • deployments

please follow up this sample notebook.

8. Summary and next steps

You successfully completed this notebook! You learned how to use export/import assets client apis. Check out our Online Documentation for more samples, tutorials, documentation, how-tos, and blog posts.

Authors

Mithun - [email protected], Software Engineer

Mateusz Szewczyk, Software Engineer at watsonx.ai

Copyright © 2020-2026 IBM. This notebook and its source code are released under the terms of the MIT License.