Skip to content

Cli

zenml.cli

ZenML CLI.

The ZenML CLI tool is usually downloaded and installed via PyPI and a pip install zenml command. Please see the Installation & Setup section above for more information about that process.

How to use the CLI

Our CLI behaves similarly to many other CLIs for basic features. In order to find out which version of ZenML you are running, type:

   zenml version

If you ever need more information on exactly what a certain command will do, use the --help flag attached to the end of your command string.

For example, to get a sense of all the commands available to you while using the zenml command, type:

   zenml --help

If you were instead looking to know more about a specific command, you can type something like this:

   zenml artifact-store register --help

This will give you information about how to register an artifact store. (See below for more on that).

If you want to instead understand what the concept behind a group is, you can use the explain sub-command. For example, to see more details behind what a artifact-store is, you can type:

zenml artifact-store explain

This will give you an explanation of that concept in more detail.

Beginning a Project

In order to start working on your project, initialize a ZenML repository within your current directory with ZenML's own config and resource management tools:

zenml init

This is all you need to begin using all the MLOps goodness that ZenML provides!

By default, zenml init will install its own hidden .zen folder inside the current directory from which you are running the command. You can also pass in a directory path manually using the --path option:

zenml init --path /path/to/dir

If you wish to use one of the available ZenML project templates to generate a ready-to-use project scaffold in your repository, you can do so by passing the --template option:

zenml init --template <name_of_template>

Running the above command will result in input prompts being shown to you. If you would like to rely on default values for the ZenML project template - you can add --template-with-defaults to the same command, like this:

zenml init --template <name_of_template> --template-with-defaults

In a similar fashion, if you would like to quickly explore the capabilities of ZenML through a notebook, you can also use:

zenml go

Cleaning up

If you wish to delete all data relating to your project from the directory, use the zenml clean command. This will:

  • delete all pipelines, pipeline runs and associated metadata
  • delete all artifacts

Using Integrations

Integrations are the different pieces of a project stack that enable custom functionality. This ranges from bigger libraries like kubeflow for orchestration down to smaller visualization tools like facets. Our CLI is an easy way to get started with these integrations.

To list all the integrations available to you, type:

zenml integration list

To see the requirements for a specific integration, use the requirements command:

zenml integration requirements INTEGRATION_NAME

If you wish to install the integration, using the requirements listed in the previous command, install allows you to do this for your local environment:

zenml integration install INTEGRATION_NAME

Note that if you don't specify a specific integration to be installed, the ZenML CLI will install all available integrations.

If you want to install all integrations apart from one or multiple integrations, use the following syntax, for example, which will install all integrations except feast and aws:

zenml integration install -i feast -i aws

Uninstalling a specific integration is as simple as typing:

zenml integration uninstall INTEGRATION_NAME

For all these zenml integration commands, you can pass the --uv flag and we will use uv as the package manager instead of pip. This will resolve and install much faster than with pip, but note that it requires uv to be installed on your machine. This is an experimental feature and may not work on all systems. In particular, note that installing onto machines with GPU acceleration may not work as expected.

If you would like to export the requirements of all ZenML integrations, you can use the command:

zenml integration export-requirements

Here, you can also select a list of integrations and write the result into and output file:

zenml integration export-requirements gcp kubeflow -o OUTPUT_FILE

Filtering when listing

Certain CLI list commands allow you to filter their output. For example, all stack components allow you to pass custom parameters to the list command that will filter the output. To learn more about the available filters, a good quick reference is to use the --help command, as in the following example:

zenml orchestrator list --help

You will see a list of all the available filters for the list command along with examples of how to use them.

The --sort_by option allows you to sort the output by a specific field and takes an asc or desc argument to specify the order. For example, to sort the output of the list command by the name field in ascending order, you would type:

zenml orchestrator list --sort_by "asc:name"

For fields marked as being of type TEXT or UUID, you can use the contains, startswith and endswith keywords along with their particular identifier. For example, for the orchestrator list command, you can use the following filter to find all orchestrators that contain the string sagemaker in their name:

zenml orchestrator list --name "contains:sagemaker"

For fields marked as being of type BOOL, you can use the 'True' or 'False' values to filter the output.

Finally, for fields marked as being of type DATETIME, you can pass in datetime values in the %Y-%m-%d %H:%M:%S format. These can be combined with the gte, lte, gt and lt keywords (greater than or equal, less than or equal, greater than and less than respectively) to specify the range of the filter. For example, if I wanted to find all orchestrators that were created after the 1st of January 2021, I would type:

zenml orchestrator list --created "gt:2021-01-01 00:00:00"

This syntax can also be combined to create more complex filters using the or and and keywords.

Artifact Stores

In ZenML, the artifact store is where all the inputs and outputs of your pipeline steps are stored. By default, ZenML initializes your repository with an artifact store with everything kept on your local machine. You can get a better understanding about the concept of artifact stores by executing:

zenml artifact-store explain

If you wish to register a new artifact store, do so with the register command:

zenml artifact-store register ARTIFACT_STORE_NAME --flavor=ARTIFACT_STORE_FLAVOR [--OPTIONS]

You can also add any labels to your stack component using the --label or -l flag:

zenml artifact-store register ARTIFACT_STORE_NAME --flavor=ARTIFACT_STORE_FLAVOR -l key1=value1 -l key2=value2

As you can see from the command above, when you register a new artifact store, you have to choose a flavor. To see the full list of available artifact store flavors, you can use the command:

zenml artifact-store flavor list

This list will show you which integration these flavors belong to and which service connectors they are adaptable with. If you would like to get additional information regarding a specific flavor, you can utilize the command:

zenml artifact-store flavor describe FLAVOR_NAME

If you wish to list the artifact stores that have already been registered within your ZenML:

zenml artifact-store list

If you want the name of the artifact store in the active stack, you can also use the get command:

zenml artifact-store get

For details about a particular artifact store, use the describe command. By default, (without a specific artifact store name passed in) it will describe the active or currently used artifact store:

zenml artifact-store describe ARTIFACT_STORE_NAME

If you wish to update/rename an artifact store, you can use the following commands respectively:

zenml artifact-store update ARTIFACT_STORE_NAME --property_to_update=new_value
zenml artifact-store rename ARTIFACT_STORE_OLD_NAME ARTIFACT_STORE_NEW_NAME

If you wish to delete a particular artifact store, pass the name of the artifact store into the CLI with the following command:

zenml artifact-store delete ARTIFACT_STORE_NAME

If you would like to connect/disconnect your artifact store to/from a service connector, you can use the following commands:

zenml artifact-store connect ARTIFACT_STORE_NAME -c CONNECTOR_NAME
zenml artifact-store disconnect

The ZenML CLI provides a few more utility functions for you to manage your artifact stores. In order to get a full list of available functions, use the command:

zenml artifact-store --help

Orchestrators

An orchestrator is a special kind of backend that manages the running of each step of the pipeline. Orchestrators administer the actual pipeline runs. By default, ZenML initializes your repository with an orchestrator that runs everything on your local machine. In order to get a more detailed explanation, you can use the command:

zenml orchestrator explain

If you wish to register a new orchestrator, do so with the register command:

zenml orchestrator register ORCHESTRATOR_NAME --flavor=ORCHESTRATOR_FLAVOR [--ORCHESTRATOR_OPTIONS]

You can also add any label to your stack component using the --label or -l flag:

zenml orchestrator register ORCHESTRATOR_NAME --flavor=ORCHESTRATOR_FLAVOR -l key1=value1 -l key2=value2

As you can see from the command above, when you register a new orchestrator, you have to choose a flavor. To see the full list of available orchestrator flavors, you can use the command:

zenml orchestrator flavor list

This list will show you which integration these flavors belong to and which service connectors they are adaptable with. If you would like to get additional information regarding a specific flavor, you can utilize the command:

zenml orchestrator flavor describe FLAVOR_NAME

If you wish to list the orchestrators that have already been registered, type:

zenml orchestrator list

If you want the name of the orchestrator in the active stack, you can also use the get command:

zenml orchestrator get

For details about a particular orchestrator, use the describe command. By default, (without a specific orchestrator name passed in) it will describe the active or currently used orchestrator:

zenml orchestrator describe [ORCHESTRATOR_NAME]

If you wish to update/rename an orchestrator, you can use the following commands respectively:

zenml orchestrator update ORCHESTRATOR_NAME --property_to_update=new_value
zenml orchestrator rename ORCHESTRATOR_OLD_NAME ORCHESTRATOR_NEW_NAME

If you wish to delete a particular orchestrator, pass the name of the orchestrator into the CLI with the following command:

zenml orchestrator delete ORCHESTRATOR_NAME

If you would like to connect/disconnect your orchestrator to/from a service connector, you can use the following commands:

zenml orchestrator connect ORCHESTRATOR_NAME -c CONNECTOR_NAME
zenml orchestrator disconnect

The ZenML CLI provides a few more utility functions for you to manage your orchestrators. In order to get a full list of available functions, use the command:

zenml orchestrators --help

Container Registries

The container registry is where all the images that are used by a container-based orchestrator are stored. To get a better understanding regarding container registries, use the command:

zenml container-registry explain

By default, a default ZenML local stack will not register a container registry. If you wish to register a new container registry, do so with the register command:

zenml container-registry register REGISTRY_NAME --flavor=REGISTRY_FLAVOR [--REGISTRY_OPTIONS]

You can also add any label to your stack component using the --label or -l flag:

zenml container-registry register REGISTRY_NAME --flavor=REGISTRY_FLAVOR -l key1=value1 -l key2=value2

As you can see from the command above, when you register a new container registry, you have to choose a flavor. To see the full list of available container registry flavors, you can use the command:

zenml container-registry flavor list

This list will show you which integration these flavors belong to and which service connectors they are adaptable with. If you would like to get additional information regarding a specific flavor, you can utilize the command:

zenml container-registry flavor describe FLAVOR_NAME

To list all container registries available and registered for use, use the list command:

zenml container-registry list

If you want the name of the container registry in the active stack, you can also use the get command:

zenml container-registry get

For details about a particular container registry, use the describe command. By default, (without a specific registry name passed in) it will describe the active or currently used container registry:

zenml container-registry describe [CONTAINER_REGISTRY_NAME]

If you wish to update/rename a container registry, you can use the following commands respectively:

zenml container-registry update CONTAINER_REGISTRY_NAME --property_to_update=new_value
zenml container-registry rename CONTAINER_REGISTRY_OLD_NAME CONTAINER_REGISTRY_NEW_NAME

To delete a container registry (and all of its contents), use the delete command:

zenml container-registry delete REGISTRY_NAME

If you would like to connect/disconnect your container registry to/from a service connector, you can use the following commands:

zenml container-registry connect CONTAINER_REGISTRY_NAME -c CONNECTOR_NAME
zenml container-registry disconnect

The ZenML CLI provides a few more utility functions for you to manage your container registries. In order to get a full list of available functions, use the command:

zenml container-registry --help

Data Validators

In ZenML, data validators help you profile and validate your data.

By default, a default ZenML local stack will not register a data validator. If you wish to register a new data validator, do so with the register command:

zenml data-validator register DATA_VALIDATOR_NAME --flavor DATA_VALIDATOR_FLAVOR [--DATA_VALIDATOR_OPTIONS]

You can also add any label to your stack component using the --label or -l flag:

zenml data-validator register DATA_VALIDATOR_NAME --flavor DATA_VALIDATOR_FLAVOR -l key1=value1 -l key2=value2

As you can see from the command above, when you register a new data validator, you have to choose a flavor. To see the full list of available data validator flavors, you can use the command:

zenml data-validator flavor list

This list will show you which integration these flavors belong to and which service connectors they are adaptable with. If you would like to get additional information regarding a specific flavor, you can utilize the command:

zenml data-validator flavor describe FLAVOR_NAME

To list all data validators available and registered for use, use the list command:

zenml data-validator list

If you want the name of the data validator in the active stack, use the get command:

zenml data-validator get

For details about a particular data validator, use the describe command. By default, (without a specific data validator name passed in) it will describe the active or currently-used data validator:

zenml data-validator describe [DATA_VALIDATOR_NAME]

If you wish to update/rename a data validator, you can use the following commands respectively:

zenml data-validator update DATA_VALIDATOR_NAME --property_to_update=new_value
zenml data-validator rename DATA_VALIDATOR_OLD_NAME DATA_VALIDATOR_NEW_NAME

To delete a data validator (and all of its contents), use the delete command:

zenml data-validator delete DATA_VALIDATOR_NAME

If you would like to connect/disconnect your data validator to/from a service connector, you can use the following commands:

zenml data-validator connect DATA_VALIDATOR_NAME -c CONNECTOR_NAME
zenml data-validator disconnect

The ZenML CLI provides a few more utility functions for you to manage your data validators. In order to get a full list of available functions, use the command:

zenml data-validator --help

Experiment Trackers

Experiment trackers let you track your ML experiments by logging the parameters and allow you to compare between different runs. To get a better understanding regarding experiment trackers, use the command:

zenml experiment-tracker explain

By default, a default ZenML local stack will not register an experiment tracker. If you want to use an experiment tracker in one of your stacks, you need to first register it:

zenml experiment-tracker register EXPERIMENT_TRACKER_NAME     --flavor=EXPERIMENT_TRACKER_FLAVOR [--EXPERIMENT_TRACKER_OPTIONS]

You can also add any label to your stack component using the --label or -l flag:

zenml experiment-tracker register EXPERIMENT_TRACKER_NAME       --flavor=EXPERIMENT_TRACKER_FLAVOR -l key1=value1 -l key2=value2

As you can see from the command above, when you register a new experiment tracker, you have to choose a flavor. To see the full list of available experiment tracker flavors, you can use the command:

zenml experiment-tracker flavor list

This list will show you which integration these flavors belong to and which service connectors they are adaptable with. If you would like to get additional information regarding a specific flavor, you can utilize the command:

zenml experiment-tracker flavor describe FLAVOR_NAME

To list all experiment trackers available and registered for use, use the list command:

zenml experiment-tracker list

If you want the name of the experiment tracker in the active stack, use the get command:

zenml experiment-tracker get

For details about a particular experiment tracker, use the describe command. By default, (without a specific experiment tracker name passed in) it will describe the active or currently-used experiment tracker:

zenml experiment-tracker describe [EXPERIMENT_TRACKER_NAME]

If you wish to update/rename an experiment tracker, you can use the following commands respectively:

zenml experiment-tracker update EXPERIMENT_TRACKER_NAME --property_to_update=new_value
zenml experiment-tracker rename EXPERIMENT_TRACKER_OLD_NAME EXPERIMENT_TRACKER_NEW_NAME

To delete an experiment tracker, use the delete command:

zenml experiment-tracker delete EXPERIMENT_TRACKER_NAME

If you would like to connect/disconnect your experiment tracker to/from a service connector, you can use the following commands:

zenml experiment-tracker connect EXPERIMENT_TRACKER_NAME -c CONNECTOR_NAME
zenml experiment-tracker disconnect

The ZenML CLI provides a few more utility functions for you to manage your experiment trackers. In order to get a full list of available functions, use the command:

zenml experiment-tracker --help

Model Deployers

Model deployers are stack components responsible for online model serving. They are responsible for deploying models to a remote server. Model deployers also act as a registry for models that are served with ZenML. To get a better understanding regarding model deployers, use the command:

zenml model-deployer explain

By default, a default ZenML local stack will not register a model deployer. If you wish to register a new model deployer, do so with the register command:

zenml model-deployer register MODEL_DEPLOYER_NAME --flavor MODEL_DEPLOYER_FLAVOR [--MODEL_DEPLOYER_OPTIONS]

You can also add any label to your stack component using the --label or -l flag:

zenml model-deployer register MODEL_DEPLOYER_NAME --flavor MODEL_DEPLOYER_FLAVOR -l key1=value1 -l key2=value2

As you can see from the command above, when you register a new model deployer, you have to choose a flavor. To see the full list of available model deployer flavors, you can use the command:

zenml model-deployer flavor list

This list will show you which integration these flavors belong to and which service connectors they are adaptable with. If you would like to get additional information regarding a specific flavor, you can utilize the command:

zenml model-deployer flavor describe FLAVOR_NAME

To list all model deployers available and registered for use, use the list command:

zenml model-deployer list

If you want the name of the model deployer in the active stack, use the get command:

zenml model-deployer get

For details about a particular model deployer, use the describe command. By default, (without a specific operator name passed in) it will describe the active or currently used model deployer:

zenml model-deployer describe [MODEL_DEPLOYER_NAME]

If you wish to update/rename a model deployer, you can use the following commands respectively:

zenml model-deployer update MODEL_DEPLOYER_NAME --property_to_update=new_value
zenml model-deployer rename MODEL_DEPLOYER_OLD_NAME MODEL_DEPLOYER_NEW_NAME

To delete a model deployer (and all of its contents), use the delete command:

zenml model-deployer delete MODEL_DEPLOYER_NAME

If you would like to connect/disconnect your model deployer to/from a service connector, you can use the following commands:

zenml model-deployer connect MODEL_DEPLOYER_NAME -c CONNECTOR_NAME
zenml model-deployer disconnect

Moreover, ZenML features a set of CLI commands specific to the model deployer interface. If you want to simply see what models have been deployed within your stack, run the following command:

zenml model-deployer models list

This should give you a list of served models containing their uuid, the name of the pipeline that produced them including the run id and the step name as well as the status. This information should help you identify the different models.

If you want further information about a specific model, simply copy the UUID and the following command.

zenml model-deployer models describe <UUID>

If you are only interested in the prediction url of the specific model you can also run:

zenml model-deployer models get-url <UUID>

Finally, you will also be able to start/stop the services using the following two commands:

zenml model-deployer models start <UUID>
zenml model-deployer models stop <UUID>

If you want to completely remove a served model you can also irreversibly delete it using:

zenml model-deployer models delete <UUID>

The ZenML CLI provides a few more utility functions for you to manage your model deployers. In order to get a full list of available functions, use the command:

zenml model-deployer --help

Step Operators

Step operators allow you to run individual steps in a custom environment different from the default one used by your active orchestrator. One example use-case is to run a training step of your pipeline in an environment with GPUs available. To get a better understanding regarding step operators, use the command:

zenml step-operator explain

By default, a default ZenML local stack will not register a step operator. If you wish to register a new step operator, do so with the register command:

zenml step-operator register STEP_OPERATOR_NAME --flavor STEP_OPERATOR_FLAVOR [--STEP_OPERATOR_OPTIONS]

You can also add any label to your stack component using the --label or -l flag:

zenml step-operator register STEP_OPERATOR_NAME --flavor STEP_OPERATOR_FLAVOR -l key1=value1 -l key2=value2

As you can see from the command above, when you register a new step operator, you have to choose a flavor. To see the full list of available step operator flavors, you can use the command:

zenml step-operator flavor list

This list will show you which integration these flavors belong to and which service connectors they are adaptable with. If you would like to get additional information regarding a specific flavor, you can utilize the command:

zenml step-operator flavor describe FLAVOR_NAME

To list all step operators available and registered for use, use the list command:

zenml step-operator list

If you want the name of the step operator in the active stack, use the get command:

zenml step-operator get

For details about a particular step operator, use the describe command. By default, (without a specific operator name passed in) it will describe the active or currently used step operator:

zenml step-operator describe [STEP_OPERATOR_NAME]

If you wish to update/rename a step operator, you can use the following commands respectively:

zenml step-operator update STEP_OPERATOR_NAME --property_to_update=new_value
zenml step-operator rename STEP_OPERATOR_OLD_NAME STEP_OPERATOR_NEW_NAME

To delete a step operator (and all of its contents), use the delete command:

zenml step-operator delete STEP_OPERATOR_NAME

If you would like to connect/disconnect your step operator to/from a service connector, you can use the following commands:

zenml step-operator connect STEP_OPERATOR_NAME -c CONNECTOR_NAME
zenml step-operator disconnect

The ZenML CLI provides a few more utility functions for you to manage your step operators. In order to get a full list of available functions, use the command:

zenml step-operator --help

Alerters

In ZenML, alerters allow you to send alerts from within your pipeline.

By default, a default ZenML local stack will not register an alerter. If you wish to register a new alerter, do so with the register command:

zenml alerter register ALERTER_NAME --flavor ALERTER_FLAVOR [--ALERTER_OPTIONS]

You can also add any label to your stack component using the --label or -l flag:

zenml alerter register ALERTER_NAME --flavor ALERTER_FLAVOR -l key1=value1 -l key2=value2

As you can see from the command above, when you register a new alerter, you have to choose a flavor. To see the full list of available alerter flavors, you can use the command:

zenml alerter flavor list

This list will show you which integration these flavors belong to and which service connectors they are adaptable with. If you would like to get additional information regarding a specific flavor, you can utilize the command:

zenml alerter flavor describe FLAVOR_NAME

To list all alerters available and registered for use, use the list command:

zenml alerter list

If you want the name of the alerter in the active stack, use the get command:

zenml alerter get

For details about a particular alerter, use the describe command. By default, (without a specific alerter name passed in) it will describe the active or currently used alerter:

zenml alerter describe [ALERTER_NAME]

If you wish to update/rename an alerter, you can use the following commands respectively:

zenml alerter update ALERTER_NAME --property_to_update=new_value
zenml alerter rename ALERTER_OLD_NAME ALERTER_NEW_NAME

To delete an alerter (and all of its contents), use the delete command:

zenml alerter delete ALERTER_NAME

If you would like to connect/disconnect your alerter to/from a service connector, you can use the following commands:

zenml alerter connect ALERTER_NAME -c CONNECTOR_NAME
zenml alerter disconnect

The ZenML CLI provides a few more utility functions for you to manage your alerters. In order to get a full list of available functions, use the command:

zenml alerter --help

Feature Stores

Feature stores allow data teams to serve data via an offline store and an online low-latency store where data is kept in sync between the two. To get a better understanding regarding feature stores, use the command:

zenml feature-store explain

By default, a default ZenML local stack will not register a feature store. If you wish to register a new feature store, do so with the register command:

zenml feature-store register FEATURE_STORE_NAME --flavor FEATURE_STORE_FLAVOR [--FEATURE_STORE_OPTIONS]

You can also add any label to your stack component using the --label or -l flag:

zenml feature-store register FEATURE_STORE_NAME --flavor FEATURE_STORE_FLAVOR -l key1=value1 -l key2=value2

As you can see from the command above, when you register a new feature store, you have to choose a flavor. To see the full list of available feature store flavors, you can use the command:

zenml feature-store flavor list

This list will show you which integration these flavors belong to and which service connectors they are adaptable with. If you would like to get additional information regarding a specific flavor, you can utilize the command:

Note: Currently, ZenML only supports connecting to a Redis-backed Feast feature store as a stack component integration.

zenml feature-store flavor describe FLAVOR_NAME

To list all feature stores available and registered for use, use the list command:

zenml feature-store list

If you want the name of the feature store in the active stack, use the get command:

zenml feature-store get

For details about a particular feature store, use the describe command. By default, (without a specific feature store name passed in) it will describe the active or currently-used feature store:

zenml feature-store describe [FEATURE_STORE_NAME]

If you wish to update/rename a feature store, you can use the following commands respectively:

zenml feature-store update FEATURE_STORE_NAME --property_to_update=new_value
zenml feature-store rename FEATURE_STORE_OLD_NAME FEATURE_STORE_NEW_NAME

To delete a feature store (and all of its contents), use the delete command:

zenml feature-store delete FEATURE_STORE_NAME

If you would like to connect/disconnect your feature store to/from a service connector, you can use the following commands:

zenml feature-store connect FEATURE_STORE_NAME -c CONNECTOR_NAME
zenml feature-store disconnect

The ZenML CLI provides a few more utility functions for you to manage your feature stores. In order to get a full list of available functions, use the command:

zenml feature-store --help

Annotators

Annotators enable the use of data annotation as part of your ZenML stack and pipelines.

By default, a default ZenML local stack will not register an annotator. If you wish to register a new annotator, do so with the register command:

zenml annotator register ANNOTATOR_NAME --flavor ANNOTATOR_FLAVOR [--ANNOTATOR_OPTIONS]

You can also add any label to your stack component using the --label or -l flag:

zenml annotator register ANNOTATOR_NAME --flavor ANNOTATOR_FLAVOR -l key1=value1 -l key2=value2

As you can see from the command above, when you register a new annotator, you have to choose a flavor. To see the full list of available annotator flavors, you can use the command:

zenml annotator flavor list

This list will show you which integration these flavors belong to and which service connectors they are adaptable with. If you would like to get additional information regarding a specific flavor, you can utilize the command:

zenml annotator flavor describe FLAVOR_NAME

To list all annotator available and registered for use, use the list command:

zenml annotator list

If you want the name of the annotator in the active stack, use the get command:

zenml annotator get

For details about a particular annotator, use the describe command. By default, (without a specific annotator name passed in) it will describe the active or currently used annotator:

zenml annotator describe [ANNOTATOR_NAME]

If you wish to update/rename an annotator, you can use the following commands respectively:

zenml annotator update ANNOTATOR_NAME --property_to_update=new_value
zenml annotator rename ANNOTATOR_OLD_NAME ANNOTATOR_NEW_NAME

To delete an annotator (and all of its contents), use the delete command:

zenml annotator delete ANNOTATOR_NAME

If you would like to connect/disconnect your annotator to/from a service connector, you can use the following commands:

zenml annotator connect ANNOTATOR_NAME -c CONNECTOR_NAME
zenml annotator disconnect

Finally, you can use the dataset command to interact with your annotation datasets:

zenml annotator dataset --help

The ZenML CLI provides a few more utility functions for you to manage your annotator. In order to get a full list of available functions, use the command:

zenml annotator --help

Image Builders

In ZenML, image builders allow you to build container images such that your machine-learning pipelines and steps can be executed in remote environments.

By default, a default ZenML local stack will not register an image builder. If you wish to register a new image builder, do so with the register command:

zenml image-builder register IMAGE_BUILDER_NAME --flavor IMAGE_BUILDER_FLAVOR [--IMAGE_BUILDER_OPTIONS]

You can also add any label to your stack component using the --label or -l flag:

zenml image-builder register IMAGE_BUILDER_NAME --flavor IMAGE_BUILDER_FLAVOR -l key1=value1 -l key2=value2

As you can see from the command above, when you register a new image builder, you have to choose a flavor. To see the full list of available image builder flavors, you can use the command:

zenml image-builder flavor list

This list will show you which integration these flavors belong to and which service connectors they are adaptable with. If you would like to get additional information regarding a specific flavor, you can utilize the command:

zenml image-builder flavor describe FLAVOR_NAME

To list all image builders available and registered for use, use the list command:

zenml image-builder list

If you want the name of the image builder in the active stack, use the get command:

zenml image-builder get

For details about a particular image builder, use the describe command. By default, (without a specific image builder name passed in) it will describe the active or currently used image builder:

zenml image-builder describe [IMAGE_BUILDER_NAME]

If you wish to update/rename an image builder, you can use the following commands respectively:

zenml image-builder update IMAGE_BUILDER_NAME --property_to_update=new_value
zenml image-builder rename IMAGE_BUILDER_OLD_NAME IMAGE_BUILDER_NEW_NAME

To delete a image builder (and all of its contents), use the delete command:

zenml image-builder delete IMAGE_BUILDER_NAME

If you would like to connect/disconnect your image builder to/from a service connector, you can use the following commands:

zenml image-builder connect IMAGE_BUILDER_NAME -c CONNECTOR_NAME
zenml image-builder disconnect

The ZenML CLI provides a few more utility functions for you to manage your image builders. In order to get a full list of available functions, use the command:

zenml image-builder --help

Model Registries

Model registries are centralized repositories that facilitate the collaboration and management of machine learning models. To get a better understanding regarding model registries as a concept, use the command:

zenml model-registry explain

By default, a default ZenML local stack will not register a model registry. If you wish to register a new model registry, do so with the register command:

zenml model-registry register MODEL_REGISTRY_NAME --flavor MODEL_REGISTRY_FLAVOR [--MODEL_REGISTRY_OPTIONS]

You can also add any label to your stack component using the --label or -l flag:

zenml model-registry register MODEL_REGISTRY_NAME --flavor MODEL_REGISTRY_FLAVOR -l key1=value1 -l key2=value2

As you can see from the command above, when you register a new model registry, you have to choose a flavor. To see the full list of available model registry flavors, you can use the command:

zenml model-registry flavor list

This list will show you which integration these flavors belong to and which service connectors they are adaptable with. If you would like to get additional information regarding a specific flavor, you can utilize the command:

zenml model-registry flavor describe FLAVOR_NAME

To list all model registries available and registered for use, use the list command:

zenml model-registry list

If you want the name of the model registry in the active stack, use the get command:

zenml model-registry get

For details about a particular model registry, use the describe command. By default, (without a specific operator name passed in) it will describe the active or currently used model registry:

zenml model-registry describe [MODEL_REGISTRY_NAME]

If you wish to update/rename a model registry, you can use the following commands respectively:

zenml model-registry update MODEL_REGISTRY_NAME --property_to_update=new_value
zenml model-registry rename MODEL_REGISTRY_OLD_NAME MODEL_REGISTRY_NEW_NAME

To delete a model registry (and all of its contents), use the delete command:

zenml model-registry delete MODEL_REGISTRY_NAME

If you would like to connect/disconnect your model registry to/from a service connector, you can use the following commands:

zenml model-registry connect MODEL_REGISTRY_NAME -c CONNECTOR_NAME
zenml model-registry disconnect

The ZenML CLI provides a few more utility functions for you to manage your model registries. In order to get a full list of available functions, use the command:

zenml model-registry --help

Managing your Stacks

The stack is a grouping of your artifact store, your orchestrator, and other optional MLOps tools like experiment trackers or model deployers. With the ZenML tool, switching from a local stack to a distributed cloud environment can be accomplished with just a few CLI commands.

To register a new stack, you must already have registered the individual components of the stack using the commands listed above.

Use the zenml stack register command to register your stack. It takes four arguments as in the following example:

zenml stack register STACK_NAME        -a ARTIFACT_STORE_NAME        -o ORCHESTRATOR_NAME

Each corresponding argument should be the name, id or even the first few letters of the id that uniquely identify the artifact store or orchestrator.

To create a new stack using the new service connector with a set of minimal components, use the following command:

zenml stack register STACK_NAME        -p CLOUD_PROVIDER

To create a new stack using the existing service connector with a set of minimal components, use the following command:

zenml stack register STACK_NAME        -sc SERVICE_CONNECTOR_NAME

To create a new stack using the existing service connector with existing components ( important, that the components are already registered in the service connector), use the following command:

zenml stack register STACK_NAME        -sc SERVICE_CONNECTOR_NAME        -a ARTIFACT_STORE_NAME        -o ORCHESTRATOR_NAME        ...

If you want to immediately set this newly created stack as your active stack, simply pass along the --set flag.

zenml stack register STACK_NAME ... --set

To list the stacks that you have registered, type:

zenml stack list

To delete a stack that you have previously registered, type:

zenml stack delete STACK_NAME

By default, ZenML uses a local stack whereby all pipelines run on your local computer. If you wish to set a different stack as the current active stack to be used when running your pipeline, type:

zenml stack set STACK_NAME

This changes a configuration property within your local environment.

To see which stack is currently set as the default active stack, type:

zenml stack get

If you want to copy a stack, run the following command:

zenml stack copy SOURCE_STACK_NAME TARGET_STACK_NAME

If you wish to transfer one of your stacks to another machine, you can do so by exporting the stack configuration and then importing it again.

To export a stack to YAML, run the following command:

zenml stack export STACK_NAME FILENAME.yaml

This will create a FILENAME.yaml containing the config of your stack and all of its components, which you can then import again like this:

zenml stack import STACK_NAME -f FILENAME.yaml

If you wish to update a stack that you have already registered, first make sure you have registered whatever components you want to use, then use the following command:

# assuming that you have already registered a new orchestrator
# with NEW_ORCHESTRATOR_NAME
zenml stack update STACK_NAME -o NEW_ORCHESTRATOR_NAME

You can update one or many stack components at the same time out of the ones that ZenML supports. To see the full list of options for updating a stack, use the following command:

zenml stack update --help

To remove a stack component from a stack, use the following command:

# assuming you want to remove the image builder and the feature-store
# from your stack
zenml stack remove-component -i -f

If you wish to rename your stack, use the following command:

zenml stack rename STACK_NAME NEW_STACK_NAME

If you would like to export the requirements of your stack, you can use the command:

zenml stack export-requirements <STACK_NAME>

If you want to copy a stack component, run the following command:

zenml STACK_COMPONENT copy SOURCE_COMPONENT_NAME TARGET_COMPONENT_NAME

If you wish to update a specific stack component, use the following command, switching out "STACK_COMPONENT" for the component you wish to update (i.e. 'orchestrator' or 'artifact-store' etc.):

zenml STACK_COMPONENT update --some_property=NEW_VALUE

Note that you are not permitted to update the stack name or UUID in this way. To change the name of your stack component, use the following command:

zenml STACK_COMPONENT rename STACK_COMPONENT_NAME NEW_STACK_COMPONENT_NAME

If you wish to remove an attribute (or multiple attributes) from a stack component, use the following command:

zenml STACK_COMPONENT remove-attribute STACK_COMPONENT_NAME ATTRIBUTE_NAME [OTHER_ATTRIBUTE_NAME]

Note that you can only remove optional attributes.

If you want to register secrets for all secret references in a stack, use the following command:

zenml stack register-secrets [<STACK_NAME>]

If you want to connect a service connector to a stack's components, you can use the connect command:

zenml stack connect STACK_NAME -c CONNECTOR_NAME

Note that this only connects the service connector to the current components of the stack and not to the stack itself, which means that you need to rerun the command after adding new components to the stack.

The ZenML CLI provides a few more utility functions for you to manage your stacks. In order to get a full list of available functions, use the command:

zenml stack --help

Managing your Models

ZenML provides several CLI commands to help you administer your models and their versions as part of the Model Control Plane.

To register a new model, you can use the following CLI command:

zenml model register --name <NAME> [--MODEL_OPTIONS]

To list all registered models, use:

zenml model list [MODEL_FILTER_OPTIONS]

To update a model, use:

zenml model update <MODEL_NAME_OR_ID> [--MODEL_OPTIONS]

If you would like to add or remove tags from the model, use:

zenml model update <MODEL_NAME_OR_ID> --tag <TAG> --tag <TAG> ..
   --remove-tag <TAG> --remove-tag <TAG> ..

To delete a model, use:

zenml model delete <MODEL_NAME_OR_ID>

The CLI interface for models also helps to navigate through artifacts linked to a specific model versions.

zenml model data_artifacts <MODEL_NAME_OR_ID> [-v <VERSION>]
zenml model deployment_artifacts <MODEL_NAME_OR_ID> [-v <VERSION>]
zenml model model_artifacts <MODEL_NAME_OR_ID> [-v <VERSION>]

You can also navigate the pipeline runs linked to a specific model versions:

zenml model runs <MODEL_NAME_OR_ID> [-v <VERSION>]

To list the model versions of a specific model, use:

zenml model version list [--model-name <MODEL_NAME> --name <MODEL_VERSION_NAME> OTHER_OPTIONS]

To delete a model version, use:

zenml model version delete <MODEL_NAME_OR_ID> <VERSION>

To update a model version, use:

zenml model version update <MODEL_NAME_OR_ID> <VERSION> [--MODEL_VERSION_OPTIONS]

These are some of the more common uses of model version updates:

  • stage (i.e. promotion)
zenml model version update <MODEL_NAME_OR_ID> <VERSION> --stage <STAGE>
  • tags
zenml model version update <MODEL_NAME_OR_ID> <VERSION> --tag <TAG> --tag <TAG> ..
   --remove-tag <TAG> --remove-tag <TAG> ..

Managing your Pipelines & Artifacts

ZenML provides several CLI commands to help you administer your pipelines and pipeline runs.

To explicitly register a pipeline you need to point to a pipeline instance in your Python code. Let's say you have a Python file called run.py and it contains the following code:

from zenml import pipeline

@pipeline
def my_pipeline(...):
   # Connect your pipeline steps here
   pass

You can register your pipeline like this:

zenml pipeline register run.my_pipeline

To list all registered pipelines, use:

zenml pipeline list

To delete a pipeline, run:

zenml pipeline delete <PIPELINE_NAME>

This will delete the pipeline and change all corresponding pipeline runs to become unlisted (not linked to any pipeline).

To list all pipeline runs that you have executed, use:

zenml pipeline runs list

To delete a pipeline run, use:

zenml pipeline runs delete <PIPELINE_RUN_NAME_OR_ID>

To refresh the status of a pipeline run, you can use the refresh command ( only supported for pipelines executed on Vertex, Sagemaker or AzureML).

zenml pipeline runs refresh <PIPELINE_RUN_NAME_OR_ID>

If you run any of your pipelines with pipeline.run(schedule=...), ZenML keeps track of the schedule and you can list all schedules via:

zenml pipeline schedule list

To delete a schedule, use:

zenml pipeline schedule delete <SCHEDULE_NAME_OR_ID>

Note, however, that this will only delete the reference saved in ZenML and does NOT stop/delete the schedule in the respective orchestrator. This still needs to be done manually. For example, using the Airflow orchestrator you would have to open the web UI to manually click to stop the schedule from executing.

Each pipeline run automatically saves its artifacts in the artifact store. To list all artifacts that have been saved, use:

zenml artifact list

Each artifact has one or several versions. To list artifact versions, use:

zenml artifact versions list

If you would like to rename an artifact or adjust the tags of an artifact or artifact version, use the corresponding update command:

zenml artifact update <NAME> -n <NEW_NAME>
zenml artifact update <NAME> -t <TAG1> -t <TAG2> -r <TAG_TO_REMOVE>
zenml artifact version update <NAME> -v <VERSION> -t <TAG1> -t <TAG2> -r <TAG_TO_REMOVE>

The metadata of artifacts or artifact versions stored by ZenML can only be deleted once they are no longer used by any pipeline runs. I.e., an artifact version can only be deleted if the run that produced it and all runs that used it as an input have been deleted. Similarly, an artifact can only be deleted if all its versions can be deleted.

To delete all artifacts and artifact versions that are no longer linked to any pipeline runs, use:

zenml artifact prune

You might find that some artifacts throw errors when you try to prune them, likely because they were stored locally and no longer exist. If you wish to continue pruning and to ignore these errors, please add the --ignore-errors flag. Warning messages will still be output to the terminal during this process.

Each pipeline run that requires Docker images also stores a build which contains the image names used for this run. To list all builds, use:

zenml pipeline builds list

To delete a specific build, use:

zenml pipeline builds delete <BUILD_ID>

Managing the local ZenML Dashboard

The ZenML dashboard is a web-based UI that allows you to visualize and navigate the stack configurations, pipelines and pipeline runs tracked by ZenML among other things. You can start the ZenML dashboard locally by running the following command:

zenml login --local

This will start the dashboard on your local machine where you can access it at the URL printed to the console.

If you have closed the dashboard in your browser and want to open it again, you can run:

zenml show

If you want to stop the dashboard, simply run:

zenml logout --local

The zenml login --local command has a few additional options that you can use to customize how the ZenML dashboard is running.

By default, the dashboard is started as a background process. On some operating systems, this capability is not available. In this case, you can use the --blocking flag to start the dashboard in the foreground:

zenml login --local --blocking

This will block the terminal until you stop the dashboard with CTRL-C.

Another option you can use, if you have Docker installed on your machine, is to run the dashboard in a Docker container. This is useful if you don't want to install all the Zenml server dependencies on your machine. To do so, simply run:

zenml login --local --docker

The TCP port and the host address that the dashboard uses to listen for connections can also be customized. Using an IP address that is not the default localhost or 127.0.0.1 is especially useful if you're running some type of local ZenML orchestrator, such as the k3d Kubeflow orchestrator or Docker orchestrator, that cannot directly connect to the local ZenML server.

For example, to start the dashboard on port 9000 and have it listen on all locally available interfaces on your machine, run:

zenml login --local --port 9000 --ip-address 0.0.0.0

Note that the above 0.0.0.0 IP address also exposes your ZenML dashboard externally through your public interface. Alternatively, you can choose an explicit IP address that is configured on one of your local interfaces, such as the Docker bridge interface, which usually has the IP address 172.17.0.1:

zenml login --local --port 9000 --ip-address 172.17.0.1

If you would like to take a look at the logs for the local ZenML server:

zenml logs

Connecting to a ZenML Server

The ZenML client can be configured to connect to a local ZenML server, a remote database or a remote ZenML server with the zenml login command.

To connect or re-connect to any ZenML server, if you know its URL, you can simply run:

zenml login https://zenml.example.com:8080

Running zenml login without any arguments will check if your current ZenML server session is still valid. If it is not, you will be prompted to log in again. This is useful if you quickly want to refresh your CLI session when the current session expires.

You can open the ZenML dashboard of your currently connected ZenML server using the following command:

zenml server show

Note that if you have set your AUTO_OPEN_DASHBOARD environment variable to false then this will not open the dashboard until you set it back to true.

The CLI can be authenticated to multiple ZenML servers at the same time, even though it can only be connected to one server at a time. You can list all the ZenML servers that the client is currently authenticated to by running:

zenml server list

To disconnect from the current ZenML server and revert to using the local default database, use the following command:

zenml logout

You can inspect the current ZenML configuration at any given time using the following command:

zenml status

Example output:

$ zenml status
-----ZenML Client Status-----
Connected to a ZenML Pro server: `test-zenml-login` [16f8a35d-5c2f-44aa-a564-b34186fbf6d6]
  ZenML Pro Organization: My Organization
  ZenML Pro authentication: valid until 2024-10-26 10:18:51 CEST (in 20h37m9s)
  Dashboard: https://cloud.zenml.io/organizations/bf873af9-aaf9-4ad1-a08e-3dc6d920d590/tenants/16f8336d-5c2f-44aa-a534-b34186fbf6d6
  API: https://6784e58f-zenml.staging.cloudinfra.zenml.io
  Server status: 'available'
  Server authentication: never expires
  The active user is: 'user'
  The active stack is: 'default' (global)
Using configuration from: '/home/user/.config/zenml'
Local store files are located at: '/home/user/.config/zenml/local_stores'

-----Local ZenML Server Status-----
The local daemon server is running at: http://127.0.0.1:8237

When connecting to a ZenML server using the web login flow, you will be provided with the option to Trust this device. If you opt out of it a 24-hour token will be issued for the authentication service. If you opt-in, you will be issued a 30-day token instead.

If you would like to see a list of all trusted devices, you can use:

zenml authorized-device list

or if you would like to get the details regarding a specific device, you can use:

zenml authorized-device describe DEVICE_ID_OR_PREFIX

Alternatively, you can lock and unlock an authorized device by using the following commands:

zenml authorized-device lock DEVICE_ID_OR_PREFIX
zenml authorized-device unlock DEVICE_ID_OR_PREFIX

Finally, you can remove an authorized device by using the delete command:

zenml authorized-device delete DEVICE_ID_OR_PREFIX

Secrets management

ZenML offers a way to securely store secrets associated with your other stack components and infrastructure. A ZenML Secret is a collection or grouping of key-value pairs stored by the ZenML secrets store. ZenML Secrets are identified by a unique name which allows you to fetch or reference them in your pipelines and stacks.

Depending on how you set up and deployed ZenML, the secrets store keeps secrets in the local database or uses the ZenML server your client is connected to:

  • if you are using the default ZenML client settings, or if you connect your ZenML client to a local ZenML server started with zenml login --local, the secrets store is using the same local SQLite database as the rest of ZenML
  • if you connect your ZenML client to a remote ZenML server, the secrets are no longer managed on your local machine, but through the remote server instead. Secrets are stored in whatever secrets store back-end the remote server is configured to use. This can be a SQL database, one of the managed cloud secrets management services, or even a custom back-end.

To create a secret, use the create command and pass the key-value pairs as command-line arguments:

zenml secret create SECRET_NAME --key1=value1 --key2=value2 --key3=value3 ...

# Another option is to use the '--values' option and provide key-value pairs in either JSON or YAML format.
zenml secret create SECRET_NAME --values='{"key1":"value2","key2":"value2","key3":"value3"}'

Note that when using the previous command the keys and values will be preserved in your bash_history file, so you may prefer to use the interactive create command instead:

zenml secret create SECRET_NAME -i

As an alternative to the interactive mode, also useful for values that are long or contain newline or special characters, you can also use the special @ syntax to indicate to ZenML that the value needs to be read from a file:

zenml secret create SECRET_NAME    --aws_access_key_id=1234567890    --aws_secret_access_key=abcdefghij    --aws_session_token=@/path/to/token.txt

# Alternatively for providing key-value pairs, you can utilize the '--values' option by specifying a file path containing
# key-value pairs in either JSON or YAML format.
zenml secret create SECRET_NAME --values=@/path/to/token.txt

To list all the secrets available, use the list command:

zenml secret list

To get the key-value pairs for a particular secret, use the get command:

zenml secret get SECRET_NAME

To update a secret, use the update command:

zenml secret update SECRET_NAME --key1=value1 --key2=value2 --key3=value3 ...

# Another option is to use the '--values' option and provide key-value pairs in either JSON or YAML format.
zenml secret update SECRET_NAME --values='{"key1":"value2","key2":"value2","key3":"value3"}'

Note that when using the previous command the keys and values will be preserved in your bash_history file, so you may prefer to use the interactive update command instead:

zenml secret update SECRET_NAME -i

Finally, to delete a secret, use the delete command:

zenml secret delete SECRET_NAME

Secrets can be either private or public. Private secrets are only accessible to the current user. Public secrets are accessible to all other users. By default, secrets are public. To make a secret private, use the --private flag in the create or update commands.

Auth management

Building and maintaining an MLOps workflow can involve numerous third-party libraries and external services. In most cases, this ultimately presents a challenge in configuring uninterrupted, secure access to infrastructure resources. In ZenML, Service Connectors streamline this process by abstracting away the complexity of authentication and help you connect your stack to your resources. You can find the full docs on the ZenML service connectors here.

The ZenML CLI features a variety of commands to help you manage your service connectors. First of all, to explore all the types of service connectors available in ZenML, you can use the following commands:

# To get the complete list
zenml service-connector list-types

# To get the details regarding a single type
zenml service-connector describe-type

For each type of service connector, you will also see a list of supported resource types. These types provide a way for organizing different resources into logical classes based on the standard and/or protocol used to access them. In addition to the resource types, each type will feature a different set of authentication methods.

Once you decided which service connector to use, you can create it with the register command as follows:

zenml service-connector register SERVICE_CONNECTOR_NAME     --type TYPE [--description DESCRIPTION] [--resource-type RESOURCE_TYPE]     [--auth-method AUTH_METHOD] ...

For more details on how to create a service connector, please refer to our docs.

To check if your service connector is registered properly, you can verify it. By doing this, you can both check if it is configured correctly and also, you can fetch the list of resources it has access to:

zenml service-connector verify SERVICE_CONNECTOR_NAME_ID_OR_PREFIX

Some service connectors come equipped with the capability of configuring the clients and SDKs on your local machine with the credentials inferred from your service connector. To use this functionality, simply use the login command:

zenml service-connector login SERVICE_CONNECTOR_NAME_ID_OR_PREFIX

To list all the service connectors that you have registered, you can use:

zenml service-connector list

Moreover, if you would like to list all the resources accessible by your service connectors, you can use the following command:

zenml service-connector list-resources [--resource-type RESOURCE_TYPE] /
    [--connector-type CONNECTOR_TYPE] ...

This command can possibly take a long time depending on the number of service connectors you have registered. Consider using the right filters when you are listing resources.

If you want to see the details about a specific service connector that you have registered, you can use the describe command:

zenml service-connector describe SERVICE_CONNECTOR_NAME_ID_OR_PREFIX

You can update a registered service connector by using the update command. Keep in mind that all service connector updates are validated before being applied. If you want to disable this behavior please use the --no-verify flag.

zenml service-connector update SERVICE_CONNECTOR_NAME_ID_OR_PREFIX ...

Finally, if you wish to remove a service connector, you can use the delete command:

zenml service-connector delete SERVICE_CONNECTOR_NAME_ID_OR_PREFIX

Managing users

When using the ZenML service, you can manage permissions by managing users using the CLI. If you want to create a new user or delete an existing one, run either

zenml user create USER_NAME
zenml user delete USER_NAME

To see a list of all users, run:

zenml user list

For detail about the particular user, use the describe command. By default, (without a specific user name passed in) it will describe the active user:

zenml user describe [USER_NAME]

If you want to update any properties of a specific user, you can use the update command. Use the --help flag to get a full list of available properties to update:

zenml user update --help

If you want to change the password of the current user account:

zenml user change-password --help

Service Accounts

ZenML supports the use of service accounts to authenticate clients to the ZenML server using API keys. This is useful for automating tasks such as running pipelines or deploying models.

To create a new service account, run:

zenml service-account create SERVICE_ACCOUNT_NAME

This command creates a service account and an API key for it. The API key is displayed as part of the command output and cannot be retrieved later. You can then use the issued API key to connect your ZenML client to the server with the CLI:

zenml login https://... --api-key

or by setting the ZENML_STORE_URL and ZENML_STORE_API_KEY environment variables when you set up your ZenML client for the first time:

export ZENML_STORE_URL=https://...
export ZENML_STORE_API_KEY=<API_KEY>

You don't need to run zenml login after setting these two environment variables and can start interacting with your server right away.

To see all the service accounts you've created and their API keys, use the following commands:

zenml service-account list
zenml service-account api-key <SERVICE_ACCOUNT_NAME> list

Additionally, the following command allows you to more precisely inspect one of these service accounts and an API key:

zenml service-account describe <SERVICE_ACCOUNT_NAME>
zenml service-account api-key <SERVICE_ACCOUNT_NAME> describe <API_KEY_NAME>

API keys don't have an expiration date. For increased security, we recommend that you regularly rotate the API keys to prevent unauthorized access to your ZenML server. You can do this with the ZenML CLI:

zenml service-account api-key <SERVICE_ACCOUNT_NAME> rotate <API_KEY_NAME>

Running this command will create a new API key and invalidate the old one. The new API key is displayed as part of the command output and cannot be retrieved later. You can then use the new API key to connect your ZenML client to the server just as described above.

When rotating an API key, you can also configure a retention period for the old API key. This is useful if you need to keep the old API key for a while to ensure that all your workloads have been updated to use the new API key. You can do this with the --retain flag. For example, to rotate an API key and keep the old one for 60 minutes, you can run the following command:

zenml service-account api-key <SERVICE_ACCOUNT_NAME> rotate <API_KEY_NAME>       --retain 60

For increased security, you can deactivate a service account or an API key using one of the following commands:

zenml service-account update <SERVICE_ACCOUNT_NAME> --active false
zenml service-account api-key <SERVICE_ACCOUNT_NAME> update <API_KEY_NAME>       --active false

Deactivating a service account or an API key will prevent it from being used to authenticate and has immediate effect on all workloads that use it.

To permanently delete an API key for a service account, use the following command:

zenml service-account api-key <SERVICE_ACCOUNT_NAME> delete <API_KEY_NAME>

Managing Code Repositories

Code repositories enable ZenML to keep track of the code version that you use for your pipeline runs. Additionally, running a pipeline which is tracked in a registered code repository can decrease the time it takes Docker to build images for containerized stack components.

To register a code repository, use the following CLI command:

zenml code-repository register <NAME> --type=<CODE_REPOSITORY_TYPE]    [--CODE_REPOSITORY_OPTIONS]

ZenML currently supports code repositories of type github and gitlab, but you can also use your custom code repository implementation by passing the type custom and a source of your repository class.

zenml code-repository register <NAME> --type=custom    --source=<CODE_REPOSITORY_SOURCE> [--CODE_REPOSITORY_OPTIONS]

The CODE_REPOSITORY_OPTIONS depend on the configuration necessary for the type of code repository that you're using.

If you want to list your registered code repositories, run:

zenml code-repository list

You can delete one of your registered code repositories like this:

zenml code-repository delete <REPOSITORY_NAME_OR_ID>

Building an image without Runs

To build or run a pipeline from the CLI, you need to know the source path of your pipeline. Let's imagine you have defined your pipeline in a python file called run.py like this:

from zenml import pipeline

@pipeline
def my_pipeline(...):
   # Connect your pipeline steps here
   pass

The source path of your pipeline will be run.my_pipeline. In a generalized way, this will be <MODULE_PATH>.<PIPELINE_FUNCTION_NAME>. If the python file defining the pipeline is not in your current directory, the module path consists of the full path to the file, separated by dots, e.g. some_directory.some_file.my_pipeline.

To build Docker images for your pipeline without actually running the pipeline, use:

zenml pipeline build <PIPELINE_SOURCE_PATH>

To specify settings for the Docker builds, use the --config/-c option of the command. For more information about the structure of this configuration file, check out the zenml.pipelines.base_pipeline.BasePipeline.build(...) method.

zenml pipeline build <PIPELINE_SOURCE_PATH> --config=<PATH_TO_CONFIG_YAML>

If you want to build the pipeline for a stack other than your current active stack, use the --stack option.

zenml pipeline build <PIPELINE_SOURCE_PATH> --stack=<STACK_ID_OR_NAME>

To run a pipeline that was previously registered, use:

zenml pipeline run <PIPELINE_SOURCE_PATH>

To specify settings for the pipeline, use the --config/-c option of the command. For more information about the structure of this configuration file, check out the zenml.pipelines.base_pipeline.BasePipeline.run(...) method.

zenml pipeline run <PIPELINE_SOURCE_PATH> --config=<PATH_TO_CONFIG_YAML>

If you want to run the pipeline on a stack different than your current active stack, use the --stack option.

zenml pipeline run <PIPELINE_SOURCE_PATH> --stack=<STACK_ID_OR_NAME>

If you want to create a run template based on your pipeline that can later be used to trigger a run either from the dashboard or through an HTTP request:

zenml pipeline create-run-template <PIPELINE_SOURCE_PATH>    --name=<TEMPLATE_NAME>

To specify a config file, use the --config/-c option. If you would like to use a different stack than the active one, use the --stack option.

zenml pipeline create-run-template <PIPELINE_SOURCE_PATH>    --name=<TEMPLATE_NAME>    --config=<PATH_TO_CONFIG_YAML>    --stack=<STACK_ID_OR_NAME>

Tagging your resources with ZenML

When you are using ZenML, you can use tags to organize and categorize your assets. This way, you can streamline your workflows and enhance the discoverability of your resources more easily.

Currently, you can use tags with artifacts, models and their versions:

# Tag the artifact
zenml artifact update ARTIFACT_NAME -t TAG_NAME

# Tag the artifact version
zenml artifact version update ARTIFACT_NAME ARTIFACT_VERSION -t TAG_NAME

# Tag an existing model
zenml model update MODEL_NAME --tag TAG_NAME

# Tag a specific model version
zenml model version update MODEL_NAME VERSION_NAME --tag TAG_NAME

Besides these interactions, you can also create a new tag by using the register command:

zenml tag register -n TAG_NAME [-c COLOR]

If you would like to list all the tags that you have, you can use the command:

zenml tag list

To update the properties of a specific tag, you can use the update subcommand:

zenml tag update TAG_NAME_OR_ID [-n NEW_NAME] [-c NEW_COLOR]

Finally, in order to delete a tag, you can execute:

zenml tag delete TAG_NAME_OR_ID

Managing the Global Configuration

The ZenML global configuration CLI commands cover options such as enabling or disabling the collection of anonymous usage statistics, changing the logging verbosity.

In order to help us better understand how the community uses ZenML, the library reports anonymized usage statistics. You can always opt out by using the CLI command:

zenml analytics opt-out

If you want to opt back in, use the following command:

zenml analytics opt-in

The verbosity of the ZenML client output can be configured using the zenml logging command. For example, to set the verbosity to DEBUG, run:

zenml logging set-verbosity DEBUG

Attributes

ENV_ZENML_ENABLE_REPO_INIT_WARNINGS = 'ZENML_ENABLE_REPO_INIT_WARNINGS' module-attribute

REPOSITORY_DIRECTORY_NAME = '.zen' module-attribute

SECRET_VALUES = 'values' module-attribute

TUTORIAL_REPO = 'https://github.com/zenml-io/zenml' module-attribute

ZENML_PROJECT_TEMPLATES = dict(e2e_batch=ZenMLProjectTemplateLocation(github_url='zenml-io/template-e2e-batch', github_tag='2024.11.28'), starter=ZenMLProjectTemplateLocation(github_url='zenml-io/template-starter', github_tag='2024.11.28'), nlp=ZenMLProjectTemplateLocation(github_url='zenml-io/template-nlp', github_tag='2025.04.07'), llm_finetuning=ZenMLProjectTemplateLocation(github_url='zenml-io/template-llm-finetuning', github_tag='2024.11.28')) module-attribute

ZENML_PRO_API_URL = os.getenv(ENV_ZENML_PRO_API_URL, default=DEFAULT_ZENML_PRO_API_URL) module-attribute

ascii_arts = [" \n .-') _ ('-. .-') _ _ .-') \n ( OO) )_( OO) ( OO ) )( '.( OO )_ \n ,(_)----.(,------.,--./ ,--,' ,--. ,--.),--. \n | | | .---'| \\ | |\\ | `.' | | |.-') \n '--. / | | | \\| | ) | | | | OO ) \n (_/ / (| '--. | . |/ | |'.'| | | |`-' | \n / /___ | .--' | |\\ | | | | |(| '---.' \n | || `---.| | \\ | | | | | | | \n `--------'`------'`--' `--' `--' `--' `------' \n ", "\n ____..--' .-''-. ,---. .--. ,---. ,---. .---. \n | | .'_ _ \\ | \\ | | | \\ / | | ,_| \n | .-' ' / ( ` ) ' | , \\ | | | , \\/ , | ,-./ ) \n |.-'.' / . (_ o _) | | |\\_ \\| | | |\\_ /| | \\ '_ '`) \n / _/ | (_,_)___| | _( )_\\ | | _( )_/ | | > (_) ) \n .'._( )_ ' \\ .---. | (_ o _) | | (_ o _) | | ( . .-' \n .' (_'o._) \\ `-' / | (_,_)\\ | | (_,_) | | `-'`-'|___ \n | (_,_)| \\ / | | | | | | | | | \\ \n |_________| `'-..-' '--' '--' '--' '--' `--------` \n ", '\n ________ __ __ __ \n | \\ | \\ / \\| \\ \n \\$$$$$$$$ ______ _______ | $$\\ / $$| $$ \n / $$ / \\ | \\ | $$$\\ / $$$| $$ \n / $$ | $$$$$$\\| $$$$$$$\\| $$$$\\ $$$$| $$ \n / $$ | $$ $$| $$ | $$| $$\\$$ $$ $$| $$ \n / $$___ | $$$$$$$$| $$ | $$| $$ \\$$$| $$| $$_____ \n | $$ \\ \\$$ \\| $$ | $$| $$ \\$ | $$| $$ \\\n \\$$$$$$$$ \\$$$$$$$ \\$$ \\$$ \\$$ \\$$ \\$$$$$$$$\n ', "\n ) * ( \n ( /( ( ` )\\ ) \n )\\()) ( )\\))( (()/( \n ((_)\\ ))\\ ( ((_)()\\ /(_)) \n _((_) /((_) )\\ ) (_()((_) (_)) \n |_ / (_)) _(_/( | \\/ | | | \n / / / -_) | ' \\)) | |\\/| | | |__ \n /___| \\___| |_||_| |_| |_| |____| \n ", '\n███████ ███████ ███ ██ ███ ███ ██ \n ███ ██ ████ ██ ████ ████ ██ \n ███ █████ ██ ██ ██ ██ ████ ██ ██ \n ███ ██ ██ ██ ██ ██ ██ ██ ██ \n███████ ███████ ██ ████ ██ ██ ███████ \n '] module-attribute

console = Console(theme=zenml_custom_theme, markup=True) module-attribute

integration_registry = IntegrationRegistry() module-attribute

logger = get_logger(__name__) module-attribute

zenml_version: str = version_file.read().strip() module-attribute

Classes

APIKeyFilter

Bases: BaseFilter

Filter model for API keys.

Functions
apply_filter(query: AnyQuery, table: Type[AnySchema]) -> AnyQuery

Override to apply the service account scope as an additional filter.

Parameters:

Name Type Description Default
query AnyQuery

The query to which to apply the filter.

required
table Type[AnySchema]

The query table.

required

Returns:

Type Description
AnyQuery

The query with filter applied.

Source code in src/zenml/models/v2/core/api_key.py
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
def apply_filter(
    self,
    query: AnyQuery,
    table: Type["AnySchema"],
) -> AnyQuery:
    """Override to apply the service account scope as an additional filter.

    Args:
        query: The query to which to apply the filter.
        table: The query table.

    Returns:
        The query with filter applied.
    """
    query = super().apply_filter(query=query, table=table)

    if self.service_account:
        scope_filter = (
            getattr(table, "service_account_id") == self.service_account
        )
        query = query.where(scope_filter)

    return query
set_service_account(service_account_id: UUID) -> None

Set the service account by which to scope this query.

Parameters:

Name Type Description Default
service_account_id UUID

The service account ID.

required
Source code in src/zenml/models/v2/core/api_key.py
377
378
379
380
381
382
383
def set_service_account(self, service_account_id: UUID) -> None:
    """Set the service account by which to scope this query.

    Args:
        service_account_id: The service account ID.
    """
    self.service_account = service_account_id

AnalyticsEvent

Bases: str, Enum

Enum of events to track in segment.

AnalyticsEventSource

Bases: StrEnum

Enum to identify analytics events source.

ArtifactFilter

Bases: ProjectScopedFilter, TaggableFilter

Model to enable advanced filtering of artifacts.

Functions
apply_sorting(query: AnyQuery, table: Type[AnySchema]) -> AnyQuery

Apply sorting to the query for Artifacts.

Parameters:

Name Type Description Default
query AnyQuery

The query to which to apply the sorting.

required
table Type[AnySchema]

The query table.

required

Returns:

Type Description
AnyQuery

The query with sorting applied.

Source code in src/zenml/models/v2/core/artifact.py
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
def apply_sorting(
    self,
    query: AnyQuery,
    table: Type["AnySchema"],
) -> AnyQuery:
    """Apply sorting to the query for Artifacts.

    Args:
        query: The query to which to apply the sorting.
        table: The query table.

    Returns:
        The query with sorting applied.
    """
    from sqlmodel import asc, case, col, desc, func, select

    from zenml.enums import SorterOps
    from zenml.zen_stores.schemas import (
        ArtifactSchema,
        ArtifactVersionSchema,
    )

    sort_by, operand = self.sorting_params

    if sort_by == SORT_BY_LATEST_VERSION_KEY:
        # Subquery to find the latest version per artifact
        latest_version_subquery = (
            select(
                ArtifactSchema.id,
                case(
                    (
                        func.max(ArtifactVersionSchema.created).is_(None),
                        ArtifactSchema.created,
                    ),
                    else_=func.max(ArtifactVersionSchema.created),
                ).label("latest_version_created"),
            )
            .outerjoin(
                ArtifactVersionSchema,
                ArtifactSchema.id == ArtifactVersionSchema.artifact_id,  # type: ignore[arg-type]
            )
            .group_by(col(ArtifactSchema.id))
            .subquery()
        )

        query = query.add_columns(
            latest_version_subquery.c.latest_version_created,
        ).where(ArtifactSchema.id == latest_version_subquery.c.id)

        # Apply sorting based on the operand
        if operand == SorterOps.ASCENDING:
            query = query.order_by(
                asc(latest_version_subquery.c.latest_version_created),
                asc(ArtifactSchema.id),
            )
        else:
            query = query.order_by(
                desc(latest_version_subquery.c.latest_version_created),
                desc(ArtifactSchema.id),
            )
        return query

    # For other sorting cases, delegate to the parent class
    return super().apply_sorting(query=query, table=table)

ArtifactResponse

Bases: ProjectScopedResponse[ArtifactResponseBody, ArtifactResponseMetadata, ArtifactResponseResources]

Artifact response model.

Attributes
has_custom_name: bool property

The has_custom_name property.

Returns:

Type Description
bool

the value of the property.

latest_version_id: Optional[UUID] property

The latest_version_id property.

Returns:

Type Description
Optional[UUID]

the value of the property.

latest_version_name: Optional[str] property

The latest_version_name property.

Returns:

Type Description
Optional[str]

the value of the property.

tags: List[TagResponse] property

The tags property.

Returns:

Type Description
List[TagResponse]

the value of the property.

versions: Dict[str, ArtifactVersionResponse] property

Get a list of all versions of this artifact.

Returns:

Type Description
Dict[str, ArtifactVersionResponse]

A list of all versions of this artifact.

Functions
get_hydrated_version() -> ArtifactResponse

Get the hydrated version of this artifact.

Returns:

Type Description
ArtifactResponse

an instance of the same entity with the metadata field attached.

Source code in src/zenml/models/v2/core/artifact.py
119
120
121
122
123
124
125
126
127
def get_hydrated_version(self) -> "ArtifactResponse":
    """Get the hydrated version of this artifact.

    Returns:
        an instance of the same entity with the metadata field attached.
    """
    from zenml.client import Client

    return Client().zen_store.get_artifact(self.id)

ArtifactVersionFilter

Bases: ProjectScopedFilter, TaggableFilter, RunMetadataFilterMixin

Model to enable advanced filtering of artifact versions.

Functions
get_custom_filters(table: Type[AnySchema]) -> List[Union[ColumnElement[bool]]]

Get custom filters.

Parameters:

Name Type Description Default
table Type[AnySchema]

The query table.

required

Returns:

Type Description
List[Union[ColumnElement[bool]]]

A list of custom filters.

Source code in src/zenml/models/v2/core/artifact_version.py
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
def get_custom_filters(
    self, table: Type["AnySchema"]
) -> List[Union["ColumnElement[bool]"]]:
    """Get custom filters.

    Args:
        table: The query table.

    Returns:
        A list of custom filters.
    """
    custom_filters = super().get_custom_filters(table)

    from sqlmodel import and_, or_, select

    from zenml.zen_stores.schemas import (
        ArtifactSchema,
        ArtifactVersionSchema,
        ModelSchema,
        ModelVersionArtifactSchema,
        ModelVersionSchema,
        PipelineRunSchema,
        StepRunInputArtifactSchema,
        StepRunOutputArtifactSchema,
        StepRunSchema,
    )

    if self.artifact:
        value, operator = self._resolve_operator(self.artifact)
        artifact_filter = and_(
            ArtifactVersionSchema.artifact_id == ArtifactSchema.id,
            self.generate_name_or_id_query_conditions(
                value=self.artifact, table=ArtifactSchema
            ),
        )
        custom_filters.append(artifact_filter)

    if self.only_unused:
        unused_filter = and_(
            ArtifactVersionSchema.id.notin_(  # type: ignore[attr-defined]
                select(StepRunOutputArtifactSchema.artifact_id)
            ),
            ArtifactVersionSchema.id.notin_(  # type: ignore[attr-defined]
                select(StepRunInputArtifactSchema.artifact_id)
            ),
        )
        custom_filters.append(unused_filter)

    if self.model_version_id:
        value, operator = self._resolve_operator(self.model_version_id)

        model_version_filter = and_(
            ArtifactVersionSchema.id
            == ModelVersionArtifactSchema.artifact_version_id,
            ModelVersionArtifactSchema.model_version_id
            == ModelVersionSchema.id,
            FilterGenerator(ModelVersionSchema)
            .define_filter(column="id", value=value, operator=operator)
            .generate_query_conditions(ModelVersionSchema),
        )
        custom_filters.append(model_version_filter)

    if self.has_custom_name is not None:
        custom_name_filter = and_(
            ArtifactVersionSchema.artifact_id == ArtifactSchema.id,
            ArtifactSchema.has_custom_name == self.has_custom_name,
        )
        custom_filters.append(custom_name_filter)

    if self.model:
        model_filter = and_(
            ArtifactVersionSchema.id
            == ModelVersionArtifactSchema.artifact_version_id,
            ModelVersionArtifactSchema.model_version_id
            == ModelVersionSchema.id,
            ModelVersionSchema.model_id == ModelSchema.id,
            self.generate_name_or_id_query_conditions(
                value=self.model, table=ModelSchema
            ),
        )
        custom_filters.append(model_filter)

    if self.pipeline_run:
        pipeline_run_filter = and_(
            or_(
                and_(
                    ArtifactVersionSchema.id
                    == StepRunOutputArtifactSchema.artifact_id,
                    StepRunOutputArtifactSchema.step_id
                    == StepRunSchema.id,
                ),
                and_(
                    ArtifactVersionSchema.id
                    == StepRunInputArtifactSchema.artifact_id,
                    StepRunInputArtifactSchema.step_id == StepRunSchema.id,
                ),
            ),
            StepRunSchema.pipeline_run_id == PipelineRunSchema.id,
            self.generate_name_or_id_query_conditions(
                value=self.pipeline_run, table=PipelineRunSchema
            ),
        )
        custom_filters.append(pipeline_run_filter)

    return custom_filters

ArtifactVersionResponse

Bases: ProjectScopedResponse[ArtifactVersionResponseBody, ArtifactVersionResponseMetadata, ArtifactVersionResponseResources]

Response model for artifact versions.

Attributes
artifact: ArtifactResponse property

The artifact property.

Returns:

Type Description
ArtifactResponse

the value of the property.

artifact_store_id: Optional[UUID] property

The artifact_store_id property.

Returns:

Type Description
Optional[UUID]

the value of the property.

data_type: Source property

The data_type property.

Returns:

Type Description
Source

the value of the property.

materializer: Source property

The materializer property.

Returns:

Type Description
Source

the value of the property.

name: str property

The name property.

Returns:

Type Description
str

the value of the property.

producer_pipeline_run_id: Optional[UUID] property

The producer_pipeline_run_id property.

Returns:

Type Description
Optional[UUID]

the value of the property.

producer_step_run_id: Optional[UUID] property

The producer_step_run_id property.

Returns:

Type Description
Optional[UUID]

the value of the property.

run: PipelineRunResponse property

Get the pipeline run that produced this artifact.

Returns:

Type Description
PipelineRunResponse

The pipeline run that produced this artifact.

run_metadata: Dict[str, MetadataType] property

The metadata property.

Returns:

Type Description
Dict[str, MetadataType]

the value of the property.

save_type: ArtifactSaveType property

The save_type property.

Returns:

Type Description
ArtifactSaveType

the value of the property.

step: StepRunResponse property

Get the step that produced this artifact.

Returns:

Type Description
StepRunResponse

The step that produced this artifact.

tags: List[TagResponse] property

The tags property.

Returns:

Type Description
List[TagResponse]

the value of the property.

type: ArtifactType property

The type property.

Returns:

Type Description
ArtifactType

the value of the property.

uri: str property

The uri property.

Returns:

Type Description
str

the value of the property.

version: Union[str, int] property

The version property.

Returns:

Type Description
Union[str, int]

the value of the property.

visualizations: Optional[List[ArtifactVisualizationResponse]] property

The visualizations property.

Returns:

Type Description
Optional[List[ArtifactVisualizationResponse]]

the value of the property.

Functions
download_files(path: str, overwrite: bool = False) -> None

Downloads data for an artifact with no materializing.

Any artifacts will be saved as a zip file to the given path.

Parameters:

Name Type Description Default
path str

The path to save the binary data to.

required
overwrite bool

Whether to overwrite the file if it already exists.

False

Raises:

Type Description
ValueError

If the path does not end with '.zip'.

Source code in src/zenml/models/v2/core/artifact_version.py
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
def download_files(self, path: str, overwrite: bool = False) -> None:
    """Downloads data for an artifact with no materializing.

    Any artifacts will be saved as a zip file to the given path.

    Args:
        path: The path to save the binary data to.
        overwrite: Whether to overwrite the file if it already exists.

    Raises:
        ValueError: If the path does not end with '.zip'.
    """
    if not path.endswith(".zip"):
        raise ValueError(
            "The path should end with '.zip' to save the binary data."
        )
    from zenml.artifacts.utils import (
        download_artifact_files_from_response,
    )

    download_artifact_files_from_response(
        self,
        path=path,
        overwrite=overwrite,
    )
get_hydrated_version() -> ArtifactVersionResponse

Get the hydrated version of this artifact version.

Returns:

Type Description
ArtifactVersionResponse

an instance of the same entity with the metadata field attached.

Source code in src/zenml/models/v2/core/artifact_version.py
262
263
264
265
266
267
268
269
270
def get_hydrated_version(self) -> "ArtifactVersionResponse":
    """Get the hydrated version of this artifact version.

    Returns:
        an instance of the same entity with the metadata field attached.
    """
    from zenml.client import Client

    return Client().zen_store.get_artifact_version(self.id)
load() -> Any

Materializes (loads) the data stored in this artifact.

Returns:

Type Description
Any

The materialized data.

Source code in src/zenml/models/v2/core/artifact_version.py
424
425
426
427
428
429
430
431
432
def load(self) -> Any:
    """Materializes (loads) the data stored in this artifact.

    Returns:
        The materialized data.
    """
    from zenml.artifacts.utils import load_artifact_from_response

    return load_artifact_from_response(self)
visualize(title: Optional[str] = None) -> None

Visualize the artifact in notebook environments.

Parameters:

Name Type Description Default
title Optional[str]

Optional title to show before the visualizations.

None
Source code in src/zenml/models/v2/core/artifact_version.py
460
461
462
463
464
465
466
467
468
def visualize(self, title: Optional[str] = None) -> None:
    """Visualize the artifact in notebook environments.

    Args:
        title: Optional title to show before the visualizations.
    """
    from zenml.utils.visualization_utils import visualize_artifact

    visualize_artifact(self, title=title)

AuthorizationException(message: Optional[str] = None, url: Optional[str] = None)

Bases: ZenMLBaseException

Raised when an authorization error occurred while trying to access a ZenML resource .

Source code in src/zenml/exceptions.py
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
def __init__(
    self,
    message: Optional[str] = None,
    url: Optional[str] = None,
):
    """The BaseException used to format messages displayed to the user.

    Args:
        message: Message with details of exception. This message
                 will be appended with another message directing user to
                 `url` for more information. If `None`, then default
                 Exception behavior is used.
        url: URL to point to in exception message. If `None`, then no url
             is appended.
    """
    if message and url:
        message += f" For more information, visit {url}."
    super().__init__(message)

BaseCodeRepository(id: UUID, name: str, config: Dict[str, Any])

Bases: ABC

Base class for code repositories.

Code repositories are used to connect to a remote code repository and store information about the repository, such as the URL, the owner, the repository name, and the host. They also provide methods to download files from the repository when a pipeline is run remotely.

Initializes a code repository.

Parameters:

Name Type Description Default
id UUID

The ID of the code repository.

required
name str

The name of the code repository.

required
config Dict[str, Any]

The config of the code repository.

required
Source code in src/zenml/code_repositories/base_code_repository.py
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
def __init__(
    self,
    id: UUID,
    name: str,
    config: Dict[str, Any],
) -> None:
    """Initializes a code repository.

    Args:
        id: The ID of the code repository.
        name: The name of the code repository.
        config: The config of the code repository.
    """
    self._id = id
    self._name = name
    self._config = config
    self.login()
Attributes
config: BaseCodeRepositoryConfig property

Config class for Code Repository.

Returns:

Type Description
BaseCodeRepositoryConfig

The config class.

id: UUID property

ID of the code repository.

Returns:

Type Description
UUID

The ID of the code repository.

name: str property

Name of the code repository.

Returns:

Type Description
str

The name of the code repository.

requirements: Set[str] property

Set of PyPI requirements for the repository.

Returns:

Type Description
Set[str]

A set of PyPI requirements for the repository.

Functions
download_files(commit: str, directory: str, repo_sub_directory: Optional[str]) -> None abstractmethod

Downloads files from the code repository to a local directory.

Parameters:

Name Type Description Default
commit str

The commit hash to download files from.

required
directory str

The directory to download files to.

required
repo_sub_directory Optional[str]

The subdirectory in the repository to download files from.

required

Raises:

Type Description
RuntimeError

If the download fails.

Source code in src/zenml/code_repositories/base_code_repository.py
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
@abstractmethod
def download_files(
    self, commit: str, directory: str, repo_sub_directory: Optional[str]
) -> None:
    """Downloads files from the code repository to a local directory.

    Args:
        commit: The commit hash to download files from.
        directory: The directory to download files to.
        repo_sub_directory: The subdirectory in the repository to
            download files from.

    Raises:
        RuntimeError: If the download fails.
    """
    pass
from_model(model: CodeRepositoryResponse) -> BaseCodeRepository classmethod

Loads a code repository from a model.

Parameters:

Name Type Description Default
model CodeRepositoryResponse

The CodeRepositoryResponseModel to load from.

required

Returns:

Type Description
BaseCodeRepository

The loaded code repository object.

Source code in src/zenml/code_repositories/base_code_repository.py
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
@classmethod
def from_model(cls, model: CodeRepositoryResponse) -> "BaseCodeRepository":
    """Loads a code repository from a model.

    Args:
        model: The CodeRepositoryResponseModel to load from.

    Returns:
        The loaded code repository object.
    """
    class_: Type[BaseCodeRepository] = (
        source_utils.load_and_validate_class(
            source=model.source, expected_class=BaseCodeRepository
        )
    )
    return class_(id=model.id, name=model.name, config=model.config)
get_local_context(path: str) -> Optional[LocalRepositoryContext] abstractmethod

Gets a local repository context from a path.

Parameters:

Name Type Description Default
path str

The path to the local repository.

required

Returns:

Type Description
Optional[LocalRepositoryContext]

The local repository context object.

Source code in src/zenml/code_repositories/base_code_repository.py
162
163
164
165
166
167
168
169
170
171
172
173
174
@abstractmethod
def get_local_context(
    self, path: str
) -> Optional["LocalRepositoryContext"]:
    """Gets a local repository context from a path.

    Args:
        path: The path to the local repository.

    Returns:
        The local repository context object.
    """
    pass
login() -> None abstractmethod

Logs into the code repository.

This method is called when the code repository is initialized. It should be used to authenticate with the code repository.

Raises:

Type Description
RuntimeError

If the login fails.

Source code in src/zenml/code_repositories/base_code_repository.py
133
134
135
136
137
138
139
140
141
142
143
@abstractmethod
def login(self) -> None:
    """Logs into the code repository.

    This method is called when the code repository is initialized.
    It should be used to authenticate with the code repository.

    Raises:
        RuntimeError: If the login fails.
    """
    pass
validate_config(config: Dict[str, Any]) -> None classmethod

Validate the code repository config.

This method should check that the config/credentials are valid and the configured repository exists.

Parameters:

Name Type Description Default
config Dict[str, Any]

The configuration.

required
Source code in src/zenml/code_repositories/base_code_repository.py
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
@classmethod
def validate_config(cls, config: Dict[str, Any]) -> None:
    """Validate the code repository config.

    This method should check that the config/credentials are valid and
    the configured repository exists.

    Args:
        config: The configuration.
    """
    # The initialization calls the login to verify the credentials
    code_repo = cls(id=uuid4(), name="", config=config)

    # Explicitly access the config for pydantic validation
    _ = code_repo.config

CliCategories

Bases: StrEnum

All possible categories for CLI commands.

Note: The order of the categories is important. The same order is used to sort the commands in the CLI help output.

Client(root: Optional[Path] = None)

ZenML client class.

The ZenML client manages configuration options for ZenML stacks as well as their components.

Initializes the global client instance.

Client is a singleton class: only one instance can exist. Calling this constructor multiple times will always yield the same instance (see the exception below).

The root argument is only meant for internal use and testing purposes. User code must never pass them to the constructor. When a custom root value is passed, an anonymous Client instance is created and returned independently of the Client singleton and that will have no effect as far as the rest of the ZenML core code is concerned.

Instead of creating a new Client instance to reflect a different repository root, to change the active root in the global Client, call Client().activate_root(<new-root>).

Parameters:

Name Type Description Default
root Optional[Path]

(internal use) custom root directory for the client. If no path is given, the repository root is determined using the environment variable ZENML_REPOSITORY_PATH (if set) and by recursively searching in the parent directories of the current working directory. Only used to initialize new clients internally.

None
Source code in src/zenml/client.py
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
def __init__(
    self,
    root: Optional[Path] = None,
) -> None:
    """Initializes the global client instance.

    Client is a singleton class: only one instance can exist. Calling
    this constructor multiple times will always yield the same instance (see
    the exception below).

    The `root` argument is only meant for internal use and testing purposes.
    User code must never pass them to the constructor.
    When a custom `root` value is passed, an anonymous Client instance
    is created and returned independently of the Client singleton and
    that will have no effect as far as the rest of the ZenML core code is
    concerned.

    Instead of creating a new Client instance to reflect a different
    repository root, to change the active root in the global Client,
    call `Client().activate_root(<new-root>)`.

    Args:
        root: (internal use) custom root directory for the client. If
            no path is given, the repository root is determined using the
            environment variable `ZENML_REPOSITORY_PATH` (if set) and by
            recursively searching in the parent directories of the
            current working directory. Only used to initialize new
            clients internally.
    """
    self._root: Optional[Path] = None
    self._config: Optional[ClientConfiguration] = None

    self._set_active_root(root)
Attributes
active_project: ProjectResponse property

Get the currently active project of the local client.

If no active project is configured locally for the client, the active project in the global configuration is used instead.

Returns:

Type Description
ProjectResponse

The active project.

Raises:

Type Description
RuntimeError

If the active project is not set.

active_stack: Stack property

The active stack for this client.

Returns:

Type Description
Stack

The active stack for this client.

active_stack_model: StackResponse property

The model of the active stack for this client.

If no active stack is configured locally for the client, the active stack in the global configuration is used instead.

Returns:

Type Description
StackResponse

The model of the active stack for this client.

Raises:

Type Description
RuntimeError

If the active stack is not set.

active_user: UserResponse property

Get the user that is currently in use.

Returns:

Type Description
UserResponse

The active user.

config_directory: Optional[Path] property

The configuration directory of this client.

Returns:

Type Description
Optional[Path]

The configuration directory of this client, or None, if the

Optional[Path]

client doesn't have an active root.

root: Optional[Path] property

The root directory of this client.

Returns:

Type Description
Optional[Path]

The root directory of this client, or None, if the client

Optional[Path]

has not been initialized.

uses_local_configuration: bool property

Check if the client is using a local configuration.

Returns:

Type Description
bool

True if the client is using a local configuration,

bool

False otherwise.

zen_store: BaseZenStore property

Shortcut to return the global zen store.

Returns:

Type Description
BaseZenStore

The global zen store.

Functions
activate_root(root: Optional[Path] = None) -> None

Set the active repository root directory.

Parameters:

Name Type Description Default
root Optional[Path]

The path to set as the active repository root. If not set, the repository root is determined using the environment variable ZENML_REPOSITORY_PATH (if set) and by recursively searching in the parent directories of the current working directory.

None
Source code in src/zenml/client.py
670
671
672
673
674
675
676
677
678
679
680
def activate_root(self, root: Optional[Path] = None) -> None:
    """Set the active repository root directory.

    Args:
        root: The path to set as the active repository root. If not set,
            the repository root is determined using the environment
            variable `ZENML_REPOSITORY_PATH` (if set) and by recursively
            searching in the parent directories of the current working
            directory.
    """
    self._set_active_root(root)
activate_stack(stack_name_id_or_prefix: Union[str, UUID]) -> None

Sets the stack as active.

Parameters:

Name Type Description Default
stack_name_id_or_prefix Union[str, UUID]

Model of the stack to activate.

required

Raises:

Type Description
KeyError

If the stack is not registered.

Source code in src/zenml/client.py
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
def activate_stack(
    self, stack_name_id_or_prefix: Union[str, UUID]
) -> None:
    """Sets the stack as active.

    Args:
        stack_name_id_or_prefix: Model of the stack to activate.

    Raises:
        KeyError: If the stack is not registered.
    """
    # Make sure the stack is registered
    try:
        stack = self.get_stack(name_id_or_prefix=stack_name_id_or_prefix)
    except KeyError as e:
        raise KeyError(
            f"Stack '{stack_name_id_or_prefix}' cannot be activated since "
            f"it is not registered yet. Please register it first."
        ) from e

    if self._config:
        self._config.set_active_stack(stack=stack)

    else:
        # set the active stack globally only if the client doesn't use
        # a local configuration
        GlobalConfiguration().set_active_stack(stack=stack)
attach_tag(tag_name_or_id: Union[str, UUID], resources: List[TagResource]) -> None

Attach a tag to resources.

Parameters:

Name Type Description Default
tag_name_or_id Union[str, UUID]

name or id of the tag to be attached.

required
resources List[TagResource]

the resources to attach the tag to.

required
Source code in src/zenml/client.py
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
def attach_tag(
    self,
    tag_name_or_id: Union[str, UUID],
    resources: List[TagResource],
) -> None:
    """Attach a tag to resources.

    Args:
        tag_name_or_id: name or id of the tag to be attached.
        resources: the resources to attach the tag to.
    """
    if isinstance(tag_name_or_id, str):
        try:
            tag_model = self.create_tag(name=tag_name_or_id)
        except EntityExistsError:
            tag_model = self.get_tag(tag_name_or_id)
    else:
        tag_model = self.get_tag(tag_name_or_id)

    self.zen_store.batch_create_tag_resource(
        tag_resources=[
            TagResourceRequest(
                tag_id=tag_model.id,
                resource_id=resource.id,
                resource_type=resource.type,
            )
            for resource in resources
        ]
    )
backup_secrets(ignore_errors: bool = True, delete_secrets: bool = False) -> None

Backs up all secrets to the configured backup secrets store.

Parameters:

Name Type Description Default
ignore_errors bool

Whether to ignore individual errors during the backup process and attempt to backup all secrets.

True
delete_secrets bool

Whether to delete the secrets that have been successfully backed up from the primary secrets store. Setting this flag effectively moves all secrets from the primary secrets store to the backup secrets store.

False
Source code in src/zenml/client.py
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
def backup_secrets(
    self,
    ignore_errors: bool = True,
    delete_secrets: bool = False,
) -> None:
    """Backs up all secrets to the configured backup secrets store.

    Args:
        ignore_errors: Whether to ignore individual errors during the backup
            process and attempt to backup all secrets.
        delete_secrets: Whether to delete the secrets that have been
            successfully backed up from the primary secrets store. Setting
            this flag effectively moves all secrets from the primary secrets
            store to the backup secrets store.
    """
    self.zen_store.backup_secrets(
        ignore_errors=ignore_errors, delete_secrets=delete_secrets
    )
create_action(name: str, flavor: str, action_type: PluginSubType, configuration: Dict[str, Any], service_account_id: UUID, auth_window: Optional[int] = None, description: str = '') -> ActionResponse

Create an action.

Parameters:

Name Type Description Default
name str

The name of the action.

required
flavor str

The flavor of the action,

required
action_type PluginSubType

The action subtype.

required
configuration Dict[str, Any]

The action configuration.

required
service_account_id UUID

The service account that is used to execute the action.

required
auth_window Optional[int]

The time window in minutes for which the service account is authorized to execute the action. Set this to 0 to authorize the service account indefinitely (not recommended).

None
description str

The description of the action.

''

Returns:

Type Description
ActionResponse

The created action

Source code in src/zenml/client.py
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
@_fail_for_sql_zen_store
def create_action(
    self,
    name: str,
    flavor: str,
    action_type: PluginSubType,
    configuration: Dict[str, Any],
    service_account_id: UUID,
    auth_window: Optional[int] = None,
    description: str = "",
) -> ActionResponse:
    """Create an action.

    Args:
        name: The name of the action.
        flavor: The flavor of the action,
        action_type: The action subtype.
        configuration: The action configuration.
        service_account_id: The service account that is used to execute the
            action.
        auth_window: The time window in minutes for which the service
            account is authorized to execute the action. Set this to 0 to
            authorize the service account indefinitely (not recommended).
        description: The description of the action.

    Returns:
        The created action
    """
    action = ActionRequest(
        name=name,
        description=description,
        flavor=flavor,
        plugin_subtype=action_type,
        configuration=configuration,
        service_account_id=service_account_id,
        auth_window=auth_window,
        project=self.active_project.id,
    )

    return self.zen_store.create_action(action=action)
create_api_key(service_account_name_id_or_prefix: Union[str, UUID], name: str, description: str = '', set_key: bool = False) -> APIKeyResponse

Create a new API key and optionally set it as the active API key.

Parameters:

Name Type Description Default
service_account_name_id_or_prefix Union[str, UUID]

The name, ID or prefix of the service account to create the API key for.

required
name str

Name of the API key.

required
description str

The description of the API key.

''
set_key bool

Whether to set the created API key as the active API key.

False

Returns:

Type Description
APIKeyResponse

The created API key.

Source code in src/zenml/client.py
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
def create_api_key(
    self,
    service_account_name_id_or_prefix: Union[str, UUID],
    name: str,
    description: str = "",
    set_key: bool = False,
) -> APIKeyResponse:
    """Create a new API key and optionally set it as the active API key.

    Args:
        service_account_name_id_or_prefix: The name, ID or prefix of the
            service account to create the API key for.
        name: Name of the API key.
        description: The description of the API key.
        set_key: Whether to set the created API key as the active API key.

    Returns:
        The created API key.
    """
    service_account = self.get_service_account(
        name_id_or_prefix=service_account_name_id_or_prefix,
        allow_name_prefix_match=False,
    )
    request = APIKeyRequest(
        name=name,
        description=description,
    )
    api_key = self.zen_store.create_api_key(
        service_account_id=service_account.id, api_key=request
    )
    assert api_key.key is not None

    if set_key:
        self.set_api_key(key=api_key.key)

    return api_key
create_code_repository(name: str, config: Dict[str, Any], source: Source, description: Optional[str] = None, logo_url: Optional[str] = None) -> CodeRepositoryResponse

Create a new code repository.

Parameters:

Name Type Description Default
name str

Name of the code repository.

required
config Dict[str, Any]

The configuration for the code repository.

required
source Source

The code repository implementation source.

required
description Optional[str]

The code repository description.

None
logo_url Optional[str]

URL of a logo (png, jpg or svg) for the code repository.

None

Returns:

Type Description
CodeRepositoryResponse

The created code repository.

Source code in src/zenml/client.py
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
def create_code_repository(
    self,
    name: str,
    config: Dict[str, Any],
    source: Source,
    description: Optional[str] = None,
    logo_url: Optional[str] = None,
) -> CodeRepositoryResponse:
    """Create a new code repository.

    Args:
        name: Name of the code repository.
        config: The configuration for the code repository.
        source: The code repository implementation source.
        description: The code repository description.
        logo_url: URL of a logo (png, jpg or svg) for the code repository.

    Returns:
        The created code repository.
    """
    self._validate_code_repository_config(source=source, config=config)
    repo_request = CodeRepositoryRequest(
        project=self.active_project.id,
        name=name,
        config=config,
        source=source,
        description=description,
        logo_url=logo_url,
    )
    return self.zen_store.create_code_repository(
        code_repository=repo_request
    )
create_event_source(name: str, configuration: Dict[str, Any], flavor: str, event_source_subtype: PluginSubType, description: str = '') -> EventSourceResponse

Registers an event source.

Parameters:

Name Type Description Default
name str

The name of the event source to create.

required
configuration Dict[str, Any]

Configuration for this event source.

required
flavor str

The flavor of event source.

required
event_source_subtype PluginSubType

The event source subtype.

required
description str

The description of the event source.

''

Returns:

Type Description
EventSourceResponse

The model of the registered event source.

Source code in src/zenml/client.py
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
@_fail_for_sql_zen_store
def create_event_source(
    self,
    name: str,
    configuration: Dict[str, Any],
    flavor: str,
    event_source_subtype: PluginSubType,
    description: str = "",
) -> EventSourceResponse:
    """Registers an event source.

    Args:
        name: The name of the event source to create.
        configuration: Configuration for this event source.
        flavor: The flavor of event source.
        event_source_subtype: The event source subtype.
        description: The description of the event source.

    Returns:
        The model of the registered event source.
    """
    event_source = EventSourceRequest(
        name=name,
        configuration=configuration,
        description=description,
        flavor=flavor,
        plugin_type=PluginType.EVENT_SOURCE,
        plugin_subtype=event_source_subtype,
        project=self.active_project.id,
    )

    return self.zen_store.create_event_source(event_source=event_source)
create_flavor(source: str, component_type: StackComponentType) -> FlavorResponse

Creates a new flavor.

Parameters:

Name Type Description Default
source str

The flavor to create.

required
component_type StackComponentType

The type of the flavor.

required

Returns:

Type Description
FlavorResponse

The created flavor (in model form).

Raises:

Type Description
ValueError

in case the config_schema of the flavor is too large.

Source code in src/zenml/client.py
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
def create_flavor(
    self,
    source: str,
    component_type: StackComponentType,
) -> FlavorResponse:
    """Creates a new flavor.

    Args:
        source: The flavor to create.
        component_type: The type of the flavor.

    Returns:
        The created flavor (in model form).

    Raises:
        ValueError: in case the config_schema of the flavor is too large.
    """
    from zenml.stack.flavor import validate_flavor_source

    flavor = validate_flavor_source(
        source=source, component_type=component_type
    )()

    if len(flavor.config_schema) > TEXT_FIELD_MAX_LENGTH:
        raise ValueError(
            "Json representation of configuration schema"
            "exceeds max length. This could be caused by an"
            "overly long docstring on the flavors "
            "configuration class' docstring."
        )

    flavor_request = flavor.to_model(integration="custom", is_custom=True)
    return self.zen_store.create_flavor(flavor=flavor_request)
create_model(name: str, license: Optional[str] = None, description: Optional[str] = None, audience: Optional[str] = None, use_cases: Optional[str] = None, limitations: Optional[str] = None, trade_offs: Optional[str] = None, ethics: Optional[str] = None, tags: Optional[List[str]] = None, save_models_to_registry: bool = True) -> ModelResponse

Creates a new model in Model Control Plane.

Parameters:

Name Type Description Default
name str

The name of the model.

required
license Optional[str]

The license under which the model is created.

None
description Optional[str]

The description of the model.

None
audience Optional[str]

The target audience of the model.

None
use_cases Optional[str]

The use cases of the model.

None
limitations Optional[str]

The known limitations of the model.

None
trade_offs Optional[str]

The tradeoffs of the model.

None
ethics Optional[str]

The ethical implications of the model.

None
tags Optional[List[str]]

Tags associated with the model.

None
save_models_to_registry bool

Whether to save the model to the registry.

True

Returns:

Type Description
ModelResponse

The newly created model.

Source code in src/zenml/client.py
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
def create_model(
    self,
    name: str,
    license: Optional[str] = None,
    description: Optional[str] = None,
    audience: Optional[str] = None,
    use_cases: Optional[str] = None,
    limitations: Optional[str] = None,
    trade_offs: Optional[str] = None,
    ethics: Optional[str] = None,
    tags: Optional[List[str]] = None,
    save_models_to_registry: bool = True,
) -> ModelResponse:
    """Creates a new model in Model Control Plane.

    Args:
        name: The name of the model.
        license: The license under which the model is created.
        description: The description of the model.
        audience: The target audience of the model.
        use_cases: The use cases of the model.
        limitations: The known limitations of the model.
        trade_offs: The tradeoffs of the model.
        ethics: The ethical implications of the model.
        tags: Tags associated with the model.
        save_models_to_registry: Whether to save the model to the
            registry.

    Returns:
        The newly created model.
    """
    return self.zen_store.create_model(
        model=ModelRequest(
            name=name,
            license=license,
            description=description,
            audience=audience,
            use_cases=use_cases,
            limitations=limitations,
            trade_offs=trade_offs,
            ethics=ethics,
            tags=tags,
            project=self.active_project.id,
            save_models_to_registry=save_models_to_registry,
        )
    )
create_model_version(model_name_or_id: Union[str, UUID], name: Optional[str] = None, description: Optional[str] = None, tags: Optional[List[str]] = None, project: Optional[Union[str, UUID]] = None) -> ModelVersionResponse

Creates a new model version in Model Control Plane.

Parameters:

Name Type Description Default
model_name_or_id Union[str, UUID]

the name or id of the model to create model version in.

required
name Optional[str]

the name of the Model Version to be created.

None
description Optional[str]

the description of the Model Version to be created.

None
tags Optional[List[str]]

Tags associated with the model.

None
project Optional[Union[str, UUID]]

The project name/ID to filter by.

None

Returns:

Type Description
ModelVersionResponse

The newly created model version.

Source code in src/zenml/client.py
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
def create_model_version(
    self,
    model_name_or_id: Union[str, UUID],
    name: Optional[str] = None,
    description: Optional[str] = None,
    tags: Optional[List[str]] = None,
    project: Optional[Union[str, UUID]] = None,
) -> ModelVersionResponse:
    """Creates a new model version in Model Control Plane.

    Args:
        model_name_or_id: the name or id of the model to create model
            version in.
        name: the name of the Model Version to be created.
        description: the description of the Model Version to be created.
        tags: Tags associated with the model.
        project: The project name/ID to filter by.

    Returns:
        The newly created model version.
    """
    model = self.get_model(
        model_name_or_id=model_name_or_id, project=project
    )
    return self.zen_store.create_model_version(
        model_version=ModelVersionRequest(
            name=name,
            description=description,
            project=model.project.id,
            model=model.id,
            tags=tags,
        )
    )
create_project(name: str, description: str, display_name: Optional[str] = None) -> ProjectResponse

Create a new project.

Parameters:

Name Type Description Default
name str

Name of the project.

required
description str

Description of the project.

required
display_name Optional[str]

Display name of the project.

None

Returns:

Type Description
ProjectResponse

The created project.

Source code in src/zenml/client.py
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
def create_project(
    self,
    name: str,
    description: str,
    display_name: Optional[str] = None,
) -> ProjectResponse:
    """Create a new project.

    Args:
        name: Name of the project.
        description: Description of the project.
        display_name: Display name of the project.

    Returns:
        The created project.
    """
    return self.zen_store.create_project(
        ProjectRequest(
            name=name,
            description=description,
            display_name=display_name or "",
        )
    )
create_run_metadata(metadata: Dict[str, MetadataType], resources: List[RunMetadataResource], stack_component_id: Optional[UUID] = None, publisher_step_id: Optional[UUID] = None) -> None

Create run metadata.

Parameters:

Name Type Description Default
metadata Dict[str, MetadataType]

The metadata to create as a dictionary of key-value pairs.

required
resources List[RunMetadataResource]

The list of IDs and types of the resources for that the metadata was produced.

required
stack_component_id Optional[UUID]

The ID of the stack component that produced the metadata.

None
publisher_step_id Optional[UUID]

The ID of the step execution that publishes this metadata automatically.

None
Source code in src/zenml/client.py
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
def create_run_metadata(
    self,
    metadata: Dict[str, "MetadataType"],
    resources: List[RunMetadataResource],
    stack_component_id: Optional[UUID] = None,
    publisher_step_id: Optional[UUID] = None,
) -> None:
    """Create run metadata.

    Args:
        metadata: The metadata to create as a dictionary of key-value pairs.
        resources: The list of IDs and types of the resources for that the
            metadata was produced.
        stack_component_id: The ID of the stack component that produced
            the metadata.
        publisher_step_id: The ID of the step execution that publishes
            this metadata automatically.
    """
    from zenml.metadata.metadata_types import get_metadata_type

    values: Dict[str, "MetadataType"] = {}
    types: Dict[str, "MetadataTypeEnum"] = {}
    for key, value in metadata.items():
        # Skip metadata that is too large to be stored in the database.
        if len(json.dumps(value)) > TEXT_FIELD_MAX_LENGTH:
            logger.warning(
                f"Metadata value for key '{key}' is too large to be "
                "stored in the database. Skipping."
            )
            continue
        # Skip metadata that is not of a supported type.
        try:
            metadata_type = get_metadata_type(value)
        except ValueError as e:
            logger.warning(
                f"Metadata value for key '{key}' is not of a supported "
                f"type. Skipping. Full error: {e}"
            )
            continue
        values[key] = value
        types[key] = metadata_type

    run_metadata = RunMetadataRequest(
        project=self.active_project.id,
        resources=resources,
        stack_component_id=stack_component_id,
        publisher_step_id=publisher_step_id,
        values=values,
        types=types,
    )
    self.zen_store.create_run_metadata(run_metadata)
create_run_template(name: str, deployment_id: UUID, description: Optional[str] = None, tags: Optional[List[str]] = None) -> RunTemplateResponse

Create a run template.

Parameters:

Name Type Description Default
name str

The name of the run template.

required
deployment_id UUID

ID of the deployment which this template should be based off of.

required
description Optional[str]

The description of the run template.

None
tags Optional[List[str]]

Tags associated with the run template.

None

Returns:

Type Description
RunTemplateResponse

The created run template.

Source code in src/zenml/client.py
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
def create_run_template(
    self,
    name: str,
    deployment_id: UUID,
    description: Optional[str] = None,
    tags: Optional[List[str]] = None,
) -> RunTemplateResponse:
    """Create a run template.

    Args:
        name: The name of the run template.
        deployment_id: ID of the deployment which this template should be
            based off of.
        description: The description of the run template.
        tags: Tags associated with the run template.

    Returns:
        The created run template.
    """
    return self.zen_store.create_run_template(
        template=RunTemplateRequest(
            name=name,
            description=description,
            source_deployment_id=deployment_id,
            tags=tags,
            project=self.active_project.id,
        )
    )
create_secret(name: str, values: Dict[str, str], private: bool = False) -> SecretResponse

Creates a new secret.

Parameters:

Name Type Description Default
name str

The name of the secret.

required
values Dict[str, str]

The values of the secret.

required
private bool

Whether the secret is private. A private secret is only accessible to the user who created it.

False

Returns:

Type Description
SecretResponse

The created secret (in model form).

Raises:

Type Description
NotImplementedError

If centralized secrets management is not enabled.

Source code in src/zenml/client.py
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
def create_secret(
    self,
    name: str,
    values: Dict[str, str],
    private: bool = False,
) -> SecretResponse:
    """Creates a new secret.

    Args:
        name: The name of the secret.
        values: The values of the secret.
        private: Whether the secret is private. A private secret is only
            accessible to the user who created it.

    Returns:
        The created secret (in model form).

    Raises:
        NotImplementedError: If centralized secrets management is not
            enabled.
    """
    create_secret_request = SecretRequest(
        name=name,
        values=values,
        private=private,
    )
    try:
        return self.zen_store.create_secret(secret=create_secret_request)
    except NotImplementedError:
        raise NotImplementedError(
            "centralized secrets management is not supported or explicitly "
            "disabled in the target ZenML deployment."
        )
create_service(config: ServiceConfig, service_type: ServiceType, model_version_id: Optional[UUID] = None) -> ServiceResponse

Registers a service.

Parameters:

Name Type Description Default
config ServiceConfig

The configuration of the service.

required
service_type ServiceType

The type of the service.

required
model_version_id Optional[UUID]

The ID of the model version to associate with the service.

None

Returns:

Type Description
ServiceResponse

The registered service.

Source code in src/zenml/client.py
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
def create_service(
    self,
    config: "ServiceConfig",
    service_type: ServiceType,
    model_version_id: Optional[UUID] = None,
) -> ServiceResponse:
    """Registers a service.

    Args:
        config: The configuration of the service.
        service_type: The type of the service.
        model_version_id: The ID of the model version to associate with the
            service.

    Returns:
        The registered service.
    """
    service_request = ServiceRequest(
        name=config.service_name,
        service_type=service_type,
        config=config.model_dump(),
        project=self.active_project.id,
        model_version_id=model_version_id,
    )
    # Register the service
    return self.zen_store.create_service(service_request)
create_service_account(name: str, description: str = '') -> ServiceAccountResponse

Create a new service account.

Parameters:

Name Type Description Default
name str

The name of the service account.

required
description str

The description of the service account.

''

Returns:

Type Description
ServiceAccountResponse

The created service account.

Source code in src/zenml/client.py
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
def create_service_account(
    self,
    name: str,
    description: str = "",
) -> ServiceAccountResponse:
    """Create a new service account.

    Args:
        name: The name of the service account.
        description: The description of the service account.

    Returns:
        The created service account.
    """
    service_account = ServiceAccountRequest(
        name=name, description=description, active=True
    )
    created_service_account = self.zen_store.create_service_account(
        service_account=service_account
    )

    return created_service_account
create_service_connector(name: str, connector_type: str, resource_type: Optional[str] = None, auth_method: Optional[str] = None, configuration: Optional[Dict[str, str]] = None, resource_id: Optional[str] = None, description: str = '', expiration_seconds: Optional[int] = None, expires_at: Optional[datetime] = None, expires_skew_tolerance: Optional[int] = None, labels: Optional[Dict[str, str]] = None, auto_configure: bool = False, verify: bool = True, list_resources: bool = True, register: bool = True) -> Tuple[Optional[Union[ServiceConnectorResponse, ServiceConnectorRequest]], Optional[ServiceConnectorResourcesModel]]

Create, validate and/or register a service connector.

Parameters:

Name Type Description Default
name str

The name of the service connector.

required
connector_type str

The service connector type.

required
auth_method Optional[str]

The authentication method of the service connector. May be omitted if auto-configuration is used.

None
resource_type Optional[str]

The resource type for the service connector.

None
configuration Optional[Dict[str, str]]

The configuration of the service connector.

None
resource_id Optional[str]

The resource id of the service connector.

None
description str

The description of the service connector.

''
expiration_seconds Optional[int]

The expiration time of the service connector.

None
expires_at Optional[datetime]

The expiration time of the service connector.

None
expires_skew_tolerance Optional[int]

The allowed expiration skew for the service connector credentials.

None
labels Optional[Dict[str, str]]

The labels of the service connector.

None
auto_configure bool

Whether to automatically configure the service connector from the local environment.

False
verify bool

Whether to verify that the service connector configuration and credentials can be used to gain access to the resource.

True
list_resources bool

Whether to also list the resources that the service connector can give access to (if verify is True).

True
register bool

Whether to register the service connector or not.

True

Returns:

Type Description
Optional[Union[ServiceConnectorResponse, ServiceConnectorRequest]]

The model of the registered service connector and the resources

Optional[ServiceConnectorResourcesModel]

that the service connector can give access to (if verify is True).

Raises:

Type Description
ValueError

If the arguments are invalid.

KeyError

If the service connector type is not found.

NotImplementedError

If auto-configuration is not supported or not implemented for the service connector type.

AuthorizationException

If the connector verification failed due to authorization issues.

Source code in src/zenml/client.py
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
def create_service_connector(
    self,
    name: str,
    connector_type: str,
    resource_type: Optional[str] = None,
    auth_method: Optional[str] = None,
    configuration: Optional[Dict[str, str]] = None,
    resource_id: Optional[str] = None,
    description: str = "",
    expiration_seconds: Optional[int] = None,
    expires_at: Optional[datetime] = None,
    expires_skew_tolerance: Optional[int] = None,
    labels: Optional[Dict[str, str]] = None,
    auto_configure: bool = False,
    verify: bool = True,
    list_resources: bool = True,
    register: bool = True,
) -> Tuple[
    Optional[
        Union[
            ServiceConnectorResponse,
            ServiceConnectorRequest,
        ]
    ],
    Optional[ServiceConnectorResourcesModel],
]:
    """Create, validate and/or register a service connector.

    Args:
        name: The name of the service connector.
        connector_type: The service connector type.
        auth_method: The authentication method of the service connector.
            May be omitted if auto-configuration is used.
        resource_type: The resource type for the service connector.
        configuration: The configuration of the service connector.
        resource_id: The resource id of the service connector.
        description: The description of the service connector.
        expiration_seconds: The expiration time of the service connector.
        expires_at: The expiration time of the service connector.
        expires_skew_tolerance: The allowed expiration skew for the service
            connector credentials.
        labels: The labels of the service connector.
        auto_configure: Whether to automatically configure the service
            connector from the local environment.
        verify: Whether to verify that the service connector configuration
            and credentials can be used to gain access to the resource.
        list_resources: Whether to also list the resources that the service
            connector can give access to (if verify is True).
        register: Whether to register the service connector or not.

    Returns:
        The model of the registered service connector and the resources
        that the service connector can give access to (if verify is True).

    Raises:
        ValueError: If the arguments are invalid.
        KeyError: If the service connector type is not found.
        NotImplementedError: If auto-configuration is not supported or
            not implemented for the service connector type.
        AuthorizationException: If the connector verification failed due
            to authorization issues.
    """
    from zenml.service_connectors.service_connector_registry import (
        service_connector_registry,
    )

    connector_instance: Optional[ServiceConnector] = None
    connector_resources: Optional[ServiceConnectorResourcesModel] = None

    # Get the service connector type class
    try:
        connector = self.zen_store.get_service_connector_type(
            connector_type=connector_type,
        )
    except KeyError:
        raise KeyError(
            f"Service connector type {connector_type} not found."
            "Please check that you have installed all required "
            "Python packages and ZenML integrations and try again."
        )

    if not resource_type and len(connector.resource_types) == 1:
        resource_type = connector.resource_types[0].resource_type

    # If auto_configure is set, we will try to automatically configure the
    # service connector from the local environment
    if auto_configure:
        if not connector.supports_auto_configuration:
            raise NotImplementedError(
                f"The {connector.name} service connector type "
                "does not support auto-configuration."
            )
        if not connector.local:
            raise NotImplementedError(
                f"The {connector.name} service connector type "
                "implementation is not available locally. Please "
                "check that you have installed all required Python "
                "packages and ZenML integrations and try again, or "
                "skip auto-configuration."
            )

        assert connector.connector_class is not None

        connector_instance = connector.connector_class.auto_configure(
            resource_type=resource_type,
            auth_method=auth_method,
            resource_id=resource_id,
        )
        assert connector_instance is not None
        connector_request = connector_instance.to_model(
            name=name,
            description=description or "",
            labels=labels,
        )

        if verify:
            # Prefer to verify the connector config server-side if the
            # implementation if available there, because it ensures
            # that the connector can be shared with other users or used
            # from other machines and because some auth methods rely on the
            # server-side authentication environment
            if connector.remote:
                connector_resources = (
                    self.zen_store.verify_service_connector_config(
                        connector_request,
                        list_resources=list_resources,
                    )
                )
            else:
                connector_resources = connector_instance.verify(
                    list_resources=list_resources,
                )

            if connector_resources.error:
                # Raise an exception if the connector verification failed
                raise AuthorizationException(connector_resources.error)

    else:
        if not auth_method:
            if len(connector.auth_methods) == 1:
                auth_method = connector.auth_methods[0].auth_method
            else:
                raise ValueError(
                    f"Multiple authentication methods are available for "
                    f"the {connector.name} service connector type. Please "
                    f"specify one of the following: "
                    f"{list(connector.auth_method_dict.keys())}."
                )

        connector_request = ServiceConnectorRequest(
            name=name,
            connector_type=connector_type,
            description=description,
            auth_method=auth_method,
            expiration_seconds=expiration_seconds,
            expires_at=expires_at,
            expires_skew_tolerance=expires_skew_tolerance,
            labels=labels or {},
        )
        # Validate and configure the resources
        connector_request.validate_and_configure_resources(
            connector_type=connector,
            resource_types=resource_type,
            resource_id=resource_id,
            configuration=configuration,
        )
        if verify:
            # Prefer to verify the connector config server-side if the
            # implementation if available there, because it ensures
            # that the connector can be shared with other users or used
            # from other machines and because some auth methods rely on the
            # server-side authentication environment
            if connector.remote:
                connector_resources = (
                    self.zen_store.verify_service_connector_config(
                        connector_request,
                        list_resources=list_resources,
                    )
                )
            else:
                connector_instance = (
                    service_connector_registry.instantiate_connector(
                        model=connector_request
                    )
                )
                connector_resources = connector_instance.verify(
                    list_resources=list_resources,
                )

            if connector_resources.error:
                # Raise an exception if the connector verification failed
                raise AuthorizationException(connector_resources.error)

            # For resource types that don't support multi-instances, it's
            # better to save the default resource ID in the connector, if
            # available. Otherwise, we'll need to instantiate the connector
            # again to get the default resource ID.
            connector_request.resource_id = (
                connector_request.resource_id
                or connector_resources.get_default_resource_id()
            )

    if not register:
        return connector_request, connector_resources

    # Register the new model
    connector_response = self.zen_store.create_service_connector(
        service_connector=connector_request
    )

    if connector_resources:
        connector_resources.id = connector_response.id
        connector_resources.name = connector_response.name
        connector_resources.connector_type = (
            connector_response.connector_type
        )

    return connector_response, connector_resources
create_stack(name: str, components: Mapping[StackComponentType, Union[str, UUID]], stack_spec_file: Optional[str] = None, labels: Optional[Dict[str, Any]] = None) -> StackResponse

Registers a stack and its components.

Parameters:

Name Type Description Default
name str

The name of the stack to register.

required
components Mapping[StackComponentType, Union[str, UUID]]

dictionary which maps component types to component names

required
stack_spec_file Optional[str]

path to the stack spec file

None
labels Optional[Dict[str, Any]]

The labels of the stack.

None

Returns:

Type Description
StackResponse

The model of the registered stack.

Source code in src/zenml/client.py
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
def create_stack(
    self,
    name: str,
    components: Mapping[StackComponentType, Union[str, UUID]],
    stack_spec_file: Optional[str] = None,
    labels: Optional[Dict[str, Any]] = None,
) -> StackResponse:
    """Registers a stack and its components.

    Args:
        name: The name of the stack to register.
        components: dictionary which maps component types to component names
        stack_spec_file: path to the stack spec file
        labels: The labels of the stack.

    Returns:
        The model of the registered stack.
    """
    stack_components = {}

    for c_type, c_identifier in components.items():
        # Skip non-existent components.
        if not c_identifier:
            continue

        # Get the component.
        component = self.get_stack_component(
            name_id_or_prefix=c_identifier,
            component_type=c_type,
        )
        stack_components[c_type] = [component.id]

    stack = StackRequest(
        name=name,
        components=stack_components,
        stack_spec_path=stack_spec_file,
        labels=labels,
    )

    self._validate_stack_configuration(stack=stack)

    return self.zen_store.create_stack(stack=stack)
create_stack_component(name: str, flavor: str, component_type: StackComponentType, configuration: Dict[str, str], labels: Optional[Dict[str, Any]] = None) -> ComponentResponse

Registers a stack component.

Parameters:

Name Type Description Default
name str

The name of the stack component.

required
flavor str

The flavor of the stack component.

required
component_type StackComponentType

The type of the stack component.

required
configuration Dict[str, str]

The configuration of the stack component.

required
labels Optional[Dict[str, Any]]

The labels of the stack component.

None

Returns:

Type Description
ComponentResponse

The model of the registered component.

Source code in src/zenml/client.py
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
def create_stack_component(
    self,
    name: str,
    flavor: str,
    component_type: StackComponentType,
    configuration: Dict[str, str],
    labels: Optional[Dict[str, Any]] = None,
) -> "ComponentResponse":
    """Registers a stack component.

    Args:
        name: The name of the stack component.
        flavor: The flavor of the stack component.
        component_type: The type of the stack component.
        configuration: The configuration of the stack component.
        labels: The labels of the stack component.

    Returns:
        The model of the registered component.
    """
    from zenml.stack.utils import (
        validate_stack_component_config,
        warn_if_config_server_mismatch,
    )

    validated_config = validate_stack_component_config(
        configuration_dict=configuration,
        flavor=flavor,
        component_type=component_type,
        # Always enforce validation of custom flavors
        validate_custom_flavors=True,
    )
    # Guaranteed to not be None by setting
    # `validate_custom_flavors=True` above
    assert validated_config is not None
    warn_if_config_server_mismatch(validated_config)

    create_component_model = ComponentRequest(
        name=name,
        type=component_type,
        flavor=flavor,
        configuration=configuration,
        labels=labels,
    )

    # Register the new model
    return self.zen_store.create_stack_component(
        component=create_component_model
    )
create_tag(name: str, exclusive: bool = False, color: Optional[Union[str, ColorVariants]] = None) -> TagResponse

Creates a new tag.

Parameters:

Name Type Description Default
name str

the name of the tag.

required
exclusive bool

the boolean to decide whether the tag is an exclusive tag. An exclusive tag means that the tag can exist only for a single: - pipeline run within the scope of a pipeline - artifact version within the scope of an artifact - run template

False
color Optional[Union[str, ColorVariants]]

the color of the tag

None

Returns:

Type Description
TagResponse

The newly created tag.

Source code in src/zenml/client.py
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
def create_tag(
    self,
    name: str,
    exclusive: bool = False,
    color: Optional[Union[str, ColorVariants]] = None,
) -> TagResponse:
    """Creates a new tag.

    Args:
        name: the name of the tag.
        exclusive: the boolean to decide whether the tag is an exclusive tag.
            An exclusive tag means that the tag can exist only for a single:
                - pipeline run within the scope of a pipeline
                - artifact version within the scope of an artifact
                - run template
        color: the color of the tag

    Returns:
        The newly created tag.
    """
    request_model = TagRequest(name=name, exclusive=exclusive)

    if color is not None:
        request_model.color = ColorVariants(color)

    return self.zen_store.create_tag(tag=request_model)
create_trigger(name: str, event_source_id: UUID, event_filter: Dict[str, Any], action_id: UUID, description: str = '') -> TriggerResponse

Registers a trigger.

Parameters:

Name Type Description Default
name str

The name of the trigger to create.

required
event_source_id UUID

The id of the event source id

required
event_filter Dict[str, Any]

The event filter

required
action_id UUID

The ID of the action that should be triggered.

required
description str

The description of the trigger

''

Returns:

Type Description
TriggerResponse

The created trigger.

Source code in src/zenml/client.py
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
@_fail_for_sql_zen_store
def create_trigger(
    self,
    name: str,
    event_source_id: UUID,
    event_filter: Dict[str, Any],
    action_id: UUID,
    description: str = "",
) -> TriggerResponse:
    """Registers a trigger.

    Args:
        name: The name of the trigger to create.
        event_source_id: The id of the event source id
        event_filter: The event filter
        action_id: The ID of the action that should be triggered.
        description: The description of the trigger

    Returns:
        The created trigger.
    """
    trigger = TriggerRequest(
        name=name,
        description=description,
        event_source_id=event_source_id,
        event_filter=event_filter,
        action_id=action_id,
        project=self.active_project.id,
    )

    return self.zen_store.create_trigger(trigger=trigger)
create_user(name: str, password: Optional[str] = None, is_admin: bool = False) -> UserResponse

Create a new user.

Parameters:

Name Type Description Default
name str

The name of the user.

required
password Optional[str]

The password of the user. If not provided, the user will be created with empty password.

None
is_admin bool

Whether the user should be an admin.

False

Returns:

Type Description
UserResponse

The model of the created user.

Source code in src/zenml/client.py
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
def create_user(
    self,
    name: str,
    password: Optional[str] = None,
    is_admin: bool = False,
) -> UserResponse:
    """Create a new user.

    Args:
        name: The name of the user.
        password: The password of the user. If not provided, the user will
            be created with empty password.
        is_admin: Whether the user should be an admin.

    Returns:
        The model of the created user.
    """
    user = UserRequest(
        name=name, password=password or None, is_admin=is_admin
    )
    user.active = (
        password != "" if self.zen_store.type != StoreType.REST else True
    )
    created_user = self.zen_store.create_user(user=user)

    return created_user
deactivate_user(name_id_or_prefix: str) -> UserResponse

Deactivate a user and generate an activation token.

Parameters:

Name Type Description Default
name_id_or_prefix str

The name or ID of the user to reset.

required

Returns:

Type Description
UserResponse

The deactivated user.

Source code in src/zenml/client.py
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
@_fail_for_sql_zen_store
def deactivate_user(self, name_id_or_prefix: str) -> "UserResponse":
    """Deactivate a user and generate an activation token.

    Args:
        name_id_or_prefix: The name or ID of the user to reset.

    Returns:
        The deactivated user.
    """
    from zenml.zen_stores.rest_zen_store import RestZenStore

    user = self.get_user(name_id_or_prefix, allow_name_prefix_match=False)
    assert isinstance(self.zen_store, RestZenStore)
    return self.zen_store.deactivate_user(user_name_or_id=user.name)
delete_action(name_id_or_prefix: Union[str, UUID], project: Optional[Union[str, UUID]] = None) -> None

Delete an action.

Parameters:

Name Type Description Default
name_id_or_prefix Union[str, UUID]

The name, id or prefix id of the action to delete.

required
project Optional[Union[str, UUID]]

The project name/ID to filter by.

None
Source code in src/zenml/client.py
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
@_fail_for_sql_zen_store
def delete_action(
    self,
    name_id_or_prefix: Union[str, UUID],
    project: Optional[Union[str, UUID]] = None,
) -> None:
    """Delete an action.

    Args:
        name_id_or_prefix: The name, id or prefix id of the action
            to delete.
        project: The project name/ID to filter by.
    """
    action = self.get_action(
        name_id_or_prefix=name_id_or_prefix,
        allow_name_prefix_match=False,
        project=project,
    )

    self.zen_store.delete_action(action_id=action.id)
    logger.info("Deleted action with name '%s'.", action.name)

Delete all model version to artifact links in Model Control Plane.

Parameters:

Name Type Description Default
model_version_id UUID

The id of the model version holding the link.

required
only_links bool

If true, only delete the link to the artifact.

required
Source code in src/zenml/client.py
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
def delete_all_model_version_artifact_links(
    self, model_version_id: UUID, only_links: bool
) -> None:
    """Delete all model version to artifact links in Model Control Plane.

    Args:
        model_version_id: The id of the model version holding the link.
        only_links: If true, only delete the link to the artifact.
    """
    self.zen_store.delete_all_model_version_artifact_links(
        model_version_id, only_links
    )
delete_api_key(service_account_name_id_or_prefix: Union[str, UUID], name_id_or_prefix: Union[str, UUID]) -> None

Delete an API key.

Parameters:

Name Type Description Default
service_account_name_id_or_prefix Union[str, UUID]

The name, ID or prefix of the service account to delete the API key for.

required
name_id_or_prefix Union[str, UUID]

The name, ID or prefix of the API key.

required
Source code in src/zenml/client.py
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
def delete_api_key(
    self,
    service_account_name_id_or_prefix: Union[str, UUID],
    name_id_or_prefix: Union[str, UUID],
) -> None:
    """Delete an API key.

    Args:
        service_account_name_id_or_prefix: The name, ID or prefix of the
            service account to delete the API key for.
        name_id_or_prefix: The name, ID or prefix of the API key.
    """
    api_key = self.get_api_key(
        service_account_name_id_or_prefix=service_account_name_id_or_prefix,
        name_id_or_prefix=name_id_or_prefix,
        allow_name_prefix_match=False,
    )
    self.zen_store.delete_api_key(
        service_account_id=api_key.service_account.id,
        api_key_name_or_id=api_key.id,
    )
delete_artifact(name_id_or_prefix: Union[str, UUID], project: Optional[Union[str, UUID]] = None) -> None

Delete an artifact.

Parameters:

Name Type Description Default
name_id_or_prefix Union[str, UUID]

The name, ID or prefix of the artifact to delete.

required
project Optional[Union[str, UUID]]

The project name/ID to filter by.

None
Source code in src/zenml/client.py
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
def delete_artifact(
    self,
    name_id_or_prefix: Union[str, UUID],
    project: Optional[Union[str, UUID]] = None,
) -> None:
    """Delete an artifact.

    Args:
        name_id_or_prefix: The name, ID or prefix of the artifact to delete.
        project: The project name/ID to filter by.
    """
    artifact = self.get_artifact(
        name_id_or_prefix=name_id_or_prefix,
        project=project,
    )
    self.zen_store.delete_artifact(artifact_id=artifact.id)
    logger.info(f"Deleted artifact '{artifact.name}'.")
delete_artifact_version(name_id_or_prefix: Union[str, UUID], version: Optional[str] = None, delete_metadata: bool = True, delete_from_artifact_store: bool = False, project: Optional[Union[str, UUID]] = None) -> None

Delete an artifact version.

By default, this will delete only the metadata of the artifact from the database, not the actual object stored in the artifact store.

Parameters:

Name Type Description Default
name_id_or_prefix Union[str, UUID]

The ID of artifact version or name or prefix of the artifact to delete.

required
version Optional[str]

The version of the artifact to delete.

None
delete_metadata bool

If True, delete the metadata of the artifact version from the database.

True
delete_from_artifact_store bool

If True, delete the artifact object itself from the artifact store.

False
project Optional[Union[str, UUID]]

The project name/ID to filter by.

None
Source code in src/zenml/client.py
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
def delete_artifact_version(
    self,
    name_id_or_prefix: Union[str, UUID],
    version: Optional[str] = None,
    delete_metadata: bool = True,
    delete_from_artifact_store: bool = False,
    project: Optional[Union[str, UUID]] = None,
) -> None:
    """Delete an artifact version.

    By default, this will delete only the metadata of the artifact from the
    database, not the actual object stored in the artifact store.

    Args:
        name_id_or_prefix: The ID of artifact version or name or prefix of the artifact to
            delete.
        version: The version of the artifact to delete.
        delete_metadata: If True, delete the metadata of the artifact
            version from the database.
        delete_from_artifact_store: If True, delete the artifact object
                itself from the artifact store.
        project: The project name/ID to filter by.
    """
    artifact_version = self.get_artifact_version(
        name_id_or_prefix=name_id_or_prefix,
        version=version,
        project=project,
    )
    if delete_from_artifact_store:
        self._delete_artifact_from_artifact_store(
            artifact_version=artifact_version
        )
    if delete_metadata:
        self._delete_artifact_version(artifact_version=artifact_version)
delete_authorized_device(id_or_prefix: Union[str, UUID]) -> None

Delete an authorized device.

Parameters:

Name Type Description Default
id_or_prefix Union[str, UUID]

The ID or ID prefix of the authorized device.

required
Source code in src/zenml/client.py
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
def delete_authorized_device(
    self,
    id_or_prefix: Union[str, UUID],
) -> None:
    """Delete an authorized device.

    Args:
        id_or_prefix: The ID or ID prefix of the authorized device.
    """
    device = self.get_authorized_device(
        id_or_prefix=id_or_prefix,
        allow_id_prefix_match=False,
    )
    self.zen_store.delete_authorized_device(device.id)
delete_build(id_or_prefix: str, project: Optional[Union[str, UUID]] = None) -> None

Delete a build.

Parameters:

Name Type Description Default
id_or_prefix str

The id or id prefix of the build.

required
project Optional[Union[str, UUID]]

The project name/ID to filter by.

None
Source code in src/zenml/client.py
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
def delete_build(
    self, id_or_prefix: str, project: Optional[Union[str, UUID]] = None
) -> None:
    """Delete a build.

    Args:
        id_or_prefix: The id or id prefix of the build.
        project: The project name/ID to filter by.
    """
    build = self.get_build(id_or_prefix=id_or_prefix, project=project)
    self.zen_store.delete_build(build_id=build.id)
delete_code_repository(name_id_or_prefix: Union[str, UUID], project: Optional[Union[str, UUID]] = None) -> None

Delete a code repository.

Parameters:

Name Type Description Default
name_id_or_prefix Union[str, UUID]

The name, ID or prefix of the code repository.

required
project Optional[Union[str, UUID]]

The project name/ID to filter by.

None
Source code in src/zenml/client.py
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
def delete_code_repository(
    self,
    name_id_or_prefix: Union[str, UUID],
    project: Optional[Union[str, UUID]] = None,
) -> None:
    """Delete a code repository.

    Args:
        name_id_or_prefix: The name, ID or prefix of the code repository.
        project: The project name/ID to filter by.
    """
    repo = self.get_code_repository(
        name_id_or_prefix=name_id_or_prefix,
        allow_name_prefix_match=False,
        project=project,
    )
    self.zen_store.delete_code_repository(code_repository_id=repo.id)
delete_deployment(id_or_prefix: str, project: Optional[Union[str, UUID]] = None) -> None

Delete a deployment.

Parameters:

Name Type Description Default
id_or_prefix str

The id or id prefix of the deployment.

required
project Optional[Union[str, UUID]]

The project name/ID to filter by.

None
Source code in src/zenml/client.py
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
def delete_deployment(
    self,
    id_or_prefix: str,
    project: Optional[Union[str, UUID]] = None,
) -> None:
    """Delete a deployment.

    Args:
        id_or_prefix: The id or id prefix of the deployment.
        project: The project name/ID to filter by.
    """
    deployment = self.get_deployment(
        id_or_prefix=id_or_prefix,
        project=project,
        hydrate=False,
    )
    self.zen_store.delete_deployment(deployment_id=deployment.id)
delete_event_source(name_id_or_prefix: Union[str, UUID], project: Optional[Union[str, UUID]] = None) -> None

Deletes an event_source.

Parameters:

Name Type Description Default
name_id_or_prefix Union[str, UUID]

The name, id or prefix id of the event_source to deregister.

required
project Optional[Union[str, UUID]]

The project name/ID to filter by.

None
Source code in src/zenml/client.py
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
@_fail_for_sql_zen_store
def delete_event_source(
    self,
    name_id_or_prefix: Union[str, UUID],
    project: Optional[Union[str, UUID]] = None,
) -> None:
    """Deletes an event_source.

    Args:
        name_id_or_prefix: The name, id or prefix id of the event_source
            to deregister.
        project: The project name/ID to filter by.
    """
    event_source = self.get_event_source(
        name_id_or_prefix=name_id_or_prefix,
        allow_name_prefix_match=False,
        project=project,
    )

    self.zen_store.delete_event_source(event_source_id=event_source.id)
    logger.info("Deleted event_source with name '%s'.", event_source.name)
delete_flavor(name_id_or_prefix: str) -> None

Deletes a flavor.

Parameters:

Name Type Description Default
name_id_or_prefix str

The name, id or prefix of the id for the flavor to delete.

required
Source code in src/zenml/client.py
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
def delete_flavor(self, name_id_or_prefix: str) -> None:
    """Deletes a flavor.

    Args:
        name_id_or_prefix: The name, id or prefix of the id for the
            flavor to delete.
    """
    flavor = self.get_flavor(
        name_id_or_prefix, allow_name_prefix_match=False
    )
    self.zen_store.delete_flavor(flavor_id=flavor.id)

    logger.info(f"Deleted flavor '{flavor.name}' of type '{flavor.type}'.")
delete_model(model_name_or_id: Union[str, UUID], project: Optional[Union[str, UUID]] = None) -> None

Deletes a model from Model Control Plane.

Parameters:

Name Type Description Default
model_name_or_id Union[str, UUID]

name or id of the model to be deleted.

required
project Optional[Union[str, UUID]]

The project name/ID to filter by.

None
Source code in src/zenml/client.py
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
def delete_model(
    self,
    model_name_or_id: Union[str, UUID],
    project: Optional[Union[str, UUID]] = None,
) -> None:
    """Deletes a model from Model Control Plane.

    Args:
        model_name_or_id: name or id of the model to be deleted.
        project: The project name/ID to filter by.
    """
    model = self.get_model(
        model_name_or_id=model_name_or_id, project=project
    )
    self.zen_store.delete_model(model_id=model.id)
delete_model_version(model_version_id: UUID) -> None

Deletes a model version from Model Control Plane.

Parameters:

Name Type Description Default
model_version_id UUID

Id of the model version to be deleted.

required
Source code in src/zenml/client.py
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
def delete_model_version(
    self,
    model_version_id: UUID,
) -> None:
    """Deletes a model version from Model Control Plane.

    Args:
        model_version_id: Id of the model version to be deleted.
    """
    self.zen_store.delete_model_version(
        model_version_id=model_version_id,
    )

Delete model version to artifact link in Model Control Plane.

Parameters:

Name Type Description Default
model_version_id UUID

The id of the model version holding the link.

required
artifact_version_id UUID

The id of the artifact version to be deleted.

required

Raises:

Type Description
RuntimeError

If more than one artifact link is found for given filters.

Source code in src/zenml/client.py
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
def delete_model_version_artifact_link(
    self, model_version_id: UUID, artifact_version_id: UUID
) -> None:
    """Delete model version to artifact link in Model Control Plane.

    Args:
        model_version_id: The id of the model version holding the link.
        artifact_version_id: The id of the artifact version to be deleted.

    Raises:
        RuntimeError: If more than one artifact link is found for given filters.
    """
    artifact_links = self.list_model_version_artifact_links(
        model_version_id=model_version_id,
        artifact_version_id=artifact_version_id,
    )
    if artifact_links.items:
        if artifact_links.total > 1:
            raise RuntimeError(
                "More than one artifact link found for give model version "
                f"`{model_version_id}` and artifact version "
                f"`{artifact_version_id}`. This should not be happening and "
                "might indicate a corrupted state of your ZenML database. "
                "Please seek support via Community Slack."
            )
        self.zen_store.delete_model_version_artifact_link(
            model_version_id=model_version_id,
            model_version_artifact_link_name_or_id=artifact_links.items[
                0
            ].id,
        )
delete_pipeline(name_id_or_prefix: Union[str, UUID], project: Optional[Union[str, UUID]] = None) -> None

Delete a pipeline.

Parameters:

Name Type Description Default
name_id_or_prefix Union[str, UUID]

The name, ID or ID prefix of the pipeline.

required
project Optional[Union[str, UUID]]

The project name/ID to filter by.

None
Source code in src/zenml/client.py
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
def delete_pipeline(
    self,
    name_id_or_prefix: Union[str, UUID],
    project: Optional[Union[str, UUID]] = None,
) -> None:
    """Delete a pipeline.

    Args:
        name_id_or_prefix: The name, ID or ID prefix of the pipeline.
        project: The project name/ID to filter by.
    """
    pipeline = self.get_pipeline(
        name_id_or_prefix=name_id_or_prefix, project=project
    )
    self.zen_store.delete_pipeline(pipeline_id=pipeline.id)
delete_pipeline_run(name_id_or_prefix: Union[str, UUID], project: Optional[Union[str, UUID]] = None) -> None

Deletes a pipeline run.

Parameters:

Name Type Description Default
name_id_or_prefix Union[str, UUID]

Name, ID, or prefix of the pipeline run.

required
project Optional[Union[str, UUID]]

The project name/ID to filter by.

None
Source code in src/zenml/client.py
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
def delete_pipeline_run(
    self,
    name_id_or_prefix: Union[str, UUID],
    project: Optional[Union[str, UUID]] = None,
) -> None:
    """Deletes a pipeline run.

    Args:
        name_id_or_prefix: Name, ID, or prefix of the pipeline run.
        project: The project name/ID to filter by.
    """
    run = self.get_pipeline_run(
        name_id_or_prefix=name_id_or_prefix,
        allow_name_prefix_match=False,
        project=project,
    )
    self.zen_store.delete_run(run_id=run.id)
delete_project(name_id_or_prefix: str) -> None

Delete a project.

Parameters:

Name Type Description Default
name_id_or_prefix str

The name or ID of the project to delete.

required

Raises:

Type Description
IllegalOperationError

If the project to delete is the active project.

Source code in src/zenml/client.py
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
def delete_project(self, name_id_or_prefix: str) -> None:
    """Delete a project.

    Args:
        name_id_or_prefix: The name or ID of the project to delete.

    Raises:
        IllegalOperationError: If the project to delete is the active
            project.
    """
    project = self.get_project(
        name_id_or_prefix, allow_name_prefix_match=False
    )
    if self.active_project.id == project.id:
        raise IllegalOperationError(
            f"Project '{name_id_or_prefix}' cannot be deleted since "
            "it is currently active. Please set another project as "
            "active first."
        )
    self.zen_store.delete_project(project_name_or_id=project.id)
delete_run_template(name_id_or_prefix: Union[str, UUID], project: Optional[Union[str, UUID]] = None) -> None

Delete a run template.

Parameters:

Name Type Description Default
name_id_or_prefix Union[str, UUID]

Name/ID/ID prefix of the template to delete.

required
project Optional[Union[str, UUID]]

The project name/ID to filter by.

None
Source code in src/zenml/client.py
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
def delete_run_template(
    self,
    name_id_or_prefix: Union[str, UUID],
    project: Optional[Union[str, UUID]] = None,
) -> None:
    """Delete a run template.

    Args:
        name_id_or_prefix: Name/ID/ID prefix of the template to delete.
        project: The project name/ID to filter by.
    """
    if is_valid_uuid(name_id_or_prefix):
        template_id = (
            UUID(name_id_or_prefix)
            if isinstance(name_id_or_prefix, str)
            else name_id_or_prefix
        )
    else:
        template_id = self.get_run_template(
            name_id_or_prefix,
            project=project,
            hydrate=False,
        ).id

    self.zen_store.delete_run_template(template_id=template_id)
delete_schedule(name_id_or_prefix: Union[str, UUID], project: Optional[Union[str, UUID]] = None) -> None

Delete a schedule.

Parameters:

Name Type Description Default
name_id_or_prefix Union[str, UUID]

The name, id or prefix id of the schedule to delete.

required
project Optional[Union[str, UUID]]

The project name/ID to filter by.

None
Source code in src/zenml/client.py
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
def delete_schedule(
    self,
    name_id_or_prefix: Union[str, UUID],
    project: Optional[Union[str, UUID]] = None,
) -> None:
    """Delete a schedule.

    Args:
        name_id_or_prefix: The name, id or prefix id of the schedule
            to delete.
        project: The project name/ID to filter by.
    """
    schedule = self.get_schedule(
        name_id_or_prefix=name_id_or_prefix,
        allow_name_prefix_match=False,
        project=project,
    )
    logger.warning(
        f"Deleting schedule '{name_id_or_prefix}'... This will only delete "
        "the reference of the schedule from ZenML. Please make sure to "
        "manually stop/delete this schedule in your orchestrator as well!"
    )
    self.zen_store.delete_schedule(schedule_id=schedule.id)
delete_secret(name_id_or_prefix: str, private: Optional[bool] = None) -> None

Deletes a secret.

Parameters:

Name Type Description Default
name_id_or_prefix str

The name or ID of the secret.

required
private Optional[bool]

The private status of the secret to delete.

None
Source code in src/zenml/client.py
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
def delete_secret(
    self, name_id_or_prefix: str, private: Optional[bool] = None
) -> None:
    """Deletes a secret.

    Args:
        name_id_or_prefix: The name or ID of the secret.
        private: The private status of the secret to delete.
    """
    secret = self.get_secret(
        name_id_or_prefix=name_id_or_prefix,
        private=private,
        # Don't allow partial name matches, but allow partial ID matches
        allow_partial_name_match=False,
        allow_partial_id_match=True,
    )

    self.zen_store.delete_secret(secret_id=secret.id)
delete_service(name_id_or_prefix: UUID, project: Optional[Union[str, UUID]] = None) -> None

Delete a service.

Parameters:

Name Type Description Default
name_id_or_prefix UUID

The name or ID of the service to delete.

required
project Optional[Union[str, UUID]]

The project name/ID to filter by.

None
Source code in src/zenml/client.py
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
def delete_service(
    self,
    name_id_or_prefix: UUID,
    project: Optional[Union[str, UUID]] = None,
) -> None:
    """Delete a service.

    Args:
        name_id_or_prefix: The name or ID of the service to delete.
        project: The project name/ID to filter by.
    """
    service = self.get_service(
        name_id_or_prefix,
        allow_name_prefix_match=False,
        project=project,
    )
    self.zen_store.delete_service(service_id=service.id)
delete_service_account(name_id_or_prefix: Union[str, UUID]) -> None

Delete a service account.

Parameters:

Name Type Description Default
name_id_or_prefix Union[str, UUID]

The name or ID of the service account to delete.

required
Source code in src/zenml/client.py
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
def delete_service_account(
    self,
    name_id_or_prefix: Union[str, UUID],
) -> None:
    """Delete a service account.

    Args:
        name_id_or_prefix: The name or ID of the service account to delete.
    """
    service_account = self.get_service_account(
        name_id_or_prefix=name_id_or_prefix, allow_name_prefix_match=False
    )
    self.zen_store.delete_service_account(
        service_account_name_or_id=service_account.id
    )
delete_service_connector(name_id_or_prefix: Union[str, UUID]) -> None

Deletes a registered service connector.

Parameters:

Name Type Description Default
name_id_or_prefix Union[str, UUID]

The ID or name of the service connector to delete.

required
Source code in src/zenml/client.py
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
def delete_service_connector(
    self,
    name_id_or_prefix: Union[str, UUID],
) -> None:
    """Deletes a registered service connector.

    Args:
        name_id_or_prefix: The ID or name of the service connector to delete.
    """
    service_connector = self.get_service_connector(
        name_id_or_prefix=name_id_or_prefix,
        allow_name_prefix_match=False,
    )

    self.zen_store.delete_service_connector(
        service_connector_id=service_connector.id
    )
    logger.info(
        "Removed service connector (type: %s) with name '%s'.",
        service_connector.type,
        service_connector.name,
    )
delete_stack(name_id_or_prefix: Union[str, UUID], recursive: bool = False) -> None

Deregisters a stack.

Parameters:

Name Type Description Default
name_id_or_prefix Union[str, UUID]

The name, id or prefix id of the stack to deregister.

required
recursive bool

If True, all components of the stack which are not associated with any other stack will also be deleted.

False

Raises:

Type Description
ValueError

If the stack is the currently active stack for this client.

Source code in src/zenml/client.py
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
def delete_stack(
    self, name_id_or_prefix: Union[str, UUID], recursive: bool = False
) -> None:
    """Deregisters a stack.

    Args:
        name_id_or_prefix: The name, id or prefix id of the stack
            to deregister.
        recursive: If `True`, all components of the stack which are not
            associated with any other stack will also be deleted.

    Raises:
        ValueError: If the stack is the currently active stack for this
            client.
    """
    stack = self.get_stack(
        name_id_or_prefix=name_id_or_prefix, allow_name_prefix_match=False
    )

    if stack.id == self.active_stack_model.id:
        raise ValueError(
            f"Unable to deregister active stack '{stack.name}'. Make "
            f"sure to designate a new active stack before deleting this "
            f"one."
        )

    cfg = GlobalConfiguration()
    if stack.id == cfg.active_stack_id:
        raise ValueError(
            f"Unable to deregister '{stack.name}' as it is the active "
            f"stack within your global configuration. Make "
            f"sure to designate a new active stack before deleting this "
            f"one."
        )

    if recursive:
        stack_components_free_for_deletion = []

        # Get all stack components associated with this stack
        for component_type, component_model in stack.components.items():
            # Get stack associated with the stack component

            stacks = self.list_stacks(
                component_id=component_model[0].id, size=2, page=1
            )

            # Check if the stack component is part of another stack
            if len(stacks) == 1 and stack.id == stacks[0].id:
                stack_components_free_for_deletion.append(
                    (component_type, component_model)
                )

        self.delete_stack(stack.id)

        for (
            stack_component_type,
            stack_component_model,
        ) in stack_components_free_for_deletion:
            self.delete_stack_component(
                stack_component_model[0].name, stack_component_type
            )

        logger.info("Deregistered stack with name '%s'.", stack.name)
        return

    self.zen_store.delete_stack(stack_id=stack.id)
    logger.info("Deregistered stack with name '%s'.", stack.name)
delete_stack_component(name_id_or_prefix: Union[str, UUID], component_type: StackComponentType) -> None

Deletes a registered stack component.

Parameters:

Name Type Description Default
name_id_or_prefix Union[str, UUID]

The model of the component to delete.

required
component_type StackComponentType

The type of the component to delete.

required
Source code in src/zenml/client.py
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
def delete_stack_component(
    self,
    name_id_or_prefix: Union[str, UUID],
    component_type: StackComponentType,
) -> None:
    """Deletes a registered stack component.

    Args:
        name_id_or_prefix: The model of the component to delete.
        component_type: The type of the component to delete.
    """
    component = self.get_stack_component(
        name_id_or_prefix=name_id_or_prefix,
        component_type=component_type,
        allow_name_prefix_match=False,
    )

    self.zen_store.delete_stack_component(component_id=component.id)
    logger.info(
        "Deregistered stack component (type: %s) with name '%s'.",
        component.type,
        component.name,
    )
delete_tag(tag_name_or_id: Union[str, UUID]) -> None

Deletes a tag.

Parameters:

Name Type Description Default
tag_name_or_id Union[str, UUID]

name or id of the tag to be deleted.

required
Source code in src/zenml/client.py
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
def delete_tag(
    self,
    tag_name_or_id: Union[str, UUID],
) -> None:
    """Deletes a tag.

    Args:
        tag_name_or_id: name or id of the tag to be deleted.
    """
    self.zen_store.delete_tag(
        tag_name_or_id=tag_name_or_id,
    )
delete_trigger(name_id_or_prefix: Union[str, UUID], project: Optional[Union[str, UUID]] = None) -> None

Deletes an trigger.

Parameters:

Name Type Description Default
name_id_or_prefix Union[str, UUID]

The name, id or prefix id of the trigger to deregister.

required
project Optional[Union[str, UUID]]

The project name/ID to filter by.

None
Source code in src/zenml/client.py
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
@_fail_for_sql_zen_store
def delete_trigger(
    self,
    name_id_or_prefix: Union[str, UUID],
    project: Optional[Union[str, UUID]] = None,
) -> None:
    """Deletes an trigger.

    Args:
        name_id_or_prefix: The name, id or prefix id of the trigger
            to deregister.
        project: The project name/ID to filter by.
    """
    trigger = self.get_trigger(
        name_id_or_prefix=name_id_or_prefix,
        allow_name_prefix_match=False,
        project=project,
    )

    self.zen_store.delete_trigger(trigger_id=trigger.id)
    logger.info("Deleted trigger with name '%s'.", trigger.name)
delete_trigger_execution(trigger_execution_id: UUID) -> None

Delete a trigger execution.

Parameters:

Name Type Description Default
trigger_execution_id UUID

The ID of the trigger execution to delete.

required
Source code in src/zenml/client.py
7011
7012
7013
7014
7015
7016
7017
7018
7019
def delete_trigger_execution(self, trigger_execution_id: UUID) -> None:
    """Delete a trigger execution.

    Args:
        trigger_execution_id: The ID of the trigger execution to delete.
    """
    self.zen_store.delete_trigger_execution(
        trigger_execution_id=trigger_execution_id
    )
delete_user(name_id_or_prefix: str) -> None

Delete a user.

Parameters:

Name Type Description Default
name_id_or_prefix str

The name or ID of the user to delete.

required
Source code in src/zenml/client.py
956
957
958
959
960
961
962
963
def delete_user(self, name_id_or_prefix: str) -> None:
    """Delete a user.

    Args:
        name_id_or_prefix: The name or ID of the user to delete.
    """
    user = self.get_user(name_id_or_prefix, allow_name_prefix_match=False)
    self.zen_store.delete_user(user_name_or_id=user.name)
detach_tag(tag_name_or_id: Union[str, UUID], resources: List[TagResource]) -> None

Detach a tag from resources.

Parameters:

Name Type Description Default
tag_name_or_id Union[str, UUID]

name or id of the tag to be detached.

required
resources List[TagResource]

the resources to detach the tag from.

required
Source code in src/zenml/client.py
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
def detach_tag(
    self,
    tag_name_or_id: Union[str, UUID],
    resources: List[TagResource],
) -> None:
    """Detach a tag from resources.

    Args:
        tag_name_or_id: name or id of the tag to be detached.
        resources: the resources to detach the tag from.
    """
    tag_model = self.get_tag(tag_name_or_id)

    self.zen_store.batch_delete_tag_resource(
        tag_resources=[
            TagResourceRequest(
                tag_id=tag_model.id,
                resource_id=resource.id,
                resource_type=resource.type,
            )
            for resource in resources
        ]
    )
find_repository(path: Optional[Path] = None, enable_warnings: bool = False) -> Optional[Path] staticmethod

Search for a ZenML repository directory.

Parameters:

Name Type Description Default
path Optional[Path]

Optional path to look for the repository. If no path is given, this function tries to find the repository using the environment variable ZENML_REPOSITORY_PATH (if set) and recursively searching in the parent directories of the current working directory.

None
enable_warnings bool

If True, warnings are printed if the repository root cannot be found.

False

Returns:

Type Description
Optional[Path]

Absolute path to a ZenML repository directory or None if no

Optional[Path]

repository directory was found.

Source code in src/zenml/client.py
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
@staticmethod
def find_repository(
    path: Optional[Path] = None, enable_warnings: bool = False
) -> Optional[Path]:
    """Search for a ZenML repository directory.

    Args:
        path: Optional path to look for the repository. If no path is
            given, this function tries to find the repository using the
            environment variable `ZENML_REPOSITORY_PATH` (if set) and
            recursively searching in the parent directories of the current
            working directory.
        enable_warnings: If `True`, warnings are printed if the repository
            root cannot be found.

    Returns:
        Absolute path to a ZenML repository directory or None if no
        repository directory was found.
    """
    if not path:
        # try to get path from the environment variable
        env_var_path = os.getenv(ENV_ZENML_REPOSITORY_PATH)
        if env_var_path:
            path = Path(env_var_path)

    if path:
        # explicit path via parameter or environment variable, don't search
        # parent directories
        search_parent_directories = False
        warning_message = (
            f"Unable to find ZenML repository at path '{path}'. Make sure "
            f"to create a ZenML repository by calling `zenml init` when "
            f"specifying an explicit repository path in code or via the "
            f"environment variable '{ENV_ZENML_REPOSITORY_PATH}'."
        )
    else:
        # try to find the repository in the parent directories of the
        # current working directory
        path = Path.cwd()
        search_parent_directories = True
        warning_message = (
            f"Unable to find ZenML repository in your current working "
            f"directory ({path}) or any parent directories. If you "
            f"want to use an existing repository which is in a different "
            f"location, set the environment variable "
            f"'{ENV_ZENML_REPOSITORY_PATH}'. If you want to create a new "
            f"repository, run `zenml init`."
        )

    def _find_repository_helper(path_: Path) -> Optional[Path]:
        """Recursively search parent directories for a ZenML repository.

        Args:
            path_: The path to search.

        Returns:
            Absolute path to a ZenML repository directory or None if no
            repository directory was found.
        """
        if Client.is_repository_directory(path_):
            return path_

        if not search_parent_directories or io_utils.is_root(str(path_)):
            return None

        return _find_repository_helper(path_.parent)

    repository_path = _find_repository_helper(path)

    if repository_path:
        return repository_path.resolve()
    if enable_warnings:
        logger.warning(warning_message)
    return None
get_action(name_id_or_prefix: Union[UUID, str], allow_name_prefix_match: bool = True, project: Optional[Union[str, UUID]] = None, hydrate: bool = True) -> ActionResponse

Get an action by name, ID or prefix.

Parameters:

Name Type Description Default
name_id_or_prefix Union[UUID, str]

The name, ID or prefix of the action.

required
allow_name_prefix_match bool

If True, allow matching by name prefix.

True
project Optional[Union[str, UUID]]

The project name/ID to filter by.

None
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

True

Returns:

Type Description
ActionResponse

The action.

Source code in src/zenml/client.py
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
@_fail_for_sql_zen_store
def get_action(
    self,
    name_id_or_prefix: Union[UUID, str],
    allow_name_prefix_match: bool = True,
    project: Optional[Union[str, UUID]] = None,
    hydrate: bool = True,
) -> ActionResponse:
    """Get an action by name, ID or prefix.

    Args:
        name_id_or_prefix: The name, ID or prefix of the action.
        allow_name_prefix_match: If True, allow matching by name prefix.
        project: The project name/ID to filter by.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        The action.
    """
    return self._get_entity_by_id_or_name_or_prefix(
        get_method=self.zen_store.get_action,
        list_method=self.list_actions,
        name_id_or_prefix=name_id_or_prefix,
        allow_name_prefix_match=allow_name_prefix_match,
        project=project,
        hydrate=hydrate,
    )
get_api_key(service_account_name_id_or_prefix: Union[str, UUID], name_id_or_prefix: Union[str, UUID], allow_name_prefix_match: bool = True, hydrate: bool = True) -> APIKeyResponse

Get an API key by name, id or prefix.

Parameters:

Name Type Description Default
service_account_name_id_or_prefix Union[str, UUID]

The name, ID or prefix of the service account to get the API key for.

required
name_id_or_prefix Union[str, UUID]

The name, ID or ID prefix of the API key.

required
allow_name_prefix_match bool

If True, allow matching by name prefix.

True
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

True

Returns:

Type Description
APIKeyResponse

The API key.

Source code in src/zenml/client.py
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
def get_api_key(
    self,
    service_account_name_id_or_prefix: Union[str, UUID],
    name_id_or_prefix: Union[str, UUID],
    allow_name_prefix_match: bool = True,
    hydrate: bool = True,
) -> APIKeyResponse:
    """Get an API key by name, id or prefix.

    Args:
        service_account_name_id_or_prefix: The name, ID or prefix of the
            service account to get the API key for.
        name_id_or_prefix: The name, ID or ID prefix of the API key.
        allow_name_prefix_match: If True, allow matching by name prefix.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        The API key.
    """
    service_account = self.get_service_account(
        name_id_or_prefix=service_account_name_id_or_prefix,
        allow_name_prefix_match=False,
    )

    def get_api_key_method(
        api_key_name_or_id: str, hydrate: bool = True
    ) -> APIKeyResponse:
        return self.zen_store.get_api_key(
            service_account_id=service_account.id,
            api_key_name_or_id=api_key_name_or_id,
            hydrate=hydrate,
        )

    def list_api_keys_method(
        hydrate: bool = True,
        **filter_args: Any,
    ) -> Page[APIKeyResponse]:
        return self.list_api_keys(
            service_account_name_id_or_prefix=service_account.id,
            hydrate=hydrate,
            **filter_args,
        )

    return self._get_entity_by_id_or_name_or_prefix(
        get_method=get_api_key_method,
        list_method=list_api_keys_method,
        name_id_or_prefix=name_id_or_prefix,
        allow_name_prefix_match=allow_name_prefix_match,
        hydrate=hydrate,
    )
get_artifact(name_id_or_prefix: Union[str, UUID], project: Optional[Union[str, UUID]] = None, hydrate: bool = False) -> ArtifactResponse

Get an artifact by name, id or prefix.

Parameters:

Name Type Description Default
name_id_or_prefix Union[str, UUID]

The name, ID or prefix of the artifact to get.

required
project Optional[Union[str, UUID]]

The project name/ID to filter by.

None
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

False

Returns:

Type Description
ArtifactResponse

The artifact.

Source code in src/zenml/client.py
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
def get_artifact(
    self,
    name_id_or_prefix: Union[str, UUID],
    project: Optional[Union[str, UUID]] = None,
    hydrate: bool = False,
) -> ArtifactResponse:
    """Get an artifact by name, id or prefix.

    Args:
        name_id_or_prefix: The name, ID or prefix of the artifact to get.
        project: The project name/ID to filter by.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        The artifact.
    """
    return self._get_entity_by_id_or_name_or_prefix(
        get_method=self.zen_store.get_artifact,
        list_method=self.list_artifacts,
        name_id_or_prefix=name_id_or_prefix,
        project=project,
        hydrate=hydrate,
    )
get_artifact_version(name_id_or_prefix: Union[str, UUID], version: Optional[str] = None, project: Optional[Union[str, UUID]] = None, hydrate: bool = True) -> ArtifactVersionResponse

Get an artifact version by ID or artifact name.

Parameters:

Name Type Description Default
name_id_or_prefix Union[str, UUID]

Either the ID of the artifact version or the name of the artifact.

required
version Optional[str]

The version of the artifact to get. Only used if name_id_or_prefix is the name of the artifact. If not specified, the latest version is returned.

None
project Optional[Union[str, UUID]]

The project name/ID to filter by.

None
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

True

Returns:

Type Description
ArtifactVersionResponse

The artifact version.

Source code in src/zenml/client.py
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
def get_artifact_version(
    self,
    name_id_or_prefix: Union[str, UUID],
    version: Optional[str] = None,
    project: Optional[Union[str, UUID]] = None,
    hydrate: bool = True,
) -> ArtifactVersionResponse:
    """Get an artifact version by ID or artifact name.

    Args:
        name_id_or_prefix: Either the ID of the artifact version or the
            name of the artifact.
        version: The version of the artifact to get. Only used if
            `name_id_or_prefix` is the name of the artifact. If not
            specified, the latest version is returned.
        project: The project name/ID to filter by.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        The artifact version.
    """
    from zenml import get_step_context

    if cll := client_lazy_loader(
        method_name="get_artifact_version",
        name_id_or_prefix=name_id_or_prefix,
        version=version,
        project=project,
        hydrate=hydrate,
    ):
        return cll  # type: ignore[return-value]

    artifact = self._get_entity_version_by_id_or_name_or_prefix(
        get_method=self.zen_store.get_artifact_version,
        list_method=self.list_artifact_versions,
        name_id_or_prefix=name_id_or_prefix,
        version=version,
        project=project,
        hydrate=hydrate,
    )
    try:
        step_run = get_step_context().step_run
        client = Client()
        client.zen_store.update_run_step(
            step_run_id=step_run.id,
            step_run_update=StepRunUpdate(
                loaded_artifact_versions={artifact.name: artifact.id}
            ),
        )
    except RuntimeError:
        pass  # Cannot link to step run if called outside a step
    return artifact
get_authorized_device(id_or_prefix: Union[UUID, str], allow_id_prefix_match: bool = True, hydrate: bool = True) -> OAuthDeviceResponse

Get an authorized device by id or prefix.

Parameters:

Name Type Description Default
id_or_prefix Union[UUID, str]

The ID or ID prefix of the authorized device.

required
allow_id_prefix_match bool

If True, allow matching by ID prefix.

True
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

True

Returns:

Type Description
OAuthDeviceResponse

The requested authorized device.

Raises:

Type Description
KeyError

If no authorized device is found with the given ID or prefix.

Source code in src/zenml/client.py
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
def get_authorized_device(
    self,
    id_or_prefix: Union[UUID, str],
    allow_id_prefix_match: bool = True,
    hydrate: bool = True,
) -> OAuthDeviceResponse:
    """Get an authorized device by id or prefix.

    Args:
        id_or_prefix: The ID or ID prefix of the authorized device.
        allow_id_prefix_match: If True, allow matching by ID prefix.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        The requested authorized device.

    Raises:
        KeyError: If no authorized device is found with the given ID or
            prefix.
    """
    if isinstance(id_or_prefix, str):
        try:
            id_or_prefix = UUID(id_or_prefix)
        except ValueError:
            if not allow_id_prefix_match:
                raise KeyError(
                    f"No authorized device found with id or prefix "
                    f"'{id_or_prefix}'."
                )
    if isinstance(id_or_prefix, UUID):
        return self.zen_store.get_authorized_device(
            id_or_prefix, hydrate=hydrate
        )
    return self._get_entity_by_prefix(
        get_method=self.zen_store.get_authorized_device,
        list_method=self.list_authorized_devices,
        partial_id_or_name=id_or_prefix,
        allow_name_prefix_match=False,
        hydrate=hydrate,
    )
get_build(id_or_prefix: Union[str, UUID], project: Optional[Union[str, UUID]] = None, hydrate: bool = True) -> PipelineBuildResponse

Get a build by id or prefix.

Parameters:

Name Type Description Default
id_or_prefix Union[str, UUID]

The id or id prefix of the build.

required
project Optional[Union[str, UUID]]

The project name/ID to filter by.

None
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

True

Returns:

Type Description
PipelineBuildResponse

The build.

Raises:

Type Description
KeyError

If no build was found for the given id or prefix.

ZenKeyError

If multiple builds were found that match the given id or prefix.

Source code in src/zenml/client.py
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
def get_build(
    self,
    id_or_prefix: Union[str, UUID],
    project: Optional[Union[str, UUID]] = None,
    hydrate: bool = True,
) -> PipelineBuildResponse:
    """Get a build by id or prefix.

    Args:
        id_or_prefix: The id or id prefix of the build.
        project: The project name/ID to filter by.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        The build.

    Raises:
        KeyError: If no build was found for the given id or prefix.
        ZenKeyError: If multiple builds were found that match the given
            id or prefix.
    """
    from zenml.utils.uuid_utils import is_valid_uuid

    # First interpret as full UUID
    if is_valid_uuid(id_or_prefix):
        if not isinstance(id_or_prefix, UUID):
            id_or_prefix = UUID(id_or_prefix, version=4)

        return self.zen_store.get_build(
            id_or_prefix,
            hydrate=hydrate,
        )

    list_kwargs: Dict[str, Any] = dict(
        id=f"startswith:{id_or_prefix}",
        hydrate=hydrate,
    )
    scope = ""
    if project:
        list_kwargs["project"] = project
        scope = f" in project {project}"

    entity = self.list_builds(**list_kwargs)

    # If only a single entity is found, return it.
    if entity.total == 1:
        return entity.items[0]

    # If no entity is found, raise an error.
    if entity.total == 0:
        raise KeyError(
            f"No builds have been found that have either an id or prefix "
            f"that matches the provided string '{id_or_prefix}'{scope}."
        )

    raise ZenKeyError(
        f"{entity.total} builds have been found{scope} that have "
        f"an ID that matches the provided "
        f"string '{id_or_prefix}':\n"
        f"{[entity.items]}.\n"
        f"Please use the id to uniquely identify "
        f"only one of the builds."
    )
get_code_repository(name_id_or_prefix: Union[str, UUID], allow_name_prefix_match: bool = True, project: Optional[Union[str, UUID]] = None, hydrate: bool = True) -> CodeRepositoryResponse

Get a code repository by name, id or prefix.

Parameters:

Name Type Description Default
name_id_or_prefix Union[str, UUID]

The name, ID or ID prefix of the code repository.

required
allow_name_prefix_match bool

If True, allow matching by name prefix.

True
project Optional[Union[str, UUID]]

The project name/ID to filter by.

None
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

True

Returns:

Type Description
CodeRepositoryResponse

The code repository.

Source code in src/zenml/client.py
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
def get_code_repository(
    self,
    name_id_or_prefix: Union[str, UUID],
    allow_name_prefix_match: bool = True,
    project: Optional[Union[str, UUID]] = None,
    hydrate: bool = True,
) -> CodeRepositoryResponse:
    """Get a code repository by name, id or prefix.

    Args:
        name_id_or_prefix: The name, ID or ID prefix of the code repository.
        allow_name_prefix_match: If True, allow matching by name prefix.
        project: The project name/ID to filter by.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        The code repository.
    """
    return self._get_entity_by_id_or_name_or_prefix(
        get_method=self.zen_store.get_code_repository,
        list_method=self.list_code_repositories,
        name_id_or_prefix=name_id_or_prefix,
        allow_name_prefix_match=allow_name_prefix_match,
        hydrate=hydrate,
        project=project,
    )
get_deployment(id_or_prefix: Union[str, UUID], project: Optional[Union[str, UUID]] = None, hydrate: bool = True) -> PipelineDeploymentResponse

Get a deployment by id or prefix.

Parameters:

Name Type Description Default
id_or_prefix Union[str, UUID]

The id or id prefix of the deployment.

required
project Optional[Union[str, UUID]]

The project name/ID to filter by.

None
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

True

Returns:

Type Description
PipelineDeploymentResponse

The deployment.

Raises:

Type Description
KeyError

If no deployment was found for the given id or prefix.

ZenKeyError

If multiple deployments were found that match the given id or prefix.

Source code in src/zenml/client.py
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
def get_deployment(
    self,
    id_or_prefix: Union[str, UUID],
    project: Optional[Union[str, UUID]] = None,
    hydrate: bool = True,
) -> PipelineDeploymentResponse:
    """Get a deployment by id or prefix.

    Args:
        id_or_prefix: The id or id prefix of the deployment.
        project: The project name/ID to filter by.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        The deployment.

    Raises:
        KeyError: If no deployment was found for the given id or prefix.
        ZenKeyError: If multiple deployments were found that match the given
            id or prefix.
    """
    from zenml.utils.uuid_utils import is_valid_uuid

    # First interpret as full UUID
    if is_valid_uuid(id_or_prefix):
        id_ = (
            UUID(id_or_prefix)
            if isinstance(id_or_prefix, str)
            else id_or_prefix
        )
        return self.zen_store.get_deployment(id_, hydrate=hydrate)

    list_kwargs: Dict[str, Any] = dict(
        id=f"startswith:{id_or_prefix}",
        hydrate=hydrate,
    )
    scope = ""
    if project:
        list_kwargs["project"] = project
        scope = f" in project {project}"

    entity = self.list_deployments(**list_kwargs)

    # If only a single entity is found, return it.
    if entity.total == 1:
        return entity.items[0]

    # If no entity is found, raise an error.
    if entity.total == 0:
        raise KeyError(
            f"No deployment have been found that have either an id or "
            f"prefix that matches the provided string '{id_or_prefix}'{scope}."
        )

    raise ZenKeyError(
        f"{entity.total} deployments have been found{scope} that have "
        f"an ID that matches the provided "
        f"string '{id_or_prefix}':\n"
        f"{[entity.items]}.\n"
        f"Please use the id to uniquely identify "
        f"only one of the deployments."
    )
get_event_source(name_id_or_prefix: Union[UUID, str], allow_name_prefix_match: bool = True, project: Optional[Union[str, UUID]] = None, hydrate: bool = True) -> EventSourceResponse

Get an event source by name, ID or prefix.

Parameters:

Name Type Description Default
name_id_or_prefix Union[UUID, str]

The name, ID or prefix of the stack.

required
allow_name_prefix_match bool

If True, allow matching by name prefix.

True
project Optional[Union[str, UUID]]

The project name/ID to filter by.

None
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

True

Returns:

Type Description
EventSourceResponse

The event_source.

Source code in src/zenml/client.py
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
@_fail_for_sql_zen_store
def get_event_source(
    self,
    name_id_or_prefix: Union[UUID, str],
    allow_name_prefix_match: bool = True,
    project: Optional[Union[str, UUID]] = None,
    hydrate: bool = True,
) -> EventSourceResponse:
    """Get an event source by name, ID or prefix.

    Args:
        name_id_or_prefix: The name, ID or prefix of the stack.
        allow_name_prefix_match: If True, allow matching by name prefix.
        project: The project name/ID to filter by.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        The event_source.
    """
    return self._get_entity_by_id_or_name_or_prefix(
        get_method=self.zen_store.get_event_source,
        list_method=self.list_event_sources,
        name_id_or_prefix=name_id_or_prefix,
        allow_name_prefix_match=allow_name_prefix_match,
        project=project,
        hydrate=hydrate,
    )
get_flavor(name_id_or_prefix: str, allow_name_prefix_match: bool = True, hydrate: bool = True) -> FlavorResponse

Get a stack component flavor.

Parameters:

Name Type Description Default
name_id_or_prefix str

The name, ID or prefix to the id of the flavor to get.

required
allow_name_prefix_match bool

If True, allow matching by name prefix.

True
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

True

Returns:

Type Description
FlavorResponse

The stack component flavor.

Source code in src/zenml/client.py
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
def get_flavor(
    self,
    name_id_or_prefix: str,
    allow_name_prefix_match: bool = True,
    hydrate: bool = True,
) -> FlavorResponse:
    """Get a stack component flavor.

    Args:
        name_id_or_prefix: The name, ID or prefix to the id of the flavor
            to get.
        allow_name_prefix_match: If True, allow matching by name prefix.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        The stack component flavor.
    """
    return self._get_entity_by_id_or_name_or_prefix(
        get_method=self.zen_store.get_flavor,
        list_method=self.list_flavors,
        name_id_or_prefix=name_id_or_prefix,
        allow_name_prefix_match=allow_name_prefix_match,
        hydrate=hydrate,
    )
get_flavor_by_name_and_type(name: str, component_type: StackComponentType) -> FlavorResponse

Fetches a registered flavor.

Parameters:

Name Type Description Default
component_type StackComponentType

The type of the component to fetch.

required
name str

The name of the flavor to fetch.

required

Returns:

Type Description
FlavorResponse

The registered flavor.

Raises:

Type Description
KeyError

If no flavor exists for the given type and name.

Source code in src/zenml/client.py
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
def get_flavor_by_name_and_type(
    self, name: str, component_type: "StackComponentType"
) -> FlavorResponse:
    """Fetches a registered flavor.

    Args:
        component_type: The type of the component to fetch.
        name: The name of the flavor to fetch.

    Returns:
        The registered flavor.

    Raises:
        KeyError: If no flavor exists for the given type and name.
    """
    logger.debug(
        f"Fetching the flavor of type {component_type} with name {name}."
    )

    if not (
        flavors := self.list_flavors(
            type=component_type, name=name, hydrate=True
        ).items
    ):
        raise KeyError(
            f"No flavor with name '{name}' and type '{component_type}' "
            "exists."
        )
    if len(flavors) > 1:
        raise KeyError(
            f"More than one flavor with name {name} and type "
            f"{component_type} exists."
        )

    return flavors[0]
get_flavors_by_type(component_type: StackComponentType) -> Page[FlavorResponse]

Fetches the list of flavor for a stack component type.

Parameters:

Name Type Description Default
component_type StackComponentType

The type of the component to fetch.

required

Returns:

Type Description
Page[FlavorResponse]

The list of flavors.

Source code in src/zenml/client.py
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
def get_flavors_by_type(
    self, component_type: "StackComponentType"
) -> Page[FlavorResponse]:
    """Fetches the list of flavor for a stack component type.

    Args:
        component_type: The type of the component to fetch.

    Returns:
        The list of flavors.
    """
    logger.debug(f"Fetching the flavors of type {component_type}.")

    return self.list_flavors(
        type=component_type,
    )
get_instance() -> Optional[Client] classmethod

Return the Client singleton instance.

Returns:

Type Description
Optional[Client]

The Client singleton instance or None, if the Client hasn't

Optional[Client]

been initialized yet.

Source code in src/zenml/client.py
387
388
389
390
391
392
393
394
395
@classmethod
def get_instance(cls) -> Optional["Client"]:
    """Return the Client singleton instance.

    Returns:
        The Client singleton instance or None, if the Client hasn't
        been initialized yet.
    """
    return cls._global_client
get_model(model_name_or_id: Union[str, UUID], project: Optional[Union[str, UUID]] = None, hydrate: bool = True, bypass_lazy_loader: bool = False) -> ModelResponse

Get an existing model from Model Control Plane.

Parameters:

Name Type Description Default
model_name_or_id Union[str, UUID]

name or id of the model to be retrieved.

required
project Optional[Union[str, UUID]]

The project name/ID to filter by.

None
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

True
bypass_lazy_loader bool

Whether to bypass the lazy loader.

False

Returns:

Type Description
ModelResponse

The model of interest.

Source code in src/zenml/client.py
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
def get_model(
    self,
    model_name_or_id: Union[str, UUID],
    project: Optional[Union[str, UUID]] = None,
    hydrate: bool = True,
    bypass_lazy_loader: bool = False,
) -> ModelResponse:
    """Get an existing model from Model Control Plane.

    Args:
        model_name_or_id: name or id of the model to be retrieved.
        project: The project name/ID to filter by.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.
        bypass_lazy_loader: Whether to bypass the lazy loader.

    Returns:
        The model of interest.
    """
    if not bypass_lazy_loader:
        if cll := client_lazy_loader(
            "get_model",
            model_name_or_id=model_name_or_id,
            hydrate=hydrate,
            project=project,
        ):
            return cll  # type: ignore[return-value]

    return self._get_entity_by_id_or_name_or_prefix(
        get_method=self.zen_store.get_model,
        list_method=self.list_models,
        name_id_or_prefix=model_name_or_id,
        project=project,
        hydrate=hydrate,
    )
get_model_version(model_name_or_id: Optional[Union[str, UUID]] = None, model_version_name_or_number_or_id: Optional[Union[str, int, ModelStages, UUID]] = None, project: Optional[Union[str, UUID]] = None, hydrate: bool = True) -> ModelVersionResponse

Get an existing model version from Model Control Plane.

Parameters:

Name Type Description Default
model_name_or_id Optional[Union[str, UUID]]

name or id of the model containing the model version.

None
model_version_name_or_number_or_id Optional[Union[str, int, ModelStages, UUID]]

name, id, stage or number of the model version to be retrieved. If skipped - latest version is retrieved.

None
project Optional[Union[str, UUID]]

The project name/ID to filter by.

None
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

True

Returns:

Type Description
ModelVersionResponse

The model version of interest.

Raises:

Type Description
RuntimeError

In case method inputs don't adhere to restrictions.

KeyError

In case no model version with the identifiers exists.

ValueError

In case retrieval is attempted using non UUID model version identifier and no model identifier provided.

Source code in src/zenml/client.py
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
def get_model_version(
    self,
    model_name_or_id: Optional[Union[str, UUID]] = None,
    model_version_name_or_number_or_id: Optional[
        Union[str, int, ModelStages, UUID]
    ] = None,
    project: Optional[Union[str, UUID]] = None,
    hydrate: bool = True,
) -> ModelVersionResponse:
    """Get an existing model version from Model Control Plane.

    Args:
        model_name_or_id: name or id of the model containing the model
            version.
        model_version_name_or_number_or_id: name, id, stage or number of
            the model version to be retrieved. If skipped - latest version
            is retrieved.
        project: The project name/ID to filter by.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        The model version of interest.

    Raises:
        RuntimeError: In case method inputs don't adhere to restrictions.
        KeyError: In case no model version with the identifiers exists.
        ValueError: In case retrieval is attempted using non UUID model version
            identifier and no model identifier provided.
    """
    if (
        not is_valid_uuid(model_version_name_or_number_or_id)
        and model_name_or_id is None
    ):
        raise ValueError(
            "No model identifier provided and model version identifier "
            f"`{model_version_name_or_number_or_id}` is not a valid UUID."
        )
    if cll := client_lazy_loader(
        "get_model_version",
        model_name_or_id=model_name_or_id,
        model_version_name_or_number_or_id=model_version_name_or_number_or_id,
        project=project,
        hydrate=hydrate,
    ):
        return cll  # type: ignore[return-value]

    if model_version_name_or_number_or_id is None:
        model_version_name_or_number_or_id = ModelStages.LATEST

    if isinstance(model_version_name_or_number_or_id, UUID):
        return self.zen_store.get_model_version(
            model_version_id=model_version_name_or_number_or_id,
            hydrate=hydrate,
        )
    elif isinstance(model_version_name_or_number_or_id, int):
        model_versions = self.zen_store.list_model_versions(
            model_version_filter_model=ModelVersionFilter(
                model=model_name_or_id,
                number=model_version_name_or_number_or_id,
                project=project or self.active_project.id,
            ),
            hydrate=hydrate,
        ).items
    elif isinstance(model_version_name_or_number_or_id, str):
        if model_version_name_or_number_or_id == ModelStages.LATEST:
            model_versions = self.zen_store.list_model_versions(
                model_version_filter_model=ModelVersionFilter(
                    model=model_name_or_id,
                    sort_by=f"{SorterOps.DESCENDING}:number",
                    project=project or self.active_project.id,
                ),
                hydrate=hydrate,
            ).items

            if len(model_versions) > 0:
                model_versions = [model_versions[0]]
            else:
                model_versions = []
        elif model_version_name_or_number_or_id in ModelStages.values():
            model_versions = self.zen_store.list_model_versions(
                model_version_filter_model=ModelVersionFilter(
                    model=model_name_or_id,
                    stage=model_version_name_or_number_or_id,
                    project=project or self.active_project.id,
                ),
                hydrate=hydrate,
            ).items
        else:
            model_versions = self.zen_store.list_model_versions(
                model_version_filter_model=ModelVersionFilter(
                    model=model_name_or_id,
                    name=model_version_name_or_number_or_id,
                    project=project or self.active_project.id,
                ),
                hydrate=hydrate,
            ).items
    else:
        raise RuntimeError(
            f"The model version identifier "
            f"`{model_version_name_or_number_or_id}` is not"
            f"of the correct type."
        )

    if len(model_versions) == 1:
        return model_versions[0]
    elif len(model_versions) == 0:
        raise KeyError(
            f"No model version found for model "
            f"`{model_name_or_id}` with version identifier "
            f"`{model_version_name_or_number_or_id}`."
        )
    else:
        raise RuntimeError(
            f"The model version identifier "
            f"`{model_version_name_or_number_or_id}` is not"
            f"unique for model `{model_name_or_id}`."
        )
get_pipeline(name_id_or_prefix: Union[str, UUID], project: Optional[Union[str, UUID]] = None, hydrate: bool = True) -> PipelineResponse

Get a pipeline by name, id or prefix.

Parameters:

Name Type Description Default
name_id_or_prefix Union[str, UUID]

The name, ID or ID prefix of the pipeline.

required
project Optional[Union[str, UUID]]

The project name/ID to filter by.

None
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

True

Returns:

Type Description
PipelineResponse

The pipeline.

Source code in src/zenml/client.py
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
def get_pipeline(
    self,
    name_id_or_prefix: Union[str, UUID],
    project: Optional[Union[str, UUID]] = None,
    hydrate: bool = True,
) -> PipelineResponse:
    """Get a pipeline by name, id or prefix.

    Args:
        name_id_or_prefix: The name, ID or ID prefix of the pipeline.
        project: The project name/ID to filter by.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        The pipeline.
    """
    return self._get_entity_by_id_or_name_or_prefix(
        get_method=self.zen_store.get_pipeline,
        list_method=self.list_pipelines,
        name_id_or_prefix=name_id_or_prefix,
        project=project,
        hydrate=hydrate,
    )
get_pipeline_run(name_id_or_prefix: Union[str, UUID], allow_name_prefix_match: bool = True, project: Optional[Union[str, UUID]] = None, hydrate: bool = True) -> PipelineRunResponse

Gets a pipeline run by name, ID, or prefix.

Parameters:

Name Type Description Default
name_id_or_prefix Union[str, UUID]

Name, ID, or prefix of the pipeline run.

required
allow_name_prefix_match bool

If True, allow matching by name prefix.

True
project Optional[Union[str, UUID]]

The project name/ID to filter by.

None
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

True

Returns:

Type Description
PipelineRunResponse

The pipeline run.

Source code in src/zenml/client.py
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
def get_pipeline_run(
    self,
    name_id_or_prefix: Union[str, UUID],
    allow_name_prefix_match: bool = True,
    project: Optional[Union[str, UUID]] = None,
    hydrate: bool = True,
) -> PipelineRunResponse:
    """Gets a pipeline run by name, ID, or prefix.

    Args:
        name_id_or_prefix: Name, ID, or prefix of the pipeline run.
        allow_name_prefix_match: If True, allow matching by name prefix.
        project: The project name/ID to filter by.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        The pipeline run.
    """
    return self._get_entity_by_id_or_name_or_prefix(
        get_method=self.zen_store.get_run,
        list_method=self.list_pipeline_runs,
        name_id_or_prefix=name_id_or_prefix,
        allow_name_prefix_match=allow_name_prefix_match,
        project=project,
        hydrate=hydrate,
    )
get_project(name_id_or_prefix: Optional[Union[UUID, str]], allow_name_prefix_match: bool = True, hydrate: bool = True) -> ProjectResponse

Gets a project.

Parameters:

Name Type Description Default
name_id_or_prefix Optional[Union[UUID, str]]

The name or ID of the project.

required
allow_name_prefix_match bool

If True, allow matching by name prefix.

True
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

True

Returns:

Type Description
ProjectResponse

The project

Source code in src/zenml/client.py
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
def get_project(
    self,
    name_id_or_prefix: Optional[Union[UUID, str]],
    allow_name_prefix_match: bool = True,
    hydrate: bool = True,
) -> ProjectResponse:
    """Gets a project.

    Args:
        name_id_or_prefix: The name or ID of the project.
        allow_name_prefix_match: If True, allow matching by name prefix.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        The project
    """
    if not name_id_or_prefix:
        return self.active_project
    return self._get_entity_by_id_or_name_or_prefix(
        get_method=self.zen_store.get_project,
        list_method=self.list_projects,
        name_id_or_prefix=name_id_or_prefix,
        allow_name_prefix_match=allow_name_prefix_match,
        hydrate=hydrate,
    )
get_run_step(step_run_id: UUID, hydrate: bool = True) -> StepRunResponse

Get a step run by ID.

Parameters:

Name Type Description Default
step_run_id UUID

The ID of the step run to get.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

True

Returns:

Type Description
StepRunResponse

The step run.

Source code in src/zenml/client.py
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
def get_run_step(
    self,
    step_run_id: UUID,
    hydrate: bool = True,
) -> StepRunResponse:
    """Get a step run by ID.

    Args:
        step_run_id: The ID of the step run to get.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        The step run.
    """
    return self.zen_store.get_run_step(
        step_run_id,
        hydrate=hydrate,
    )
get_run_template(name_id_or_prefix: Union[str, UUID], project: Optional[Union[str, UUID]] = None, hydrate: bool = True) -> RunTemplateResponse

Get a run template.

Parameters:

Name Type Description Default
name_id_or_prefix Union[str, UUID]

Name/ID/ID prefix of the template to get.

required
project Optional[Union[str, UUID]]

The project name/ID to filter by.

None
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

True

Returns:

Type Description
RunTemplateResponse

The run template.

Source code in src/zenml/client.py
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
def get_run_template(
    self,
    name_id_or_prefix: Union[str, UUID],
    project: Optional[Union[str, UUID]] = None,
    hydrate: bool = True,
) -> RunTemplateResponse:
    """Get a run template.

    Args:
        name_id_or_prefix: Name/ID/ID prefix of the template to get.
        project: The project name/ID to filter by.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        The run template.
    """
    return self._get_entity_by_id_or_name_or_prefix(
        get_method=self.zen_store.get_run_template,
        list_method=self.list_run_templates,
        name_id_or_prefix=name_id_or_prefix,
        allow_name_prefix_match=False,
        project=project,
        hydrate=hydrate,
    )
get_schedule(name_id_or_prefix: Union[str, UUID], allow_name_prefix_match: bool = True, project: Optional[Union[str, UUID]] = None, hydrate: bool = True) -> ScheduleResponse

Get a schedule by name, id or prefix.

Parameters:

Name Type Description Default
name_id_or_prefix Union[str, UUID]

The name, id or prefix of the schedule.

required
allow_name_prefix_match bool

If True, allow matching by name prefix.

True
project Optional[Union[str, UUID]]

The project name/ID to filter by.

None
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

True

Returns:

Type Description
ScheduleResponse

The schedule.

Source code in src/zenml/client.py
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
def get_schedule(
    self,
    name_id_or_prefix: Union[str, UUID],
    allow_name_prefix_match: bool = True,
    project: Optional[Union[str, UUID]] = None,
    hydrate: bool = True,
) -> ScheduleResponse:
    """Get a schedule by name, id or prefix.

    Args:
        name_id_or_prefix: The name, id or prefix of the schedule.
        allow_name_prefix_match: If True, allow matching by name prefix.
        project: The project name/ID to filter by.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        The schedule.
    """
    return self._get_entity_by_id_or_name_or_prefix(
        get_method=self.zen_store.get_schedule,
        list_method=self.list_schedules,
        name_id_or_prefix=name_id_or_prefix,
        allow_name_prefix_match=allow_name_prefix_match,
        project=project,
        hydrate=hydrate,
    )
get_secret(name_id_or_prefix: Union[str, UUID], private: Optional[bool] = None, allow_partial_name_match: bool = True, allow_partial_id_match: bool = True, hydrate: bool = True) -> SecretResponse

Get a secret.

Get a secret identified by a name, ID or prefix of the name or ID and optionally a scope.

If a private status is not provided, privately scoped secrets will be searched for first, followed by publicly scoped secrets. When a name or prefix is used instead of a UUID value, each scope is first searched for an exact match, then for a ID prefix or name substring match before moving on to the next scope.

Parameters:

Name Type Description Default
name_id_or_prefix Union[str, UUID]

The name, ID or prefix to the id of the secret to get.

required
private Optional[bool]

Whether the secret is private. If not set, all secrets will be searched for, prioritizing privately scoped secrets.

None
allow_partial_name_match bool

If True, allow partial name matches.

True
allow_partial_id_match bool

If True, allow partial ID matches.

True
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

True

Returns:

Type Description
SecretResponse

The secret.

Raises:

Type Description
KeyError

If no secret is found.

ZenKeyError

If multiple secrets are found.

NotImplementedError

If centralized secrets management is not enabled.

Source code in src/zenml/client.py
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
def get_secret(
    self,
    name_id_or_prefix: Union[str, UUID],
    private: Optional[bool] = None,
    allow_partial_name_match: bool = True,
    allow_partial_id_match: bool = True,
    hydrate: bool = True,
) -> SecretResponse:
    """Get a secret.

    Get a secret identified by a name, ID or prefix of the name or ID and
    optionally a scope.

    If a private status is not provided, privately scoped secrets will be
    searched for first, followed by publicly scoped secrets. When a name or
    prefix is used instead of a UUID value, each scope is first searched for
    an exact match, then for a ID prefix or name substring match before
    moving on to the next scope.

    Args:
        name_id_or_prefix: The name, ID or prefix to the id of the secret
            to get.
        private: Whether the secret is private. If not set, all secrets will
            be searched for, prioritizing privately scoped secrets.
        allow_partial_name_match: If True, allow partial name matches.
        allow_partial_id_match: If True, allow partial ID matches.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        The secret.

    Raises:
        KeyError: If no secret is found.
        ZenKeyError: If multiple secrets are found.
        NotImplementedError: If centralized secrets management is not
            enabled.
    """
    from zenml.utils.uuid_utils import is_valid_uuid

    try:
        # First interpret as full UUID
        if is_valid_uuid(name_id_or_prefix):
            # Fetch by ID; filter by scope if provided
            secret = self.zen_store.get_secret(
                secret_id=UUID(name_id_or_prefix)
                if isinstance(name_id_or_prefix, str)
                else name_id_or_prefix,
                hydrate=hydrate,
            )
            if private is not None and secret.private != private:
                raise KeyError(
                    f"No secret found with ID {str(name_id_or_prefix)}"
                )

            return secret
    except NotImplementedError:
        raise NotImplementedError(
            "centralized secrets management is not supported or explicitly "
            "disabled in the target ZenML deployment."
        )

    # If not a UUID, try to find by name and then by prefix
    assert not isinstance(name_id_or_prefix, UUID)

    # Private statuses to search in order of priority
    search_private_statuses = (
        [False, True] if private is None else [private]
    )

    secrets = self.list_secrets(
        logical_operator=LogicalOperators.OR,
        name=f"contains:{name_id_or_prefix}"
        if allow_partial_name_match
        else f"equals:{name_id_or_prefix}",
        id=f"startswith:{name_id_or_prefix}"
        if allow_partial_id_match
        else None,
        hydrate=hydrate,
    )

    for search_private_status in search_private_statuses:
        partial_matches: List[SecretResponse] = []
        for secret in secrets.items:
            if secret.private != search_private_status:
                continue
            # Exact match
            if secret.name == name_id_or_prefix:
                # Need to fetch the secret again to get the secret values
                return self.zen_store.get_secret(
                    secret_id=secret.id,
                    hydrate=hydrate,
                )
            # Partial match
            partial_matches.append(secret)

        if len(partial_matches) > 1:
            match_summary = "\n".join(
                [
                    f"[{secret.id}]: name = {secret.name}"
                    for secret in partial_matches
                ]
            )
            raise ZenKeyError(
                f"{len(partial_matches)} secrets have been found that have "
                f"a name or ID that matches the provided "
                f"string '{name_id_or_prefix}':\n"
                f"{match_summary}.\n"
                f"Please use the id to uniquely identify "
                f"only one of the secrets."
            )

        # If only a single secret is found, return it
        if len(partial_matches) == 1:
            # Need to fetch the secret again to get the secret values
            return self.zen_store.get_secret(
                secret_id=partial_matches[0].id,
                hydrate=hydrate,
            )
    private_status = ""
    if private is not None:
        private_status = "private " if private else "public "
    msg = (
        f"No {private_status}secret found with name, ID or prefix "
        f"'{name_id_or_prefix}'"
    )

    raise KeyError(msg)
get_secret_by_name_and_private_status(name: str, private: Optional[bool] = None, hydrate: bool = True) -> SecretResponse

Fetches a registered secret with a given name and optional private status.

This is a version of get_secret that restricts the search to a given name and an optional private status, without doing any prefix or UUID matching.

If no private status is provided, the search will be done first for private secrets, then for public secrets.

Parameters:

Name Type Description Default
name str

The name of the secret to get.

required
private Optional[bool]

The private status of the secret to get.

None
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

True

Returns:

Type Description
SecretResponse

The registered secret.

Raises:

Type Description
KeyError

If no secret exists for the given name in the given scope.

Source code in src/zenml/client.py
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
def get_secret_by_name_and_private_status(
    self,
    name: str,
    private: Optional[bool] = None,
    hydrate: bool = True,
) -> SecretResponse:
    """Fetches a registered secret with a given name and optional private status.

    This is a version of get_secret that restricts the search to a given
    name and an optional private status, without doing any prefix or UUID
    matching.

    If no private status is provided, the search will be done first for
    private secrets, then for public secrets.

    Args:
        name: The name of the secret to get.
        private: The private status of the secret to get.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        The registered secret.

    Raises:
        KeyError: If no secret exists for the given name in the given scope.
    """
    logger.debug(
        f"Fetching the secret with name '{name}' and private status "
        f"'{private}'."
    )

    # Private statuses to search in order of priority
    search_private_statuses = (
        [False, True] if private is None else [private]
    )

    for search_private_status in search_private_statuses:
        secrets = self.list_secrets(
            logical_operator=LogicalOperators.AND,
            name=f"equals:{name}",
            private=search_private_status,
            hydrate=hydrate,
        )

        if len(secrets.items) >= 1:
            # Need to fetch the secret again to get the secret values
            return self.zen_store.get_secret(
                secret_id=secrets.items[0].id, hydrate=hydrate
            )

    private_status = ""
    if private is not None:
        private_status = "private " if private else "public "
    msg = f"No {private_status}secret with name '{name}' was found"

    raise KeyError(msg)
get_service(name_id_or_prefix: Union[str, UUID], allow_name_prefix_match: bool = True, hydrate: bool = True, type: Optional[str] = None, project: Optional[Union[str, UUID]] = None) -> ServiceResponse

Gets a service.

Parameters:

Name Type Description Default
name_id_or_prefix Union[str, UUID]

The name or ID of the service.

required
allow_name_prefix_match bool

If True, allow matching by name prefix.

True
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

True
type Optional[str]

The type of the service.

None
project Optional[Union[str, UUID]]

The project name/ID to filter by.

None

Returns:

Type Description
ServiceResponse

The Service

Source code in src/zenml/client.py
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
def get_service(
    self,
    name_id_or_prefix: Union[str, UUID],
    allow_name_prefix_match: bool = True,
    hydrate: bool = True,
    type: Optional[str] = None,
    project: Optional[Union[str, UUID]] = None,
) -> ServiceResponse:
    """Gets a service.

    Args:
        name_id_or_prefix: The name or ID of the service.
        allow_name_prefix_match: If True, allow matching by name prefix.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.
        type: The type of the service.
        project: The project name/ID to filter by.

    Returns:
        The Service
    """

    def type_scoped_list_method(
        hydrate: bool = True,
        **kwargs: Any,
    ) -> Page[ServiceResponse]:
        """Call `zen_store.list_services` with type scoping.

        Args:
            hydrate: Flag deciding whether to hydrate the output model(s)
                by including metadata fields in the response.
            **kwargs: Keyword arguments to pass to `ServiceFilterModel`.

        Returns:
            The type-scoped list of services.
        """
        service_filter_model = ServiceFilter(**kwargs)
        if type:
            service_filter_model.set_type(type=type)
        return self.zen_store.list_services(
            filter_model=service_filter_model,
            hydrate=hydrate,
        )

    return self._get_entity_by_id_or_name_or_prefix(
        get_method=self.zen_store.get_service,
        list_method=type_scoped_list_method,
        name_id_or_prefix=name_id_or_prefix,
        allow_name_prefix_match=allow_name_prefix_match,
        project=project,
        hydrate=hydrate,
    )
get_service_account(name_id_or_prefix: Union[str, UUID], allow_name_prefix_match: bool = True, hydrate: bool = True) -> ServiceAccountResponse

Gets a service account.

Parameters:

Name Type Description Default
name_id_or_prefix Union[str, UUID]

The name or ID of the service account.

required
allow_name_prefix_match bool

If True, allow matching by name prefix.

True
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

True

Returns:

Type Description
ServiceAccountResponse

The ServiceAccount

Source code in src/zenml/client.py
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
def get_service_account(
    self,
    name_id_or_prefix: Union[str, UUID],
    allow_name_prefix_match: bool = True,
    hydrate: bool = True,
) -> ServiceAccountResponse:
    """Gets a service account.

    Args:
        name_id_or_prefix: The name or ID of the service account.
        allow_name_prefix_match: If True, allow matching by name prefix.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        The ServiceAccount
    """
    return self._get_entity_by_id_or_name_or_prefix(
        get_method=self.zen_store.get_service_account,
        list_method=self.list_service_accounts,
        name_id_or_prefix=name_id_or_prefix,
        allow_name_prefix_match=allow_name_prefix_match,
        hydrate=hydrate,
    )
get_service_connector(name_id_or_prefix: Union[str, UUID], allow_name_prefix_match: bool = True, load_secrets: bool = False, hydrate: bool = True) -> ServiceConnectorResponse

Fetches a registered service connector.

Parameters:

Name Type Description Default
name_id_or_prefix Union[str, UUID]

The id of the service connector to fetch.

required
allow_name_prefix_match bool

If True, allow matching by name prefix.

True
load_secrets bool

If True, load the secrets for the service connector.

False
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

True

Returns:

Type Description
ServiceConnectorResponse

The registered service connector.

Source code in src/zenml/client.py
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
def get_service_connector(
    self,
    name_id_or_prefix: Union[str, UUID],
    allow_name_prefix_match: bool = True,
    load_secrets: bool = False,
    hydrate: bool = True,
) -> ServiceConnectorResponse:
    """Fetches a registered service connector.

    Args:
        name_id_or_prefix: The id of the service connector to fetch.
        allow_name_prefix_match: If True, allow matching by name prefix.
        load_secrets: If True, load the secrets for the service connector.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        The registered service connector.
    """
    connector = self._get_entity_by_id_or_name_or_prefix(
        get_method=self.zen_store.get_service_connector,
        list_method=self.list_service_connectors,
        name_id_or_prefix=name_id_or_prefix,
        allow_name_prefix_match=allow_name_prefix_match,
        hydrate=hydrate,
    )

    if load_secrets and connector.secret_id:
        client = Client()
        try:
            secret = client.get_secret(
                name_id_or_prefix=connector.secret_id,
                allow_partial_id_match=False,
                allow_partial_name_match=False,
            )
        except KeyError as err:
            logger.error(
                "Unable to retrieve secret values associated with "
                f"service connector '{connector.name}': {err}"
            )
        else:
            # Add secret values to connector configuration
            connector.secrets.update(secret.values)

    return connector
get_service_connector_client(name_id_or_prefix: Union[UUID, str], resource_type: Optional[str] = None, resource_id: Optional[str] = None, verify: bool = False) -> ServiceConnector

Get the client side of a service connector instance to use with a local client.

Parameters:

Name Type Description Default
name_id_or_prefix Union[UUID, str]

The name, id or prefix of the service connector to use.

required
resource_type Optional[str]

The type of the resource to connect to. If not provided, the resource type from the service connector configuration will be used.

None
resource_id Optional[str]

The ID of a particular resource instance to configure the local client to connect to. If the connector instance is already configured with a resource ID that is not the same or equivalent to the one requested, a ValueError exception is raised. May be omitted for connectors and resource types that do not support multiple resource instances.

None
verify bool

Whether to verify that the service connector configuration and credentials can be used to gain access to the resource.

False

Returns:

Type Description
ServiceConnector

The client side of the indicated service connector instance that can

ServiceConnector

be used to connect to the resource locally.

Source code in src/zenml/client.py
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
def get_service_connector_client(
    self,
    name_id_or_prefix: Union[UUID, str],
    resource_type: Optional[str] = None,
    resource_id: Optional[str] = None,
    verify: bool = False,
) -> "ServiceConnector":
    """Get the client side of a service connector instance to use with a local client.

    Args:
        name_id_or_prefix: The name, id or prefix of the service connector
            to use.
        resource_type: The type of the resource to connect to. If not
            provided, the resource type from the service connector
            configuration will be used.
        resource_id: The ID of a particular resource instance to configure
            the local client to connect to. If the connector instance is
            already configured with a resource ID that is not the same or
            equivalent to the one requested, a `ValueError` exception is
            raised. May be omitted for connectors and resource types that do
            not support multiple resource instances.
        verify: Whether to verify that the service connector configuration
            and credentials can be used to gain access to the resource.

    Returns:
        The client side of the indicated service connector instance that can
        be used to connect to the resource locally.
    """
    from zenml.service_connectors.service_connector_registry import (
        service_connector_registry,
    )

    # Get the service connector model
    service_connector = self.get_service_connector(
        name_id_or_prefix=name_id_or_prefix,
        allow_name_prefix_match=False,
    )

    connector_type = self.get_service_connector_type(
        service_connector.type
    )

    # Prefer to fetch the connector client from the server if the
    # implementation if available there, because some auth methods rely on
    # the server-side authentication environment
    if connector_type.remote:
        connector_client_model = (
            self.zen_store.get_service_connector_client(
                service_connector_id=service_connector.id,
                resource_type=resource_type,
                resource_id=resource_id,
            )
        )

        connector_client = (
            service_connector_registry.instantiate_connector(
                model=connector_client_model
            )
        )

        if verify:
            # Verify the connector client on the local machine, because the
            # server-side implementation may not be able to do so
            connector_client.verify()
    else:
        connector_instance = (
            service_connector_registry.instantiate_connector(
                model=service_connector
            )
        )

        # Fetch the connector client
        connector_client = connector_instance.get_connector_client(
            resource_type=resource_type,
            resource_id=resource_id,
        )

    return connector_client
get_service_connector_type(connector_type: str) -> ServiceConnectorTypeModel

Returns the requested service connector type.

Parameters:

Name Type Description Default
connector_type str

the service connector type identifier.

required

Returns:

Type Description
ServiceConnectorTypeModel

The requested service connector type.

Source code in src/zenml/client.py
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
def get_service_connector_type(
    self,
    connector_type: str,
) -> ServiceConnectorTypeModel:
    """Returns the requested service connector type.

    Args:
        connector_type: the service connector type identifier.

    Returns:
        The requested service connector type.
    """
    return self.zen_store.get_service_connector_type(
        connector_type=connector_type,
    )
get_settings(hydrate: bool = True) -> ServerSettingsResponse

Get the server settings.

Parameters:

Name Type Description Default
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

True

Returns:

Type Description
ServerSettingsResponse

The server settings.

Source code in src/zenml/client.py
709
710
711
712
713
714
715
716
717
718
719
def get_settings(self, hydrate: bool = True) -> ServerSettingsResponse:
    """Get the server settings.

    Args:
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        The server settings.
    """
    return self.zen_store.get_server_settings(hydrate=hydrate)
get_stack(name_id_or_prefix: Optional[Union[UUID, str]] = None, allow_name_prefix_match: bool = True, hydrate: bool = True) -> StackResponse

Get a stack by name, ID or prefix.

If no name, ID or prefix is provided, the active stack is returned.

Parameters:

Name Type Description Default
name_id_or_prefix Optional[Union[UUID, str]]

The name, ID or prefix of the stack.

None
allow_name_prefix_match bool

If True, allow matching by name prefix.

True
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

True

Returns:

Type Description
StackResponse

The stack.

Source code in src/zenml/client.py
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
def get_stack(
    self,
    name_id_or_prefix: Optional[Union[UUID, str]] = None,
    allow_name_prefix_match: bool = True,
    hydrate: bool = True,
) -> StackResponse:
    """Get a stack by name, ID or prefix.

    If no name, ID or prefix is provided, the active stack is returned.

    Args:
        name_id_or_prefix: The name, ID or prefix of the stack.
        allow_name_prefix_match: If True, allow matching by name prefix.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        The stack.
    """
    if name_id_or_prefix is not None:
        return self._get_entity_by_id_or_name_or_prefix(
            get_method=self.zen_store.get_stack,
            list_method=self.list_stacks,
            name_id_or_prefix=name_id_or_prefix,
            allow_name_prefix_match=allow_name_prefix_match,
            hydrate=hydrate,
        )
    else:
        return self.active_stack_model
get_stack_component(component_type: StackComponentType, name_id_or_prefix: Optional[Union[str, UUID]] = None, allow_name_prefix_match: bool = True, hydrate: bool = True) -> ComponentResponse

Fetches a registered stack component.

If the name_id_or_prefix is provided, it will try to fetch the component with the corresponding identifier. If not, it will try to fetch the active component of the given type.

Parameters:

Name Type Description Default
component_type StackComponentType

The type of the component to fetch

required
name_id_or_prefix Optional[Union[str, UUID]]

The id of the component to fetch.

None
allow_name_prefix_match bool

If True, allow matching by name prefix.

True
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

True

Returns:

Type Description
ComponentResponse

The registered stack component.

Raises:

Type Description
KeyError

If no name_id_or_prefix is provided and no such component is part of the active stack.

Source code in src/zenml/client.py
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
def get_stack_component(
    self,
    component_type: StackComponentType,
    name_id_or_prefix: Optional[Union[str, UUID]] = None,
    allow_name_prefix_match: bool = True,
    hydrate: bool = True,
) -> ComponentResponse:
    """Fetches a registered stack component.

    If the name_id_or_prefix is provided, it will try to fetch the component
    with the corresponding identifier. If not, it will try to fetch the
    active component of the given type.

    Args:
        component_type: The type of the component to fetch
        name_id_or_prefix: The id of the component to fetch.
        allow_name_prefix_match: If True, allow matching by name prefix.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        The registered stack component.

    Raises:
        KeyError: If no name_id_or_prefix is provided and no such component
            is part of the active stack.
    """
    # If no `name_id_or_prefix` provided, try to get the active component.
    if not name_id_or_prefix:
        components = self.active_stack_model.components.get(
            component_type, None
        )
        if components:
            return components[0]
        raise KeyError(
            "No name_id_or_prefix provided and there is no active "
            f"{component_type} in the current active stack."
        )

    # Else, try to fetch the component with an explicit type filter
    def type_scoped_list_method(
        hydrate: bool = False,
        **kwargs: Any,
    ) -> Page[ComponentResponse]:
        """Call `zen_store.list_stack_components` with type scoping.

        Args:
            hydrate: Flag deciding whether to hydrate the output model(s)
                by including metadata fields in the response.
            **kwargs: Keyword arguments to pass to `ComponentFilterModel`.

        Returns:
            The type-scoped list of components.
        """
        component_filter_model = ComponentFilter(**kwargs)
        component_filter_model.set_scope_type(
            component_type=component_type
        )
        return self.zen_store.list_stack_components(
            component_filter_model=component_filter_model,
            hydrate=hydrate,
        )

    return self._get_entity_by_id_or_name_or_prefix(
        get_method=self.zen_store.get_stack_component,
        list_method=type_scoped_list_method,
        name_id_or_prefix=name_id_or_prefix,
        allow_name_prefix_match=allow_name_prefix_match,
        hydrate=hydrate,
    )
get_tag(tag_name_or_id: Union[str, UUID], hydrate: bool = True) -> TagResponse

Get an existing tag.

Parameters:

Name Type Description Default
tag_name_or_id Union[str, UUID]

name or id of the tag to be retrieved.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

True

Returns:

Type Description
TagResponse

The tag of interest.

Source code in src/zenml/client.py
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
def get_tag(
    self,
    tag_name_or_id: Union[str, UUID],
    hydrate: bool = True,
) -> TagResponse:
    """Get an existing tag.

    Args:
        tag_name_or_id: name or id of the tag to be retrieved.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        The tag of interest.
    """
    return self.zen_store.get_tag(
        tag_name_or_id=tag_name_or_id,
        hydrate=hydrate,
    )
get_trigger(name_id_or_prefix: Union[UUID, str], allow_name_prefix_match: bool = True, project: Optional[Union[str, UUID]] = None, hydrate: bool = True) -> TriggerResponse

Get a trigger by name, ID or prefix.

Parameters:

Name Type Description Default
name_id_or_prefix Union[UUID, str]

The name, ID or prefix of the trigger.

required
allow_name_prefix_match bool

If True, allow matching by name prefix.

True
project Optional[Union[str, UUID]]

The project name/ID to filter by.

None
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

True

Returns:

Type Description
TriggerResponse

The trigger.

Source code in src/zenml/client.py
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
@_fail_for_sql_zen_store
def get_trigger(
    self,
    name_id_or_prefix: Union[UUID, str],
    allow_name_prefix_match: bool = True,
    project: Optional[Union[str, UUID]] = None,
    hydrate: bool = True,
) -> TriggerResponse:
    """Get a trigger by name, ID or prefix.

    Args:
        name_id_or_prefix: The name, ID or prefix of the trigger.
        allow_name_prefix_match: If True, allow matching by name prefix.
        project: The project name/ID to filter by.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        The trigger.
    """
    return self._get_entity_by_id_or_name_or_prefix(
        get_method=self.zen_store.get_trigger,
        list_method=self.list_triggers,
        name_id_or_prefix=name_id_or_prefix,
        allow_name_prefix_match=allow_name_prefix_match,
        project=project,
        hydrate=hydrate,
    )
get_trigger_execution(trigger_execution_id: UUID, hydrate: bool = True) -> TriggerExecutionResponse

Get a trigger execution by ID.

Parameters:

Name Type Description Default
trigger_execution_id UUID

The ID of the trigger execution to get.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

True

Returns:

Type Description
TriggerExecutionResponse

The trigger execution.

Source code in src/zenml/client.py
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
def get_trigger_execution(
    self,
    trigger_execution_id: UUID,
    hydrate: bool = True,
) -> TriggerExecutionResponse:
    """Get a trigger execution by ID.

    Args:
        trigger_execution_id: The ID of the trigger execution to get.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        The trigger execution.
    """
    return self.zen_store.get_trigger_execution(
        trigger_execution_id=trigger_execution_id, hydrate=hydrate
    )
get_user(name_id_or_prefix: Union[str, UUID], allow_name_prefix_match: bool = True, hydrate: bool = True) -> UserResponse

Gets a user.

Parameters:

Name Type Description Default
name_id_or_prefix Union[str, UUID]

The name or ID of the user.

required
allow_name_prefix_match bool

If True, allow matching by name prefix.

True
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

True

Returns:

Type Description
UserResponse

The User

Source code in src/zenml/client.py
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
def get_user(
    self,
    name_id_or_prefix: Union[str, UUID],
    allow_name_prefix_match: bool = True,
    hydrate: bool = True,
) -> UserResponse:
    """Gets a user.

    Args:
        name_id_or_prefix: The name or ID of the user.
        allow_name_prefix_match: If True, allow matching by name prefix.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        The User
    """
    return self._get_entity_by_id_or_name_or_prefix(
        get_method=self.zen_store.get_user,
        list_method=self.list_users,
        name_id_or_prefix=name_id_or_prefix,
        allow_name_prefix_match=allow_name_prefix_match,
        hydrate=hydrate,
    )
initialize(root: Optional[Path] = None) -> None staticmethod

Initializes a new ZenML repository at the given path.

Parameters:

Name Type Description Default
root Optional[Path]

The root directory where the repository should be created. If None, the current working directory is used.

None

Raises:

Type Description
InitializationException

If the root directory already contains a ZenML repository.

Source code in src/zenml/client.py
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
@staticmethod
def initialize(
    root: Optional[Path] = None,
) -> None:
    """Initializes a new ZenML repository at the given path.

    Args:
        root: The root directory where the repository should be created.
            If None, the current working directory is used.

    Raises:
        InitializationException: If the root directory already contains a
            ZenML repository.
    """
    root = root or Path.cwd()
    logger.debug("Initializing new repository at path %s.", root)
    if Client.is_repository_directory(root):
        raise InitializationException(
            f"Found existing ZenML repository at path '{root}'."
        )

    config_directory = str(root / REPOSITORY_DIRECTORY_NAME)
    io_utils.create_dir_recursive_if_not_exists(config_directory)
    # Initialize the repository configuration at the custom path
    Client(root=root)
is_inside_repository(file_path: str) -> bool staticmethod

Returns whether a file is inside the active ZenML repository.

Parameters:

Name Type Description Default
file_path str

A file path.

required

Returns:

Type Description
bool

True if the file is inside the active ZenML repository, False

bool

otherwise.

Source code in src/zenml/client.py
626
627
628
629
630
631
632
633
634
635
636
637
638
639
@staticmethod
def is_inside_repository(file_path: str) -> bool:
    """Returns whether a file is inside the active ZenML repository.

    Args:
        file_path: A file path.

    Returns:
        True if the file is inside the active ZenML repository, False
        otherwise.
    """
    if repo_path := Client.find_repository():
        return repo_path in Path(file_path).resolve().parents
    return False
is_repository_directory(path: Path) -> bool staticmethod

Checks whether a ZenML client exists at the given path.

Parameters:

Name Type Description Default
path Path

The path to check.

required

Returns:

Type Description
bool

True if a ZenML client exists at the given path,

bool

False otherwise.

Source code in src/zenml/client.py
537
538
539
540
541
542
543
544
545
546
547
548
549
@staticmethod
def is_repository_directory(path: Path) -> bool:
    """Checks whether a ZenML client exists at the given path.

    Args:
        path: The path to check.

    Returns:
        True if a ZenML client exists at the given path,
        False otherwise.
    """
    config_dir = path / REPOSITORY_DIRECTORY_NAME
    return fileio.isdir(str(config_dir))
list_actions(sort_by: str = 'created', page: int = PAGINATION_STARTING_PAGE, size: int = PAGE_SIZE_DEFAULT, logical_operator: LogicalOperators = LogicalOperators.AND, id: Optional[Union[UUID, str]] = None, created: Optional[datetime] = None, updated: Optional[datetime] = None, name: Optional[str] = None, flavor: Optional[str] = None, action_type: Optional[str] = None, project: Optional[Union[str, UUID]] = None, user: Optional[Union[UUID, str]] = None, hydrate: bool = False) -> Page[ActionResponse]

List actions.

Parameters:

Name Type Description Default
sort_by str

The column to sort by

'created'
page int

The page of items

PAGINATION_STARTING_PAGE
size int

The maximum size of all pages

PAGE_SIZE_DEFAULT
logical_operator LogicalOperators

Which logical operator to use [and, or]

AND
id Optional[Union[UUID, str]]

Use the id of the action to filter by.

None
created Optional[datetime]

Use to filter by time of creation

None
updated Optional[datetime]

Use the last updated date for filtering

None
project Optional[Union[str, UUID]]

The project name/ID to filter by.

None
user Optional[Union[UUID, str]]

Filter by user name/ID.

None
name Optional[str]

The name of the action to filter by.

None
flavor Optional[str]

The flavor of the action to filter by.

None
action_type Optional[str]

The type of the action to filter by.

None
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

False

Returns:

Type Description
Page[ActionResponse]

A page of actions.

Source code in src/zenml/client.py
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
@_fail_for_sql_zen_store
def list_actions(
    self,
    sort_by: str = "created",
    page: int = PAGINATION_STARTING_PAGE,
    size: int = PAGE_SIZE_DEFAULT,
    logical_operator: LogicalOperators = LogicalOperators.AND,
    id: Optional[Union[UUID, str]] = None,
    created: Optional[datetime] = None,
    updated: Optional[datetime] = None,
    name: Optional[str] = None,
    flavor: Optional[str] = None,
    action_type: Optional[str] = None,
    project: Optional[Union[str, UUID]] = None,
    user: Optional[Union[UUID, str]] = None,
    hydrate: bool = False,
) -> Page[ActionResponse]:
    """List actions.

    Args:
        sort_by: The column to sort by
        page: The page of items
        size: The maximum size of all pages
        logical_operator: Which logical operator to use [and, or]
        id: Use the id of the action to filter by.
        created: Use to filter by time of creation
        updated: Use the last updated date for filtering
        project: The project name/ID to filter by.
        user: Filter by user name/ID.
        name: The name of the action to filter by.
        flavor: The flavor of the action to filter by.
        action_type: The type of the action to filter by.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        A page of actions.
    """
    filter_model = ActionFilter(
        page=page,
        size=size,
        sort_by=sort_by,
        logical_operator=logical_operator,
        project=project or self.active_project.id,
        user=user,
        name=name,
        id=id,
        flavor=flavor,
        plugin_subtype=action_type,
        created=created,
        updated=updated,
    )
    return self.zen_store.list_actions(filter_model, hydrate=hydrate)
list_api_keys(service_account_name_id_or_prefix: Union[str, UUID], sort_by: str = 'created', page: int = PAGINATION_STARTING_PAGE, size: int = PAGE_SIZE_DEFAULT, logical_operator: LogicalOperators = LogicalOperators.AND, id: Optional[Union[UUID, str]] = None, created: Optional[Union[datetime, str]] = None, updated: Optional[Union[datetime, str]] = None, name: Optional[str] = None, description: Optional[str] = None, active: Optional[bool] = None, last_login: Optional[Union[datetime, str]] = None, last_rotated: Optional[Union[datetime, str]] = None, hydrate: bool = False) -> Page[APIKeyResponse]

List all API keys.

Parameters:

Name Type Description Default
service_account_name_id_or_prefix Union[str, UUID]

The name, ID or prefix of the service account to list the API keys for.

required
sort_by str

The column to sort by.

'created'
page int

The page of items.

PAGINATION_STARTING_PAGE
size int

The maximum size of all pages.

PAGE_SIZE_DEFAULT
logical_operator LogicalOperators

Which logical operator to use [and, or].

AND
id Optional[Union[UUID, str]]

Use the id of the API key to filter by.

None
created Optional[Union[datetime, str]]

Use to filter by time of creation.

None
updated Optional[Union[datetime, str]]

Use the last updated date for filtering.

None
name Optional[str]

The name of the API key to filter by.

None
description Optional[str]

The description of the API key to filter by.

None
active Optional[bool]

Whether the API key is active or not.

None
last_login Optional[Union[datetime, str]]

The last time the API key was used.

None
last_rotated Optional[Union[datetime, str]]

The last time the API key was rotated.

None
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

False

Returns:

Type Description
Page[APIKeyResponse]

A page of API keys matching the filter description.

Source code in src/zenml/client.py
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
def list_api_keys(
    self,
    service_account_name_id_or_prefix: Union[str, UUID],
    sort_by: str = "created",
    page: int = PAGINATION_STARTING_PAGE,
    size: int = PAGE_SIZE_DEFAULT,
    logical_operator: LogicalOperators = LogicalOperators.AND,
    id: Optional[Union[UUID, str]] = None,
    created: Optional[Union[datetime, str]] = None,
    updated: Optional[Union[datetime, str]] = None,
    name: Optional[str] = None,
    description: Optional[str] = None,
    active: Optional[bool] = None,
    last_login: Optional[Union[datetime, str]] = None,
    last_rotated: Optional[Union[datetime, str]] = None,
    hydrate: bool = False,
) -> Page[APIKeyResponse]:
    """List all API keys.

    Args:
        service_account_name_id_or_prefix: The name, ID or prefix of the
            service account to list the API keys for.
        sort_by: The column to sort by.
        page: The page of items.
        size: The maximum size of all pages.
        logical_operator: Which logical operator to use [and, or].
        id: Use the id of the API key to filter by.
        created: Use to filter by time of creation.
        updated: Use the last updated date for filtering.
        name: The name of the API key to filter by.
        description: The description of the API key to filter by.
        active: Whether the API key is active or not.
        last_login: The last time the API key was used.
        last_rotated: The last time the API key was rotated.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        A page of API keys matching the filter description.
    """
    service_account = self.get_service_account(
        name_id_or_prefix=service_account_name_id_or_prefix,
        allow_name_prefix_match=False,
    )
    filter_model = APIKeyFilter(
        sort_by=sort_by,
        page=page,
        size=size,
        logical_operator=logical_operator,
        id=id,
        created=created,
        updated=updated,
        name=name,
        description=description,
        active=active,
        last_login=last_login,
        last_rotated=last_rotated,
    )
    return self.zen_store.list_api_keys(
        service_account_id=service_account.id,
        filter_model=filter_model,
        hydrate=hydrate,
    )
list_artifact_versions(sort_by: str = 'created', page: int = PAGINATION_STARTING_PAGE, size: int = PAGE_SIZE_DEFAULT, logical_operator: LogicalOperators = LogicalOperators.AND, id: Optional[Union[UUID, str]] = None, created: Optional[Union[datetime, str]] = None, updated: Optional[Union[datetime, str]] = None, artifact: Optional[Union[str, UUID]] = None, name: Optional[str] = None, version: Optional[Union[str, int]] = None, version_number: Optional[int] = None, artifact_store_id: Optional[Union[str, UUID]] = None, type: Optional[ArtifactType] = None, data_type: Optional[str] = None, uri: Optional[str] = None, materializer: Optional[str] = None, project: Optional[Union[str, UUID]] = None, model_version_id: Optional[Union[str, UUID]] = None, only_unused: Optional[bool] = False, has_custom_name: Optional[bool] = None, user: Optional[Union[UUID, str]] = None, model: Optional[Union[UUID, str]] = None, pipeline_run: Optional[Union[UUID, str]] = None, run_metadata: Optional[List[str]] = None, tag: Optional[str] = None, tags: Optional[List[str]] = None, hydrate: bool = False) -> Page[ArtifactVersionResponse]

Get a list of artifact versions.

Parameters:

Name Type Description Default
sort_by str

The column to sort by

'created'
page int

The page of items

PAGINATION_STARTING_PAGE
size int

The maximum size of all pages

PAGE_SIZE_DEFAULT
logical_operator LogicalOperators

Which logical operator to use [and, or]

AND
id Optional[Union[UUID, str]]

Use the id of artifact version to filter by.

None
created Optional[Union[datetime, str]]

Use to filter by time of creation

None
updated Optional[Union[datetime, str]]

Use the last updated date for filtering

None
artifact Optional[Union[str, UUID]]

The name or ID of the artifact to filter by.

None
name Optional[str]

The name of the artifact to filter by.

None
version Optional[Union[str, int]]

The version of the artifact to filter by.

None
version_number Optional[int]

The version number of the artifact to filter by.

None
artifact_store_id Optional[Union[str, UUID]]

The id of the artifact store to filter by.

None
type Optional[ArtifactType]

The type of the artifact to filter by.

None
data_type Optional[str]

The data type of the artifact to filter by.

None
uri Optional[str]

The uri of the artifact to filter by.

None
materializer Optional[str]

The materializer of the artifact to filter by.

None
project Optional[Union[str, UUID]]

The project name/ID to filter by.

None
model_version_id Optional[Union[str, UUID]]

Filter by model version ID.

None
only_unused Optional[bool]

Only return artifact versions that are not used in any pipeline runs.

False
has_custom_name Optional[bool]

Filter artifacts with/without custom names.

None
tag Optional[str]

A tag to filter by.

None
tags Optional[List[str]]

Tags to filter by.

None
user Optional[Union[UUID, str]]

Filter by user name or ID.

None
model Optional[Union[UUID, str]]

Filter by model name or ID.

None
pipeline_run Optional[Union[UUID, str]]

Filter by pipeline run name or ID.

None
run_metadata Optional[List[str]]

Filter by run metadata.

None
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

False

Returns:

Type Description
Page[ArtifactVersionResponse]

A list of artifact versions.

Source code in src/zenml/client.py
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
def list_artifact_versions(
    self,
    sort_by: str = "created",
    page: int = PAGINATION_STARTING_PAGE,
    size: int = PAGE_SIZE_DEFAULT,
    logical_operator: LogicalOperators = LogicalOperators.AND,
    id: Optional[Union[UUID, str]] = None,
    created: Optional[Union[datetime, str]] = None,
    updated: Optional[Union[datetime, str]] = None,
    artifact: Optional[Union[str, UUID]] = None,
    name: Optional[str] = None,
    version: Optional[Union[str, int]] = None,
    version_number: Optional[int] = None,
    artifact_store_id: Optional[Union[str, UUID]] = None,
    type: Optional[ArtifactType] = None,
    data_type: Optional[str] = None,
    uri: Optional[str] = None,
    materializer: Optional[str] = None,
    project: Optional[Union[str, UUID]] = None,
    model_version_id: Optional[Union[str, UUID]] = None,
    only_unused: Optional[bool] = False,
    has_custom_name: Optional[bool] = None,
    user: Optional[Union[UUID, str]] = None,
    model: Optional[Union[UUID, str]] = None,
    pipeline_run: Optional[Union[UUID, str]] = None,
    run_metadata: Optional[List[str]] = None,
    tag: Optional[str] = None,
    tags: Optional[List[str]] = None,
    hydrate: bool = False,
) -> Page[ArtifactVersionResponse]:
    """Get a list of artifact versions.

    Args:
        sort_by: The column to sort by
        page: The page of items
        size: The maximum size of all pages
        logical_operator: Which logical operator to use [and, or]
        id: Use the id of artifact version to filter by.
        created: Use to filter by time of creation
        updated: Use the last updated date for filtering
        artifact: The name or ID of the artifact to filter by.
        name: The name of the artifact to filter by.
        version: The version of the artifact to filter by.
        version_number: The version number of the artifact to filter by.
        artifact_store_id: The id of the artifact store to filter by.
        type: The type of the artifact to filter by.
        data_type: The data type of the artifact to filter by.
        uri: The uri of the artifact to filter by.
        materializer: The materializer of the artifact to filter by.
        project: The project name/ID to filter by.
        model_version_id: Filter by model version ID.
        only_unused: Only return artifact versions that are not used in
            any pipeline runs.
        has_custom_name: Filter artifacts with/without custom names.
        tag: A tag to filter by.
        tags: Tags to filter by.
        user: Filter by user name or ID.
        model: Filter by model name or ID.
        pipeline_run: Filter by pipeline run name or ID.
        run_metadata: Filter by run metadata.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        A list of artifact versions.
    """
    if name:
        artifact = name

    artifact_version_filter_model = ArtifactVersionFilter(
        sort_by=sort_by,
        page=page,
        size=size,
        logical_operator=logical_operator,
        id=id,
        created=created,
        updated=updated,
        artifact=artifact,
        version=str(version) if version else None,
        version_number=version_number,
        artifact_store_id=artifact_store_id,
        type=type,
        data_type=data_type,
        uri=uri,
        materializer=materializer,
        project=project or self.active_project.id,
        model_version_id=model_version_id,
        only_unused=only_unused,
        has_custom_name=has_custom_name,
        tag=tag,
        tags=tags,
        user=user,
        model=model,
        pipeline_run=pipeline_run,
        run_metadata=run_metadata,
    )
    return self.zen_store.list_artifact_versions(
        artifact_version_filter_model,
        hydrate=hydrate,
    )
list_artifacts(sort_by: str = 'created', page: int = PAGINATION_STARTING_PAGE, size: int = PAGE_SIZE_DEFAULT, logical_operator: LogicalOperators = LogicalOperators.AND, id: Optional[Union[UUID, str]] = None, created: Optional[Union[datetime, str]] = None, updated: Optional[Union[datetime, str]] = None, name: Optional[str] = None, has_custom_name: Optional[bool] = None, user: Optional[Union[UUID, str]] = None, project: Optional[Union[str, UUID]] = None, hydrate: bool = False, tag: Optional[str] = None, tags: Optional[List[str]] = None) -> Page[ArtifactResponse]

Get a list of artifacts.

Parameters:

Name Type Description Default
sort_by str

The column to sort by

'created'
page int

The page of items

PAGINATION_STARTING_PAGE
size int

The maximum size of all pages

PAGE_SIZE_DEFAULT
logical_operator LogicalOperators

Which logical operator to use [and, or]

AND
id Optional[Union[UUID, str]]

Use the id of artifact to filter by.

None
created Optional[Union[datetime, str]]

Use to filter by time of creation

None
updated Optional[Union[datetime, str]]

Use the last updated date for filtering

None
name Optional[str]

The name of the artifact to filter by.

None
has_custom_name Optional[bool]

Filter artifacts with/without custom names.

None
user Optional[Union[UUID, str]]

Filter by user name or ID.

None
project Optional[Union[str, UUID]]

The project name/ID to filter by.

None
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

False
tag Optional[str]

Filter artifacts by tag.

None
tags Optional[List[str]]

Tags to filter by.

None

Returns:

Type Description
Page[ArtifactResponse]

A list of artifacts.

Source code in src/zenml/client.py
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
def list_artifacts(
    self,
    sort_by: str = "created",
    page: int = PAGINATION_STARTING_PAGE,
    size: int = PAGE_SIZE_DEFAULT,
    logical_operator: LogicalOperators = LogicalOperators.AND,
    id: Optional[Union[UUID, str]] = None,
    created: Optional[Union[datetime, str]] = None,
    updated: Optional[Union[datetime, str]] = None,
    name: Optional[str] = None,
    has_custom_name: Optional[bool] = None,
    user: Optional[Union[UUID, str]] = None,
    project: Optional[Union[str, UUID]] = None,
    hydrate: bool = False,
    tag: Optional[str] = None,
    tags: Optional[List[str]] = None,
) -> Page[ArtifactResponse]:
    """Get a list of artifacts.

    Args:
        sort_by: The column to sort by
        page: The page of items
        size: The maximum size of all pages
        logical_operator: Which logical operator to use [and, or]
        id: Use the id of artifact to filter by.
        created: Use to filter by time of creation
        updated: Use the last updated date for filtering
        name: The name of the artifact to filter by.
        has_custom_name: Filter artifacts with/without custom names.
        user: Filter by user name or ID.
        project: The project name/ID to filter by.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.
        tag: Filter artifacts by tag.
        tags: Tags to filter by.

    Returns:
        A list of artifacts.
    """
    artifact_filter_model = ArtifactFilter(
        sort_by=sort_by,
        page=page,
        size=size,
        logical_operator=logical_operator,
        id=id,
        created=created,
        updated=updated,
        name=name,
        has_custom_name=has_custom_name,
        tag=tag,
        tags=tags,
        user=user,
        project=project or self.active_project.id,
    )
    return self.zen_store.list_artifacts(
        artifact_filter_model,
        hydrate=hydrate,
    )
list_authorized_devices(sort_by: str = 'created', page: int = PAGINATION_STARTING_PAGE, size: int = PAGE_SIZE_DEFAULT, logical_operator: LogicalOperators = LogicalOperators.AND, id: Optional[Union[UUID, str]] = None, created: Optional[Union[datetime, str]] = None, updated: Optional[Union[datetime, str]] = None, expires: Optional[Union[datetime, str]] = None, client_id: Union[UUID, str, None] = None, status: Union[OAuthDeviceStatus, str, None] = None, trusted_device: Union[bool, str, None] = None, user: Optional[Union[UUID, str]] = None, failed_auth_attempts: Union[int, str, None] = None, last_login: Optional[Union[datetime, str, None]] = None, hydrate: bool = False) -> Page[OAuthDeviceResponse]

List all authorized devices.

Parameters:

Name Type Description Default
sort_by str

The column to sort by.

'created'
page int

The page of items.

PAGINATION_STARTING_PAGE
size int

The maximum size of all pages.

PAGE_SIZE_DEFAULT
logical_operator LogicalOperators

Which logical operator to use [and, or].

AND
id Optional[Union[UUID, str]]

Use the id of the code repository to filter by.

None
created Optional[Union[datetime, str]]

Use to filter by time of creation.

None
updated Optional[Union[datetime, str]]

Use the last updated date for filtering.

None
expires Optional[Union[datetime, str]]

Use the expiration date for filtering.

None
client_id Union[UUID, str, None]

Use the client id for filtering.

None
status Union[OAuthDeviceStatus, str, None]

Use the status for filtering.

None
user Optional[Union[UUID, str]]

Filter by user name/ID.

None
trusted_device Union[bool, str, None]

Use the trusted device flag for filtering.

None
failed_auth_attempts Union[int, str, None]

Use the failed auth attempts for filtering.

None
last_login Optional[Union[datetime, str, None]]

Use the last login date for filtering.

None
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

False

Returns:

Type Description
Page[OAuthDeviceResponse]

A page of authorized devices matching the filter.

Source code in src/zenml/client.py
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
def list_authorized_devices(
    self,
    sort_by: str = "created",
    page: int = PAGINATION_STARTING_PAGE,
    size: int = PAGE_SIZE_DEFAULT,
    logical_operator: LogicalOperators = LogicalOperators.AND,
    id: Optional[Union[UUID, str]] = None,
    created: Optional[Union[datetime, str]] = None,
    updated: Optional[Union[datetime, str]] = None,
    expires: Optional[Union[datetime, str]] = None,
    client_id: Union[UUID, str, None] = None,
    status: Union[OAuthDeviceStatus, str, None] = None,
    trusted_device: Union[bool, str, None] = None,
    user: Optional[Union[UUID, str]] = None,
    failed_auth_attempts: Union[int, str, None] = None,
    last_login: Optional[Union[datetime, str, None]] = None,
    hydrate: bool = False,
) -> Page[OAuthDeviceResponse]:
    """List all authorized devices.

    Args:
        sort_by: The column to sort by.
        page: The page of items.
        size: The maximum size of all pages.
        logical_operator: Which logical operator to use [and, or].
        id: Use the id of the code repository to filter by.
        created: Use to filter by time of creation.
        updated: Use the last updated date for filtering.
        expires: Use the expiration date for filtering.
        client_id: Use the client id for filtering.
        status: Use the status for filtering.
        user: Filter by user name/ID.
        trusted_device: Use the trusted device flag for filtering.
        failed_auth_attempts: Use the failed auth attempts for filtering.
        last_login: Use the last login date for filtering.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        A page of authorized devices matching the filter.
    """
    filter_model = OAuthDeviceFilter(
        sort_by=sort_by,
        page=page,
        size=size,
        logical_operator=logical_operator,
        id=id,
        created=created,
        updated=updated,
        expires=expires,
        client_id=client_id,
        user=user,
        status=status,
        trusted_device=trusted_device,
        failed_auth_attempts=failed_auth_attempts,
        last_login=last_login,
    )
    return self.zen_store.list_authorized_devices(
        filter_model=filter_model,
        hydrate=hydrate,
    )
list_builds(sort_by: str = 'created', page: int = PAGINATION_STARTING_PAGE, size: int = PAGE_SIZE_DEFAULT, logical_operator: LogicalOperators = LogicalOperators.AND, id: Optional[Union[UUID, str]] = None, created: Optional[Union[datetime, str]] = None, updated: Optional[Union[datetime, str]] = None, project: Optional[Union[str, UUID]] = None, user: Optional[Union[UUID, str]] = None, pipeline_id: Optional[Union[str, UUID]] = None, stack_id: Optional[Union[str, UUID]] = None, container_registry_id: Optional[Union[UUID, str]] = None, is_local: Optional[bool] = None, contains_code: Optional[bool] = None, zenml_version: Optional[str] = None, python_version: Optional[str] = None, checksum: Optional[str] = None, stack_checksum: Optional[str] = None, duration: Optional[Union[int, str]] = None, hydrate: bool = False) -> Page[PipelineBuildResponse]

List all builds.

Parameters:

Name Type Description Default
sort_by str

The column to sort by

'created'
page int

The page of items

PAGINATION_STARTING_PAGE
size int

The maximum size of all pages

PAGE_SIZE_DEFAULT
logical_operator LogicalOperators

Which logical operator to use [and, or]

AND
id Optional[Union[UUID, str]]

Use the id of build to filter by.

None
created Optional[Union[datetime, str]]

Use to filter by time of creation

None
updated Optional[Union[datetime, str]]

Use the last updated date for filtering

None
project Optional[Union[str, UUID]]

The project name/ID to filter by.

None
user Optional[Union[UUID, str]]

Filter by user name/ID.

None
pipeline_id Optional[Union[str, UUID]]

The id of the pipeline to filter by.

None
stack_id Optional[Union[str, UUID]]

The id of the stack to filter by.

None
container_registry_id Optional[Union[UUID, str]]

The id of the container registry to filter by.

None
is_local Optional[bool]

Use to filter local builds.

None
contains_code Optional[bool]

Use to filter builds that contain code.

None
zenml_version Optional[str]

The version of ZenML to filter by.

None
python_version Optional[str]

The Python version to filter by.

None
checksum Optional[str]

The build checksum to filter by.

None
stack_checksum Optional[str]

The stack checksum to filter by.

None
duration Optional[Union[int, str]]

The duration of the build in seconds to filter by.

None
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

False

Returns:

Type Description
Page[PipelineBuildResponse]

A page with builds fitting the filter description

Source code in src/zenml/client.py
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
def list_builds(
    self,
    sort_by: str = "created",
    page: int = PAGINATION_STARTING_PAGE,
    size: int = PAGE_SIZE_DEFAULT,
    logical_operator: LogicalOperators = LogicalOperators.AND,
    id: Optional[Union[UUID, str]] = None,
    created: Optional[Union[datetime, str]] = None,
    updated: Optional[Union[datetime, str]] = None,
    project: Optional[Union[str, UUID]] = None,
    user: Optional[Union[UUID, str]] = None,
    pipeline_id: Optional[Union[str, UUID]] = None,
    stack_id: Optional[Union[str, UUID]] = None,
    container_registry_id: Optional[Union[UUID, str]] = None,
    is_local: Optional[bool] = None,
    contains_code: Optional[bool] = None,
    zenml_version: Optional[str] = None,
    python_version: Optional[str] = None,
    checksum: Optional[str] = None,
    stack_checksum: Optional[str] = None,
    duration: Optional[Union[int, str]] = None,
    hydrate: bool = False,
) -> Page[PipelineBuildResponse]:
    """List all builds.

    Args:
        sort_by: The column to sort by
        page: The page of items
        size: The maximum size of all pages
        logical_operator: Which logical operator to use [and, or]
        id: Use the id of build to filter by.
        created: Use to filter by time of creation
        updated: Use the last updated date for filtering
        project: The project name/ID to filter by.
        user: Filter by user name/ID.
        pipeline_id: The id of the pipeline to filter by.
        stack_id: The id of the stack to filter by.
        container_registry_id: The id of the container registry to
            filter by.
        is_local: Use to filter local builds.
        contains_code: Use to filter builds that contain code.
        zenml_version: The version of ZenML to filter by.
        python_version: The Python version to filter by.
        checksum: The build checksum to filter by.
        stack_checksum: The stack checksum to filter by.
        duration: The duration of the build in seconds to filter by.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        A page with builds fitting the filter description
    """
    build_filter_model = PipelineBuildFilter(
        sort_by=sort_by,
        page=page,
        size=size,
        logical_operator=logical_operator,
        id=id,
        created=created,
        updated=updated,
        project=project or self.active_project.id,
        user=user,
        pipeline_id=pipeline_id,
        stack_id=stack_id,
        container_registry_id=container_registry_id,
        is_local=is_local,
        contains_code=contains_code,
        zenml_version=zenml_version,
        python_version=python_version,
        checksum=checksum,
        stack_checksum=stack_checksum,
        duration=duration,
    )
    return self.zen_store.list_builds(
        build_filter_model=build_filter_model,
        hydrate=hydrate,
    )
list_code_repositories(sort_by: str = 'created', page: int = PAGINATION_STARTING_PAGE, size: int = PAGE_SIZE_DEFAULT, logical_operator: LogicalOperators = LogicalOperators.AND, id: Optional[Union[UUID, str]] = None, created: Optional[Union[datetime, str]] = None, updated: Optional[Union[datetime, str]] = None, name: Optional[str] = None, project: Optional[Union[str, UUID]] = None, user: Optional[Union[UUID, str]] = None, hydrate: bool = False) -> Page[CodeRepositoryResponse]

List all code repositories.

Parameters:

Name Type Description Default
sort_by str

The column to sort by.

'created'
page int

The page of items.

PAGINATION_STARTING_PAGE
size int

The maximum size of all pages.

PAGE_SIZE_DEFAULT
logical_operator LogicalOperators

Which logical operator to use [and, or].

AND
id Optional[Union[UUID, str]]

Use the id of the code repository to filter by.

None
created Optional[Union[datetime, str]]

Use to filter by time of creation.

None
updated Optional[Union[datetime, str]]

Use the last updated date for filtering.

None
name Optional[str]

The name of the code repository to filter by.

None
project Optional[Union[str, UUID]]

The project name/ID to filter by.

None
user Optional[Union[UUID, str]]

Filter by user name/ID.

None
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

False

Returns:

Type Description
Page[CodeRepositoryResponse]

A page of code repositories matching the filter description.

Source code in src/zenml/client.py
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
def list_code_repositories(
    self,
    sort_by: str = "created",
    page: int = PAGINATION_STARTING_PAGE,
    size: int = PAGE_SIZE_DEFAULT,
    logical_operator: LogicalOperators = LogicalOperators.AND,
    id: Optional[Union[UUID, str]] = None,
    created: Optional[Union[datetime, str]] = None,
    updated: Optional[Union[datetime, str]] = None,
    name: Optional[str] = None,
    project: Optional[Union[str, UUID]] = None,
    user: Optional[Union[UUID, str]] = None,
    hydrate: bool = False,
) -> Page[CodeRepositoryResponse]:
    """List all code repositories.

    Args:
        sort_by: The column to sort by.
        page: The page of items.
        size: The maximum size of all pages.
        logical_operator: Which logical operator to use [and, or].
        id: Use the id of the code repository to filter by.
        created: Use to filter by time of creation.
        updated: Use the last updated date for filtering.
        name: The name of the code repository to filter by.
        project: The project name/ID to filter by.
        user: Filter by user name/ID.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        A page of code repositories matching the filter description.
    """
    filter_model = CodeRepositoryFilter(
        sort_by=sort_by,
        page=page,
        size=size,
        logical_operator=logical_operator,
        id=id,
        created=created,
        updated=updated,
        name=name,
        project=project or self.active_project.id,
        user=user,
    )
    return self.zen_store.list_code_repositories(
        filter_model=filter_model,
        hydrate=hydrate,
    )
list_deployments(sort_by: str = 'created', page: int = PAGINATION_STARTING_PAGE, size: int = PAGE_SIZE_DEFAULT, logical_operator: LogicalOperators = LogicalOperators.AND, id: Optional[Union[UUID, str]] = None, created: Optional[Union[datetime, str]] = None, updated: Optional[Union[datetime, str]] = None, project: Optional[Union[str, UUID]] = None, user: Optional[Union[UUID, str]] = None, pipeline_id: Optional[Union[str, UUID]] = None, stack_id: Optional[Union[str, UUID]] = None, build_id: Optional[Union[str, UUID]] = None, template_id: Optional[Union[str, UUID]] = None, hydrate: bool = False) -> Page[PipelineDeploymentResponse]

List all deployments.

Parameters:

Name Type Description Default
sort_by str

The column to sort by

'created'
page int

The page of items

PAGINATION_STARTING_PAGE
size int

The maximum size of all pages

PAGE_SIZE_DEFAULT
logical_operator LogicalOperators

Which logical operator to use [and, or]

AND
id Optional[Union[UUID, str]]

Use the id of build to filter by.

None
created Optional[Union[datetime, str]]

Use to filter by time of creation

None
updated Optional[Union[datetime, str]]

Use the last updated date for filtering

None
project Optional[Union[str, UUID]]

The project name/ID to filter by.

None
user Optional[Union[UUID, str]]

Filter by user name/ID.

None
pipeline_id Optional[Union[str, UUID]]

The id of the pipeline to filter by.

None
stack_id Optional[Union[str, UUID]]

The id of the stack to filter by.

None
build_id Optional[Union[str, UUID]]

The id of the build to filter by.

None
template_id Optional[Union[str, UUID]]

The ID of the template to filter by.

None
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

False

Returns:

Type Description
Page[PipelineDeploymentResponse]

A page with deployments fitting the filter description

Source code in src/zenml/client.py
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
def list_deployments(
    self,
    sort_by: str = "created",
    page: int = PAGINATION_STARTING_PAGE,
    size: int = PAGE_SIZE_DEFAULT,
    logical_operator: LogicalOperators = LogicalOperators.AND,
    id: Optional[Union[UUID, str]] = None,
    created: Optional[Union[datetime, str]] = None,
    updated: Optional[Union[datetime, str]] = None,
    project: Optional[Union[str, UUID]] = None,
    user: Optional[Union[UUID, str]] = None,
    pipeline_id: Optional[Union[str, UUID]] = None,
    stack_id: Optional[Union[str, UUID]] = None,
    build_id: Optional[Union[str, UUID]] = None,
    template_id: Optional[Union[str, UUID]] = None,
    hydrate: bool = False,
) -> Page[PipelineDeploymentResponse]:
    """List all deployments.

    Args:
        sort_by: The column to sort by
        page: The page of items
        size: The maximum size of all pages
        logical_operator: Which logical operator to use [and, or]
        id: Use the id of build to filter by.
        created: Use to filter by time of creation
        updated: Use the last updated date for filtering
        project: The project name/ID to filter by.
        user: Filter by user name/ID.
        pipeline_id: The id of the pipeline to filter by.
        stack_id: The id of the stack to filter by.
        build_id: The id of the build to filter by.
        template_id: The ID of the template to filter by.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        A page with deployments fitting the filter description
    """
    deployment_filter_model = PipelineDeploymentFilter(
        sort_by=sort_by,
        page=page,
        size=size,
        logical_operator=logical_operator,
        id=id,
        created=created,
        updated=updated,
        project=project or self.active_project.id,
        user=user,
        pipeline_id=pipeline_id,
        stack_id=stack_id,
        build_id=build_id,
        template_id=template_id,
    )
    return self.zen_store.list_deployments(
        deployment_filter_model=deployment_filter_model,
        hydrate=hydrate,
    )
list_event_sources(sort_by: str = 'created', page: int = PAGINATION_STARTING_PAGE, size: int = PAGE_SIZE_DEFAULT, logical_operator: LogicalOperators = LogicalOperators.AND, id: Optional[Union[UUID, str]] = None, created: Optional[datetime] = None, updated: Optional[datetime] = None, name: Optional[str] = None, flavor: Optional[str] = None, event_source_type: Optional[str] = None, project: Optional[Union[str, UUID]] = None, user: Optional[Union[UUID, str]] = None, hydrate: bool = False) -> Page[EventSourceResponse]

Lists all event_sources.

Parameters:

Name Type Description Default
sort_by str

The column to sort by

'created'
page int

The page of items

PAGINATION_STARTING_PAGE
size int

The maximum size of all pages

PAGE_SIZE_DEFAULT
logical_operator LogicalOperators

Which logical operator to use [and, or]

AND
id Optional[Union[UUID, str]]

Use the id of event_sources to filter by.

None
created Optional[datetime]

Use to filter by time of creation

None
updated Optional[datetime]

Use the last updated date for filtering

None
project Optional[Union[str, UUID]]

The project name/ID to filter by.

None
user Optional[Union[UUID, str]]

Filter by user name/ID.

None
name Optional[str]

The name of the event_source to filter by.

None
flavor Optional[str]

The flavor of the event_source to filter by.

None
event_source_type Optional[str]

The subtype of the event_source to filter by.

None
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

False

Returns:

Type Description
Page[EventSourceResponse]

A page of event_sources.

Source code in src/zenml/client.py
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
def list_event_sources(
    self,
    sort_by: str = "created",
    page: int = PAGINATION_STARTING_PAGE,
    size: int = PAGE_SIZE_DEFAULT,
    logical_operator: LogicalOperators = LogicalOperators.AND,
    id: Optional[Union[UUID, str]] = None,
    created: Optional[datetime] = None,
    updated: Optional[datetime] = None,
    name: Optional[str] = None,
    flavor: Optional[str] = None,
    event_source_type: Optional[str] = None,
    project: Optional[Union[str, UUID]] = None,
    user: Optional[Union[UUID, str]] = None,
    hydrate: bool = False,
) -> Page[EventSourceResponse]:
    """Lists all event_sources.

    Args:
        sort_by: The column to sort by
        page: The page of items
        size: The maximum size of all pages
        logical_operator: Which logical operator to use [and, or]
        id: Use the id of event_sources to filter by.
        created: Use to filter by time of creation
        updated: Use the last updated date for filtering
        project: The project name/ID to filter by.
        user: Filter by user name/ID.
        name: The name of the event_source to filter by.
        flavor: The flavor of the event_source to filter by.
        event_source_type: The subtype of the event_source to filter by.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        A page of event_sources.
    """
    event_source_filter_model = EventSourceFilter(
        page=page,
        size=size,
        sort_by=sort_by,
        logical_operator=logical_operator,
        project=project or self.active_project.id,
        user=user,
        name=name,
        flavor=flavor,
        plugin_subtype=event_source_type,
        id=id,
        created=created,
        updated=updated,
    )
    return self.zen_store.list_event_sources(
        event_source_filter_model, hydrate=hydrate
    )
list_flavors(sort_by: str = 'created', page: int = PAGINATION_STARTING_PAGE, size: int = PAGE_SIZE_DEFAULT, logical_operator: LogicalOperators = LogicalOperators.AND, id: Optional[Union[UUID, str]] = None, created: Optional[datetime] = None, updated: Optional[datetime] = None, name: Optional[str] = None, type: Optional[str] = None, integration: Optional[str] = None, user: Optional[Union[UUID, str]] = None, hydrate: bool = False) -> Page[FlavorResponse]

Fetches all the flavor models.

Parameters:

Name Type Description Default
sort_by str

The column to sort by

'created'
page int

The page of items

PAGINATION_STARTING_PAGE
size int

The maximum size of all pages

PAGE_SIZE_DEFAULT
logical_operator LogicalOperators

Which logical operator to use [and, or]

AND
id Optional[Union[UUID, str]]

Use the id of flavors to filter by.

None
created Optional[datetime]

Use to flavors by time of creation

None
updated Optional[datetime]

Use the last updated date for filtering

None
user Optional[Union[UUID, str]]

Filter by user name/ID.

None
name Optional[str]

The name of the flavor to filter by.

None
type Optional[str]

The type of the flavor to filter by.

None
integration Optional[str]

The integration of the flavor to filter by.

None
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

False

Returns:

Type Description
Page[FlavorResponse]

A list of all the flavor models.

Source code in src/zenml/client.py
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
def list_flavors(
    self,
    sort_by: str = "created",
    page: int = PAGINATION_STARTING_PAGE,
    size: int = PAGE_SIZE_DEFAULT,
    logical_operator: LogicalOperators = LogicalOperators.AND,
    id: Optional[Union[UUID, str]] = None,
    created: Optional[datetime] = None,
    updated: Optional[datetime] = None,
    name: Optional[str] = None,
    type: Optional[str] = None,
    integration: Optional[str] = None,
    user: Optional[Union[UUID, str]] = None,
    hydrate: bool = False,
) -> Page[FlavorResponse]:
    """Fetches all the flavor models.

    Args:
        sort_by: The column to sort by
        page: The page of items
        size: The maximum size of all pages
        logical_operator: Which logical operator to use [and, or]
        id: Use the id of flavors to filter by.
        created: Use to flavors by time of creation
        updated: Use the last updated date for filtering
        user: Filter by user name/ID.
        name: The name of the flavor to filter by.
        type: The type of the flavor to filter by.
        integration: The integration of the flavor to filter by.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        A list of all the flavor models.
    """
    flavor_filter_model = FlavorFilter(
        page=page,
        size=size,
        sort_by=sort_by,
        logical_operator=logical_operator,
        user=user,
        name=name,
        type=type,
        integration=integration,
        id=id,
        created=created,
        updated=updated,
    )
    return self.zen_store.list_flavors(
        flavor_filter_model=flavor_filter_model, hydrate=hydrate
    )

Get model version to artifact links by filter in Model Control Plane.

Parameters:

Name Type Description Default
sort_by str

The column to sort by

'created'
page int

The page of items

PAGINATION_STARTING_PAGE
size int

The maximum size of all pages

PAGE_SIZE_DEFAULT
logical_operator LogicalOperators

Which logical operator to use [and, or]

AND
created Optional[Union[datetime, str]]

Use to filter by time of creation

None
updated Optional[Union[datetime, str]]

Use the last updated date for filtering

None
model_version_id Optional[Union[UUID, str]]

Use the model version id for filtering

None
artifact_version_id Optional[Union[UUID, str]]

Use the artifact id for filtering

None
artifact_name Optional[str]

Use the artifact name for filtering

None
only_data_artifacts Optional[bool]

Use to filter by data artifacts

None
only_model_artifacts Optional[bool]

Use to filter by model artifacts

None
only_deployment_artifacts Optional[bool]

Use to filter by deployment artifacts

None
has_custom_name Optional[bool]

Filter artifacts with/without custom names.

None
user Optional[Union[UUID, str]]

Filter by user name/ID.

None
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

False

Returns:

Type Description
Page[ModelVersionArtifactResponse]

A page of all model version to artifact links.

Source code in src/zenml/client.py
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
def list_model_version_artifact_links(
    self,
    sort_by: str = "created",
    page: int = PAGINATION_STARTING_PAGE,
    size: int = PAGE_SIZE_DEFAULT,
    logical_operator: LogicalOperators = LogicalOperators.AND,
    created: Optional[Union[datetime, str]] = None,
    updated: Optional[Union[datetime, str]] = None,
    model_version_id: Optional[Union[UUID, str]] = None,
    artifact_version_id: Optional[Union[UUID, str]] = None,
    artifact_name: Optional[str] = None,
    only_data_artifacts: Optional[bool] = None,
    only_model_artifacts: Optional[bool] = None,
    only_deployment_artifacts: Optional[bool] = None,
    has_custom_name: Optional[bool] = None,
    user: Optional[Union[UUID, str]] = None,
    hydrate: bool = False,
) -> Page[ModelVersionArtifactResponse]:
    """Get model version to artifact links by filter in Model Control Plane.

    Args:
        sort_by: The column to sort by
        page: The page of items
        size: The maximum size of all pages
        logical_operator: Which logical operator to use [and, or]
        created: Use to filter by time of creation
        updated: Use the last updated date for filtering
        model_version_id: Use the model version id for filtering
        artifact_version_id: Use the artifact id for filtering
        artifact_name: Use the artifact name for filtering
        only_data_artifacts: Use to filter by data artifacts
        only_model_artifacts: Use to filter by model artifacts
        only_deployment_artifacts: Use to filter by deployment artifacts
        has_custom_name: Filter artifacts with/without custom names.
        user: Filter by user name/ID.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        A page of all model version to artifact links.
    """
    return self.zen_store.list_model_version_artifact_links(
        ModelVersionArtifactFilter(
            sort_by=sort_by,
            logical_operator=logical_operator,
            page=page,
            size=size,
            created=created,
            updated=updated,
            model_version_id=model_version_id,
            artifact_version_id=artifact_version_id,
            artifact_name=artifact_name,
            only_data_artifacts=only_data_artifacts,
            only_model_artifacts=only_model_artifacts,
            only_deployment_artifacts=only_deployment_artifacts,
            has_custom_name=has_custom_name,
            user=user,
        ),
        hydrate=hydrate,
    )

Get all model version to pipeline run links by filter.

Parameters:

Name Type Description Default
sort_by str

The column to sort by

'created'
page int

The page of items

PAGINATION_STARTING_PAGE
size int

The maximum size of all pages

PAGE_SIZE_DEFAULT
logical_operator LogicalOperators

Which logical operator to use [and, or]

AND
created Optional[Union[datetime, str]]

Use to filter by time of creation

None
updated Optional[Union[datetime, str]]

Use the last updated date for filtering

None
model_version_id Optional[Union[UUID, str]]

Use the model version id for filtering

None
pipeline_run_id Optional[Union[UUID, str]]

Use the pipeline run id for filtering

None
pipeline_run_name Optional[str]

Use the pipeline run name for filtering

None
user Optional[Union[UUID, str]]

Filter by user name or ID.

None
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response

False

Returns:

Type Description
Page[ModelVersionPipelineRunResponse]

A page of all model version to pipeline run links.

Source code in src/zenml/client.py
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
def list_model_version_pipeline_run_links(
    self,
    sort_by: str = "created",
    page: int = PAGINATION_STARTING_PAGE,
    size: int = PAGE_SIZE_DEFAULT,
    logical_operator: LogicalOperators = LogicalOperators.AND,
    created: Optional[Union[datetime, str]] = None,
    updated: Optional[Union[datetime, str]] = None,
    model_version_id: Optional[Union[UUID, str]] = None,
    pipeline_run_id: Optional[Union[UUID, str]] = None,
    pipeline_run_name: Optional[str] = None,
    user: Optional[Union[UUID, str]] = None,
    hydrate: bool = False,
) -> Page[ModelVersionPipelineRunResponse]:
    """Get all model version to pipeline run links by filter.

    Args:
        sort_by: The column to sort by
        page: The page of items
        size: The maximum size of all pages
        logical_operator: Which logical operator to use [and, or]
        created: Use to filter by time of creation
        updated: Use the last updated date for filtering
        model_version_id: Use the model version id for filtering
        pipeline_run_id: Use the pipeline run id for filtering
        pipeline_run_name: Use the pipeline run name for filtering
        user: Filter by user name or ID.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response

    Returns:
        A page of all model version to pipeline run links.
    """
    return self.zen_store.list_model_version_pipeline_run_links(
        ModelVersionPipelineRunFilter(
            sort_by=sort_by,
            logical_operator=logical_operator,
            page=page,
            size=size,
            created=created,
            updated=updated,
            model_version_id=model_version_id,
            pipeline_run_id=pipeline_run_id,
            pipeline_run_name=pipeline_run_name,
            user=user,
        ),
        hydrate=hydrate,
    )
list_model_versions(model: Optional[Union[str, UUID]] = None, model_name_or_id: Optional[Union[str, UUID]] = None, sort_by: str = 'number', page: int = PAGINATION_STARTING_PAGE, size: int = PAGE_SIZE_DEFAULT, logical_operator: LogicalOperators = LogicalOperators.AND, created: Optional[Union[datetime, str]] = None, updated: Optional[Union[datetime, str]] = None, name: Optional[str] = None, id: Optional[Union[UUID, str]] = None, number: Optional[int] = None, stage: Optional[Union[str, ModelStages]] = None, run_metadata: Optional[List[str]] = None, user: Optional[Union[UUID, str]] = None, hydrate: bool = False, tag: Optional[str] = None, tags: Optional[List[str]] = None, project: Optional[Union[str, UUID]] = None) -> Page[ModelVersionResponse]

Get model versions by filter from Model Control Plane.

Parameters:

Name Type Description Default
model Optional[Union[str, UUID]]

The model to filter by.

None
model_name_or_id Optional[Union[str, UUID]]

name or id of the model containing the model version.

None
sort_by str

The column to sort by

'number'
page int

The page of items

PAGINATION_STARTING_PAGE
size int

The maximum size of all pages

PAGE_SIZE_DEFAULT
logical_operator LogicalOperators

Which logical operator to use [and, or]

AND
created Optional[Union[datetime, str]]

Use to filter by time of creation

None
updated Optional[Union[datetime, str]]

Use the last updated date for filtering

None
name Optional[str]

name or id of the model version.

None
id Optional[Union[UUID, str]]

id of the model version.

None
number Optional[int]

number of the model version.

None
stage Optional[Union[str, ModelStages]]

stage of the model version.

None
run_metadata Optional[List[str]]

run metadata of the model version.

None
user Optional[Union[UUID, str]]

Filter by user name/ID.

None
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

False
tag Optional[str]

The tag to filter by.

None
tags Optional[List[str]]

Tags to filter by.

None
project Optional[Union[str, UUID]]

The project name/ID to filter by.

None

Returns:

Type Description
Page[ModelVersionResponse]

A page object with all model versions.

Source code in src/zenml/client.py
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
def list_model_versions(
    self,
    model: Optional[Union[str, UUID]] = None,
    model_name_or_id: Optional[Union[str, UUID]] = None,
    sort_by: str = "number",
    page: int = PAGINATION_STARTING_PAGE,
    size: int = PAGE_SIZE_DEFAULT,
    logical_operator: LogicalOperators = LogicalOperators.AND,
    created: Optional[Union[datetime, str]] = None,
    updated: Optional[Union[datetime, str]] = None,
    name: Optional[str] = None,
    id: Optional[Union[UUID, str]] = None,
    number: Optional[int] = None,
    stage: Optional[Union[str, ModelStages]] = None,
    run_metadata: Optional[List[str]] = None,
    user: Optional[Union[UUID, str]] = None,
    hydrate: bool = False,
    tag: Optional[str] = None,
    tags: Optional[List[str]] = None,
    project: Optional[Union[str, UUID]] = None,
) -> Page[ModelVersionResponse]:
    """Get model versions by filter from Model Control Plane.

    Args:
        model: The model to filter by.
        model_name_or_id: name or id of the model containing the model
            version.
        sort_by: The column to sort by
        page: The page of items
        size: The maximum size of all pages
        logical_operator: Which logical operator to use [and, or]
        created: Use to filter by time of creation
        updated: Use the last updated date for filtering
        name: name or id of the model version.
        id: id of the model version.
        number: number of the model version.
        stage: stage of the model version.
        run_metadata: run metadata of the model version.
        user: Filter by user name/ID.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.
        tag: The tag to filter by.
        tags: Tags to filter by.
        project: The project name/ID to filter by.

    Returns:
        A page object with all model versions.
    """
    if model_name_or_id:
        logger.warning(
            "The `model_name_or_id` argument is deprecated. "
            "Please use the `model` argument instead."
        )
        if model is None:
            model = model_name_or_id
        else:
            logger.warning(
                "Ignoring `model_name_or_id` argument as `model` argument "
                "was also provided."
            )

    model_version_filter_model = ModelVersionFilter(
        page=page,
        size=size,
        sort_by=sort_by,
        logical_operator=logical_operator,
        created=created,
        updated=updated,
        name=name,
        id=id,
        number=number,
        stage=stage,
        run_metadata=run_metadata,
        tag=tag,
        tags=tags,
        user=user,
        model=model,
        project=project or self.active_project.id,
    )

    return self.zen_store.list_model_versions(
        model_version_filter_model=model_version_filter_model,
        hydrate=hydrate,
    )
list_models(sort_by: str = 'created', page: int = PAGINATION_STARTING_PAGE, size: int = PAGE_SIZE_DEFAULT, logical_operator: LogicalOperators = LogicalOperators.AND, created: Optional[Union[datetime, str]] = None, updated: Optional[Union[datetime, str]] = None, name: Optional[str] = None, id: Optional[Union[UUID, str]] = None, user: Optional[Union[UUID, str]] = None, project: Optional[Union[str, UUID]] = None, hydrate: bool = False, tag: Optional[str] = None, tags: Optional[List[str]] = None) -> Page[ModelResponse]

Get models by filter from Model Control Plane.

Parameters:

Name Type Description Default
sort_by str

The column to sort by

'created'
page int

The page of items

PAGINATION_STARTING_PAGE
size int

The maximum size of all pages

PAGE_SIZE_DEFAULT
logical_operator LogicalOperators

Which logical operator to use [and, or]

AND
created Optional[Union[datetime, str]]

Use to filter by time of creation

None
updated Optional[Union[datetime, str]]

Use the last updated date for filtering

None
name Optional[str]

The name of the model to filter by.

None
id Optional[Union[UUID, str]]

The id of the model to filter by.

None
user Optional[Union[UUID, str]]

Filter by user name/ID.

None
project Optional[Union[str, UUID]]

The project name/ID to filter by.

None
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

False
tag Optional[str]

The tag of the model to filter by.

None
tags Optional[List[str]]

Tags to filter by.

None

Returns:

Type Description
Page[ModelResponse]

A page object with all models.

Source code in src/zenml/client.py
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
def list_models(
    self,
    sort_by: str = "created",
    page: int = PAGINATION_STARTING_PAGE,
    size: int = PAGE_SIZE_DEFAULT,
    logical_operator: LogicalOperators = LogicalOperators.AND,
    created: Optional[Union[datetime, str]] = None,
    updated: Optional[Union[datetime, str]] = None,
    name: Optional[str] = None,
    id: Optional[Union[UUID, str]] = None,
    user: Optional[Union[UUID, str]] = None,
    project: Optional[Union[str, UUID]] = None,
    hydrate: bool = False,
    tag: Optional[str] = None,
    tags: Optional[List[str]] = None,
) -> Page[ModelResponse]:
    """Get models by filter from Model Control Plane.

    Args:
        sort_by: The column to sort by
        page: The page of items
        size: The maximum size of all pages
        logical_operator: Which logical operator to use [and, or]
        created: Use to filter by time of creation
        updated: Use the last updated date for filtering
        name: The name of the model to filter by.
        id: The id of the model to filter by.
        user: Filter by user name/ID.
        project: The project name/ID to filter by.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.
        tag: The tag of the model to filter by.
        tags: Tags to filter by.

    Returns:
        A page object with all models.
    """
    filter = ModelFilter(
        name=name,
        id=id,
        sort_by=sort_by,
        page=page,
        size=size,
        logical_operator=logical_operator,
        created=created,
        updated=updated,
        tag=tag,
        tags=tags,
        user=user,
        project=project or self.active_project.id,
    )

    return self.zen_store.list_models(
        model_filter_model=filter, hydrate=hydrate
    )
list_pipeline_runs(sort_by: str = 'desc:created', page: int = PAGINATION_STARTING_PAGE, size: int = PAGE_SIZE_DEFAULT, logical_operator: LogicalOperators = LogicalOperators.AND, id: Optional[Union[UUID, str]] = None, created: Optional[Union[datetime, str]] = None, updated: Optional[Union[datetime, str]] = None, name: Optional[str] = None, project: Optional[Union[str, UUID]] = None, pipeline_id: Optional[Union[str, UUID]] = None, pipeline_name: Optional[str] = None, stack_id: Optional[Union[str, UUID]] = None, schedule_id: Optional[Union[str, UUID]] = None, build_id: Optional[Union[str, UUID]] = None, deployment_id: Optional[Union[str, UUID]] = None, code_repository_id: Optional[Union[str, UUID]] = None, template_id: Optional[Union[str, UUID]] = None, model_version_id: Optional[Union[str, UUID]] = None, orchestrator_run_id: Optional[str] = None, status: Optional[str] = None, start_time: Optional[Union[datetime, str]] = None, end_time: Optional[Union[datetime, str]] = None, unlisted: Optional[bool] = None, templatable: Optional[bool] = None, tag: Optional[str] = None, tags: Optional[List[str]] = None, user: Optional[Union[UUID, str]] = None, run_metadata: Optional[List[str]] = None, pipeline: Optional[Union[UUID, str]] = None, code_repository: Optional[Union[UUID, str]] = None, model: Optional[Union[UUID, str]] = None, stack: Optional[Union[UUID, str]] = None, stack_component: Optional[Union[UUID, str]] = None, hydrate: bool = False) -> Page[PipelineRunResponse]

List all pipeline runs.

Parameters:

Name Type Description Default
sort_by str

The column to sort by

'desc:created'
page int

The page of items

PAGINATION_STARTING_PAGE
size int

The maximum size of all pages

PAGE_SIZE_DEFAULT
logical_operator LogicalOperators

Which logical operator to use [and, or]

AND
id Optional[Union[UUID, str]]

The id of the runs to filter by.

None
created Optional[Union[datetime, str]]

Use to filter by time of creation

None
updated Optional[Union[datetime, str]]

Use the last updated date for filtering

None
project Optional[Union[str, UUID]]

The project name/ID to filter by.

None
pipeline_id Optional[Union[str, UUID]]

The id of the pipeline to filter by.

None
pipeline_name Optional[str]

DEPRECATED. Use pipeline instead to filter by pipeline name.

None
stack_id Optional[Union[str, UUID]]

The id of the stack to filter by.

None
schedule_id Optional[Union[str, UUID]]

The id of the schedule to filter by.

None
build_id Optional[Union[str, UUID]]

The id of the build to filter by.

None
deployment_id Optional[Union[str, UUID]]

The id of the deployment to filter by.

None
code_repository_id Optional[Union[str, UUID]]

The id of the code repository to filter by.

None
template_id Optional[Union[str, UUID]]

The ID of the template to filter by.

None
model_version_id Optional[Union[str, UUID]]

The ID of the model version to filter by.

None
orchestrator_run_id Optional[str]

The run id of the orchestrator to filter by.

None
name Optional[str]

The name of the run to filter by.

None
status Optional[str]

The status of the pipeline run

None
start_time Optional[Union[datetime, str]]

The start_time for the pipeline run

None
end_time Optional[Union[datetime, str]]

The end_time for the pipeline run

None
unlisted Optional[bool]

If the runs should be unlisted or not.

None
templatable Optional[bool]

If the runs should be templatable or not.

None
tag Optional[str]

Tag to filter by.

None
tags Optional[List[str]]

Tags to filter by.

None
user Optional[Union[UUID, str]]

The name/ID of the user to filter by.

None
run_metadata Optional[List[str]]

The run_metadata of the run to filter by.

None
pipeline Optional[Union[UUID, str]]

The name/ID of the pipeline to filter by.

None
code_repository Optional[Union[UUID, str]]

Filter by code repository name/ID.

None
model Optional[Union[UUID, str]]

Filter by model name/ID.

None
stack Optional[Union[UUID, str]]

Filter by stack name/ID.

None
stack_component Optional[Union[UUID, str]]

Filter by stack component name/ID.

None
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

False

Returns:

Type Description
Page[PipelineRunResponse]

A page with Pipeline Runs fitting the filter description

Source code in src/zenml/client.py
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
def list_pipeline_runs(
    self,
    sort_by: str = "desc:created",
    page: int = PAGINATION_STARTING_PAGE,
    size: int = PAGE_SIZE_DEFAULT,
    logical_operator: LogicalOperators = LogicalOperators.AND,
    id: Optional[Union[UUID, str]] = None,
    created: Optional[Union[datetime, str]] = None,
    updated: Optional[Union[datetime, str]] = None,
    name: Optional[str] = None,
    project: Optional[Union[str, UUID]] = None,
    pipeline_id: Optional[Union[str, UUID]] = None,
    pipeline_name: Optional[str] = None,
    stack_id: Optional[Union[str, UUID]] = None,
    schedule_id: Optional[Union[str, UUID]] = None,
    build_id: Optional[Union[str, UUID]] = None,
    deployment_id: Optional[Union[str, UUID]] = None,
    code_repository_id: Optional[Union[str, UUID]] = None,
    template_id: Optional[Union[str, UUID]] = None,
    model_version_id: Optional[Union[str, UUID]] = None,
    orchestrator_run_id: Optional[str] = None,
    status: Optional[str] = None,
    start_time: Optional[Union[datetime, str]] = None,
    end_time: Optional[Union[datetime, str]] = None,
    unlisted: Optional[bool] = None,
    templatable: Optional[bool] = None,
    tag: Optional[str] = None,
    tags: Optional[List[str]] = None,
    user: Optional[Union[UUID, str]] = None,
    run_metadata: Optional[List[str]] = None,
    pipeline: Optional[Union[UUID, str]] = None,
    code_repository: Optional[Union[UUID, str]] = None,
    model: Optional[Union[UUID, str]] = None,
    stack: Optional[Union[UUID, str]] = None,
    stack_component: Optional[Union[UUID, str]] = None,
    hydrate: bool = False,
) -> Page[PipelineRunResponse]:
    """List all pipeline runs.

    Args:
        sort_by: The column to sort by
        page: The page of items
        size: The maximum size of all pages
        logical_operator: Which logical operator to use [and, or]
        id: The id of the runs to filter by.
        created: Use to filter by time of creation
        updated: Use the last updated date for filtering
        project: The project name/ID to filter by.
        pipeline_id: The id of the pipeline to filter by.
        pipeline_name: DEPRECATED. Use `pipeline` instead to filter by
            pipeline name.
        stack_id: The id of the stack to filter by.
        schedule_id: The id of the schedule to filter by.
        build_id: The id of the build to filter by.
        deployment_id: The id of the deployment to filter by.
        code_repository_id: The id of the code repository to filter by.
        template_id: The ID of the template to filter by.
        model_version_id: The ID of the model version to filter by.
        orchestrator_run_id: The run id of the orchestrator to filter by.
        name: The name of the run to filter by.
        status: The status of the pipeline run
        start_time: The start_time for the pipeline run
        end_time: The end_time for the pipeline run
        unlisted: If the runs should be unlisted or not.
        templatable: If the runs should be templatable or not.
        tag: Tag to filter by.
        tags: Tags to filter by.
        user: The name/ID of the user to filter by.
        run_metadata: The run_metadata of the run to filter by.
        pipeline: The name/ID of the pipeline to filter by.
        code_repository: Filter by code repository name/ID.
        model: Filter by model name/ID.
        stack: Filter by stack name/ID.
        stack_component: Filter by stack component name/ID.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        A page with Pipeline Runs fitting the filter description
    """
    runs_filter_model = PipelineRunFilter(
        sort_by=sort_by,
        page=page,
        size=size,
        logical_operator=logical_operator,
        id=id,
        created=created,
        updated=updated,
        name=name,
        project=project or self.active_project.id,
        pipeline_id=pipeline_id,
        pipeline_name=pipeline_name,
        schedule_id=schedule_id,
        build_id=build_id,
        deployment_id=deployment_id,
        code_repository_id=code_repository_id,
        template_id=template_id,
        model_version_id=model_version_id,
        orchestrator_run_id=orchestrator_run_id,
        stack_id=stack_id,
        status=status,
        start_time=start_time,
        end_time=end_time,
        tag=tag,
        tags=tags,
        unlisted=unlisted,
        user=user,
        run_metadata=run_metadata,
        pipeline=pipeline,
        code_repository=code_repository,
        stack=stack,
        model=model,
        stack_component=stack_component,
        templatable=templatable,
    )
    return self.zen_store.list_runs(
        runs_filter_model=runs_filter_model,
        hydrate=hydrate,
    )
list_pipelines(sort_by: str = 'created', page: int = PAGINATION_STARTING_PAGE, size: int = PAGE_SIZE_DEFAULT, logical_operator: LogicalOperators = LogicalOperators.AND, id: Optional[Union[UUID, str]] = None, created: Optional[Union[datetime, str]] = None, updated: Optional[Union[datetime, str]] = None, name: Optional[str] = None, latest_run_status: Optional[str] = None, project: Optional[Union[str, UUID]] = None, user: Optional[Union[UUID, str]] = None, tag: Optional[str] = None, tags: Optional[List[str]] = None, hydrate: bool = False) -> Page[PipelineResponse]

List all pipelines.

Parameters:

Name Type Description Default
sort_by str

The column to sort by

'created'
page int

The page of items

PAGINATION_STARTING_PAGE
size int

The maximum size of all pages

PAGE_SIZE_DEFAULT
logical_operator LogicalOperators

Which logical operator to use [and, or]

AND
id Optional[Union[UUID, str]]

Use the id of pipeline to filter by.

None
created Optional[Union[datetime, str]]

Use to filter by time of creation

None
updated Optional[Union[datetime, str]]

Use the last updated date for filtering

None
name Optional[str]

The name of the pipeline to filter by.

None
latest_run_status Optional[str]

Filter by the status of the latest run of a pipeline.

None
project Optional[Union[str, UUID]]

The project name/ID to filter by.

None
user Optional[Union[UUID, str]]

The name/ID of the user to filter by.

None
tag Optional[str]

Tag to filter by.

None
tags Optional[List[str]]

Tags to filter by.

None
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

False

Returns:

Type Description
Page[PipelineResponse]

A page with Pipeline fitting the filter description

Source code in src/zenml/client.py
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
def list_pipelines(
    self,
    sort_by: str = "created",
    page: int = PAGINATION_STARTING_PAGE,
    size: int = PAGE_SIZE_DEFAULT,
    logical_operator: LogicalOperators = LogicalOperators.AND,
    id: Optional[Union[UUID, str]] = None,
    created: Optional[Union[datetime, str]] = None,
    updated: Optional[Union[datetime, str]] = None,
    name: Optional[str] = None,
    latest_run_status: Optional[str] = None,
    project: Optional[Union[str, UUID]] = None,
    user: Optional[Union[UUID, str]] = None,
    tag: Optional[str] = None,
    tags: Optional[List[str]] = None,
    hydrate: bool = False,
) -> Page[PipelineResponse]:
    """List all pipelines.

    Args:
        sort_by: The column to sort by
        page: The page of items
        size: The maximum size of all pages
        logical_operator: Which logical operator to use [and, or]
        id: Use the id of pipeline to filter by.
        created: Use to filter by time of creation
        updated: Use the last updated date for filtering
        name: The name of the pipeline to filter by.
        latest_run_status: Filter by the status of the latest run of a
            pipeline.
        project: The project name/ID to filter by.
        user: The name/ID of the user to filter by.
        tag: Tag to filter by.
        tags: Tags to filter by.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        A page with Pipeline fitting the filter description
    """
    pipeline_filter_model = PipelineFilter(
        sort_by=sort_by,
        page=page,
        size=size,
        logical_operator=logical_operator,
        id=id,
        created=created,
        updated=updated,
        name=name,
        latest_run_status=latest_run_status,
        project=project or self.active_project.id,
        user=user,
        tag=tag,
        tags=tags,
    )
    return self.zen_store.list_pipelines(
        pipeline_filter_model=pipeline_filter_model,
        hydrate=hydrate,
    )
list_projects(sort_by: str = 'created', page: int = PAGINATION_STARTING_PAGE, size: int = PAGE_SIZE_DEFAULT, logical_operator: LogicalOperators = LogicalOperators.AND, id: Optional[Union[UUID, str]] = None, created: Optional[Union[datetime, str]] = None, updated: Optional[Union[datetime, str]] = None, name: Optional[str] = None, display_name: Optional[str] = None, hydrate: bool = False) -> Page[ProjectResponse]

List all projects.

Parameters:

Name Type Description Default
sort_by str

The column to sort by

'created'
page int

The page of items

PAGINATION_STARTING_PAGE
size int

The maximum size of all pages

PAGE_SIZE_DEFAULT
logical_operator LogicalOperators

Which logical operator to use [and, or]

AND
id Optional[Union[UUID, str]]

Use the project ID to filter by.

None
created Optional[Union[datetime, str]]

Use to filter by time of creation

None
updated Optional[Union[datetime, str]]

Use the last updated date for filtering

None
name Optional[str]

Use the project name for filtering

None
display_name Optional[str]

Use the project display name for filtering

None
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

False

Returns:

Type Description
Page[ProjectResponse]

Page of projects

Source code in src/zenml/client.py
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
def list_projects(
    self,
    sort_by: str = "created",
    page: int = PAGINATION_STARTING_PAGE,
    size: int = PAGE_SIZE_DEFAULT,
    logical_operator: LogicalOperators = LogicalOperators.AND,
    id: Optional[Union[UUID, str]] = None,
    created: Optional[Union[datetime, str]] = None,
    updated: Optional[Union[datetime, str]] = None,
    name: Optional[str] = None,
    display_name: Optional[str] = None,
    hydrate: bool = False,
) -> Page[ProjectResponse]:
    """List all projects.

    Args:
        sort_by: The column to sort by
        page: The page of items
        size: The maximum size of all pages
        logical_operator: Which logical operator to use [and, or]
        id: Use the project ID to filter by.
        created: Use to filter by time of creation
        updated: Use the last updated date for filtering
        name: Use the project name for filtering
        display_name: Use the project display name for filtering
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        Page of projects
    """
    return self.zen_store.list_projects(
        ProjectFilter(
            sort_by=sort_by,
            page=page,
            size=size,
            logical_operator=logical_operator,
            id=id,
            created=created,
            updated=updated,
            name=name,
            display_name=display_name,
        ),
        hydrate=hydrate,
    )
list_run_steps(sort_by: str = 'created', page: int = PAGINATION_STARTING_PAGE, size: int = PAGE_SIZE_DEFAULT, logical_operator: LogicalOperators = LogicalOperators.AND, id: Optional[Union[UUID, str]] = None, created: Optional[Union[datetime, str]] = None, updated: Optional[Union[datetime, str]] = None, name: Optional[str] = None, cache_key: Optional[str] = None, code_hash: Optional[str] = None, status: Optional[str] = None, start_time: Optional[Union[datetime, str]] = None, end_time: Optional[Union[datetime, str]] = None, pipeline_run_id: Optional[Union[str, UUID]] = None, deployment_id: Optional[Union[str, UUID]] = None, original_step_run_id: Optional[Union[str, UUID]] = None, project: Optional[Union[str, UUID]] = None, user: Optional[Union[UUID, str]] = None, model_version_id: Optional[Union[str, UUID]] = None, model: Optional[Union[UUID, str]] = None, run_metadata: Optional[List[str]] = None, hydrate: bool = False) -> Page[StepRunResponse]

List all pipelines.

Parameters:

Name Type Description Default
sort_by str

The column to sort by

'created'
page int

The page of items

PAGINATION_STARTING_PAGE
size int

The maximum size of all pages

PAGE_SIZE_DEFAULT
logical_operator LogicalOperators

Which logical operator to use [and, or]

AND
id Optional[Union[UUID, str]]

Use the id of runs to filter by.

None
created Optional[Union[datetime, str]]

Use to filter by time of creation

None
updated Optional[Union[datetime, str]]

Use the last updated date for filtering

None
start_time Optional[Union[datetime, str]]

Use to filter by the time when the step started running

None
end_time Optional[Union[datetime, str]]

Use to filter by the time when the step finished running

None
project Optional[Union[str, UUID]]

The project name/ID to filter by.

None
user Optional[Union[UUID, str]]

Filter by user name/ID.

None
pipeline_run_id Optional[Union[str, UUID]]

The id of the pipeline run to filter by.

None
deployment_id Optional[Union[str, UUID]]

The id of the deployment to filter by.

None
original_step_run_id Optional[Union[str, UUID]]

The id of the original step run to filter by.

None
model_version_id Optional[Union[str, UUID]]

The ID of the model version to filter by.

None
model Optional[Union[UUID, str]]

Filter by model name/ID.

None
name Optional[str]

The name of the step run to filter by.

None
cache_key Optional[str]

The cache key of the step run to filter by.

None
code_hash Optional[str]

The code hash of the step run to filter by.

None
status Optional[str]

The name of the run to filter by.

None
run_metadata Optional[List[str]]

Filter by run metadata.

None
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

False

Returns:

Type Description
Page[StepRunResponse]

A page with Pipeline fitting the filter description

Source code in src/zenml/client.py
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
def list_run_steps(
    self,
    sort_by: str = "created",
    page: int = PAGINATION_STARTING_PAGE,
    size: int = PAGE_SIZE_DEFAULT,
    logical_operator: LogicalOperators = LogicalOperators.AND,
    id: Optional[Union[UUID, str]] = None,
    created: Optional[Union[datetime, str]] = None,
    updated: Optional[Union[datetime, str]] = None,
    name: Optional[str] = None,
    cache_key: Optional[str] = None,
    code_hash: Optional[str] = None,
    status: Optional[str] = None,
    start_time: Optional[Union[datetime, str]] = None,
    end_time: Optional[Union[datetime, str]] = None,
    pipeline_run_id: Optional[Union[str, UUID]] = None,
    deployment_id: Optional[Union[str, UUID]] = None,
    original_step_run_id: Optional[Union[str, UUID]] = None,
    project: Optional[Union[str, UUID]] = None,
    user: Optional[Union[UUID, str]] = None,
    model_version_id: Optional[Union[str, UUID]] = None,
    model: Optional[Union[UUID, str]] = None,
    run_metadata: Optional[List[str]] = None,
    hydrate: bool = False,
) -> Page[StepRunResponse]:
    """List all pipelines.

    Args:
        sort_by: The column to sort by
        page: The page of items
        size: The maximum size of all pages
        logical_operator: Which logical operator to use [and, or]
        id: Use the id of runs to filter by.
        created: Use to filter by time of creation
        updated: Use the last updated date for filtering
        start_time: Use to filter by the time when the step started running
        end_time: Use to filter by the time when the step finished running
        project: The project name/ID to filter by.
        user: Filter by user name/ID.
        pipeline_run_id: The id of the pipeline run to filter by.
        deployment_id: The id of the deployment to filter by.
        original_step_run_id: The id of the original step run to filter by.
        model_version_id: The ID of the model version to filter by.
        model: Filter by model name/ID.
        name: The name of the step run to filter by.
        cache_key: The cache key of the step run to filter by.
        code_hash: The code hash of the step run to filter by.
        status: The name of the run to filter by.
        run_metadata: Filter by run metadata.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        A page with Pipeline fitting the filter description
    """
    step_run_filter_model = StepRunFilter(
        sort_by=sort_by,
        page=page,
        size=size,
        logical_operator=logical_operator,
        id=id,
        cache_key=cache_key,
        code_hash=code_hash,
        pipeline_run_id=pipeline_run_id,
        deployment_id=deployment_id,
        original_step_run_id=original_step_run_id,
        status=status,
        created=created,
        updated=updated,
        start_time=start_time,
        end_time=end_time,
        name=name,
        project=project or self.active_project.id,
        user=user,
        model_version_id=model_version_id,
        model=model,
        run_metadata=run_metadata,
    )
    return self.zen_store.list_run_steps(
        step_run_filter_model=step_run_filter_model,
        hydrate=hydrate,
    )
list_run_templates(sort_by: str = 'created', page: int = PAGINATION_STARTING_PAGE, size: int = PAGE_SIZE_DEFAULT, logical_operator: LogicalOperators = LogicalOperators.AND, created: Optional[Union[datetime, str]] = None, updated: Optional[Union[datetime, str]] = None, id: Optional[Union[UUID, str]] = None, name: Optional[str] = None, hidden: Optional[bool] = False, tag: Optional[str] = None, project: Optional[Union[str, UUID]] = None, pipeline_id: Optional[Union[str, UUID]] = None, build_id: Optional[Union[str, UUID]] = None, stack_id: Optional[Union[str, UUID]] = None, code_repository_id: Optional[Union[str, UUID]] = None, user: Optional[Union[UUID, str]] = None, pipeline: Optional[Union[UUID, str]] = None, stack: Optional[Union[UUID, str]] = None, hydrate: bool = False) -> Page[RunTemplateResponse]

Get a page of run templates.

Parameters:

Name Type Description Default
sort_by str

The column to sort by.

'created'
page int

The page of items.

PAGINATION_STARTING_PAGE
size int

The maximum size of all pages.

PAGE_SIZE_DEFAULT
logical_operator LogicalOperators

Which logical operator to use [and, or].

AND
created Optional[Union[datetime, str]]

Filter by the creation date.

None
updated Optional[Union[datetime, str]]

Filter by the last updated date.

None
id Optional[Union[UUID, str]]

Filter by run template ID.

None
name Optional[str]

Filter by run template name.

None
hidden Optional[bool]

Filter by run template hidden status.

False
tag Optional[str]

Filter by run template tags.

None
project Optional[Union[str, UUID]]

Filter by project name/ID.

None
pipeline_id Optional[Union[str, UUID]]

Filter by pipeline ID.

None
build_id Optional[Union[str, UUID]]

Filter by build ID.

None
stack_id Optional[Union[str, UUID]]

Filter by stack ID.

None
code_repository_id Optional[Union[str, UUID]]

Filter by code repository ID.

None
user Optional[Union[UUID, str]]

Filter by user name/ID.

None
pipeline Optional[Union[UUID, str]]

Filter by pipeline name/ID.

None
stack Optional[Union[UUID, str]]

Filter by stack name/ID.

None
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

False

Returns:

Type Description
Page[RunTemplateResponse]

A page of run templates.

Source code in src/zenml/client.py
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
def list_run_templates(
    self,
    sort_by: str = "created",
    page: int = PAGINATION_STARTING_PAGE,
    size: int = PAGE_SIZE_DEFAULT,
    logical_operator: LogicalOperators = LogicalOperators.AND,
    created: Optional[Union[datetime, str]] = None,
    updated: Optional[Union[datetime, str]] = None,
    id: Optional[Union[UUID, str]] = None,
    name: Optional[str] = None,
    hidden: Optional[bool] = False,
    tag: Optional[str] = None,
    project: Optional[Union[str, UUID]] = None,
    pipeline_id: Optional[Union[str, UUID]] = None,
    build_id: Optional[Union[str, UUID]] = None,
    stack_id: Optional[Union[str, UUID]] = None,
    code_repository_id: Optional[Union[str, UUID]] = None,
    user: Optional[Union[UUID, str]] = None,
    pipeline: Optional[Union[UUID, str]] = None,
    stack: Optional[Union[UUID, str]] = None,
    hydrate: bool = False,
) -> Page[RunTemplateResponse]:
    """Get a page of run templates.

    Args:
        sort_by: The column to sort by.
        page: The page of items.
        size: The maximum size of all pages.
        logical_operator: Which logical operator to use [and, or].
        created: Filter by the creation date.
        updated: Filter by the last updated date.
        id: Filter by run template ID.
        name: Filter by run template name.
        hidden: Filter by run template hidden status.
        tag: Filter by run template tags.
        project: Filter by project name/ID.
        pipeline_id: Filter by pipeline ID.
        build_id: Filter by build ID.
        stack_id: Filter by stack ID.
        code_repository_id: Filter by code repository ID.
        user: Filter by user name/ID.
        pipeline: Filter by pipeline name/ID.
        stack: Filter by stack name/ID.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        A page of run templates.
    """
    filter = RunTemplateFilter(
        sort_by=sort_by,
        page=page,
        size=size,
        logical_operator=logical_operator,
        created=created,
        updated=updated,
        id=id,
        name=name,
        hidden=hidden,
        tag=tag,
        project=project or self.active_project.id,
        pipeline_id=pipeline_id,
        build_id=build_id,
        stack_id=stack_id,
        code_repository_id=code_repository_id,
        user=user,
        pipeline=pipeline,
        stack=stack,
    )

    return self.zen_store.list_run_templates(
        template_filter_model=filter, hydrate=hydrate
    )
list_schedules(sort_by: str = 'created', page: int = PAGINATION_STARTING_PAGE, size: int = PAGE_SIZE_DEFAULT, logical_operator: LogicalOperators = LogicalOperators.AND, id: Optional[Union[UUID, str]] = None, created: Optional[Union[datetime, str]] = None, updated: Optional[Union[datetime, str]] = None, name: Optional[str] = None, project: Optional[Union[str, UUID]] = None, user: Optional[Union[UUID, str]] = None, pipeline_id: Optional[Union[str, UUID]] = None, orchestrator_id: Optional[Union[str, UUID]] = None, active: Optional[Union[str, bool]] = None, cron_expression: Optional[str] = None, start_time: Optional[Union[datetime, str]] = None, end_time: Optional[Union[datetime, str]] = None, interval_second: Optional[int] = None, catchup: Optional[Union[str, bool]] = None, hydrate: bool = False, run_once_start_time: Optional[Union[datetime, str]] = None) -> Page[ScheduleResponse]

List schedules.

Parameters:

Name Type Description Default
sort_by str

The column to sort by

'created'
page int

The page of items

PAGINATION_STARTING_PAGE
size int

The maximum size of all pages

PAGE_SIZE_DEFAULT
logical_operator LogicalOperators

Which logical operator to use [and, or]

AND
id Optional[Union[UUID, str]]

Use the id of stacks to filter by.

None
created Optional[Union[datetime, str]]

Use to filter by time of creation

None
updated Optional[Union[datetime, str]]

Use the last updated date for filtering

None
name Optional[str]

The name of the stack to filter by.

None
project Optional[Union[str, UUID]]

The project name/ID to filter by.

None
user Optional[Union[UUID, str]]

Filter by user name/ID.

None
pipeline_id Optional[Union[str, UUID]]

The id of the pipeline to filter by.

None
orchestrator_id Optional[Union[str, UUID]]

The id of the orchestrator to filter by.

None
active Optional[Union[str, bool]]

Use to filter by active status.

None
cron_expression Optional[str]

Use to filter by cron expression.

None
start_time Optional[Union[datetime, str]]

Use to filter by start time.

None
end_time Optional[Union[datetime, str]]

Use to filter by end time.

None
interval_second Optional[int]

Use to filter by interval second.

None
catchup Optional[Union[str, bool]]

Use to filter by catchup.

None
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

False
run_once_start_time Optional[Union[datetime, str]]

Use to filter by run once start time.

None

Returns:

Type Description
Page[ScheduleResponse]

A list of schedules.

Source code in src/zenml/client.py
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
def list_schedules(
    self,
    sort_by: str = "created",
    page: int = PAGINATION_STARTING_PAGE,
    size: int = PAGE_SIZE_DEFAULT,
    logical_operator: LogicalOperators = LogicalOperators.AND,
    id: Optional[Union[UUID, str]] = None,
    created: Optional[Union[datetime, str]] = None,
    updated: Optional[Union[datetime, str]] = None,
    name: Optional[str] = None,
    project: Optional[Union[str, UUID]] = None,
    user: Optional[Union[UUID, str]] = None,
    pipeline_id: Optional[Union[str, UUID]] = None,
    orchestrator_id: Optional[Union[str, UUID]] = None,
    active: Optional[Union[str, bool]] = None,
    cron_expression: Optional[str] = None,
    start_time: Optional[Union[datetime, str]] = None,
    end_time: Optional[Union[datetime, str]] = None,
    interval_second: Optional[int] = None,
    catchup: Optional[Union[str, bool]] = None,
    hydrate: bool = False,
    run_once_start_time: Optional[Union[datetime, str]] = None,
) -> Page[ScheduleResponse]:
    """List schedules.

    Args:
        sort_by: The column to sort by
        page: The page of items
        size: The maximum size of all pages
        logical_operator: Which logical operator to use [and, or]
        id: Use the id of stacks to filter by.
        created: Use to filter by time of creation
        updated: Use the last updated date for filtering
        name: The name of the stack to filter by.
        project: The project name/ID to filter by.
        user: Filter by user name/ID.
        pipeline_id: The id of the pipeline to filter by.
        orchestrator_id: The id of the orchestrator to filter by.
        active: Use to filter by active status.
        cron_expression: Use to filter by cron expression.
        start_time: Use to filter by start time.
        end_time: Use to filter by end time.
        interval_second: Use to filter by interval second.
        catchup: Use to filter by catchup.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.
        run_once_start_time: Use to filter by run once start time.

    Returns:
        A list of schedules.
    """
    schedule_filter_model = ScheduleFilter(
        sort_by=sort_by,
        page=page,
        size=size,
        logical_operator=logical_operator,
        id=id,
        created=created,
        updated=updated,
        name=name,
        project=project or self.active_project.id,
        user=user,
        pipeline_id=pipeline_id,
        orchestrator_id=orchestrator_id,
        active=active,
        cron_expression=cron_expression,
        start_time=start_time,
        end_time=end_time,
        interval_second=interval_second,
        catchup=catchup,
        run_once_start_time=run_once_start_time,
    )
    return self.zen_store.list_schedules(
        schedule_filter_model=schedule_filter_model,
        hydrate=hydrate,
    )
list_secrets(sort_by: str = 'created', page: int = PAGINATION_STARTING_PAGE, size: int = PAGE_SIZE_DEFAULT, logical_operator: LogicalOperators = LogicalOperators.AND, id: Optional[Union[UUID, str]] = None, created: Optional[datetime] = None, updated: Optional[datetime] = None, name: Optional[str] = None, private: Optional[bool] = None, user: Optional[Union[UUID, str]] = None, hydrate: bool = False) -> Page[SecretResponse]

Fetches all the secret models.

The returned secrets do not contain the secret values. To get the secret values, use get_secret individually for each secret.

Parameters:

Name Type Description Default
sort_by str

The column to sort by

'created'
page int

The page of items

PAGINATION_STARTING_PAGE
size int

The maximum size of all pages

PAGE_SIZE_DEFAULT
logical_operator LogicalOperators

Which logical operator to use [and, or]

AND
id Optional[Union[UUID, str]]

Use the id of secrets to filter by.

None
created Optional[datetime]

Use to secrets by time of creation

None
updated Optional[datetime]

Use the last updated date for filtering

None
name Optional[str]

The name of the secret to filter by.

None
private Optional[bool]

The private status of the secret to filter by.

None
user Optional[Union[UUID, str]]

Filter by user name/ID.

None
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

False

Returns:

Type Description
Page[SecretResponse]

A list of all the secret models without the secret values.

Raises:

Type Description
NotImplementedError

If centralized secrets management is not enabled.

Source code in src/zenml/client.py
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
def list_secrets(
    self,
    sort_by: str = "created",
    page: int = PAGINATION_STARTING_PAGE,
    size: int = PAGE_SIZE_DEFAULT,
    logical_operator: LogicalOperators = LogicalOperators.AND,
    id: Optional[Union[UUID, str]] = None,
    created: Optional[datetime] = None,
    updated: Optional[datetime] = None,
    name: Optional[str] = None,
    private: Optional[bool] = None,
    user: Optional[Union[UUID, str]] = None,
    hydrate: bool = False,
) -> Page[SecretResponse]:
    """Fetches all the secret models.

    The returned secrets do not contain the secret values. To get the
    secret values, use `get_secret` individually for each secret.

    Args:
        sort_by: The column to sort by
        page: The page of items
        size: The maximum size of all pages
        logical_operator: Which logical operator to use [and, or]
        id: Use the id of secrets to filter by.
        created: Use to secrets by time of creation
        updated: Use the last updated date for filtering
        name: The name of the secret to filter by.
        private: The private status of the secret to filter by.
        user: Filter by user name/ID.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        A list of all the secret models without the secret values.

    Raises:
        NotImplementedError: If centralized secrets management is not
            enabled.
    """
    secret_filter_model = SecretFilter(
        page=page,
        size=size,
        sort_by=sort_by,
        logical_operator=logical_operator,
        user=user,
        name=name,
        private=private,
        id=id,
        created=created,
        updated=updated,
    )
    try:
        return self.zen_store.list_secrets(
            secret_filter_model=secret_filter_model,
            hydrate=hydrate,
        )
    except NotImplementedError:
        raise NotImplementedError(
            "centralized secrets management is not supported or explicitly "
            "disabled in the target ZenML deployment."
        )
list_secrets_by_private_status(private: bool, hydrate: bool = False) -> Page[SecretResponse]

Fetches the list of secrets with a given private status.

The returned secrets do not contain the secret values. To get the secret values, use get_secret individually for each secret.

Parameters:

Name Type Description Default
private bool

The private status of the secrets to search for.

required
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

False

Returns:

Type Description
Page[SecretResponse]

The list of secrets in the given scope without the secret values.

Source code in src/zenml/client.py
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
def list_secrets_by_private_status(
    self,
    private: bool,
    hydrate: bool = False,
) -> Page[SecretResponse]:
    """Fetches the list of secrets with a given private status.

    The returned secrets do not contain the secret values. To get the
    secret values, use `get_secret` individually for each secret.

    Args:
        private: The private status of the secrets to search for.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        The list of secrets in the given scope without the secret values.
    """
    logger.debug(f"Fetching the secrets with private status '{private}'.")

    return self.list_secrets(private=private, hydrate=hydrate)
list_service_accounts(sort_by: str = 'created', page: int = PAGINATION_STARTING_PAGE, size: int = PAGE_SIZE_DEFAULT, logical_operator: LogicalOperators = LogicalOperators.AND, id: Optional[Union[UUID, str]] = None, created: Optional[Union[datetime, str]] = None, updated: Optional[Union[datetime, str]] = None, name: Optional[str] = None, description: Optional[str] = None, active: Optional[bool] = None, hydrate: bool = False) -> Page[ServiceAccountResponse]

List all service accounts.

Parameters:

Name Type Description Default
sort_by str

The column to sort by

'created'
page int

The page of items

PAGINATION_STARTING_PAGE
size int

The maximum size of all pages

PAGE_SIZE_DEFAULT
logical_operator LogicalOperators

Which logical operator to use [and, or]

AND
id Optional[Union[UUID, str]]

Use the id of stacks to filter by.

None
created Optional[Union[datetime, str]]

Use to filter by time of creation

None
updated Optional[Union[datetime, str]]

Use the last updated date for filtering

None
name Optional[str]

Use the service account name for filtering

None
description Optional[str]

Use the service account description for filtering

None
active Optional[bool]

Use the service account active status for filtering

None
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

False

Returns:

Type Description
Page[ServiceAccountResponse]

The list of service accounts matching the filter description.

Source code in src/zenml/client.py
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
def list_service_accounts(
    self,
    sort_by: str = "created",
    page: int = PAGINATION_STARTING_PAGE,
    size: int = PAGE_SIZE_DEFAULT,
    logical_operator: LogicalOperators = LogicalOperators.AND,
    id: Optional[Union[UUID, str]] = None,
    created: Optional[Union[datetime, str]] = None,
    updated: Optional[Union[datetime, str]] = None,
    name: Optional[str] = None,
    description: Optional[str] = None,
    active: Optional[bool] = None,
    hydrate: bool = False,
) -> Page[ServiceAccountResponse]:
    """List all service accounts.

    Args:
        sort_by: The column to sort by
        page: The page of items
        size: The maximum size of all pages
        logical_operator: Which logical operator to use [and, or]
        id: Use the id of stacks to filter by.
        created: Use to filter by time of creation
        updated: Use the last updated date for filtering
        name: Use the service account name for filtering
        description: Use the service account description for filtering
        active: Use the service account active status for filtering
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        The list of service accounts matching the filter description.
    """
    return self.zen_store.list_service_accounts(
        ServiceAccountFilter(
            sort_by=sort_by,
            page=page,
            size=size,
            logical_operator=logical_operator,
            id=id,
            created=created,
            updated=updated,
            name=name,
            description=description,
            active=active,
        ),
        hydrate=hydrate,
    )
list_service_connector_resources(connector_type: Optional[str] = None, resource_type: Optional[str] = None, resource_id: Optional[str] = None) -> List[ServiceConnectorResourcesModel]

List resources that can be accessed by service connectors.

Parameters:

Name Type Description Default
connector_type Optional[str]

The type of service connector to filter by.

None
resource_type Optional[str]

The type of resource to filter by.

None
resource_id Optional[str]

The ID of a particular resource instance to filter by.

None

Returns:

Type Description
List[ServiceConnectorResourcesModel]

The matching list of resources that available service

List[ServiceConnectorResourcesModel]

connectors have access to.

Source code in src/zenml/client.py
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
def list_service_connector_resources(
    self,
    connector_type: Optional[str] = None,
    resource_type: Optional[str] = None,
    resource_id: Optional[str] = None,
) -> List[ServiceConnectorResourcesModel]:
    """List resources that can be accessed by service connectors.

    Args:
        connector_type: The type of service connector to filter by.
        resource_type: The type of resource to filter by.
        resource_id: The ID of a particular resource instance to filter by.

    Returns:
        The matching list of resources that available service
        connectors have access to.
    """
    return self.zen_store.list_service_connector_resources(
        ServiceConnectorFilter(
            connector_type=connector_type,
            resource_type=resource_type,
            resource_id=resource_id,
        )
    )
list_service_connector_types(connector_type: Optional[str] = None, resource_type: Optional[str] = None, auth_method: Optional[str] = None) -> List[ServiceConnectorTypeModel]

Get a list of service connector types.

Parameters:

Name Type Description Default
connector_type Optional[str]

Filter by connector type.

None
resource_type Optional[str]

Filter by resource type.

None
auth_method Optional[str]

Filter by authentication method.

None

Returns:

Type Description
List[ServiceConnectorTypeModel]

List of service connector types.

Source code in src/zenml/client.py
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
def list_service_connector_types(
    self,
    connector_type: Optional[str] = None,
    resource_type: Optional[str] = None,
    auth_method: Optional[str] = None,
) -> List[ServiceConnectorTypeModel]:
    """Get a list of service connector types.

    Args:
        connector_type: Filter by connector type.
        resource_type: Filter by resource type.
        auth_method: Filter by authentication method.

    Returns:
        List of service connector types.
    """
    return self.zen_store.list_service_connector_types(
        connector_type=connector_type,
        resource_type=resource_type,
        auth_method=auth_method,
    )
list_service_connectors(sort_by: str = 'created', page: int = PAGINATION_STARTING_PAGE, size: int = PAGE_SIZE_DEFAULT, logical_operator: LogicalOperators = LogicalOperators.AND, id: Optional[Union[UUID, str]] = None, created: Optional[datetime] = None, updated: Optional[datetime] = None, name: Optional[str] = None, connector_type: Optional[str] = None, auth_method: Optional[str] = None, resource_type: Optional[str] = None, resource_id: Optional[str] = None, user: Optional[Union[UUID, str]] = None, labels: Optional[Dict[str, Optional[str]]] = None, secret_id: Optional[Union[str, UUID]] = None, hydrate: bool = False) -> Page[ServiceConnectorResponse]

Lists all registered service connectors.

Parameters:

Name Type Description Default
sort_by str

The column to sort by

'created'
page int

The page of items

PAGINATION_STARTING_PAGE
size int

The maximum size of all pages

PAGE_SIZE_DEFAULT
logical_operator LogicalOperators

Which logical operator to use [and, or]

AND
id Optional[Union[UUID, str]]

The id of the service connector to filter by.

None
created Optional[datetime]

Filter service connectors by time of creation

None
updated Optional[datetime]

Use the last updated date for filtering

None
connector_type Optional[str]

Use the service connector type for filtering

None
auth_method Optional[str]

Use the service connector auth method for filtering

None
resource_type Optional[str]

Filter service connectors by the resource type that they can give access to.

None
resource_id Optional[str]

Filter service connectors by the resource id that they can give access to.

None
user Optional[Union[UUID, str]]

Filter by user name/ID.

None
name Optional[str]

The name of the service connector to filter by.

None
labels Optional[Dict[str, Optional[str]]]

The labels of the service connector to filter by.

None
secret_id Optional[Union[str, UUID]]

Filter by the id of the secret that is referenced by the service connector.

None
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

False

Returns:

Type Description
Page[ServiceConnectorResponse]

A page of service connectors.

Source code in src/zenml/client.py
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
def list_service_connectors(
    self,
    sort_by: str = "created",
    page: int = PAGINATION_STARTING_PAGE,
    size: int = PAGE_SIZE_DEFAULT,
    logical_operator: LogicalOperators = LogicalOperators.AND,
    id: Optional[Union[UUID, str]] = None,
    created: Optional[datetime] = None,
    updated: Optional[datetime] = None,
    name: Optional[str] = None,
    connector_type: Optional[str] = None,
    auth_method: Optional[str] = None,
    resource_type: Optional[str] = None,
    resource_id: Optional[str] = None,
    user: Optional[Union[UUID, str]] = None,
    labels: Optional[Dict[str, Optional[str]]] = None,
    secret_id: Optional[Union[str, UUID]] = None,
    hydrate: bool = False,
) -> Page[ServiceConnectorResponse]:
    """Lists all registered service connectors.

    Args:
        sort_by: The column to sort by
        page: The page of items
        size: The maximum size of all pages
        logical_operator: Which logical operator to use [and, or]
        id: The id of the service connector to filter by.
        created: Filter service connectors by time of creation
        updated: Use the last updated date for filtering
        connector_type: Use the service connector type for filtering
        auth_method: Use the service connector auth method for filtering
        resource_type: Filter service connectors by the resource type that
            they can give access to.
        resource_id: Filter service connectors by the resource id that
            they can give access to.
        user: Filter by user name/ID.
        name: The name of the service connector to filter by.
        labels: The labels of the service connector to filter by.
        secret_id: Filter by the id of the secret that is referenced by the
            service connector.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        A page of service connectors.
    """
    connector_filter_model = ServiceConnectorFilter(
        page=page,
        size=size,
        sort_by=sort_by,
        logical_operator=logical_operator,
        user=user,
        name=name,
        connector_type=connector_type,
        auth_method=auth_method,
        resource_type=resource_type,
        resource_id=resource_id,
        id=id,
        created=created,
        updated=updated,
        labels=labels,
        secret_id=secret_id,
    )
    return self.zen_store.list_service_connectors(
        filter_model=connector_filter_model,
        hydrate=hydrate,
    )
list_services(sort_by: str = 'created', page: int = PAGINATION_STARTING_PAGE, size: int = PAGE_SIZE_DEFAULT, logical_operator: LogicalOperators = LogicalOperators.AND, id: Optional[Union[UUID, str]] = None, created: Optional[datetime] = None, updated: Optional[datetime] = None, type: Optional[str] = None, flavor: Optional[str] = None, user: Optional[Union[UUID, str]] = None, project: Optional[Union[str, UUID]] = None, hydrate: bool = False, running: Optional[bool] = None, service_name: Optional[str] = None, pipeline_name: Optional[str] = None, pipeline_run_id: Optional[str] = None, pipeline_step_name: Optional[str] = None, model_version_id: Optional[Union[str, UUID]] = None, config: Optional[Dict[str, Any]] = None) -> Page[ServiceResponse]

List all services.

Parameters:

Name Type Description Default
sort_by str

The column to sort by

'created'
page int

The page of items

PAGINATION_STARTING_PAGE
size int

The maximum size of all pages

PAGE_SIZE_DEFAULT
logical_operator LogicalOperators

Which logical operator to use [and, or]

AND
id Optional[Union[UUID, str]]

Use the id of services to filter by.

None
created Optional[datetime]

Use to filter by time of creation

None
updated Optional[datetime]

Use the last updated date for filtering

None
type Optional[str]

Use the service type for filtering

None
flavor Optional[str]

Use the service flavor for filtering

None
project Optional[Union[str, UUID]]

The project name/ID to filter by.

None
user Optional[Union[UUID, str]]

Filter by user name/ID.

None
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

False
running Optional[bool]

Use the running status for filtering

None
pipeline_name Optional[str]

Use the pipeline name for filtering

None
service_name Optional[str]

Use the service name or model name for filtering

None
pipeline_step_name Optional[str]

Use the pipeline step name for filtering

None
model_version_id Optional[Union[str, UUID]]

Use the model version id for filtering

None
config Optional[Dict[str, Any]]

Use the config for filtering

None
pipeline_run_id Optional[str]

Use the pipeline run id for filtering

None

Returns:

Type Description
Page[ServiceResponse]

The Service response page.

Source code in src/zenml/client.py
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
def list_services(
    self,
    sort_by: str = "created",
    page: int = PAGINATION_STARTING_PAGE,
    size: int = PAGE_SIZE_DEFAULT,
    logical_operator: LogicalOperators = LogicalOperators.AND,
    id: Optional[Union[UUID, str]] = None,
    created: Optional[datetime] = None,
    updated: Optional[datetime] = None,
    type: Optional[str] = None,
    flavor: Optional[str] = None,
    user: Optional[Union[UUID, str]] = None,
    project: Optional[Union[str, UUID]] = None,
    hydrate: bool = False,
    running: Optional[bool] = None,
    service_name: Optional[str] = None,
    pipeline_name: Optional[str] = None,
    pipeline_run_id: Optional[str] = None,
    pipeline_step_name: Optional[str] = None,
    model_version_id: Optional[Union[str, UUID]] = None,
    config: Optional[Dict[str, Any]] = None,
) -> Page[ServiceResponse]:
    """List all services.

    Args:
        sort_by: The column to sort by
        page: The page of items
        size: The maximum size of all pages
        logical_operator: Which logical operator to use [and, or]
        id: Use the id of services to filter by.
        created: Use to filter by time of creation
        updated: Use the last updated date for filtering
        type: Use the service type for filtering
        flavor: Use the service flavor for filtering
        project: The project name/ID to filter by.
        user: Filter by user name/ID.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.
        running: Use the running status for filtering
        pipeline_name: Use the pipeline name for filtering
        service_name: Use the service name or model name
            for filtering
        pipeline_step_name: Use the pipeline step name for filtering
        model_version_id: Use the model version id for filtering
        config: Use the config for filtering
        pipeline_run_id: Use the pipeline run id for filtering

    Returns:
        The Service response page.
    """
    service_filter_model = ServiceFilter(
        sort_by=sort_by,
        page=page,
        size=size,
        logical_operator=logical_operator,
        id=id,
        created=created,
        updated=updated,
        type=type,
        flavor=flavor,
        project=project or self.active_project.id,
        user=user,
        running=running,
        name=service_name,
        pipeline_name=pipeline_name,
        pipeline_step_name=pipeline_step_name,
        model_version_id=model_version_id,
        pipeline_run_id=pipeline_run_id,
        config=dict_to_bytes(config) if config else None,
    )
    return self.zen_store.list_services(
        filter_model=service_filter_model, hydrate=hydrate
    )
list_stack_components(sort_by: str = 'created', page: int = PAGINATION_STARTING_PAGE, size: int = PAGE_SIZE_DEFAULT, logical_operator: LogicalOperators = LogicalOperators.AND, id: Optional[Union[UUID, str]] = None, created: Optional[datetime] = None, updated: Optional[datetime] = None, name: Optional[str] = None, flavor: Optional[str] = None, type: Optional[str] = None, connector_id: Optional[Union[str, UUID]] = None, stack_id: Optional[Union[str, UUID]] = None, user: Optional[Union[UUID, str]] = None, hydrate: bool = False) -> Page[ComponentResponse]

Lists all registered stack components.

Parameters:

Name Type Description Default
sort_by str

The column to sort by

'created'
page int

The page of items

PAGINATION_STARTING_PAGE
size int

The maximum size of all pages

PAGE_SIZE_DEFAULT
logical_operator LogicalOperators

Which logical operator to use [and, or]

AND
id Optional[Union[UUID, str]]

Use the id of component to filter by.

None
created Optional[datetime]

Use to component by time of creation

None
updated Optional[datetime]

Use the last updated date for filtering

None
flavor Optional[str]

Use the component flavor for filtering

None
type Optional[str]

Use the component type for filtering

None
connector_id Optional[Union[str, UUID]]

The id of the connector to filter by.

None
stack_id Optional[Union[str, UUID]]

The id of the stack to filter by.

None
name Optional[str]

The name of the component to filter by.

None
user Optional[Union[UUID, str]]

The ID of name of the user to filter by.

None
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

False

Returns:

Type Description
Page[ComponentResponse]

A page of stack components.

Source code in src/zenml/client.py
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
def list_stack_components(
    self,
    sort_by: str = "created",
    page: int = PAGINATION_STARTING_PAGE,
    size: int = PAGE_SIZE_DEFAULT,
    logical_operator: LogicalOperators = LogicalOperators.AND,
    id: Optional[Union[UUID, str]] = None,
    created: Optional[datetime] = None,
    updated: Optional[datetime] = None,
    name: Optional[str] = None,
    flavor: Optional[str] = None,
    type: Optional[str] = None,
    connector_id: Optional[Union[str, UUID]] = None,
    stack_id: Optional[Union[str, UUID]] = None,
    user: Optional[Union[UUID, str]] = None,
    hydrate: bool = False,
) -> Page[ComponentResponse]:
    """Lists all registered stack components.

    Args:
        sort_by: The column to sort by
        page: The page of items
        size: The maximum size of all pages
        logical_operator: Which logical operator to use [and, or]
        id: Use the id of component to filter by.
        created: Use to component by time of creation
        updated: Use the last updated date for filtering
        flavor: Use the component flavor for filtering
        type: Use the component type for filtering
        connector_id: The id of the connector to filter by.
        stack_id: The id of the stack to filter by.
        name: The name of the component to filter by.
        user: The ID of name of the user to filter by.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        A page of stack components.
    """
    component_filter_model = ComponentFilter(
        page=page,
        size=size,
        sort_by=sort_by,
        logical_operator=logical_operator,
        connector_id=connector_id,
        stack_id=stack_id,
        name=name,
        flavor=flavor,
        type=type,
        id=id,
        created=created,
        updated=updated,
        user=user,
    )

    return self.zen_store.list_stack_components(
        component_filter_model=component_filter_model, hydrate=hydrate
    )
list_stacks(sort_by: str = 'created', page: int = PAGINATION_STARTING_PAGE, size: int = PAGE_SIZE_DEFAULT, logical_operator: LogicalOperators = LogicalOperators.AND, id: Optional[Union[UUID, str]] = None, created: Optional[Union[datetime, str]] = None, updated: Optional[Union[datetime, str]] = None, name: Optional[str] = None, description: Optional[str] = None, component_id: Optional[Union[str, UUID]] = None, user: Optional[Union[UUID, str]] = None, component: Optional[Union[UUID, str]] = None, hydrate: bool = False) -> Page[StackResponse]

Lists all stacks.

Parameters:

Name Type Description Default
sort_by str

The column to sort by

'created'
page int

The page of items

PAGINATION_STARTING_PAGE
size int

The maximum size of all pages

PAGE_SIZE_DEFAULT
logical_operator LogicalOperators

Which logical operator to use [and, or]

AND
id Optional[Union[UUID, str]]

Use the id of stacks to filter by.

None
created Optional[Union[datetime, str]]

Use to filter by time of creation

None
updated Optional[Union[datetime, str]]

Use the last updated date for filtering

None
description Optional[str]

Use the stack description for filtering

None
component_id Optional[Union[str, UUID]]

The id of the component to filter by.

None
user Optional[Union[UUID, str]]

The name/ID of the user to filter by.

None
component Optional[Union[UUID, str]]

The name/ID of the component to filter by.

None
name Optional[str]

The name of the stack to filter by.

None
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

False

Returns:

Type Description
Page[StackResponse]

A page of stacks.

Source code in src/zenml/client.py
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
def list_stacks(
    self,
    sort_by: str = "created",
    page: int = PAGINATION_STARTING_PAGE,
    size: int = PAGE_SIZE_DEFAULT,
    logical_operator: LogicalOperators = LogicalOperators.AND,
    id: Optional[Union[UUID, str]] = None,
    created: Optional[Union[datetime, str]] = None,
    updated: Optional[Union[datetime, str]] = None,
    name: Optional[str] = None,
    description: Optional[str] = None,
    component_id: Optional[Union[str, UUID]] = None,
    user: Optional[Union[UUID, str]] = None,
    component: Optional[Union[UUID, str]] = None,
    hydrate: bool = False,
) -> Page[StackResponse]:
    """Lists all stacks.

    Args:
        sort_by: The column to sort by
        page: The page of items
        size: The maximum size of all pages
        logical_operator: Which logical operator to use [and, or]
        id: Use the id of stacks to filter by.
        created: Use to filter by time of creation
        updated: Use the last updated date for filtering
        description: Use the stack description for filtering
        component_id: The id of the component to filter by.
        user: The name/ID of the user to filter by.
        component: The name/ID of the component to filter by.
        name: The name of the stack to filter by.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        A page of stacks.
    """
    stack_filter_model = StackFilter(
        page=page,
        size=size,
        sort_by=sort_by,
        logical_operator=logical_operator,
        component_id=component_id,
        user=user,
        component=component,
        name=name,
        description=description,
        id=id,
        created=created,
        updated=updated,
    )
    return self.zen_store.list_stacks(stack_filter_model, hydrate=hydrate)
list_tags(sort_by: str = 'created', page: int = PAGINATION_STARTING_PAGE, size: int = PAGE_SIZE_DEFAULT, logical_operator: LogicalOperators = LogicalOperators.AND, id: Optional[Union[UUID, str]] = None, user: Optional[Union[UUID, str]] = None, created: Optional[Union[datetime, str]] = None, updated: Optional[Union[datetime, str]] = None, name: Optional[str] = None, color: Optional[Union[str, ColorVariants]] = None, exclusive: Optional[bool] = None, resource_type: Optional[Union[str, TaggableResourceTypes]] = None, hydrate: bool = False) -> Page[TagResponse]

Get tags by filter.

Parameters:

Name Type Description Default
sort_by str

The column to sort by.

'created'
page int

The page of items.

PAGINATION_STARTING_PAGE
size int

The maximum size of all pages

PAGE_SIZE_DEFAULT
logical_operator LogicalOperators

Which logical operator to use [and, or].

AND
id Optional[Union[UUID, str]]

Use the id of stacks to filter by.

None
user Optional[Union[UUID, str]]

Use the user to filter by.

None
created Optional[Union[datetime, str]]

Use to filter by time of creation.

None
updated Optional[Union[datetime, str]]

Use the last updated date for filtering.

None
name Optional[str]

The name of the tag.

None
color Optional[Union[str, ColorVariants]]

The color of the tag.

None
exclusive Optional[bool]

Flag indicating whether the tag is exclusive.

None
resource_type Optional[Union[str, TaggableResourceTypes]]

Filter tags associated with a specific resource type.

None
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

False

Returns:

Type Description
Page[TagResponse]

A page of all tags.

Source code in src/zenml/client.py
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
def list_tags(
    self,
    sort_by: str = "created",
    page: int = PAGINATION_STARTING_PAGE,
    size: int = PAGE_SIZE_DEFAULT,
    logical_operator: LogicalOperators = LogicalOperators.AND,
    id: Optional[Union[UUID, str]] = None,
    user: Optional[Union[UUID, str]] = None,
    created: Optional[Union[datetime, str]] = None,
    updated: Optional[Union[datetime, str]] = None,
    name: Optional[str] = None,
    color: Optional[Union[str, ColorVariants]] = None,
    exclusive: Optional[bool] = None,
    resource_type: Optional[Union[str, TaggableResourceTypes]] = None,
    hydrate: bool = False,
) -> Page[TagResponse]:
    """Get tags by filter.

    Args:
        sort_by: The column to sort by.
        page: The page of items.
        size: The maximum size of all pages
        logical_operator: Which logical operator to use [and, or].
        id: Use the id of stacks to filter by.
        user: Use the user to filter by.
        created: Use to filter by time of creation.
        updated: Use the last updated date for filtering.
        name: The name of the tag.
        color: The color of the tag.
        exclusive: Flag indicating whether the tag is exclusive.
        resource_type: Filter tags associated with a specific resource type.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        A page of all tags.
    """
    return self.zen_store.list_tags(
        tag_filter_model=TagFilter(
            sort_by=sort_by,
            page=page,
            size=size,
            logical_operator=logical_operator,
            id=id,
            user=user,
            created=created,
            updated=updated,
            name=name,
            color=color,
            exclusive=exclusive,
            resource_type=resource_type,
        ),
        hydrate=hydrate,
    )
list_trigger_executions(sort_by: str = 'created', page: int = PAGINATION_STARTING_PAGE, size: int = PAGE_SIZE_DEFAULT, logical_operator: LogicalOperators = LogicalOperators.AND, trigger_id: Optional[UUID] = None, user: Optional[Union[UUID, str]] = None, project: Optional[Union[UUID, str]] = None, hydrate: bool = False) -> Page[TriggerExecutionResponse]

List all trigger executions matching the given filter criteria.

Parameters:

Name Type Description Default
sort_by str

The column to sort by.

'created'
page int

The page of items.

PAGINATION_STARTING_PAGE
size int

The maximum size of all pages.

PAGE_SIZE_DEFAULT
logical_operator LogicalOperators

Which logical operator to use [and, or].

AND
trigger_id Optional[UUID]

ID of the trigger to filter by.

None
user Optional[Union[UUID, str]]

Filter by user name/ID.

None
project Optional[Union[UUID, str]]

Filter by project name/ID.

None
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

False

Returns:

Type Description
Page[TriggerExecutionResponse]

A list of all trigger executions matching the filter criteria.

Source code in src/zenml/client.py
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
def list_trigger_executions(
    self,
    sort_by: str = "created",
    page: int = PAGINATION_STARTING_PAGE,
    size: int = PAGE_SIZE_DEFAULT,
    logical_operator: LogicalOperators = LogicalOperators.AND,
    trigger_id: Optional[UUID] = None,
    user: Optional[Union[UUID, str]] = None,
    project: Optional[Union[UUID, str]] = None,
    hydrate: bool = False,
) -> Page[TriggerExecutionResponse]:
    """List all trigger executions matching the given filter criteria.

    Args:
        sort_by: The column to sort by.
        page: The page of items.
        size: The maximum size of all pages.
        logical_operator: Which logical operator to use [and, or].
        trigger_id: ID of the trigger to filter by.
        user: Filter by user name/ID.
        project: Filter by project name/ID.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        A list of all trigger executions matching the filter criteria.
    """
    filter_model = TriggerExecutionFilter(
        trigger_id=trigger_id,
        sort_by=sort_by,
        page=page,
        size=size,
        user=user,
        logical_operator=logical_operator,
        project=project or self.active_project.id,
    )
    return self.zen_store.list_trigger_executions(
        trigger_execution_filter_model=filter_model, hydrate=hydrate
    )
list_triggers(sort_by: str = 'created', page: int = PAGINATION_STARTING_PAGE, size: int = PAGE_SIZE_DEFAULT, logical_operator: LogicalOperators = LogicalOperators.AND, id: Optional[Union[UUID, str]] = None, created: Optional[datetime] = None, updated: Optional[datetime] = None, name: Optional[str] = None, event_source_id: Optional[UUID] = None, action_id: Optional[UUID] = None, event_source_flavor: Optional[str] = None, event_source_subtype: Optional[str] = None, action_flavor: Optional[str] = None, action_subtype: Optional[str] = None, project: Optional[Union[str, UUID]] = None, user: Optional[Union[UUID, str]] = None, hydrate: bool = False) -> Page[TriggerResponse]

Lists all triggers.

Parameters:

Name Type Description Default
sort_by str

The column to sort by

'created'
page int

The page of items

PAGINATION_STARTING_PAGE
size int

The maximum size of all pages

PAGE_SIZE_DEFAULT
logical_operator LogicalOperators

Which logical operator to use [and, or]

AND
id Optional[Union[UUID, str]]

Use the id of triggers to filter by.

None
created Optional[datetime]

Use to filter by time of creation

None
updated Optional[datetime]

Use the last updated date for filtering

None
project Optional[Union[str, UUID]]

The project name/ID to filter by.

None
user Optional[Union[UUID, str]]

Filter by user name/ID.

None
name Optional[str]

The name of the trigger to filter by.

None
event_source_id Optional[UUID]

The event source associated with the trigger.

None
action_id Optional[UUID]

The action associated with the trigger.

None
event_source_flavor Optional[str]

Flavor of the event source associated with the trigger.

None
event_source_subtype Optional[str]

Type of the event source associated with the trigger.

None
action_flavor Optional[str]

Flavor of the action associated with the trigger.

None
action_subtype Optional[str]

Type of the action associated with the trigger.

None
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

False

Returns:

Type Description
Page[TriggerResponse]

A page of triggers.

Source code in src/zenml/client.py
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
@_fail_for_sql_zen_store
def list_triggers(
    self,
    sort_by: str = "created",
    page: int = PAGINATION_STARTING_PAGE,
    size: int = PAGE_SIZE_DEFAULT,
    logical_operator: LogicalOperators = LogicalOperators.AND,
    id: Optional[Union[UUID, str]] = None,
    created: Optional[datetime] = None,
    updated: Optional[datetime] = None,
    name: Optional[str] = None,
    event_source_id: Optional[UUID] = None,
    action_id: Optional[UUID] = None,
    event_source_flavor: Optional[str] = None,
    event_source_subtype: Optional[str] = None,
    action_flavor: Optional[str] = None,
    action_subtype: Optional[str] = None,
    project: Optional[Union[str, UUID]] = None,
    user: Optional[Union[UUID, str]] = None,
    hydrate: bool = False,
) -> Page[TriggerResponse]:
    """Lists all triggers.

    Args:
        sort_by: The column to sort by
        page: The page of items
        size: The maximum size of all pages
        logical_operator: Which logical operator to use [and, or]
        id: Use the id of triggers to filter by.
        created: Use to filter by time of creation
        updated: Use the last updated date for filtering
        project: The project name/ID to filter by.
        user: Filter by user name/ID.
        name: The name of the trigger to filter by.
        event_source_id: The event source associated with the trigger.
        action_id: The action associated with the trigger.
        event_source_flavor: Flavor of the event source associated with the
            trigger.
        event_source_subtype: Type of the event source associated with the
            trigger.
        action_flavor: Flavor of the action associated with the trigger.
        action_subtype: Type of the action associated with the trigger.
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        A page of triggers.
    """
    trigger_filter_model = TriggerFilter(
        page=page,
        size=size,
        sort_by=sort_by,
        logical_operator=logical_operator,
        project=project or self.active_project.id,
        user=user,
        name=name,
        event_source_id=event_source_id,
        action_id=action_id,
        event_source_flavor=event_source_flavor,
        event_source_subtype=event_source_subtype,
        action_flavor=action_flavor,
        action_subtype=action_subtype,
        id=id,
        created=created,
        updated=updated,
    )
    return self.zen_store.list_triggers(
        trigger_filter_model, hydrate=hydrate
    )
list_users(sort_by: str = 'created', page: int = PAGINATION_STARTING_PAGE, size: int = PAGE_SIZE_DEFAULT, logical_operator: LogicalOperators = LogicalOperators.AND, id: Optional[Union[UUID, str]] = None, external_user_id: Optional[str] = None, created: Optional[Union[datetime, str]] = None, updated: Optional[Union[datetime, str]] = None, name: Optional[str] = None, full_name: Optional[str] = None, email: Optional[str] = None, active: Optional[bool] = None, email_opted_in: Optional[bool] = None, hydrate: bool = False) -> Page[UserResponse]

List all users.

Parameters:

Name Type Description Default
sort_by str

The column to sort by

'created'
page int

The page of items

PAGINATION_STARTING_PAGE
size int

The maximum size of all pages

PAGE_SIZE_DEFAULT
logical_operator LogicalOperators

Which logical operator to use [and, or]

AND
id Optional[Union[UUID, str]]

Use the id of stacks to filter by.

None
external_user_id Optional[str]

Use the external user id for filtering.

None
created Optional[Union[datetime, str]]

Use to filter by time of creation

None
updated Optional[Union[datetime, str]]

Use the last updated date for filtering

None
name Optional[str]

Use the username for filtering

None
full_name Optional[str]

Use the user full name for filtering

None
email Optional[str]

Use the user email for filtering

None
active Optional[bool]

User the user active status for filtering

None
email_opted_in Optional[bool]

Use the user opt in status for filtering

None
hydrate bool

Flag deciding whether to hydrate the output model(s) by including metadata fields in the response.

False

Returns:

Type Description
Page[UserResponse]

The User

Source code in src/zenml/client.py
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
def list_users(
    self,
    sort_by: str = "created",
    page: int = PAGINATION_STARTING_PAGE,
    size: int = PAGE_SIZE_DEFAULT,
    logical_operator: LogicalOperators = LogicalOperators.AND,
    id: Optional[Union[UUID, str]] = None,
    external_user_id: Optional[str] = None,
    created: Optional[Union[datetime, str]] = None,
    updated: Optional[Union[datetime, str]] = None,
    name: Optional[str] = None,
    full_name: Optional[str] = None,
    email: Optional[str] = None,
    active: Optional[bool] = None,
    email_opted_in: Optional[bool] = None,
    hydrate: bool = False,
) -> Page[UserResponse]:
    """List all users.

    Args:
        sort_by: The column to sort by
        page: The page of items
        size: The maximum size of all pages
        logical_operator: Which logical operator to use [and, or]
        id: Use the id of stacks to filter by.
        external_user_id: Use the external user id for filtering.
        created: Use to filter by time of creation
        updated: Use the last updated date for filtering
        name: Use the username for filtering
        full_name: Use the user full name for filtering
        email: Use the user email for filtering
        active: User the user active status for filtering
        email_opted_in: Use the user opt in status for filtering
        hydrate: Flag deciding whether to hydrate the output model(s)
            by including metadata fields in the response.

    Returns:
        The User
    """
    return self.zen_store.list_users(
        UserFilter(
            sort_by=sort_by,
            page=page,
            size=size,
            logical_operator=logical_operator,
            id=id,
            external_user_id=external_user_id,
            created=created,
            updated=updated,
            name=name,
            full_name=full_name,
            email=email,
            active=active,
            email_opted_in=email_opted_in,
        ),
        hydrate=hydrate,
    )
login_service_connector(name_id_or_prefix: Union[UUID, str], resource_type: Optional[str] = None, resource_id: Optional[str] = None, **kwargs: Any) -> ServiceConnector

Use a service connector to authenticate a local client/SDK.

Parameters:

Name Type Description Default
name_id_or_prefix Union[UUID, str]

The name, id or prefix of the service connector to use.

required
resource_type Optional[str]

The type of the resource to connect to. If not provided, the resource type from the service connector configuration will be used.

None
resource_id Optional[str]

The ID of a particular resource instance to configure the local client to connect to. If the connector instance is already configured with a resource ID that is not the same or equivalent to the one requested, a ValueError exception is raised. May be omitted for connectors and resource types that do not support multiple resource instances.

None
kwargs Any

Additional implementation specific keyword arguments to use to configure the client.

{}

Returns:

Type Description
ServiceConnector

The service connector client instance that was used to configure the

ServiceConnector

local client.

Source code in src/zenml/client.py
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
def login_service_connector(
    self,
    name_id_or_prefix: Union[UUID, str],
    resource_type: Optional[str] = None,
    resource_id: Optional[str] = None,
    **kwargs: Any,
) -> "ServiceConnector":
    """Use a service connector to authenticate a local client/SDK.

    Args:
        name_id_or_prefix: The name, id or prefix of the service connector
            to use.
        resource_type: The type of the resource to connect to. If not
            provided, the resource type from the service connector
            configuration will be used.
        resource_id: The ID of a particular resource instance to configure
            the local client to connect to. If the connector instance is
            already configured with a resource ID that is not the same or
            equivalent to the one requested, a `ValueError` exception is
            raised. May be omitted for connectors and resource types that do
            not support multiple resource instances.
        kwargs: Additional implementation specific keyword arguments to use
            to configure the client.

    Returns:
        The service connector client instance that was used to configure the
        local client.
    """
    connector_client = self.get_service_connector_client(
        name_id_or_prefix=name_id_or_prefix,
        resource_type=resource_type,
        resource_id=resource_id,
        verify=False,
    )

    connector_client.configure_local_client(
        **kwargs,
    )

    return connector_client
prune_artifacts(only_versions: bool = True, delete_from_artifact_store: bool = False, project: Optional[Union[str, UUID]] = None) -> None

Delete all unused artifacts and artifact versions.

Parameters:

Name Type Description Default
only_versions bool

Only delete artifact versions, keeping artifacts

True
delete_from_artifact_store bool

Delete data from artifact metadata

False
project Optional[Union[str, UUID]]

The project name/ID to filter by.

None
Source code in src/zenml/client.py
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
def prune_artifacts(
    self,
    only_versions: bool = True,
    delete_from_artifact_store: bool = False,
    project: Optional[Union[str, UUID]] = None,
) -> None:
    """Delete all unused artifacts and artifact versions.

    Args:
        only_versions: Only delete artifact versions, keeping artifacts
        delete_from_artifact_store: Delete data from artifact metadata
        project: The project name/ID to filter by.
    """
    if delete_from_artifact_store:
        unused_artifact_versions = depaginate(
            self.list_artifact_versions,
            only_unused=True,
            project=project,
        )
        for unused_artifact_version in unused_artifact_versions:
            self._delete_artifact_from_artifact_store(
                unused_artifact_version
            )

    project = project or self.active_project.id

    self.zen_store.prune_artifact_versions(
        project_name_or_id=project, only_versions=only_versions
    )
    logger.info("All unused artifacts and artifact versions deleted.")
restore_secrets(ignore_errors: bool = False, delete_secrets: bool = False) -> None

Restore all secrets from the configured backup secrets store.

Parameters:

Name Type Description Default
ignore_errors bool

Whether to ignore individual errors during the restore process and attempt to restore all secrets.

False
delete_secrets bool

Whether to delete the secrets that have been successfully restored from the backup secrets store. Setting this flag effectively moves all secrets from the backup secrets store to the primary secrets store.

False
Source code in src/zenml/client.py
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
def restore_secrets(
    self,
    ignore_errors: bool = False,
    delete_secrets: bool = False,
) -> None:
    """Restore all secrets from the configured backup secrets store.

    Args:
        ignore_errors: Whether to ignore individual errors during the
            restore process and attempt to restore all secrets.
        delete_secrets: Whether to delete the secrets that have been
            successfully restored from the backup secrets store. Setting
            this flag effectively moves all secrets from the backup secrets
            store to the primary secrets store.
    """
    self.zen_store.restore_secrets(
        ignore_errors=ignore_errors, delete_secrets=delete_secrets
    )
rotate_api_key(service_account_name_id_or_prefix: Union[str, UUID], name_id_or_prefix: Union[UUID, str], retain_period_minutes: int = 0, set_key: bool = False) -> APIKeyResponse

Rotate an API key.

Parameters:

Name Type Description Default
service_account_name_id_or_prefix Union[str, UUID]

The name, ID or prefix of the service account to rotate the API key for.

required
name_id_or_prefix Union[UUID, str]

Name, ID or prefix of the API key to update.

required
retain_period_minutes int

The number of minutes to retain the old API key for. If set to 0, the old API key will be invalidated.

0
set_key bool

Whether to set the rotated API key as the active API key.

False

Returns:

Type Description
APIKeyResponse

The updated API key.

Source code in src/zenml/client.py
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
def rotate_api_key(
    self,
    service_account_name_id_or_prefix: Union[str, UUID],
    name_id_or_prefix: Union[UUID, str],
    retain_period_minutes: int = 0,
    set_key: bool = False,
) -> APIKeyResponse:
    """Rotate an API key.

    Args:
        service_account_name_id_or_prefix: The name, ID or prefix of the
            service account to rotate the API key for.
        name_id_or_prefix: Name, ID or prefix of the API key to update.
        retain_period_minutes: The number of minutes to retain the old API
            key for. If set to 0, the old API key will be invalidated.
        set_key: Whether to set the rotated API key as the active API key.

    Returns:
        The updated API key.
    """
    api_key = self.get_api_key(
        service_account_name_id_or_prefix=service_account_name_id_or_prefix,
        name_id_or_prefix=name_id_or_prefix,
        allow_name_prefix_match=False,
    )
    rotate_request = APIKeyRotateRequest(
        retain_period_minutes=retain_period_minutes
    )
    new_key = self.zen_store.rotate_api_key(
        service_account_id=api_key.service_account.id,
        api_key_name_or_id=api_key.id,
        rotate_request=rotate_request,
    )
    assert new_key.key is not None
    if set_key:
        self.set_api_key(key=new_key.key)

    return new_key
set_active_project(project_name_or_id: Union[str, UUID]) -> ProjectResponse

Set the project for the local client.

Parameters:

Name Type Description Default
project_name_or_id Union[str, UUID]

The name or ID of the project to set active.

required

Returns:

Type Description
ProjectResponse

The model of the active project.

Source code in src/zenml/client.py
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
def set_active_project(
    self, project_name_or_id: Union[str, UUID]
) -> "ProjectResponse":
    """Set the project for the local client.

    Args:
        project_name_or_id: The name or ID of the project to set active.

    Returns:
        The model of the active project.
    """
    project = self.zen_store.get_project(
        project_name_or_id=project_name_or_id
    )  # raises KeyError
    if self._config:
        self._config.set_active_project(project)
        # Sanitize the client configuration to reflect the current
        # settings
        self._sanitize_config()
    else:
        # set the active project globally only if the client doesn't use
        # a local configuration
        GlobalConfiguration().set_active_project(project)
    return project
set_api_key(key: str) -> None

Configure the client with an API key.

Parameters:

Name Type Description Default
key str

The API key to use.

required

Raises:

Type Description
NotImplementedError

If the client is not connected to a ZenML server.

Source code in src/zenml/client.py
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
def set_api_key(self, key: str) -> None:
    """Configure the client with an API key.

    Args:
        key: The API key to use.

    Raises:
        NotImplementedError: If the client is not connected to a ZenML
            server.
    """
    from zenml.login.credentials_store import get_credentials_store
    from zenml.zen_stores.rest_zen_store import RestZenStore

    zen_store = self.zen_store
    if not zen_store.TYPE == StoreType.REST:
        raise NotImplementedError(
            "API key configuration is only supported if connected to a "
            "ZenML server."
        )

    credentials_store = get_credentials_store()
    assert isinstance(zen_store, RestZenStore)

    credentials_store.set_api_key(server_url=zen_store.url, api_key=key)

    # Force a re-authentication to start using the new API key
    # right away.
    zen_store.authenticate(force=True)
trigger_pipeline(pipeline_name_or_id: Union[str, UUID, None] = None, run_configuration: Union[PipelineRunConfiguration, Dict[str, Any], None] = None, config_path: Optional[str] = None, template_id: Optional[UUID] = None, stack_name_or_id: Union[str, UUID, None] = None, synchronous: bool = False, project: Optional[Union[str, UUID]] = None) -> PipelineRunResponse

Trigger a pipeline from the server.

Usage examples: * Run the latest runnable template for a pipeline:

Client().trigger_pipeline(pipeline_name_or_id=<NAME>)
  • Run the latest runnable template for a pipeline on a specific stack:
Client().trigger_pipeline(
    pipeline_name_or_id=<NAME>,
    stack_name_or_id=<STACK_NAME_OR_ID>
)
  • Run a specific template:
Client().trigger_pipeline(template_id=<ID>)

Parameters:

Name Type Description Default
pipeline_name_or_id Union[str, UUID, None]

Name or ID of the pipeline. If this is specified, the latest runnable template for this pipeline will be used for the run (Runnable here means that the build associated with the template is for a remote stack without any custom flavor stack components). If not given, a template ID that should be run needs to be specified.

None
run_configuration Union[PipelineRunConfiguration, Dict[str, Any], None]

Configuration for the run. Either this or a path to a config file can be specified.

None
config_path Optional[str]

Path to a YAML configuration file. This file will be parsed as a PipelineRunConfiguration object. Either this or the configuration in code can be specified.

None
template_id Optional[UUID]

ID of the template to run. Either this or a pipeline can be specified.

None
stack_name_or_id Union[str, UUID, None]

Name or ID of the stack on which to run the pipeline. If not specified, this method will try to find a runnable template on any stack.

None
synchronous bool

If True, this method will wait until the triggered run is finished.

False
project Optional[Union[str, UUID]]

The project name/ID to filter by.

None

Raises:

Type Description
RuntimeError

If triggering the pipeline failed.

Returns:

Type Description
PipelineRunResponse

Model of the pipeline run.

Source code in src/zenml/client.py
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
@_fail_for_sql_zen_store
def trigger_pipeline(
    self,
    pipeline_name_or_id: Union[str, UUID, None] = None,
    run_configuration: Union[
        PipelineRunConfiguration, Dict[str, Any], None
    ] = None,
    config_path: Optional[str] = None,
    template_id: Optional[UUID] = None,
    stack_name_or_id: Union[str, UUID, None] = None,
    synchronous: bool = False,
    project: Optional[Union[str, UUID]] = None,
) -> PipelineRunResponse:
    """Trigger a pipeline from the server.

    Usage examples:
    * Run the latest runnable template for a pipeline:
    ```python
    Client().trigger_pipeline(pipeline_name_or_id=<NAME>)
    ```
    * Run the latest runnable template for a pipeline on a specific stack:
    ```python
    Client().trigger_pipeline(
        pipeline_name_or_id=<NAME>,
        stack_name_or_id=<STACK_NAME_OR_ID>
    )
    ```
    * Run a specific template:
    ```python
    Client().trigger_pipeline(template_id=<ID>)
    ```

    Args:
        pipeline_name_or_id: Name or ID of the pipeline. If this is
            specified, the latest runnable template for this pipeline will
            be used for the run (Runnable here means that the build
            associated with the template is for a remote stack without any
            custom flavor stack components). If not given, a template ID
            that should be run needs to be specified.
        run_configuration: Configuration for the run. Either this or a
            path to a config file can be specified.
        config_path: Path to a YAML configuration file. This file will be
            parsed as a `PipelineRunConfiguration` object. Either this or
            the configuration in code can be specified.
        template_id: ID of the template to run. Either this or a pipeline
            can be specified.
        stack_name_or_id: Name or ID of the stack on which to run the
            pipeline. If not specified, this method will try to find a
            runnable template on any stack.
        synchronous: If `True`, this method will wait until the triggered
            run is finished.
        project: The project name/ID to filter by.

    Raises:
        RuntimeError: If triggering the pipeline failed.

    Returns:
        Model of the pipeline run.
    """
    from zenml.pipelines.run_utils import (
        validate_run_config_is_runnable_from_server,
        validate_stack_is_runnable_from_server,
        wait_for_pipeline_run_to_finish,
    )

    if Counter([template_id, pipeline_name_or_id])[None] != 1:
        raise RuntimeError(
            "You need to specify exactly one of pipeline or template "
            "to trigger."
        )

    if run_configuration and config_path:
        raise RuntimeError(
            "Only config path or runtime configuration can be specified."
        )

    if config_path:
        run_configuration = PipelineRunConfiguration.from_yaml(config_path)

    if isinstance(run_configuration, Dict):
        run_configuration = PipelineRunConfiguration.model_validate(
            run_configuration
        )

    if run_configuration:
        validate_run_config_is_runnable_from_server(run_configuration)

    if template_id:
        if stack_name_or_id:
            logger.warning(
                "Template ID and stack specified, ignoring the stack and "
                "using stack associated with the template instead."
            )

        run = self.zen_store.run_template(
            template_id=template_id,
            run_configuration=run_configuration,
        )
    else:
        assert pipeline_name_or_id
        pipeline = self.get_pipeline(name_id_or_prefix=pipeline_name_or_id)

        stack = None
        if stack_name_or_id:
            stack = self.get_stack(
                stack_name_or_id, allow_name_prefix_match=False
            )
            validate_stack_is_runnable_from_server(
                zen_store=self.zen_store, stack=stack
            )

        templates = depaginate(
            self.list_run_templates,
            pipeline_id=pipeline.id,
            stack_id=stack.id if stack else None,
            project=project or pipeline.project.id,
        )

        for template in templates:
            if not template.build:
                continue

            stack = template.build.stack
            if not stack:
                continue

            try:
                validate_stack_is_runnable_from_server(
                    zen_store=self.zen_store, stack=stack
                )
            except ValueError:
                continue

            run = self.zen_store.run_template(
                template_id=template.id,
                run_configuration=run_configuration,
            )
            break
        else:
            raise RuntimeError(
                "Unable to find a runnable template for the given stack "
                "and pipeline."
            )

    if synchronous:
        run = wait_for_pipeline_run_to_finish(run_id=run.id)

    return run
update_action(name_id_or_prefix: Union[UUID, str], name: Optional[str] = None, description: Optional[str] = None, configuration: Optional[Dict[str, Any]] = None, service_account_id: Optional[UUID] = None, auth_window: Optional[int] = None, project: Optional[Union[str, UUID]] = None) -> ActionResponse

Update an action.

Parameters:

Name Type Description Default
name_id_or_prefix Union[UUID, str]

The name, id or prefix of the action to update.

required
name Optional[str]

The new name of the action.

None
description Optional[str]

The new description of the action.

None
configuration Optional[Dict[str, Any]]

The new configuration of the action.

None
service_account_id Optional[UUID]

The new service account that is used to execute the action.

None
auth_window Optional[int]

The new time window in minutes for which the service account is authorized to execute the action. Set this to 0 to authorize the service account indefinitely (not recommended).

None
project Optional[Union[str, UUID]]

The project name/ID to filter by.

None

Returns:

Type Description
ActionResponse

The updated action.

Source code in src/zenml/client.py
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
@_fail_for_sql_zen_store
def update_action(
    self,
    name_id_or_prefix: Union[UUID, str],
    name: Optional[str] = None,
    description: Optional[str] = None,
    configuration: Optional[Dict[str, Any]] = None,
    service_account_id: Optional[UUID] = None,
    auth_window: Optional[int] = None,
    project: Optional[Union[str, UUID]] = None,
) -> ActionResponse:
    """Update an action.

    Args:
        name_id_or_prefix: The name, id or prefix of the action to update.
        name: The new name of the action.
        description: The new description of the action.
        configuration: The new configuration of the action.
        service_account_id: The new service account that is used to execute
            the action.
        auth_window: The new time window in minutes for which the service
            account is authorized to execute the action. Set this to 0 to
            authorize the service account indefinitely (not recommended).
        project: The project name/ID to filter by.

    Returns:
        The updated action.
    """
    action = self.get_action(
        name_id_or_prefix=name_id_or_prefix,
        allow_name_prefix_match=False,
        project=project,
    )

    update_model = ActionUpdate(
        name=name,
        description=description,
        configuration=configuration,
        service_account_id=service_account_id,
        auth_window=auth_window,
    )

    return self.zen_store.update_action(
        action_id=action.id,
        action_update=update_model,
    )
update_api_key(service_account_name_id_or_prefix: Union[str, UUID], name_id_or_prefix: Union[UUID, str], name: Optional[str] = None, description: Optional[str] = None, active: Optional[bool] = None) -> APIKeyResponse

Update an API key.

Parameters:

Name Type Description Default
service_account_name_id_or_prefix Union[str, UUID]

The name, ID or prefix of the service account to update the API key for.

required
name_id_or_prefix Union[UUID, str]

Name, ID or prefix of the API key to update.

required
name Optional[str]

New name of the API key.

None
description Optional[str]

New description of the API key.

None
active Optional[bool]

Whether the API key is active or not.

None

Returns:

Type Description
APIKeyResponse

The updated API key.

Source code in src/zenml/client.py
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
def update_api_key(
    self,
    service_account_name_id_or_prefix: Union[str, UUID],
    name_id_or_prefix: Union[UUID, str],
    name: Optional[str] = None,
    description: Optional[str] = None,
    active: Optional[bool] = None,
) -> APIKeyResponse:
    """Update an API key.

    Args:
        service_account_name_id_or_prefix: The name, ID or prefix of the
            service account to update the API key for.
        name_id_or_prefix: Name, ID or prefix of the API key to update.
        name: New name of the API key.
        description: New description of the API key.
        active: Whether the API key is active or not.

    Returns:
        The updated API key.
    """
    api_key = self.get_api_key(
        service_account_name_id_or_prefix=service_account_name_id_or_prefix,
        name_id_or_prefix=name_id_or_prefix,
        allow_name_prefix_match=False,
    )
    update = APIKeyUpdate(
        name=name, description=description, active=active
    )
    return self.zen_store.update_api_key(
        service_account_id=api_key.service_account.id,
        api_key_name_or_id=api_key.id,
        api_key_update=update,
    )
update_artifact(name_id_or_prefix: Union[str, UUID], new_name: Optional[str] = None, add_tags: Optional[List[str]] = None, remove_tags: Optional[List[str]] = None, has_custom_name: Optional[bool] = None, project: Optional[Union[str, UUID]] = None) -> ArtifactResponse

Update an artifact.

Parameters:

Name Type Description Default
name_id_or_prefix Union[str, UUID]

The name, ID or prefix of the artifact to update.

required
new_name Optional[str]

The new name of the artifact.

None
add_tags Optional[List[str]]

Tags to add to the artifact.

None
remove_tags Optional[List[str]]

Tags to remove from the artifact.

None
has_custom_name Optional[bool]

Whether the artifact has a custom name.

None
project Optional[Union[str, UUID]]

The project name/ID to filter by.

None

Returns:

Type Description
ArtifactResponse

The updated artifact.

Source code in src/zenml/client.py
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
def update_artifact(
    self,
    name_id_or_prefix: Union[str, UUID],
    new_name: Optional[str] = None,
    add_tags: Optional[List[str]] = None,
    remove_tags: Optional[List[str]] = None,
    has_custom_name: Optional[bool] = None,
    project: Optional[Union[str, UUID]] = None,
) -> ArtifactResponse:
    """Update an artifact.

    Args:
        name_id_or_prefix: The name, ID or prefix of the artifact to update.
        new_name: The new name of the artifact.
        add_tags: Tags to add to the artifact.
        remove_tags: Tags to remove from the artifact.
        has_custom_name: Whether the artifact has a custom name.
        project: The project name/ID to filter by.

    Returns:
        The updated artifact.
    """
    artifact = self.get_artifact(
        name_id_or_prefix=name_id_or_prefix,
        project=project,
    )
    artifact_update = ArtifactUpdate(
        name=new_name,
        add_tags=add_tags,
        remove_tags=remove_tags,
        has_custom_name=has_custom_name,
    )
    return self.zen_store.update_artifact(
        artifact_id=artifact.id, artifact_update=artifact_update
    )
update_artifact_version(name_id_or_prefix: Union[str, UUID], version: Optional[str] = None, add_tags: Optional[List[str]] = None, remove_tags: Optional[List[str]] = None, project: Optional[Union[str, UUID]] = None) -> ArtifactVersionResponse

Update an artifact version.

Parameters:

Name Type Description Default
name_id_or_prefix Union[str, UUID]

The name, ID or prefix of the artifact to update.

required
version Optional[str]

The version of the artifact to update. Only used if name_id_or_prefix is the name of the artifact. If not specified, the latest version is updated.

None
add_tags Optional[List[str]]

Tags to add to the artifact version.

None
remove_tags Optional[List[str]]

Tags to remove from the artifact version.

None
project Optional[Union[str, UUID]]

The project name/ID to filter by.

None

Returns:

Type Description
ArtifactVersionResponse

The updated artifact version.

Source code in src/zenml/client.py
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
def update_artifact_version(
    self,
    name_id_or_prefix: Union[str, UUID],
    version: Optional[str] = None,
    add_tags: Optional[List[str]] = None,
    remove_tags: Optional[List[str]] = None,
    project: Optional[Union[str, UUID]] = None,
) -> ArtifactVersionResponse:
    """Update an artifact version.

    Args:
        name_id_or_prefix: The name, ID or prefix of the artifact to update.
        version: The version of the artifact to update. Only used if
            `name_id_or_prefix` is the name of the artifact. If not
            specified, the latest version is updated.
        add_tags: Tags to add to the artifact version.
        remove_tags: Tags to remove from the artifact version.
        project: The project name/ID to filter by.

    Returns:
        The updated artifact version.
    """
    artifact_version = self.get_artifact_version(
        name_id_or_prefix=name_id_or_prefix,
        version=version,
        project=project,
    )
    artifact_version_update = ArtifactVersionUpdate(
        add_tags=add_tags, remove_tags=remove_tags
    )
    return self.zen_store.update_artifact_version(
        artifact_version_id=artifact_version.id,
        artifact_version_update=artifact_version_update,
    )
update_authorized_device(id_or_prefix: Union[UUID, str], locked: Optional[bool] = None) -> OAuthDeviceResponse

Update an authorized device.

Parameters:

Name Type Description Default
id_or_prefix Union[UUID, str]

The ID or ID prefix of the authorized device.

required
locked Optional[bool]

Whether to lock or unlock the authorized device.

None

Returns:

Type Description
OAuthDeviceResponse

The updated authorized device.

Source code in src/zenml/client.py
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
def update_authorized_device(
    self,
    id_or_prefix: Union[UUID, str],
    locked: Optional[bool] = None,
) -> OAuthDeviceResponse:
    """Update an authorized device.

    Args:
        id_or_prefix: The ID or ID prefix of the authorized device.
        locked: Whether to lock or unlock the authorized device.

    Returns:
        The updated authorized device.
    """
    device = self.get_authorized_device(
        id_or_prefix=id_or_prefix, allow_id_prefix_match=False
    )
    return self.zen_store.update_authorized_device(
        device_id=device.id,
        update=OAuthDeviceUpdate(
            locked=locked,
        ),
    )
update_code_repository(name_id_or_prefix: Union[UUID, str], name: Optional[str] = None, description: Optional[str] = None, logo_url: Optional[str] = None, config: Optional[Dict[str, Any]] = None, project: Optional[Union[str, UUID]] = None) -> CodeRepositoryResponse

Update a code repository.

Parameters:

Name Type Description Default
name_id_or_prefix Union[UUID, str]

Name, ID or prefix of the code repository to update.

required
name Optional[str]

New name of the code repository.

None
description Optional[str]

New description of the code repository.

None
logo_url Optional[str]

New logo URL of the code repository.

None
config Optional[Dict[str, Any]]

New configuration options for the code repository. Will be used to update the existing configuration values. To remove values from the existing configuration, set the value for that key to None.

None
project Optional[Union[str, UUID]]

The project name/ID to filter by.

None

Returns:

Type Description
CodeRepositoryResponse

The updated code repository.

Source code in src/zenml/client.py
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
def update_code_repository(
    self,
    name_id_or_prefix: Union[UUID, str],
    name: Optional[str] = None,
    description: Optional[str] = None,
    logo_url: Optional[str] = None,
    config: Optional[Dict[str, Any]] = None,
    project: Optional[Union[str, UUID]] = None,
) -> CodeRepositoryResponse:
    """Update a code repository.

    Args:
        name_id_or_prefix: Name, ID or prefix of the code repository to
            update.
        name: New name of the code repository.
        description: New description of the code repository.
        logo_url: New logo URL of the code repository.
        config: New configuration options for the code repository. Will
            be used to update the existing configuration values. To remove
            values from the existing configuration, set the value for that
            key to `None`.
        project: The project name/ID to filter by.

    Returns:
        The updated code repository.
    """
    repo = self.get_code_repository(
        name_id_or_prefix=name_id_or_prefix,
        allow_name_prefix_match=False,
        project=project,
    )
    update = CodeRepositoryUpdate(
        name=name, description=description, logo_url=logo_url
    )
    if config is not None:
        combined_config = repo.config
        combined_config.update(config)
        combined_config = {
            k: v for k, v in combined_config.items() if v is not None
        }

        self._validate_code_repository_config(
            source=repo.source, config=combined_config
        )
        update.config = combined_config

    return self.zen_store.update_code_repository(
        code_repository_id=repo.id, update=update
    )
update_event_source(name_id_or_prefix: Union[UUID, str], name: Optional[str] = None, description: Optional[str] = None, configuration: Optional[Dict[str, Any]] = None, rotate_secret: Optional[bool] = None, is_active: Optional[bool] = None, project: Optional[Union[str, UUID]] = None) -> EventSourceResponse

Updates an event_source.

Parameters:

Name Type Description Default
name_id_or_prefix Union[UUID, str]

The name, id or prefix of the event_source to update.

required
name Optional[str]

the new name of the event_source.

None
description Optional[str]

the new description of the event_source.

None
configuration Optional[Dict[str, Any]]

The event source configuration.

None
rotate_secret Optional[bool]

Allows rotating of secret, if true, the response will contain the new secret value

None
is_active Optional[bool]

Optional[bool] = Allows for activation/deactivating the event source

None
project Optional[Union[str, UUID]]

The project name/ID to filter by.

None

Returns:

Type Description
EventSourceResponse

The model of the updated event_source.

Raises:

Type Description
EntityExistsError

If the event_source name is already taken.

Source code in src/zenml/client.py
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
@_fail_for_sql_zen_store
def update_event_source(
    self,
    name_id_or_prefix: Union[UUID, str],
    name: Optional[str] = None,
    description: Optional[str] = None,
    configuration: Optional[Dict[str, Any]] = None,
    rotate_secret: Optional[bool] = None,
    is_active: Optional[bool] = None,
    project: Optional[Union[str, UUID]] = None,
) -> EventSourceResponse:
    """Updates an event_source.

    Args:
        name_id_or_prefix: The name, id or prefix of the event_source to update.
        name: the new name of the event_source.
        description: the new description of the event_source.
        configuration: The event source configuration.
        rotate_secret: Allows rotating of secret, if true, the response will
            contain the new secret value
        is_active: Optional[bool] = Allows for activation/deactivating the
            event source
        project: The project name/ID to filter by.

    Returns:
        The model of the updated event_source.

    Raises:
        EntityExistsError: If the event_source name is already taken.
    """
    # First, get the eve
    event_source = self.get_event_source(
        name_id_or_prefix=name_id_or_prefix,
        allow_name_prefix_match=False,
        project=project,
    )

    # Create the update model
    update_model = EventSourceUpdate(
        name=name,
        description=description,
        configuration=configuration,
        rotate_secret=rotate_secret,
        is_active=is_active,
    )

    if name:
        if self.list_event_sources(name=name):
            raise EntityExistsError(
                "There are already existing event_sources with the name "
                f"'{name}'."
            )

    updated_event_source = self.zen_store.update_event_source(
        event_source_id=event_source.id,
        event_source_update=update_model,
    )
    return updated_event_source
update_model(model_name_or_id: Union[str, UUID], name: Optional[str] = None, license: Optional[str] = None, description: Optional[str] = None, audience: Optional[str] = None, use_cases: Optional[str] = None, limitations: Optional[str] = None, trade_offs: Optional[str] = None, ethics: Optional[str] = None, add_tags: Optional[List[str]] = None, remove_tags: Optional[List[str]] = None, save_models_to_registry: Optional[bool] = None, project: Optional[Union[str, UUID]] = None) -> ModelResponse

Updates an existing model in Model Control Plane.

Parameters:

Name Type Description Default
model_name_or_id Union[str, UUID]

name or id of the model to be deleted.

required
name Optional[str]

The name of the model.

None
license Optional[str]

The license under which the model is created.

None
description Optional[str]

The description of the model.

None
audience Optional[str]

The target audience of the model.

None
use_cases Optional[str]

The use cases of the model.

None
limitations Optional[str]

The known limitations of the model.

None
trade_offs Optional[str]

The tradeoffs of the model.

None
ethics Optional[str]

The ethical implications of the model.

None
add_tags Optional[List[str]]

Tags to add to the model.

None
remove_tags Optional[List[str]]

Tags to remove from to the model.

None
save_models_to_registry Optional[bool]

Whether to save the model to the registry.

None
project Optional[Union[str, UUID]]

The project name/ID to filter by.

None

Returns:

Type Description
ModelResponse

The updated model.

Source code in src/zenml/client.py
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
def update_model(
    self,
    model_name_or_id: Union[str, UUID],
    name: Optional[str] = None,
    license: Optional[str] = None,
    description: Optional[str] = None,
    audience: Optional[str] = None,
    use_cases: Optional[str] = None,
    limitations: Optional[str] = None,
    trade_offs: Optional[str] = None,
    ethics: Optional[str] = None,
    add_tags: Optional[List[str]] = None,
    remove_tags: Optional[List[str]] = None,
    save_models_to_registry: Optional[bool] = None,
    project: Optional[Union[str, UUID]] = None,
) -> ModelResponse:
    """Updates an existing model in Model Control Plane.

    Args:
        model_name_or_id: name or id of the model to be deleted.
        name: The name of the model.
        license: The license under which the model is created.
        description: The description of the model.
        audience: The target audience of the model.
        use_cases: The use cases of the model.
        limitations: The known limitations of the model.
        trade_offs: The tradeoffs of the model.
        ethics: The ethical implications of the model.
        add_tags: Tags to add to the model.
        remove_tags: Tags to remove from to the model.
        save_models_to_registry: Whether to save the model to the
            registry.
        project: The project name/ID to filter by.

    Returns:
        The updated model.
    """
    model = self.get_model(
        model_name_or_id=model_name_or_id, project=project
    )
    return self.zen_store.update_model(
        model_id=model.id,
        model_update=ModelUpdate(
            name=name,
            license=license,
            description=description,
            audience=audience,
            use_cases=use_cases,
            limitations=limitations,
            trade_offs=trade_offs,
            ethics=ethics,
            add_tags=add_tags,
            remove_tags=remove_tags,
            save_models_to_registry=save_models_to_registry,
        ),
    )
update_model_version(model_name_or_id: Union[str, UUID], version_name_or_id: Union[str, UUID], stage: Optional[Union[str, ModelStages]] = None, force: bool = False, name: Optional[str] = None, description: Optional[str] = None, add_tags: Optional[List[str]] = None, remove_tags: Optional[List[str]] = None, project: Optional[Union[str, UUID]] = None) -> ModelVersionResponse

Get all model versions by filter.

Parameters:

Name Type Description Default
model_name_or_id Union[str, UUID]

The name or ID of the model containing model version.

required
version_name_or_id Union[str, UUID]

The name or ID of model version to be updated.

required
stage Optional[Union[str, ModelStages]]

Target model version stage to be set.

None
force bool

Whether existing model version in target stage should be silently archived or an error should be raised.

False
name Optional[str]

Target model version name to be set.

None
description Optional[str]

Target model version description to be set.

None
add_tags Optional[List[str]]

Tags to add to the model version.

None
remove_tags Optional[List[str]]

Tags to remove from to the model version.

None
project Optional[Union[str, UUID]]

The project name/ID to filter by.

None

Returns:

Type Description
ModelVersionResponse

An updated model version.

Source code in src/zenml/client.py
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
def update_model_version(
    self,
    model_name_or_id: Union[str, UUID],
    version_name_or_id: Union[str, UUID],
    stage: Optional[Union[str, ModelStages]] = None,
    force: bool = False,
    name: Optional[str] = None,
    description: Optional[str] = None,
    add_tags: Optional[List[str]] = None,
    remove_tags: Optional[List[str]] = None,
    project: Optional[Union[str, UUID]] = None,
) -> ModelVersionResponse:
    """Get all model versions by filter.

    Args:
        model_name_or_id: The name or ID of the model containing model version.
        version_name_or_id: The name or ID of model version to be updated.
        stage: Target model version stage to be set.
        force: Whether existing model version in target stage should be
            silently archived or an error should be raised.
        name: Target model version name to be set.
        description: Target model version description to be set.
        add_tags: Tags to add to the model version.
        remove_tags: Tags to remove from to the model version.
        project: The project name/ID to filter by.

    Returns:
        An updated model version.
    """
    if not is_valid_uuid(model_name_or_id):
        model = self.get_model(model_name_or_id, project=project)
        model_name_or_id = model.id
        project = project or model.project.id
    if not is_valid_uuid(version_name_or_id):
        version_name_or_id = self.get_model_version(
            model_name_or_id, version_name_or_id, project=project
        ).id

    return self.zen_store.update_model_version(
        model_version_id=version_name_or_id,  # type:ignore[arg-type]
        model_version_update_model=ModelVersionUpdate(
            stage=stage,
            force=force,
            name=name,
            description=description,
            add_tags=add_tags,
            remove_tags=remove_tags,
        ),
    )
update_project(name_id_or_prefix: Optional[Union[UUID, str]], new_name: Optional[str] = None, new_display_name: Optional[str] = None, new_description: Optional[str] = None) -> ProjectResponse

Update a project.

Parameters:

Name Type Description Default
name_id_or_prefix Optional[Union[UUID, str]]

Name, ID or prefix of the project to update.

required
new_name Optional[str]

New name of the project.

None
new_display_name Optional[str]

New display name of the project.

None
new_description Optional[str]

New description of the project.

None

Returns:

Type Description
ProjectResponse

The updated project.

Source code in src/zenml/client.py
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
def update_project(
    self,
    name_id_or_prefix: Optional[Union[UUID, str]],
    new_name: Optional[str] = None,
    new_display_name: Optional[str] = None,
    new_description: Optional[str] = None,
) -> ProjectResponse:
    """Update a project.

    Args:
        name_id_or_prefix: Name, ID or prefix of the project to update.
        new_name: New name of the project.
        new_display_name: New display name of the project.
        new_description: New description of the project.

    Returns:
        The updated project.
    """
    project = self.get_project(
        name_id_or_prefix=name_id_or_prefix, allow_name_prefix_match=False
    )
    project_update = ProjectUpdate(
        name=new_name or project.name,
        display_name=new_display_name or project.display_name,
    )
    if new_description:
        project_update.description = new_description
    return self.zen_store.update_project(
        project_id=project.id,
        project_update=project_update,
    )
update_run_template(name_id_or_prefix: Union[str, UUID], name: Optional[str] = None, description: Optional[str] = None, hidden: Optional[bool] = None, add_tags: Optional[List[str]] = None, remove_tags: Optional[List[str]] = None, project: Optional[Union[str, UUID]] = None) -> RunTemplateResponse

Update a run template.

Parameters:

Name Type Description Default
name_id_or_prefix Union[str, UUID]

Name/ID/ID prefix of the template to update.

required
name Optional[str]

The new name of the run template.

None
description Optional[str]

The new description of the run template.

None
hidden Optional[bool]

The new hidden status of the run template.

None
add_tags Optional[List[str]]

Tags to add to the run template.

None
remove_tags Optional[List[str]]

Tags to remove from the run template.

None
project Optional[Union[str, UUID]]

The project name/ID to filter by.

None

Returns:

Type Description
RunTemplateResponse

The updated run template.

Source code in src/zenml/client.py
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
def update_run_template(
    self,
    name_id_or_prefix: Union[str, UUID],
    name: Optional[str] = None,
    description: Optional[str] = None,
    hidden: Optional[bool] = None,
    add_tags: Optional[List[str]] = None,
    remove_tags: Optional[List[str]] = None,
    project: Optional[Union[str, UUID]] = None,
) -> RunTemplateResponse:
    """Update a run template.

    Args:
        name_id_or_prefix: Name/ID/ID prefix of the template to update.
        name: The new name of the run template.
        description: The new description of the run template.
        hidden: The new hidden status of the run template.
        add_tags: Tags to add to the run template.
        remove_tags: Tags to remove from the run template.
        project: The project name/ID to filter by.

    Returns:
        The updated run template.
    """
    if is_valid_uuid(name_id_or_prefix):
        template_id = (
            UUID(name_id_or_prefix)
            if isinstance(name_id_or_prefix, str)
            else name_id_or_prefix
        )
    else:
        template_id = self.get_run_template(
            name_id_or_prefix,
            project=project,
            hydrate=False,
        ).id

    return self.zen_store.update_run_template(
        template_id=template_id,
        template_update=RunTemplateUpdate(
            name=name,
            description=description,
            hidden=hidden,
            add_tags=add_tags,
            remove_tags=remove_tags,
        ),
    )
update_secret(name_id_or_prefix: Union[str, UUID], private: Optional[bool] = None, new_name: Optional[str] = None, update_private: Optional[bool] = None, add_or_update_values: Optional[Dict[str, str]] = None, remove_values: Optional[List[str]] = None) -> SecretResponse

Updates a secret.

Parameters:

Name Type Description Default
name_id_or_prefix Union[str, UUID]

The name, id or prefix of the id for the secret to update.

required
private Optional[bool]

The private status of the secret to update.

None
new_name Optional[str]

The new name of the secret.

None
update_private Optional[bool]

New value used to update the private status of the secret.

None
add_or_update_values Optional[Dict[str, str]]

The values to add or update.

None
remove_values Optional[List[str]]

The values to remove.

None

Returns:

Type Description
SecretResponse

The updated secret.

Raises:

Type Description
KeyError

If trying to remove a value that doesn't exist.

ValueError

If a key is provided in both add_or_update_values and remove_values.

Source code in src/zenml/client.py
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
def update_secret(
    self,
    name_id_or_prefix: Union[str, UUID],
    private: Optional[bool] = None,
    new_name: Optional[str] = None,
    update_private: Optional[bool] = None,
    add_or_update_values: Optional[Dict[str, str]] = None,
    remove_values: Optional[List[str]] = None,
) -> SecretResponse:
    """Updates a secret.

    Args:
        name_id_or_prefix: The name, id or prefix of the id for the
            secret to update.
        private: The private status of the secret to update.
        new_name: The new name of the secret.
        update_private: New value used to update the private status of the
            secret.
        add_or_update_values: The values to add or update.
        remove_values: The values to remove.

    Returns:
        The updated secret.

    Raises:
        KeyError: If trying to remove a value that doesn't exist.
        ValueError: If a key is provided in both add_or_update_values and
            remove_values.
    """
    secret = self.get_secret(
        name_id_or_prefix=name_id_or_prefix,
        private=private,
        # Don't allow partial name matches, but allow partial ID matches
        allow_partial_name_match=False,
        allow_partial_id_match=True,
        hydrate=True,
    )

    secret_update = SecretUpdate(name=new_name or secret.name)

    if update_private:
        secret_update.private = update_private
    values: Dict[str, Optional[SecretStr]] = {}
    if add_or_update_values:
        values.update(
            {
                key: SecretStr(value)
                for key, value in add_or_update_values.items()
            }
        )
    if remove_values:
        for key in remove_values:
            if key not in secret.values:
                raise KeyError(
                    f"Cannot remove value '{key}' from secret "
                    f"'{secret.name}' because it does not exist."
                )
            if key in values:
                raise ValueError(
                    f"Key '{key}' is supplied both in the values to add or "
                    f"update and the values to be removed."
                )
            values[key] = None
    if values:
        secret_update.values = values

    return Client().zen_store.update_secret(
        secret_id=secret.id, secret_update=secret_update
    )
update_server_settings(updated_name: Optional[str] = None, updated_logo_url: Optional[str] = None, updated_enable_analytics: Optional[bool] = None, updated_enable_announcements: Optional[bool] = None, updated_enable_updates: Optional[bool] = None, updated_onboarding_state: Optional[Dict[str, Any]] = None) -> ServerSettingsResponse

Update the server settings.

Parameters:

Name Type Description Default
updated_name Optional[str]

Updated name for the server.

None
updated_logo_url Optional[str]

Updated logo URL for the server.

None
updated_enable_analytics Optional[bool]

Updated value whether to enable analytics for the server.

None
updated_enable_announcements Optional[bool]

Updated value whether to display announcements about ZenML.

None
updated_enable_updates Optional[bool]

Updated value whether to display updates about ZenML.

None
updated_onboarding_state Optional[Dict[str, Any]]

Updated onboarding state for the server.

None

Returns:

Type Description
ServerSettingsResponse

The updated server settings.

Source code in src/zenml/client.py
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
def update_server_settings(
    self,
    updated_name: Optional[str] = None,
    updated_logo_url: Optional[str] = None,
    updated_enable_analytics: Optional[bool] = None,
    updated_enable_announcements: Optional[bool] = None,
    updated_enable_updates: Optional[bool] = None,
    updated_onboarding_state: Optional[Dict[str, Any]] = None,
) -> ServerSettingsResponse:
    """Update the server settings.

    Args:
        updated_name: Updated name for the server.
        updated_logo_url: Updated logo URL for the server.
        updated_enable_analytics: Updated value whether to enable
            analytics for the server.
        updated_enable_announcements: Updated value whether to display
            announcements about ZenML.
        updated_enable_updates: Updated value whether to display updates
            about ZenML.
        updated_onboarding_state: Updated onboarding state for the server.

    Returns:
        The updated server settings.
    """
    update_model = ServerSettingsUpdate(
        server_name=updated_name,
        logo_url=updated_logo_url,
        enable_analytics=updated_enable_analytics,
        display_announcements=updated_enable_announcements,
        display_updates=updated_enable_updates,
        onboarding_state=updated_onboarding_state,
    )
    return self.zen_store.update_server_settings(update_model)
update_service(id: UUID, name: Optional[str] = None, service_source: Optional[str] = None, admin_state: Optional[ServiceState] = None, status: Optional[Dict[str, Any]] = None, endpoint: Optional[Dict[str, Any]] = None, labels: Optional[Dict[str, str]] = None, prediction_url: Optional[str] = None, health_check_url: Optional[str] = None, model_version_id: Optional[UUID] = None) -> ServiceResponse

Update a service.

Parameters:

Name Type Description Default
id UUID

The ID of the service to update.

required
name Optional[str]

The new name of the service.

None
admin_state Optional[ServiceState]

The new admin state of the service.

None
status Optional[Dict[str, Any]]

The new status of the service.

None
endpoint Optional[Dict[str, Any]]

The new endpoint of the service.

None
service_source Optional[str]

The new service source of the service.

None
labels Optional[Dict[str, str]]

The new labels of the service.

None
prediction_url Optional[str]

The new prediction url of the service.

None
health_check_url Optional[str]

The new health check url of the service.

None
model_version_id Optional[UUID]

The new model version id of the service.

None

Returns:

Type Description
ServiceResponse

The updated service.

Source code in src/zenml/client.py
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
def update_service(
    self,
    id: UUID,
    name: Optional[str] = None,
    service_source: Optional[str] = None,
    admin_state: Optional[ServiceState] = None,
    status: Optional[Dict[str, Any]] = None,
    endpoint: Optional[Dict[str, Any]] = None,
    labels: Optional[Dict[str, str]] = None,
    prediction_url: Optional[str] = None,
    health_check_url: Optional[str] = None,
    model_version_id: Optional[UUID] = None,
) -> ServiceResponse:
    """Update a service.

    Args:
        id: The ID of the service to update.
        name: The new name of the service.
        admin_state: The new admin state of the service.
        status: The new status of the service.
        endpoint: The new endpoint of the service.
        service_source: The new service source of the service.
        labels: The new labels of the service.
        prediction_url: The new prediction url of the service.
        health_check_url: The new health check url of the service.
        model_version_id: The new model version id of the service.

    Returns:
        The updated service.
    """
    service_update = ServiceUpdate()
    if name:
        service_update.name = name
    if service_source:
        service_update.service_source = service_source
    if admin_state:
        service_update.admin_state = admin_state
    if status:
        service_update.status = status
    if endpoint:
        service_update.endpoint = endpoint
    if labels:
        service_update.labels = labels
    if prediction_url:
        service_update.prediction_url = prediction_url
    if health_check_url:
        service_update.health_check_url = health_check_url
    if model_version_id:
        service_update.model_version_id = model_version_id
    return self.zen_store.update_service(
        service_id=id, update=service_update
    )
update_service_account(name_id_or_prefix: Union[str, UUID], updated_name: Optional[str] = None, description: Optional[str] = None, active: Optional[bool] = None) -> ServiceAccountResponse

Update a service account.

Parameters:

Name Type Description Default
name_id_or_prefix Union[str, UUID]

The name or ID of the service account to update.

required
updated_name Optional[str]

The new name of the service account.

None
description Optional[str]

The new description of the service account.

None
active Optional[bool]

The new active status of the service account.

None

Returns:

Type Description
ServiceAccountResponse

The updated service account.

Source code in src/zenml/client.py
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
def update_service_account(
    self,
    name_id_or_prefix: Union[str, UUID],
    updated_name: Optional[str] = None,
    description: Optional[str] = None,
    active: Optional[bool] = None,
) -> ServiceAccountResponse:
    """Update a service account.

    Args:
        name_id_or_prefix: The name or ID of the service account to update.
        updated_name: The new name of the service account.
        description: The new description of the service account.
        active: The new active status of the service account.

    Returns:
        The updated service account.
    """
    service_account = self.get_service_account(
        name_id_or_prefix=name_id_or_prefix, allow_name_prefix_match=False
    )
    service_account_update = ServiceAccountUpdate(
        name=updated_name,
        description=description,
        active=active,
    )

    return self.zen_store.update_service_account(
        service_account_name_or_id=service_account.id,
        service_account_update=service_account_update,
    )
update_service_connector(name_id_or_prefix: Union[UUID, str], name: Optional[str] = None, auth_method: Optional[str] = None, resource_type: Optional[str] = None, configuration: Optional[Dict[str, str]] = None, resource_id: Optional[str] = None, description: Optional[str] = None, expires_at: Optional[datetime] = None, expires_skew_tolerance: Optional[int] = None, expiration_seconds: Optional[int] = None, labels: Optional[Dict[str, Optional[str]]] = None, verify: bool = True, list_resources: bool = True, update: bool = True) -> Tuple[Optional[Union[ServiceConnectorResponse, ServiceConnectorUpdate]], Optional[ServiceConnectorResourcesModel]]

Validate and/or register an updated service connector.

If the resource_type, resource_id and expiration_seconds parameters are set to their "empty" values (empty string for resource type and resource ID, 0 for expiration seconds), the existing values will be removed from the service connector. Setting them to None or omitting them will not affect the existing values.

If supplied, the configuration parameter is a full replacement of the existing configuration rather than a partial update.

Labels can be updated or removed by setting the label value to None.

Parameters:

Name Type Description Default
name_id_or_prefix Union[UUID, str]

The name, id or prefix of the service connector to update.

required
name Optional[str]

The new name of the service connector.

None
auth_method Optional[str]

The new authentication method of the service connector.

None
resource_type Optional[str]

The new resource type for the service connector. If set to the empty string, the existing resource type will be removed.

None
configuration Optional[Dict[str, str]]

The new configuration of the service connector. If set, this needs to be a full replacement of the existing configuration rather than a partial update.

None
resource_id Optional[str]

The new resource id of the service connector. If set to the empty string, the existing resource ID will be removed.

None
description Optional[str]

The description of the service connector.

None
expires_at Optional[datetime]

The new UTC expiration time of the service connector.

None
expires_skew_tolerance Optional[int]

The allowed expiration skew for the service connector credentials.

None
expiration_seconds Optional[int]

The expiration time of the service connector. If set to 0, the existing expiration time will be removed.

None
labels Optional[Dict[str, Optional[str]]]

The service connector to update or remove. If a label value is set to None, the label will be removed.

None
verify bool

Whether to verify that the service connector configuration and credentials can be used to gain access to the resource.

True
list_resources bool

Whether to also list the resources that the service connector can give access to (if verify is True).

True
update bool

Whether to update the service connector or not.

True

Returns:

Type Description
Optional[Union[ServiceConnectorResponse, ServiceConnectorUpdate]]

The model of the registered service connector and the resources

Optional[ServiceConnectorResourcesModel]

that the service connector can give access to (if verify is True).

Raises:

Type Description
AuthorizationException

If the service connector verification fails due to invalid credentials or insufficient permissions.

Source code in src/zenml/client.py
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
def update_service_connector(
    self,
    name_id_or_prefix: Union[UUID, str],
    name: Optional[str] = None,
    auth_method: Optional[str] = None,
    resource_type: Optional[str] = None,
    configuration: Optional[Dict[str, str]] = None,
    resource_id: Optional[str] = None,
    description: Optional[str] = None,
    expires_at: Optional[datetime] = None,
    expires_skew_tolerance: Optional[int] = None,
    expiration_seconds: Optional[int] = None,
    labels: Optional[Dict[str, Optional[str]]] = None,
    verify: bool = True,
    list_resources: bool = True,
    update: bool = True,
) -> Tuple[
    Optional[
        Union[
            ServiceConnectorResponse,
            ServiceConnectorUpdate,
        ]
    ],
    Optional[ServiceConnectorResourcesModel],
]:
    """Validate and/or register an updated service connector.

    If the `resource_type`, `resource_id` and `expiration_seconds`
    parameters are set to their "empty" values (empty string for resource
    type and resource ID, 0 for expiration seconds), the existing values
    will be removed from the service connector. Setting them to None or
    omitting them will not affect the existing values.

    If supplied, the `configuration` parameter is a full replacement of the
    existing configuration rather than a partial update.

    Labels can be updated or removed by setting the label value to None.

    Args:
        name_id_or_prefix: The name, id or prefix of the service connector
            to update.
        name: The new name of the service connector.
        auth_method: The new authentication method of the service connector.
        resource_type: The new resource type for the service connector.
            If set to the empty string, the existing resource type will be
            removed.
        configuration: The new configuration of the service connector. If
            set, this needs to be a full replacement of the existing
            configuration rather than a partial update.
        resource_id: The new resource id of the service connector.
            If set to the empty string, the existing resource ID will be
            removed.
        description: The description of the service connector.
        expires_at: The new UTC expiration time of the service connector.
        expires_skew_tolerance: The allowed expiration skew for the service
            connector credentials.
        expiration_seconds: The expiration time of the service connector.
            If set to 0, the existing expiration time will be removed.
        labels: The service connector to update or remove. If a label value
            is set to None, the label will be removed.
        verify: Whether to verify that the service connector configuration
            and credentials can be used to gain access to the resource.
        list_resources: Whether to also list the resources that the service
            connector can give access to (if verify is True).
        update: Whether to update the service connector or not.

    Returns:
        The model of the registered service connector and the resources
        that the service connector can give access to (if verify is True).

    Raises:
        AuthorizationException: If the service connector verification
            fails due to invalid credentials or insufficient permissions.
    """
    from zenml.service_connectors.service_connector_registry import (
        service_connector_registry,
    )

    connector_model = self.get_service_connector(
        name_id_or_prefix,
        allow_name_prefix_match=False,
        load_secrets=True,
    )

    connector_instance: Optional[ServiceConnector] = None
    connector_resources: Optional[ServiceConnectorResourcesModel] = None

    if isinstance(connector_model.connector_type, str):
        connector = self.get_service_connector_type(
            connector_model.connector_type
        )
    else:
        connector = connector_model.connector_type

    resource_types: Optional[Union[str, List[str]]] = None
    if resource_type == "":
        resource_types = None
    elif resource_type is None:
        resource_types = connector_model.resource_types
    else:
        resource_types = resource_type

    if not resource_type and len(connector.resource_types) == 1:
        resource_types = connector.resource_types[0].resource_type

    if resource_id == "":
        resource_id = None
    elif resource_id is None:
        resource_id = connector_model.resource_id

    if expiration_seconds == 0:
        expiration_seconds = None
    elif expiration_seconds is None:
        expiration_seconds = connector_model.expiration_seconds

    connector_update = ServiceConnectorUpdate(
        name=name or connector_model.name,
        connector_type=connector.connector_type,
        description=description or connector_model.description,
        auth_method=auth_method or connector_model.auth_method,
        expires_at=expires_at,
        expires_skew_tolerance=expires_skew_tolerance,
        expiration_seconds=expiration_seconds,
    )

    # Validate and configure the resources
    if configuration is not None:
        # The supplied configuration is a drop-in replacement for the
        # existing configuration and secrets
        connector_update.validate_and_configure_resources(
            connector_type=connector,
            resource_types=resource_types,
            resource_id=resource_id,
            configuration=configuration,
        )
    else:
        connector_update.validate_and_configure_resources(
            connector_type=connector,
            resource_types=resource_types,
            resource_id=resource_id,
            configuration=connector_model.configuration,
            secrets=connector_model.secrets,
        )

    # Add the labels
    if labels is not None:
        # Apply the new label values, but don't keep any labels that
        # have been set to None in the update
        connector_update.labels = {
            **{
                label: value
                for label, value in connector_model.labels.items()
                if label not in labels
            },
            **{
                label: value
                for label, value in labels.items()
                if value is not None
            },
        }
    else:
        connector_update.labels = connector_model.labels

    if verify:
        # Prefer to verify the connector config server-side if the
        # implementation, if available there, because it ensures
        # that the connector can be shared with other users or used
        # from other machines and because some auth methods rely on the
        # server-side authentication environment

        # Convert the update model to a request model for validation
        connector_request_dict = connector_update.model_dump()
        connector_request = ServiceConnectorRequest.model_validate(
            connector_request_dict
        )

        if connector.remote:
            connector_resources = (
                self.zen_store.verify_service_connector_config(
                    service_connector=connector_request,
                    list_resources=list_resources,
                )
            )
        else:
            connector_instance = (
                service_connector_registry.instantiate_connector(
                    model=connector_request,
                )
            )
            connector_resources = connector_instance.verify(
                list_resources=list_resources
            )

        if connector_resources.error:
            raise AuthorizationException(connector_resources.error)

        # For resource types that don't support multi-instances, it's
        # better to save the default resource ID in the connector, if
        # available. Otherwise, we'll need to instantiate the connector
        # again to get the default resource ID.
        connector_update.resource_id = (
            connector_update.resource_id
            or connector_resources.get_default_resource_id()
        )

    if not update:
        return connector_update, connector_resources

    # Update the model
    connector_response = self.zen_store.update_service_connector(
        service_connector_id=connector_model.id,
        update=connector_update,
    )

    if connector_resources:
        connector_resources.id = connector_response.id
        connector_resources.name = connector_response.name
        connector_resources.connector_type = (
            connector_response.connector_type
        )

    return connector_response, connector_resources
update_stack(name_id_or_prefix: Optional[Union[UUID, str]] = None, name: Optional[str] = None, stack_spec_file: Optional[str] = None, labels: Optional[Dict[str, Any]] = None, description: Optional[str] = None, component_updates: Optional[Dict[StackComponentType, List[Union[UUID, str]]]] = None) -> StackResponse

Updates a stack and its components.

Parameters:

Name Type Description Default
name_id_or_prefix Optional[Union[UUID, str]]

The name, id or prefix of the stack to update.

None
name Optional[str]

the new name of the stack.

None
stack_spec_file Optional[str]

path to the stack spec file.

None
labels Optional[Dict[str, Any]]

The new labels of the stack component.

None
description Optional[str]

the new description of the stack.

None
component_updates Optional[Dict[StackComponentType, List[Union[UUID, str]]]]

dictionary which maps stack component types to lists of new stack component names or ids.

None

Returns:

Type Description
StackResponse

The model of the updated stack.

Raises:

Type Description
EntityExistsError

If the stack name is already taken.

Source code in src/zenml/client.py
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
def update_stack(
    self,
    name_id_or_prefix: Optional[Union[UUID, str]] = None,
    name: Optional[str] = None,
    stack_spec_file: Optional[str] = None,
    labels: Optional[Dict[str, Any]] = None,
    description: Optional[str] = None,
    component_updates: Optional[
        Dict[StackComponentType, List[Union[UUID, str]]]
    ] = None,
) -> StackResponse:
    """Updates a stack and its components.

    Args:
        name_id_or_prefix: The name, id or prefix of the stack to update.
        name: the new name of the stack.
        stack_spec_file: path to the stack spec file.
        labels: The new labels of the stack component.
        description: the new description of the stack.
        component_updates: dictionary which maps stack component types to
            lists of new stack component names or ids.

    Returns:
        The model of the updated stack.

    Raises:
        EntityExistsError: If the stack name is already taken.
    """
    # First, get the stack
    stack = self.get_stack(
        name_id_or_prefix=name_id_or_prefix, allow_name_prefix_match=False
    )

    # Create the update model
    update_model = StackUpdate(
        stack_spec_path=stack_spec_file,
    )

    if name:
        if self.list_stacks(name=name):
            raise EntityExistsError(
                "There are already existing stacks with the name "
                f"'{name}'."
            )

        update_model.name = name

    if description:
        update_model.description = description

    # Get the current components
    if component_updates:
        components_dict = stack.components.copy()

        for component_type, component_id_list in component_updates.items():
            if component_id_list is not None:
                components_dict[component_type] = [
                    self.get_stack_component(
                        name_id_or_prefix=component_id,
                        component_type=component_type,
                    )
                    for component_id in component_id_list
                ]

        update_model.components = {
            c_type: [c.id for c in c_list]
            for c_type, c_list in components_dict.items()
        }

    if labels is not None:
        existing_labels = stack.labels or {}
        existing_labels.update(labels)

        existing_labels = {
            k: v for k, v in existing_labels.items() if v is not None
        }
        update_model.labels = existing_labels

    updated_stack = self.zen_store.update_stack(
        stack_id=stack.id,
        stack_update=update_model,
    )
    if updated_stack.id == self.active_stack_model.id:
        if self._config:
            self._config.set_active_stack(updated_stack)
        else:
            GlobalConfiguration().set_active_stack(updated_stack)
    return updated_stack
update_stack_component(name_id_or_prefix: Optional[Union[UUID, str]], component_type: StackComponentType, name: Optional[str] = None, configuration: Optional[Dict[str, Any]] = None, labels: Optional[Dict[str, Any]] = None, disconnect: Optional[bool] = None, connector_id: Optional[UUID] = None, connector_resource_id: Optional[str] = None) -> ComponentResponse

Updates a stack component.

Parameters:

Name Type Description Default
name_id_or_prefix Optional[Union[UUID, str]]

The name, id or prefix of the stack component to update.

required
component_type StackComponentType

The type of the stack component to update.

required
name Optional[str]

The new name of the stack component.

None
configuration Optional[Dict[str, Any]]

The new configuration of the stack component.

None
labels Optional[Dict[str, Any]]

The new labels of the stack component.

None
disconnect Optional[bool]

Whether to disconnect the stack component from its service connector.

None
connector_id Optional[UUID]

The new connector id of the stack component.

None
connector_resource_id Optional[str]

The new connector resource id of the stack component.

None

Returns:

Type Description
ComponentResponse

The updated stack component.

Raises:

Type Description
EntityExistsError

If the new name is already taken.

Source code in src/zenml/client.py
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
def update_stack_component(
    self,
    name_id_or_prefix: Optional[Union[UUID, str]],
    component_type: StackComponentType,
    name: Optional[str] = None,
    configuration: Optional[Dict[str, Any]] = None,
    labels: Optional[Dict[str, Any]] = None,
    disconnect: Optional[bool] = None,
    connector_id: Optional[UUID] = None,
    connector_resource_id: Optional[str] = None,
) -> ComponentResponse:
    """Updates a stack component.

    Args:
        name_id_or_prefix: The name, id or prefix of the stack component to
            update.
        component_type: The type of the stack component to update.
        name: The new name of the stack component.
        configuration: The new configuration of the stack component.
        labels: The new labels of the stack component.
        disconnect: Whether to disconnect the stack component from its
            service connector.
        connector_id: The new connector id of the stack component.
        connector_resource_id: The new connector resource id of the
            stack component.

    Returns:
        The updated stack component.

    Raises:
        EntityExistsError: If the new name is already taken.
    """
    # Get the existing component model
    component = self.get_stack_component(
        name_id_or_prefix=name_id_or_prefix,
        component_type=component_type,
        allow_name_prefix_match=False,
    )

    update_model = ComponentUpdate()

    if name is not None:
        existing_components = self.list_stack_components(
            name=name,
            type=component_type,
        )
        if existing_components.total > 0:
            raise EntityExistsError(
                f"There are already existing components with the "
                f"name '{name}'."
            )
        update_model.name = name

    if configuration is not None:
        existing_configuration = component.configuration
        existing_configuration.update(configuration)
        existing_configuration = {
            k: v
            for k, v in existing_configuration.items()
            if v is not None
        }

        from zenml.stack.utils import (
            validate_stack_component_config,
            warn_if_config_server_mismatch,
        )

        validated_config = validate_stack_component_config(
            configuration_dict=existing_configuration,
            flavor=component.flavor,
            component_type=component.type,
            # Always enforce validation of custom flavors
            validate_custom_flavors=True,
        )
        # Guaranteed to not be None by setting
        # `validate_custom_flavors=True` above
        assert validated_config is not None
        warn_if_config_server_mismatch(validated_config)

        update_model.configuration = existing_configuration

    if labels is not None:
        existing_labels = component.labels or {}
        existing_labels.update(labels)

        existing_labels = {
            k: v for k, v in existing_labels.items() if v is not None
        }
        update_model.labels = existing_labels

    if disconnect:
        update_model.connector = None
        update_model.connector_resource_id = None
    else:
        existing_component = self.get_stack_component(
            name_id_or_prefix=name_id_or_prefix,
            component_type=component_type,
            allow_name_prefix_match=False,
        )
        update_model.connector = connector_id
        update_model.connector_resource_id = connector_resource_id
        if connector_id is None and existing_component.connector:
            update_model.connector = existing_component.connector.id
            update_model.connector_resource_id = (
                existing_component.connector_resource_id
            )

    # Send the updated component to the ZenStore
    return self.zen_store.update_stack_component(
        component_id=component.id,
        component_update=update_model,
    )
update_tag(tag_name_or_id: Union[str, UUID], name: Optional[str] = None, exclusive: Optional[bool] = None, color: Optional[Union[str, ColorVariants]] = None) -> TagResponse

Updates an existing tag.

Parameters:

Name Type Description Default
tag_name_or_id Union[str, UUID]

name or UUID of the tag to be updated.

required
name Optional[str]

the name of the tag.

None
exclusive Optional[bool]

the boolean to decide whether the tag is an exclusive tag. An exclusive tag means that the tag can exist only for a single: - pipeline run within the scope of a pipeline - artifact version within the scope of an artifact - run template

None
color Optional[Union[str, ColorVariants]]

the color of the tag

None

Returns:

Type Description
TagResponse

The updated tag.

Source code in src/zenml/client.py
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
def update_tag(
    self,
    tag_name_or_id: Union[str, UUID],
    name: Optional[str] = None,
    exclusive: Optional[bool] = None,
    color: Optional[Union[str, ColorVariants]] = None,
) -> TagResponse:
    """Updates an existing tag.

    Args:
        tag_name_or_id: name or UUID of the tag to be updated.
        name: the name of the tag.
        exclusive: the boolean to decide whether the tag is an exclusive tag.
            An exclusive tag means that the tag can exist only for a single:
                - pipeline run within the scope of a pipeline
                - artifact version within the scope of an artifact
                - run template
        color: the color of the tag

    Returns:
        The updated tag.
    """
    update_model = TagUpdate()

    if name is not None:
        update_model.name = name

    if exclusive is not None:
        update_model.exclusive = exclusive

    if color is not None:
        if isinstance(color, str):
            update_model.color = ColorVariants(color)
        else:
            update_model.color = color

    return self.zen_store.update_tag(
        tag_name_or_id=tag_name_or_id,
        tag_update_model=update_model,
    )
update_trigger(name_id_or_prefix: Union[UUID, str], name: Optional[str] = None, description: Optional[str] = None, event_filter: Optional[Dict[str, Any]] = None, is_active: Optional[bool] = None, project: Optional[Union[str, UUID]] = None) -> TriggerResponse

Updates a trigger.

Parameters:

Name Type Description Default
name_id_or_prefix Union[UUID, str]

The name, id or prefix of the trigger to update.

required
name Optional[str]

the new name of the trigger.

None
description Optional[str]

the new description of the trigger.

None
event_filter Optional[Dict[str, Any]]

The event filter configuration.

None
is_active Optional[bool]

Whether the trigger is active or not.

None
project Optional[Union[str, UUID]]

The project name/ID to filter by.

None

Returns:

Type Description
TriggerResponse

The model of the updated trigger.

Raises:

Type Description
EntityExistsError

If the trigger name is already taken.

Source code in src/zenml/client.py
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
@_fail_for_sql_zen_store
def update_trigger(
    self,
    name_id_or_prefix: Union[UUID, str],
    name: Optional[str] = None,
    description: Optional[str] = None,
    event_filter: Optional[Dict[str, Any]] = None,
    is_active: Optional[bool] = None,
    project: Optional[Union[str, UUID]] = None,
) -> TriggerResponse:
    """Updates a trigger.

    Args:
        name_id_or_prefix: The name, id or prefix of the trigger to update.
        name: the new name of the trigger.
        description: the new description of the trigger.
        event_filter: The event filter configuration.
        is_active: Whether the trigger is active or not.
        project: The project name/ID to filter by.

    Returns:
        The model of the updated trigger.

    Raises:
        EntityExistsError: If the trigger name is already taken.
    """
    # First, get the eve
    trigger = self.get_trigger(
        name_id_or_prefix=name_id_or_prefix,
        allow_name_prefix_match=False,
        project=project,
    )

    # Create the update model
    update_model = TriggerUpdate(
        name=name,
        description=description,
        event_filter=event_filter,
        is_active=is_active,
    )

    if name:
        if self.list_triggers(name=name):
            raise EntityExistsError(
                "There are already is an existing trigger with the name "
                f"'{name}'."
            )

    updated_trigger = self.zen_store.update_trigger(
        trigger_id=trigger.id,
        trigger_update=update_model,
    )
    return updated_trigger
update_user(name_id_or_prefix: Union[str, UUID], updated_name: Optional[str] = None, updated_full_name: Optional[str] = None, updated_email: Optional[str] = None, updated_email_opt_in: Optional[bool] = None, updated_password: Optional[str] = None, old_password: Optional[str] = None, updated_is_admin: Optional[bool] = None, updated_metadata: Optional[Dict[str, Any]] = None, updated_default_project_id: Optional[UUID] = None, active: Optional[bool] = None) -> UserResponse

Update a user.

Parameters:

Name Type Description Default
name_id_or_prefix Union[str, UUID]

The name or ID of the user to update.

required
updated_name Optional[str]

The new name of the user.

None
updated_full_name Optional[str]

The new full name of the user.

None
updated_email Optional[str]

The new email of the user.

None
updated_email_opt_in Optional[bool]

The new email opt-in status of the user.

None
updated_password Optional[str]

The new password of the user.

None
old_password Optional[str]

The old password of the user. Required for password update.

None
updated_is_admin Optional[bool]

Whether the user should be an admin.

None
updated_metadata Optional[Dict[str, Any]]

The new metadata for the user.

None
updated_default_project_id Optional[UUID]

The new default project ID for the user.

None
active Optional[bool]

Use to activate or deactivate the user.

None

Returns:

Type Description
UserResponse

The updated user.

Raises:

Type Description
ValidationError

If the old password is not provided when updating the password.

Source code in src/zenml/client.py
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
def update_user(
    self,
    name_id_or_prefix: Union[str, UUID],
    updated_name: Optional[str] = None,
    updated_full_name: Optional[str] = None,
    updated_email: Optional[str] = None,
    updated_email_opt_in: Optional[bool] = None,
    updated_password: Optional[str] = None,
    old_password: Optional[str] = None,
    updated_is_admin: Optional[bool] = None,
    updated_metadata: Optional[Dict[str, Any]] = None,
    updated_default_project_id: Optional[UUID] = None,
    active: Optional[bool] = None,
) -> UserResponse:
    """Update a user.

    Args:
        name_id_or_prefix: The name or ID of the user to update.
        updated_name: The new name of the user.
        updated_full_name: The new full name of the user.
        updated_email: The new email of the user.
        updated_email_opt_in: The new email opt-in status of the user.
        updated_password: The new password of the user.
        old_password: The old password of the user. Required for password
            update.
        updated_is_admin: Whether the user should be an admin.
        updated_metadata: The new metadata for the user.
        updated_default_project_id: The new default project ID for the user.
        active: Use to activate or deactivate the user.

    Returns:
        The updated user.

    Raises:
        ValidationError: If the old password is not provided when updating
            the password.
    """
    user = self.get_user(
        name_id_or_prefix=name_id_or_prefix, allow_name_prefix_match=False
    )
    user_update = UserUpdate(name=updated_name or user.name)
    if updated_full_name:
        user_update.full_name = updated_full_name
    if updated_email is not None:
        user_update.email = updated_email
        user_update.email_opted_in = (
            updated_email_opt_in or user.email_opted_in
        )
    if updated_email_opt_in is not None:
        user_update.email_opted_in = updated_email_opt_in
    if updated_password is not None:
        user_update.password = updated_password
        if old_password is None:
            raise ValidationError(
                "Old password is required to update the password."
            )
        user_update.old_password = old_password
    if updated_is_admin is not None:
        user_update.is_admin = updated_is_admin
    if active is not None:
        user_update.active = active

    if updated_metadata is not None:
        user_update.user_metadata = updated_metadata

    if updated_default_project_id is not None:
        user_update.default_project_id = updated_default_project_id

    return self.zen_store.update_user(
        user_id=user.id, user_update=user_update
    )
verify_service_connector(name_id_or_prefix: Union[UUID, str], resource_type: Optional[str] = None, resource_id: Optional[str] = None, list_resources: bool = True) -> ServiceConnectorResourcesModel

Verifies if a service connector has access to one or more resources.

Parameters:

Name Type Description Default
name_id_or_prefix Union[UUID, str]

The name, id or prefix of the service connector to verify.

required
resource_type Optional[str]

The type of the resource for which to verify access. If not provided, the resource type from the service connector configuration will be used.

None
resource_id Optional[str]

The ID of the resource for which to verify access. If not provided, the resource ID from the service connector configuration will be used.

None
list_resources bool

Whether to list the resources that the service connector has access to.

True

Returns:

Type Description
ServiceConnectorResourcesModel

The list of resources that the service connector has access to,

ServiceConnectorResourcesModel

scoped to the supplied resource type and ID, if provided.

Raises:

Type Description
AuthorizationException

If the service connector does not have access to the resources.

Source code in src/zenml/client.py
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
def verify_service_connector(
    self,
    name_id_or_prefix: Union[UUID, str],
    resource_type: Optional[str] = None,
    resource_id: Optional[str] = None,
    list_resources: bool = True,
) -> "ServiceConnectorResourcesModel":
    """Verifies if a service connector has access to one or more resources.

    Args:
        name_id_or_prefix: The name, id or prefix of the service connector
            to verify.
        resource_type: The type of the resource for which to verify access.
            If not provided, the resource type from the service connector
            configuration will be used.
        resource_id: The ID of the resource for which to verify access. If
            not provided, the resource ID from the service connector
            configuration will be used.
        list_resources: Whether to list the resources that the service
            connector has access to.

    Returns:
        The list of resources that the service connector has access to,
        scoped to the supplied resource type and ID, if provided.

    Raises:
        AuthorizationException: If the service connector does not have
            access to the resources.
    """
    from zenml.service_connectors.service_connector_registry import (
        service_connector_registry,
    )

    # Get the service connector model
    service_connector = self.get_service_connector(
        name_id_or_prefix=name_id_or_prefix,
        allow_name_prefix_match=False,
    )

    connector_type = self.get_service_connector_type(
        service_connector.type
    )

    # Prefer to verify the connector config server-side if the
    # implementation if available there, because it ensures
    # that the connector can be shared with other users or used
    # from other machines and because some auth methods rely on the
    # server-side authentication environment
    if connector_type.remote:
        connector_resources = self.zen_store.verify_service_connector(
            service_connector_id=service_connector.id,
            resource_type=resource_type,
            resource_id=resource_id,
            list_resources=list_resources,
        )
    else:
        connector_instance = (
            service_connector_registry.instantiate_connector(
                model=service_connector
            )
        )
        connector_resources = connector_instance.verify(
            resource_type=resource_type,
            resource_id=resource_id,
            list_resources=list_resources,
        )

    if connector_resources.error:
        raise AuthorizationException(connector_resources.error)

    return connector_resources

CodeRepositoryFilter

Bases: ProjectScopedFilter

Model to enable advanced filtering of all code repositories.

ColorVariants

Bases: StrEnum

All possible color variants for frontend.

ComponentFilter

Bases: UserScopedFilter

Model to enable advanced stack component filtering.

Functions
generate_filter(table: Type[AnySchema]) -> Union[ColumnElement[bool]]

Generate the filter for the query.

Stack components can be scoped by type to narrow the search.

Parameters:

Name Type Description Default
table Type[AnySchema]

The Table that is being queried from.

required

Returns:

Type Description
Union[ColumnElement[bool]]

The filter expression for the query.

Source code in src/zenml/models/v2/core/component.py
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
def generate_filter(
    self, table: Type["AnySchema"]
) -> Union["ColumnElement[bool]"]:
    """Generate the filter for the query.

    Stack components can be scoped by type to narrow the search.

    Args:
        table: The Table that is being queried from.

    Returns:
        The filter expression for the query.
    """
    from sqlmodel import and_, or_

    from zenml.zen_stores.schemas import (
        StackComponentSchema,
        StackCompositionSchema,
    )

    base_filter = super().generate_filter(table)
    if self.scope_type:
        type_filter = getattr(table, "type") == self.scope_type
        return and_(base_filter, type_filter)

    if self.stack_id:
        operator = (
            or_ if self.logical_operator == LogicalOperators.OR else and_
        )

        stack_filter = and_(
            StackCompositionSchema.stack_id == self.stack_id,
            StackCompositionSchema.component_id == StackComponentSchema.id,
        )
        base_filter = operator(base_filter, stack_filter)

    return base_filter
set_scope_type(component_type: str) -> None

Set the type of component on which to perform the filtering to scope the response.

Parameters:

Name Type Description Default
component_type str

The type of component to scope the query to.

required
Source code in src/zenml/models/v2/core/component.py
383
384
385
386
387
388
389
def set_scope_type(self, component_type: str) -> None:
    """Set the type of component on which to perform the filtering to scope the response.

    Args:
        component_type: The type of component to scope the query to.
    """
    self.scope_type = component_type

ComponentInfo

Bases: BaseModel

Information about each stack components when creating a full stack.

CredentialsNotValid(message: Optional[str] = None, url: Optional[str] = None)

Bases: AuthorizationException

Raised when the credentials provided are invalid.

This is a subclass of AuthorizationException and should only be raised when the authentication credentials are invalid (e.g. expired API token, invalid username/password, invalid signature). If caught by the ZenML client, it will trigger an invalidation of the currently cached API token and a re-authentication flow.

Source code in src/zenml/exceptions.py
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
def __init__(
    self,
    message: Optional[str] = None,
    url: Optional[str] = None,
):
    """The BaseException used to format messages displayed to the user.

    Args:
        message: Message with details of exception. This message
                 will be appended with another message directing user to
                 `url` for more information. If `None`, then default
                 Exception behavior is used.
        url: URL to point to in exception message. If `None`, then no url
             is appended.
    """
    if message and url:
        message += f" For more information, visit {url}."
    super().__init__(message)

DatabaseBackupStrategy

Bases: StrEnum

All available database backup strategies.

EntityExistsError(message: Optional[str] = None, url: Optional[str] = None)

Bases: ZenMLBaseException

Raised when trying to register an entity that already exists.

Source code in src/zenml/exceptions.py
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
def __init__(
    self,
    message: Optional[str] = None,
    url: Optional[str] = None,
):
    """The BaseException used to format messages displayed to the user.

    Args:
        message: Message with details of exception. This message
                 will be appended with another message directing user to
                 `url` for more information. If `None`, then default
                 Exception behavior is used.
        url: URL to point to in exception message. If `None`, then no url
             is appended.
    """
    if message and url:
        message += f" For more information, visit {url}."
    super().__init__(message)

Environment()

Provides environment information.

Initializes an Environment instance.

Note: Environment is a singleton class, which means this method will only get called once. All following Environment() calls will return the previously initialized instance.

Source code in src/zenml/environment.py
105
106
107
108
109
110
111
def __init__(self) -> None:
    """Initializes an Environment instance.

    Note: Environment is a singleton class, which means this method will
    only get called once. All following `Environment()` calls will return
    the previously initialized instance.
    """
Functions
get_python_packages() -> List[str] staticmethod

Returns a list of installed Python packages.

Raises:

Type Description
RuntimeError

If the process to get the list of installed packages fails.

Returns:

Type Description
List[str]

List of installed packages in pip freeze format.

Source code in src/zenml/environment.py
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
@staticmethod
def get_python_packages() -> List[str]:
    """Returns a list of installed Python packages.

    Raises:
        RuntimeError: If the process to get the list of installed packages
            fails.

    Returns:
        List of installed packages in pip freeze format.
    """
    try:
        output = subprocess.check_output(["pip", "freeze"]).decode()
        return output.strip().split("\n")
    except subprocess.CalledProcessError:
        raise RuntimeError(
            "Failed to get list of installed Python packages"
        )
get_system_info() -> Dict[str, str] staticmethod

Information about the operating system.

Returns:

Type Description
Dict[str, str]

A dictionary containing information about the operating system.

Source code in src/zenml/environment.py
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
@staticmethod
def get_system_info() -> Dict[str, str]:
    """Information about the operating system.

    Returns:
        A dictionary containing information about the operating system.
    """
    system = platform.system()

    if system == "Windows":
        release, version, csd, ptype = platform.win32_ver()

        return {
            "os": "windows",
            "windows_version_release": release,
            "windows_version": version,
            "windows_version_service_pack": csd,
            "windows_version_os_type": ptype,
        }

    if system == "Darwin":
        return {"os": "mac", "mac_version": platform.mac_ver()[0]}

    if system == "Linux":
        return {
            "os": "linux",
            "linux_distro": distro.id(),
            "linux_distro_like": distro.like(),
            "linux_distro_version": distro.version(),
        }

    # We don't collect data for any other system.
    return {"os": "unknown"}
in_bitbucket_ci() -> bool staticmethod

If the current Python process is running in Bitbucket CI.

Returns:

Type Description
bool

True if the current Python process is running in Bitbucket

bool

CI, False otherwise.

Source code in src/zenml/environment.py
310
311
312
313
314
315
316
317
318
@staticmethod
def in_bitbucket_ci() -> bool:
    """If the current Python process is running in Bitbucket CI.

    Returns:
        `True` if the current Python process is running in Bitbucket
        CI, `False` otherwise.
    """
    return "BITBUCKET_BUILD_NUMBER" in os.environ
in_ci() -> bool staticmethod

If the current Python process is running in any CI.

Returns:

Type Description
bool

True if the current Python process is running in any

bool

CI, False otherwise.

Source code in src/zenml/environment.py
320
321
322
323
324
325
326
327
328
@staticmethod
def in_ci() -> bool:
    """If the current Python process is running in any CI.

    Returns:
        `True` if the current Python process is running in any
        CI, `False` otherwise.
    """
    return "CI" in os.environ
in_circle_ci() -> bool staticmethod

If the current Python process is running in Circle CI.

Returns:

Type Description
bool

True if the current Python process is running in Circle

bool

CI, False otherwise.

Source code in src/zenml/environment.py
300
301
302
303
304
305
306
307
308
@staticmethod
def in_circle_ci() -> bool:
    """If the current Python process is running in Circle CI.

    Returns:
        `True` if the current Python process is running in Circle
        CI, `False` otherwise.
    """
    return "CIRCLECI" in os.environ
in_container() -> bool staticmethod

If the current python process is running in a container.

Returns:

Type Description
bool

True if the current python process is running in a

bool

container, False otherwise.

Source code in src/zenml/environment.py
156
157
158
159
160
161
162
163
164
165
@staticmethod
def in_container() -> bool:
    """If the current python process is running in a container.

    Returns:
        `True` if the current python process is running in a
        container, `False` otherwise.
    """
    # TODO [ENG-167]: Make this more reliable and add test.
    return INSIDE_ZENML_CONTAINER
in_docker() -> bool staticmethod

If the current python process is running in a docker container.

Returns:

Type Description
bool

True if the current python process is running in a docker

bool

container, False otherwise.

Source code in src/zenml/environment.py
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
@staticmethod
def in_docker() -> bool:
    """If the current python process is running in a docker container.

    Returns:
        `True` if the current python process is running in a docker
        container, `False` otherwise.
    """
    if os.path.exists("./dockerenv") or os.path.exists("/.dockerinit"):
        return True

    try:
        with open("/proc/1/cgroup", "rt") as ifh:
            info = ifh.read()
            return "docker" in info
    except (FileNotFoundError, Exception):
        return False
in_github_actions() -> bool staticmethod

If the current Python process is running in GitHub Actions.

Returns:

Type Description
bool

True if the current Python process is running in GitHub

bool

Actions, False otherwise.

Source code in src/zenml/environment.py
280
281
282
283
284
285
286
287
288
@staticmethod
def in_github_actions() -> bool:
    """If the current Python process is running in GitHub Actions.

    Returns:
        `True` if the current Python process is running in GitHub
        Actions, `False` otherwise.
    """
    return "GITHUB_ACTIONS" in os.environ
in_github_codespaces() -> bool staticmethod

If the current Python process is running in GitHub Codespaces.

Returns:

Type Description
bool

True if the current Python process is running in GitHub Codespaces,

bool

False otherwise.

Source code in src/zenml/environment.py
243
244
245
246
247
248
249
250
251
252
253
254
255
@staticmethod
def in_github_codespaces() -> bool:
    """If the current Python process is running in GitHub Codespaces.

    Returns:
        `True` if the current Python process is running in GitHub Codespaces,
        `False` otherwise.
    """
    return (
        "CODESPACES" in os.environ
        or "GITHUB_CODESPACE_TOKEN" in os.environ
        or "GITHUB_CODESPACES_PORT_FORWARDING_DOMAIN" in os.environ
    )
in_gitlab_ci() -> bool staticmethod

If the current Python process is running in GitLab CI.

Returns:

Type Description
bool

True if the current Python process is running in GitLab

bool

CI, False otherwise.

Source code in src/zenml/environment.py
290
291
292
293
294
295
296
297
298
@staticmethod
def in_gitlab_ci() -> bool:
    """If the current Python process is running in GitLab CI.

    Returns:
        `True` if the current Python process is running in GitLab
        CI, `False` otherwise.
    """
    return "GITLAB_CI" in os.environ
in_google_colab() -> bool staticmethod

If the current Python process is running in a Google Colab.

Returns:

Type Description
bool

True if the current Python process is running in a Google Colab,

bool

False otherwise.

Source code in src/zenml/environment.py
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
@staticmethod
def in_google_colab() -> bool:
    """If the current Python process is running in a Google Colab.

    Returns:
        `True` if the current Python process is running in a Google Colab,
        `False` otherwise.
    """
    try:
        import google.colab  # noqa

        return True

    except ModuleNotFoundError:
        return False
in_kubernetes() -> bool staticmethod

If the current python process is running in a kubernetes pod.

Returns:

Type Description
bool

True if the current python process is running in a kubernetes

bool

pod, False otherwise.

Source code in src/zenml/environment.py
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
@staticmethod
def in_kubernetes() -> bool:
    """If the current python process is running in a kubernetes pod.

    Returns:
        `True` if the current python process is running in a kubernetes
        pod, `False` otherwise.
    """
    if "KUBERNETES_SERVICE_HOST" in os.environ:
        return True

    try:
        with open("/proc/1/cgroup", "rt") as ifh:
            info = ifh.read()
            return "kubepod" in info
    except (FileNotFoundError, Exception):
        return False
in_lightning_ai_studio() -> bool staticmethod

If the current Python process is running in Lightning.ai studios.

Returns:

Type Description
bool

True if the current Python process is running in Lightning.ai studios,

bool

False otherwise.

Source code in src/zenml/environment.py
341
342
343
344
345
346
347
348
349
350
351
352
@staticmethod
def in_lightning_ai_studio() -> bool:
    """If the current Python process is running in Lightning.ai studios.

    Returns:
        `True` if the current Python process is running in Lightning.ai studios,
        `False` otherwise.
    """
    return (
        "LIGHTNING_CLOUD_URL" in os.environ
        and "LIGHTNING_CLOUDSPACE_HOST" in os.environ
    )
in_notebook() -> bool staticmethod

If the current Python process is running in a notebook.

Returns:

Type Description
bool

True if the current Python process is running in a notebook,

bool

False otherwise.

Source code in src/zenml/environment.py
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
@staticmethod
def in_notebook() -> bool:
    """If the current Python process is running in a notebook.

    Returns:
        `True` if the current Python process is running in a notebook,
        `False` otherwise.
    """
    if Environment.in_google_colab():
        return True

    try:
        ipython = get_ipython()  # type: ignore[name-defined]
    except NameError:
        return False

    if ipython.__class__.__name__ in [
        "TerminalInteractiveShell",
        "ZMQInteractiveShell",
        "DatabricksShell",
    ]:
        return True
    return False
in_paperspace_gradient() -> bool staticmethod

If the current Python process is running in Paperspace Gradient.

Returns:

Type Description
bool

True if the current Python process is running in Paperspace

bool

Gradient, False otherwise.

Source code in src/zenml/environment.py
270
271
272
273
274
275
276
277
278
@staticmethod
def in_paperspace_gradient() -> bool:
    """If the current Python process is running in Paperspace Gradient.

    Returns:
        `True` if the current Python process is running in Paperspace
        Gradient, `False` otherwise.
    """
    return "PAPERSPACE_NOTEBOOK_REPO_ID" in os.environ
in_vscode_remote_container() -> bool staticmethod

If the current Python process is running in a VS Code Remote Container.

Returns:

Type Description
bool

True if the current Python process is running in a VS Code Remote Container,

bool

False otherwise.

Source code in src/zenml/environment.py
257
258
259
260
261
262
263
264
265
266
267
268
@staticmethod
def in_vscode_remote_container() -> bool:
    """If the current Python process is running in a VS Code Remote Container.

    Returns:
        `True` if the current Python process is running in a VS Code Remote Container,
        `False` otherwise.
    """
    return (
        "REMOTE_CONTAINERS" in os.environ
        or "VSCODE_REMOTE_CONTAINERS_SESSION" in os.environ
    )
in_wsl() -> bool staticmethod

If the current process is running in Windows Subsystem for Linux.

source: https://www.scivision.dev/python-detect-wsl/

Returns:

Type Description
bool

True if the current process is running in WSL, False otherwise.

Source code in src/zenml/environment.py
330
331
332
333
334
335
336
337
338
339
@staticmethod
def in_wsl() -> bool:
    """If the current process is running in Windows Subsystem for Linux.

    source: https://www.scivision.dev/python-detect-wsl/

    Returns:
        `True` if the current process is running in WSL, `False` otherwise.
    """
    return "microsoft-standard" in platform.uname().release
python_version() -> str staticmethod

Returns the python version of the running interpreter.

Returns:

Name Type Description
str str

the python version

Source code in src/zenml/environment.py
147
148
149
150
151
152
153
154
@staticmethod
def python_version() -> str:
    """Returns the python version of the running interpreter.

    Returns:
        str: the python version
    """
    return platform.python_version()

GitNotFoundError

Bases: ImportError

Raised when ZenML CLI is used to interact with examples on a machine with no git installation.

GlobalConfiguration(**data: Any)

Bases: BaseModel

Stores global configuration options.

Configuration options are read from a config file, but can be overwritten by environment variables. See GlobalConfiguration.__getattribute__ for more details.

Attributes:

Name Type Description
user_id UUID

Unique user id.

user_email Optional[str]

Email address associated with this client.

user_email_opt_in Optional[bool]

Whether the user has opted in to email communication.

analytics_opt_in bool

If a user agreed to sending analytics or not.

version Optional[str]

Version of ZenML that was last used to create or update the global config.

store Optional[SerializeAsAny[StoreConfiguration]]

Store configuration.

active_stack_id Optional[UUID]

The ID of the active stack.

active_project_id Optional[UUID]

The ID of the active project.

Initializes a GlobalConfiguration using values from the config file.

GlobalConfiguration is a singleton class: only one instance can exist. Calling this constructor multiple times will always yield the same instance.

Parameters:

Name Type Description Default
data Any

Custom configuration options.

{}
Source code in src/zenml/config/global_config.py
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
def __init__(self, **data: Any) -> None:
    """Initializes a GlobalConfiguration using values from the config file.

    GlobalConfiguration is a singleton class: only one instance can exist.
    Calling this constructor multiple times will always yield the same
    instance.

    Args:
        data: Custom configuration options.
    """
    config_values = self._read_config()
    config_values.update(data)

    super().__init__(**config_values)

    if not fileio.exists(self._config_file):
        self._write_config()
Attributes
config_directory: str property

Directory where the global configuration file is located.

Returns:

Type Description
str

The directory where the global configuration file is located.

is_initialized: bool property

Check if the global configuration is initialized.

Returns:

Type Description
bool

True if the global configuration is initialized.

local_stores_path: str property

Path where local stores information is stored.

Returns:

Type Description
str

The path where local stores information is stored.

store_configuration: StoreConfiguration property

Get the current store configuration.

Returns:

Type Description
StoreConfiguration

The store configuration.

zen_store: BaseZenStore property

Initialize and/or return the global zen store.

If the store hasn't been initialized yet, it is initialized when this property is first accessed according to the global store configuration.

Returns:

Type Description
BaseZenStore

The current zen store.

Functions
get_active_project() -> ProjectResponse

Get a model of the active project for the local client.

Returns:

Type Description
ProjectResponse

The model of the active project.

Source code in src/zenml/config/global_config.py
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
def get_active_project(self) -> "ProjectResponse":
    """Get a model of the active project for the local client.

    Returns:
        The model of the active project.
    """
    project_id = self.get_active_project_id()

    if self._active_project is not None:
        return self._active_project

    project = self.zen_store.get_project(
        project_name_or_id=project_id,
    )
    return self.set_active_project(project)
get_active_project_id() -> UUID

Get the ID of the active project.

Returns:

Type Description
UUID

The ID of the active project.

Raises:

Type Description
RuntimeError

If the active project is not set.

Source code in src/zenml/config/global_config.py
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
def get_active_project_id(self) -> UUID:
    """Get the ID of the active project.

    Returns:
        The ID of the active project.

    Raises:
        RuntimeError: If the active project is not set.
    """
    if self.active_project_id is None:
        _ = self.zen_store
        if self.active_project_id is None:
            raise RuntimeError(
                "No project is currently set as active. Please set the "
                "active project using the `zenml project set <NAME>` CLI "
                "command."
            )

    return self.active_project_id
get_active_stack_id() -> UUID

Get the ID of the active stack.

If the active stack doesn't exist yet, the ZenStore is reinitialized.

Returns:

Type Description
UUID

The active stack ID.

Source code in src/zenml/config/global_config.py
784
785
786
787
788
789
790
791
792
793
794
795
796
def get_active_stack_id(self) -> UUID:
    """Get the ID of the active stack.

    If the active stack doesn't exist yet, the ZenStore is reinitialized.

    Returns:
        The active stack ID.
    """
    if self.active_stack_id is None:
        _ = self.zen_store
        assert self.active_stack_id is not None

    return self.active_stack_id
get_config_environment_vars() -> Dict[str, str]

Convert the global configuration to environment variables.

Returns:

Type Description
Dict[str, str]

Environment variables dictionary.

Source code in src/zenml/config/global_config.py
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
def get_config_environment_vars(self) -> Dict[str, str]:
    """Convert the global configuration to environment variables.

    Returns:
        Environment variables dictionary.
    """
    environment_vars = {}

    for key in type(self).model_fields.keys():
        if key == "store":
            # The store configuration uses its own environment variable
            # naming scheme
            continue

        value = getattr(self, key)
        if value is not None:
            environment_vars[CONFIG_ENV_VAR_PREFIX + key.upper()] = str(
                value
            )

    store_dict = self.store_configuration.model_dump(exclude_none=True)

    # The secrets store and backup secrets store configurations use their
    # own environment variables naming scheme
    secrets_store_dict = store_dict.pop("secrets_store", None) or {}
    backup_secrets_store_dict = (
        store_dict.pop("backup_secrets_store", None) or {}
    )

    for key, value in store_dict.items():
        if key in ["username", "password"]:
            # Never include the username and password in the env vars. Use
            # the API token instead.
            continue

        environment_vars[ENV_ZENML_STORE_PREFIX + key.upper()] = str(value)

    for key, value in secrets_store_dict.items():
        environment_vars[ENV_ZENML_SECRETS_STORE_PREFIX + key.upper()] = (
            str(value)
        )

    for key, value in backup_secrets_store_dict.items():
        environment_vars[
            ENV_ZENML_BACKUP_SECRETS_STORE_PREFIX + key.upper()
        ] = str(value)

    return environment_vars
get_default_store() -> StoreConfiguration

Get the default SQLite store configuration.

Returns:

Type Description
StoreConfiguration

The default SQLite store configuration.

Source code in src/zenml/config/global_config.py
639
640
641
642
643
644
645
646
647
648
649
650
651
652
def get_default_store(self) -> StoreConfiguration:
    """Get the default SQLite store configuration.

    Returns:
        The default SQLite store configuration.
    """
    from zenml.zen_stores.base_zen_store import BaseZenStore

    return BaseZenStore.get_default_store_config(
        path=os.path.join(
            self.local_stores_path,
            DEFAULT_STORE_DIRECTORY_NAME,
        )
    )
get_instance() -> Optional[GlobalConfiguration] classmethod

Return the GlobalConfiguration singleton instance.

Returns:

Type Description
Optional[GlobalConfiguration]

The GlobalConfiguration singleton instance or None, if the

Optional[GlobalConfiguration]

GlobalConfiguration hasn't been initialized yet.

Source code in src/zenml/config/global_config.py
150
151
152
153
154
155
156
157
158
@classmethod
def get_instance(cls) -> Optional["GlobalConfiguration"]:
    """Return the GlobalConfiguration singleton instance.

    Returns:
        The GlobalConfiguration singleton instance or None, if the
        GlobalConfiguration hasn't been initialized yet.
    """
    return cls._global_config
set_active_project(project: ProjectResponse) -> ProjectResponse

Set the project for the local client.

Parameters:

Name Type Description Default
project ProjectResponse

The project to set active.

required

Returns:

Type Description
ProjectResponse

The project that was set active.

Source code in src/zenml/config/global_config.py
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
def set_active_project(
    self, project: "ProjectResponse"
) -> "ProjectResponse":
    """Set the project for the local client.

    Args:
        project: The project to set active.

    Returns:
        The project that was set active.
    """
    self.active_project_id = project.id
    self._active_project = project
    # Sanitize the global configuration to reflect the new project
    self._sanitize_config()
    return project
set_active_stack(stack: StackResponse) -> None

Set the active stack for the local client.

Parameters:

Name Type Description Default
stack StackResponse

The model of the stack to set active.

required
Source code in src/zenml/config/global_config.py
739
740
741
742
743
744
745
746
def set_active_stack(self, stack: "StackResponse") -> None:
    """Set the active stack for the local client.

    Args:
        stack: The model of the stack to set active.
    """
    self.active_stack_id = stack.id
    self._active_stack = stack
set_default_store() -> None

Initializes and sets the default store configuration.

Call this method to initialize or revert the store configuration to the default store.

Source code in src/zenml/config/global_config.py
654
655
656
657
658
659
660
661
662
663
664
665
def set_default_store(self) -> None:
    """Initializes and sets the default store configuration.

    Call this method to initialize or revert the store configuration to the
    default store.
    """
    # Apply the environment variables to the default store configuration
    default_store_cfg = self._get_store_configuration(
        baseline=self.get_default_store()
    )
    self._configure_store(default_store_cfg)
    logger.debug("Using the default store for the global config.")
set_store(config: StoreConfiguration, skip_default_registrations: bool = False, **kwargs: Any) -> None

Update the active store configuration.

Call this method to validate and update the active store configuration.

Parameters:

Name Type Description Default
config StoreConfiguration

The new store configuration to use.

required
skip_default_registrations bool

If True, the creation of the default stack and user in the store will be skipped.

False
**kwargs Any

Additional keyword arguments to pass to the store constructor.

{}
Source code in src/zenml/config/global_config.py
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
def set_store(
    self,
    config: StoreConfiguration,
    skip_default_registrations: bool = False,
    **kwargs: Any,
) -> None:
    """Update the active store configuration.

    Call this method to validate and update the active store configuration.

    Args:
        config: The new store configuration to use.
        skip_default_registrations: If `True`, the creation of the default
            stack and user in the store will be skipped.
        **kwargs: Additional keyword arguments to pass to the store
            constructor.
    """
    # Apply the environment variables to the custom store configuration
    config = self._get_store_configuration(baseline=config)
    self._configure_store(config, skip_default_registrations, **kwargs)
    logger.info("Updated the global store configuration.")
uses_default_store() -> bool

Check if the global configuration uses the default store.

Returns:

Type Description
bool

True if the global configuration uses the default store.

Source code in src/zenml/config/global_config.py
667
668
669
670
671
672
673
def uses_default_store(self) -> bool:
    """Check if the global configuration uses the default store.

    Returns:
        `True` if the global configuration uses the default store.
    """
    return self.store_configuration.url == self.get_default_store().url

IllegalOperationError(message: Optional[str] = None, url: Optional[str] = None)

Bases: ZenMLBaseException

Raised when an illegal operation is attempted.

Source code in src/zenml/exceptions.py
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
def __init__(
    self,
    message: Optional[str] = None,
    url: Optional[str] = None,
):
    """The BaseException used to format messages displayed to the user.

    Args:
        message: Message with details of exception. This message
                 will be appended with another message directing user to
                 `url` for more information. If `None`, then default
                 Exception behavior is used.
        url: URL to point to in exception message. If `None`, then no url
             is appended.
    """
    if message and url:
        message += f" For more information, visit {url}."
    super().__init__(message)

InitializationException(message: Optional[str] = None, url: Optional[str] = None)

Bases: ZenMLBaseException

Raised when an error occurred during initialization of a ZenML repository.

Source code in src/zenml/exceptions.py
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
def __init__(
    self,
    message: Optional[str] = None,
    url: Optional[str] = None,
):
    """The BaseException used to format messages displayed to the user.

    Args:
        message: Message with details of exception. This message
                 will be appended with another message directing user to
                 `url` for more information. If `None`, then default
                 Exception behavior is used.
        url: URL to point to in exception message. If `None`, then no url
             is appended.
    """
    if message and url:
        message += f" For more information, visit {url}."
    super().__init__(message)

LoggingLevels

Bases: Enum

Enum for logging levels.

ModelFilter

Bases: ProjectScopedFilter, TaggableFilter

Model to enable advanced filtering of all models.

Functions
apply_sorting(query: AnyQuery, table: Type[AnySchema]) -> AnyQuery

Apply sorting to the query for Models.

Parameters:

Name Type Description Default
query AnyQuery

The query to which to apply the sorting.

required
table Type[AnySchema]

The query table.

required

Returns:

Type Description
AnyQuery

The query with sorting applied.

Source code in src/zenml/models/v2/core/model.py
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
def apply_sorting(
    self,
    query: AnyQuery,
    table: Type["AnySchema"],
) -> AnyQuery:
    """Apply sorting to the query for Models.

    Args:
        query: The query to which to apply the sorting.
        table: The query table.

    Returns:
        The query with sorting applied.
    """
    from sqlmodel import asc, case, col, desc, func, select

    from zenml.enums import SorterOps
    from zenml.zen_stores.schemas import (
        ModelSchema,
        ModelVersionSchema,
    )

    sort_by, operand = self.sorting_params

    if sort_by == SORT_BY_LATEST_VERSION_KEY:
        # Subquery to find the latest version per model
        latest_version_subquery = (
            select(
                ModelSchema.id,
                case(
                    (
                        func.max(ModelVersionSchema.created).is_(None),
                        ModelSchema.created,
                    ),
                    else_=func.max(ModelVersionSchema.created),
                ).label("latest_version_created"),
            )
            .outerjoin(
                ModelVersionSchema,
                ModelSchema.id == ModelVersionSchema.model_id,  # type: ignore[arg-type]
            )
            .group_by(col(ModelSchema.id))
            .subquery()
        )

        query = query.add_columns(
            latest_version_subquery.c.latest_version_created,
        ).where(ModelSchema.id == latest_version_subquery.c.id)

        # Apply sorting based on the operand
        if operand == SorterOps.ASCENDING:
            query = query.order_by(
                asc(latest_version_subquery.c.latest_version_created),
                asc(ModelSchema.id),
            )
        else:
            query = query.order_by(
                desc(latest_version_subquery.c.latest_version_created),
                desc(ModelSchema.id),
            )
        return query

    # For other sorting cases, delegate to the parent class
    return super().apply_sorting(query=query, table=table)

ModelRegistryModelMetadata

Bases: BaseModel

Base class for all ZenML model registry model metadata.

The ModelRegistryModelMetadata class represents metadata associated with a registered model version, including information such as the associated pipeline name, pipeline run ID, step name, ZenML version, and custom attributes. It serves as a blueprint for creating concrete model metadata implementations in a registry, and provides a record of the history of a model and its development process.

Attributes
custom_attributes: Dict[str, str] property

Returns a dictionary of custom attributes.

Returns:

Type Description
Dict[str, str]

A dictionary of custom attributes.

Functions
model_dump(*, exclude_unset: bool = False, exclude_none: bool = True, **kwargs: Any) -> Dict[str, str]

Returns a dictionary representation of the metadata.

This method overrides the default Pydantic model_dump method to allow for the exclusion of fields with a value of None.

Parameters:

Name Type Description Default
exclude_unset bool

Whether to exclude unset attributes.

False
exclude_none bool

Whether to exclude None attributes.

True
**kwargs Any

Additional keyword arguments.

{}

Returns:

Type Description
Dict[str, str]

A dictionary representation of the metadata.

Source code in src/zenml/model_registries/base_model_registry.py
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
def model_dump(
    self,
    *,
    exclude_unset: bool = False,
    exclude_none: bool = True,
    **kwargs: Any,
) -> Dict[str, str]:
    """Returns a dictionary representation of the metadata.

    This method overrides the default Pydantic `model_dump` method to allow
    for the exclusion of fields with a value of None.

    Args:
        exclude_unset: Whether to exclude unset attributes.
        exclude_none: Whether to exclude None attributes.
        **kwargs: Additional keyword arguments.

    Returns:
        A dictionary representation of the metadata.
    """
    if exclude_none:
        return {
            k: v
            for k, v in super()
            .model_dump(exclude_unset=exclude_unset, **kwargs)
            .items()
            if v is not None
        }
    else:
        return super().model_dump(exclude_unset=exclude_unset, **kwargs)

ModelResponse

Bases: ProjectScopedResponse[ModelResponseBody, ModelResponseMetadata, ModelResponseResources]

Response model for models.

Attributes
audience: Optional[str] property

The audience property.

Returns:

Type Description
Optional[str]

the value of the property.

description: Optional[str] property

The description property.

Returns:

Type Description
Optional[str]

the value of the property.

ethics: Optional[str] property

The ethics property.

Returns:

Type Description
Optional[str]

the value of the property.

latest_version_id: Optional[UUID] property

The latest_version_id property.

Returns:

Type Description
Optional[UUID]

the value of the property.

latest_version_name: Optional[str] property

The latest_version_name property.

Returns:

Type Description
Optional[str]

the value of the property.

license: Optional[str] property

The license property.

Returns:

Type Description
Optional[str]

the value of the property.

limitations: Optional[str] property

The limitations property.

Returns:

Type Description
Optional[str]

the value of the property.

save_models_to_registry: bool property

The save_models_to_registry property.

Returns:

Type Description
bool

the value of the property.

tags: List[TagResponse] property

The tags property.

Returns:

Type Description
List[TagResponse]

the value of the property.

trade_offs: Optional[str] property

The trade_offs property.

Returns:

Type Description
Optional[str]

the value of the property.

use_cases: Optional[str] property

The use_cases property.

Returns:

Type Description
Optional[str]

the value of the property.

versions: List[Model] property

List all versions of the model.

Returns:

Type Description
List[Model]

The list of all model version.

Functions
get_hydrated_version() -> ModelResponse

Get the hydrated version of this model.

Returns:

Type Description
ModelResponse

an instance of the same entity with the metadata field attached.

Source code in src/zenml/models/v2/core/model.py
202
203
204
205
206
207
208
209
210
def get_hydrated_version(self) -> "ModelResponse":
    """Get the hydrated version of this model.

    Returns:
        an instance of the same entity with the metadata field attached.
    """
    from zenml.client import Client

    return Client().zen_store.get_model(self.id)

ModelStages

Bases: StrEnum

All possible stages of a Model Version.

ModelVersionArtifactFilter

Bases: BaseFilter

Model version pipeline run links filter model.

Functions
get_custom_filters(table: Type[AnySchema]) -> List[Union[ColumnElement[bool]]]

Get custom filters.

Parameters:

Name Type Description Default
table Type[AnySchema]

The query table.

required

Returns:

Type Description
List[Union[ColumnElement[bool]]]

A list of custom filters.

Source code in src/zenml/models/v2/core/model_version_artifact.py
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
def get_custom_filters(
    self, table: Type["AnySchema"]
) -> List[Union["ColumnElement[bool]"]]:
    """Get custom filters.

    Args:
        table: The query table.

    Returns:
        A list of custom filters.
    """
    custom_filters = super().get_custom_filters(table)

    from sqlmodel import and_, col

    from zenml.zen_stores.schemas import (
        ArtifactSchema,
        ArtifactVersionSchema,
        ModelVersionArtifactSchema,
        UserSchema,
    )

    if self.artifact_name:
        value, filter_operator = self._resolve_operator(self.artifact_name)
        filter_ = StrFilter(
            operation=GenericFilterOps(filter_operator),
            column="name",
            value=value,
        )
        artifact_name_filter = and_(
            ModelVersionArtifactSchema.artifact_version_id
            == ArtifactVersionSchema.id,
            ArtifactVersionSchema.artifact_id == ArtifactSchema.id,
            filter_.generate_query_conditions(ArtifactSchema),
        )
        custom_filters.append(artifact_name_filter)

    if self.only_data_artifacts:
        data_artifact_filter = and_(
            ModelVersionArtifactSchema.artifact_version_id
            == ArtifactVersionSchema.id,
            col(ArtifactVersionSchema.type).not_in(
                ["ServiceArtifact", "ModelArtifact"]
            ),
        )
        custom_filters.append(data_artifact_filter)

    if self.only_model_artifacts:
        model_artifact_filter = and_(
            ModelVersionArtifactSchema.artifact_version_id
            == ArtifactVersionSchema.id,
            ArtifactVersionSchema.type == "ModelArtifact",
        )
        custom_filters.append(model_artifact_filter)

    if self.only_deployment_artifacts:
        deployment_artifact_filter = and_(
            ModelVersionArtifactSchema.artifact_version_id
            == ArtifactVersionSchema.id,
            ArtifactVersionSchema.type == "ServiceArtifact",
        )
        custom_filters.append(deployment_artifact_filter)

    if self.has_custom_name is not None:
        custom_name_filter = and_(
            ModelVersionArtifactSchema.artifact_version_id
            == ArtifactVersionSchema.id,
            ArtifactVersionSchema.artifact_id == ArtifactSchema.id,
            ArtifactSchema.has_custom_name == self.has_custom_name,
        )
        custom_filters.append(custom_name_filter)

    if self.user:
        user_filter = and_(
            ModelVersionArtifactSchema.artifact_version_id
            == ArtifactVersionSchema.id,
            ArtifactVersionSchema.user_id == UserSchema.id,
            self.generate_name_or_id_query_conditions(
                value=self.user,
                table=UserSchema,
                additional_columns=["full_name"],
            ),
        )
        custom_filters.append(user_filter)

    return custom_filters

ModelVersionFilter

Bases: ProjectScopedFilter, TaggableFilter, RunMetadataFilterMixin

Filter model for model versions.

Functions
get_custom_filters(table: Type[AnySchema]) -> List[Union[ColumnElement[bool]]]

Get custom filters.

Parameters:

Name Type Description Default
table Type[AnySchema]

The query table.

required

Returns:

Type Description
List[Union[ColumnElement[bool]]]

A list of custom filters.

Source code in src/zenml/models/v2/core/model_version.py
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
def get_custom_filters(
    self, table: Type["AnySchema"]
) -> List[Union["ColumnElement[bool]"]]:
    """Get custom filters.

    Args:
        table: The query table.

    Returns:
        A list of custom filters.
    """
    from sqlalchemy import and_

    from zenml.zen_stores.schemas import (
        ModelSchema,
        ModelVersionSchema,
    )

    custom_filters = super().get_custom_filters(table)

    if self.model:
        value, operator = self._resolve_operator(self.model)
        model_filter = and_(
            ModelVersionSchema.model_id == ModelSchema.id,  # type: ignore[arg-type]
            self.generate_name_or_id_query_conditions(
                value=self.model, table=ModelSchema
            ),
        )
        custom_filters.append(model_filter)

    return custom_filters

ModelVersionPipelineRunFilter

Bases: BaseFilter

Model version pipeline run links filter model.

Functions
get_custom_filters(table: Type[AnySchema]) -> List[ColumnElement[bool]]

Get custom filters.

Parameters:

Name Type Description Default
table Type[AnySchema]

The query table.

required

Returns:

Type Description
List[ColumnElement[bool]]

A list of custom filters.

Source code in src/zenml/models/v2/core/model_version_pipeline_run.py
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
def get_custom_filters(
    self, table: Type["AnySchema"]
) -> List["ColumnElement[bool]"]:
    """Get custom filters.

    Args:
        table: The query table.

    Returns:
        A list of custom filters.
    """
    custom_filters = super().get_custom_filters(table)

    from sqlmodel import and_

    from zenml.zen_stores.schemas import (
        ModelVersionPipelineRunSchema,
        PipelineRunSchema,
        UserSchema,
    )

    if self.pipeline_run_name:
        value, filter_operator = self._resolve_operator(
            self.pipeline_run_name
        )
        filter_ = StrFilter(
            operation=GenericFilterOps(filter_operator),
            column="name",
            value=value,
        )
        pipeline_run_name_filter = and_(
            ModelVersionPipelineRunSchema.pipeline_run_id
            == PipelineRunSchema.id,
            filter_.generate_query_conditions(PipelineRunSchema),
        )
        custom_filters.append(pipeline_run_name_filter)

    if self.user:
        user_filter = and_(
            ModelVersionPipelineRunSchema.pipeline_run_id
            == PipelineRunSchema.id,
            PipelineRunSchema.user_id == UserSchema.id,
            self.generate_name_or_id_query_conditions(
                value=self.user,
                table=UserSchema,
                additional_columns=["full_name"],
            ),
        )
        custom_filters.append(user_filter)

    return custom_filters

ModelVersionResponse

Bases: ProjectScopedResponse[ModelVersionResponseBody, ModelVersionResponseMetadata, ModelVersionResponseResources]

Response model for model versions.

Attributes
data_artifact_ids: Dict[str, Dict[str, UUID]] property

The data_artifact_ids property.

Returns:

Type Description
Dict[str, Dict[str, UUID]]

the value of the property.

data_artifacts: Dict[str, Dict[str, ArtifactVersionResponse]] property

Get all data artifacts linked to this model version.

Returns:

Type Description
Dict[str, Dict[str, ArtifactVersionResponse]]

Dictionary of data artifacts with versions as

Dict[str, Dict[str, ArtifactVersionResponse]]

Dict[str, Dict[str, ArtifactResponse]]

deployment_artifact_ids: Dict[str, Dict[str, UUID]] property

The deployment_artifact_ids property.

Returns:

Type Description
Dict[str, Dict[str, UUID]]

the value of the property.

deployment_artifacts: Dict[str, Dict[str, ArtifactVersionResponse]] property

Get all deployment artifacts linked to this model version.

Returns:

Type Description
Dict[str, Dict[str, ArtifactVersionResponse]]

Dictionary of deployment artifacts with versions as

Dict[str, Dict[str, ArtifactVersionResponse]]

Dict[str, Dict[str, ArtifactResponse]]

description: Optional[str] property

The description property.

Returns:

Type Description
Optional[str]

the value of the property.

model: ModelResponse property

The model property.

Returns:

Type Description
ModelResponse

the value of the property.

model_artifact_ids: Dict[str, Dict[str, UUID]] property

The model_artifact_ids property.

Returns:

Type Description
Dict[str, Dict[str, UUID]]

the value of the property.

model_artifacts: Dict[str, Dict[str, ArtifactVersionResponse]] property

Get all model artifacts linked to this model version.

Returns:

Type Description
Dict[str, Dict[str, ArtifactVersionResponse]]

Dictionary of model artifacts with versions as

Dict[str, Dict[str, ArtifactVersionResponse]]

Dict[str, Dict[str, ArtifactResponse]]

number: int property

The number property.

Returns:

Type Description
int

the value of the property.

pipeline_run_ids: Dict[str, UUID] property

The pipeline_run_ids property.

Returns:

Type Description
Dict[str, UUID]

the value of the property.

pipeline_runs: Dict[str, PipelineRunResponse] property

Get all pipeline runs linked to this version.

Returns:

Type Description
Dict[str, PipelineRunResponse]

Dictionary of Pipeline Runs as PipelineRunResponseModel

run_metadata: Dict[str, MetadataType] property

The run_metadata property.

Returns:

Type Description
Dict[str, MetadataType]

the value of the property.

stage: Optional[str] property

The stage property.

Returns:

Type Description
Optional[str]

the value of the property.

tags: List[TagResponse] property

The tags property.

Returns:

Type Description
List[TagResponse]

the value of the property.

Functions
get_artifact(name: str, version: Optional[str] = None) -> Optional[ArtifactVersionResponse]

Get the artifact linked to this model version.

Parameters:

Name Type Description Default
name str

The name of the artifact to retrieve.

required
version Optional[str]

The version of the artifact to retrieve (None for latest/non-versioned)

None

Returns:

Type Description
Optional[ArtifactVersionResponse]

Specific version of an artifact or None

Source code in src/zenml/models/v2/core/model_version.py
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
def get_artifact(
    self,
    name: str,
    version: Optional[str] = None,
) -> Optional["ArtifactVersionResponse"]:
    """Get the artifact linked to this model version.

    Args:
        name: The name of the artifact to retrieve.
        version: The version of the artifact to retrieve (None for
            latest/non-versioned)

    Returns:
        Specific version of an artifact or None
    """
    return self._get_linked_object(name, version)
get_data_artifact(name: str, version: Optional[str] = None) -> Optional[ArtifactVersionResponse]

Get the data artifact linked to this model version.

Parameters:

Name Type Description Default
name str

The name of the data artifact to retrieve.

required
version Optional[str]

The version of the data artifact to retrieve (None for latest/non-versioned)

None

Returns:

Type Description
Optional[ArtifactVersionResponse]

Specific version of the data artifact or None

Source code in src/zenml/models/v2/core/model_version.py
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
def get_data_artifact(
    self,
    name: str,
    version: Optional[str] = None,
) -> Optional["ArtifactVersionResponse"]:
    """Get the data artifact linked to this model version.

    Args:
        name: The name of the data artifact to retrieve.
        version: The version of the data artifact to retrieve (None for
            latest/non-versioned)

    Returns:
        Specific version of the data artifact or None
    """
    return self._get_linked_object(name, version, ArtifactType.DATA)
get_deployment_artifact(name: str, version: Optional[str] = None) -> Optional[ArtifactVersionResponse]

Get the deployment artifact linked to this model version.

Parameters:

Name Type Description Default
name str

The name of the deployment artifact to retrieve.

required
version Optional[str]

The version of the deployment artifact to retrieve (None for latest/non-versioned)

None

Returns:

Type Description
Optional[ArtifactVersionResponse]

Specific version of the deployment artifact or None

Source code in src/zenml/models/v2/core/model_version.py
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
def get_deployment_artifact(
    self,
    name: str,
    version: Optional[str] = None,
) -> Optional["ArtifactVersionResponse"]:
    """Get the deployment artifact linked to this model version.

    Args:
        name: The name of the deployment artifact to retrieve.
        version: The version of the deployment artifact to retrieve (None for
            latest/non-versioned)

    Returns:
        Specific version of the deployment artifact or None
    """
    return self._get_linked_object(name, version, ArtifactType.SERVICE)
get_hydrated_version() -> ModelVersionResponse

Get the hydrated version of this model version.

Returns:

Type Description
ModelVersionResponse

an instance of the same entity with the metadata field attached.

Source code in src/zenml/models/v2/core/model_version.py
310
311
312
313
314
315
316
317
318
def get_hydrated_version(self) -> "ModelVersionResponse":
    """Get the hydrated version of this model version.

    Returns:
        an instance of the same entity with the metadata field attached.
    """
    from zenml.client import Client

    return Client().zen_store.get_model_version(self.id)
get_model_artifact(name: str, version: Optional[str] = None) -> Optional[ArtifactVersionResponse]

Get the model artifact linked to this model version.

Parameters:

Name Type Description Default
name str

The name of the model artifact to retrieve.

required
version Optional[str]

The version of the model artifact to retrieve (None for latest/non-versioned)

None

Returns:

Type Description
Optional[ArtifactVersionResponse]

Specific version of the model artifact or None

Source code in src/zenml/models/v2/core/model_version.py
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
def get_model_artifact(
    self,
    name: str,
    version: Optional[str] = None,
) -> Optional["ArtifactVersionResponse"]:
    """Get the model artifact linked to this model version.

    Args:
        name: The name of the model artifact to retrieve.
        version: The version of the model artifact to retrieve (None for
            latest/non-versioned)

    Returns:
        Specific version of the model artifact or None
    """
    return self._get_linked_object(name, version, ArtifactType.MODEL)
get_pipeline_run(name: str) -> PipelineRunResponse

Get pipeline run linked to this version.

Parameters:

Name Type Description Default
name str

The name of the pipeline run to retrieve.

required

Returns:

Type Description
PipelineRunResponse

PipelineRun as PipelineRunResponseModel

Source code in src/zenml/models/v2/core/model_version.py
528
529
530
531
532
533
534
535
536
537
538
539
def get_pipeline_run(self, name: str) -> "PipelineRunResponse":
    """Get pipeline run linked to this version.

    Args:
        name: The name of the pipeline run to retrieve.

    Returns:
        PipelineRun as PipelineRunResponseModel
    """
    from zenml.client import Client

    return Client().get_pipeline_run(self.pipeline_run_ids[name])
set_stage(stage: Union[str, ModelStages], force: bool = False) -> None

Sets this Model Version to a desired stage.

Parameters:

Name Type Description Default
stage Union[str, ModelStages]

the target stage for model version.

required
force bool

whether to force archiving of current model version in target stage or raise.

False

Raises:

Type Description
ValueError

if model_stage is not valid.

Source code in src/zenml/models/v2/core/model_version.py
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
def set_stage(
    self, stage: Union[str, ModelStages], force: bool = False
) -> None:
    """Sets this Model Version to a desired stage.

    Args:
        stage: the target stage for model version.
        force: whether to force archiving of current model version in
            target stage or raise.

    Raises:
        ValueError: if model_stage is not valid.
    """
    from zenml.client import Client

    stage = getattr(stage, "value", stage)
    if stage not in [stage.value for stage in ModelStages]:
        raise ValueError(f"`{stage}` is not a valid model stage.")

    Client().update_model_version(
        model_name_or_id=self.model.id,
        version_name_or_id=self.id,
        stage=stage,
        force=force,
    )
to_model_class(suppress_class_validation_warnings: bool = True) -> Model

Convert response model to Model object.

Parameters:

Name Type Description Default
suppress_class_validation_warnings bool

internally used to suppress repeated warnings.

True

Returns:

Type Description
Model

Model object

Source code in src/zenml/models/v2/core/model_version.py
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
def to_model_class(
    self,
    suppress_class_validation_warnings: bool = True,
) -> "Model":
    """Convert response model to Model object.

    Args:
        suppress_class_validation_warnings: internally used to suppress
            repeated warnings.

    Returns:
        Model object
    """
    from zenml.model.model import Model

    mv = Model(
        name=self.model.name,
        license=self.model.license,
        description=self.description,
        audience=self.model.audience,
        use_cases=self.model.use_cases,
        limitations=self.model.limitations,
        trade_offs=self.model.trade_offs,
        ethics=self.model.ethics,
        tags=[t.name for t in self.tags],
        version=self.name,
        suppress_class_validation_warnings=suppress_class_validation_warnings,
        model_version_id=self.id,
    )

    return mv

ModelVersionStage

Bases: Enum

Enum of the possible stages of a registered model.

OAuthDeviceFilter

Bases: UserScopedFilter

Model to enable advanced filtering of OAuth2 devices.

OldSchoolMarkdownHeading

Bases: Heading

A traditional markdown heading.

Pipeline(name: str, entrypoint: F, enable_cache: Optional[bool] = None, enable_artifact_metadata: Optional[bool] = None, enable_artifact_visualization: Optional[bool] = None, enable_step_logs: Optional[bool] = None, enable_pipeline_logs: Optional[bool] = None, settings: Optional[Mapping[str, SettingsOrDict]] = None, tags: Optional[List[Union[str, Tag]]] = None, extra: Optional[Dict[str, Any]] = None, on_failure: Optional[HookSpecification] = None, on_success: Optional[HookSpecification] = None, model: Optional[Model] = None, substitutions: Optional[Dict[str, str]] = None)

ZenML pipeline class.

Initializes a pipeline.

Parameters:

Name Type Description Default
name str

The name of the pipeline.

required
entrypoint F

The entrypoint function of the pipeline.

required
enable_cache Optional[bool]

If caching should be enabled for this pipeline.

None
enable_artifact_metadata Optional[bool]

If artifact metadata should be enabled for this pipeline.

None
enable_artifact_visualization Optional[bool]

If artifact visualization should be enabled for this pipeline.

None
enable_step_logs Optional[bool]

If step logs should be enabled for this pipeline.

None
enable_pipeline_logs Optional[bool]

If pipeline logs should be enabled for this pipeline.

None
settings Optional[Mapping[str, SettingsOrDict]]

Settings for this pipeline.

None
tags Optional[List[Union[str, Tag]]]

Tags to apply to runs of this pipeline.

None
extra Optional[Dict[str, Any]]

Extra configurations for this pipeline.

None
on_failure Optional[HookSpecification]

Callback function in event of failure of the step. Can be a function with a single argument of type BaseException, or a source path to such a function (e.g. module.my_function).

None
on_success Optional[HookSpecification]

Callback function in event of success of the step. Can be a function with no arguments, or a source path to such a function (e.g. module.my_function).

None
model Optional[Model]

configuration of the model in the Model Control Plane.

None
substitutions Optional[Dict[str, str]]

Extra placeholders to use in the name templates.

None
Source code in src/zenml/pipelines/pipeline_definition.py
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
def __init__(
    self,
    name: str,
    entrypoint: F,
    enable_cache: Optional[bool] = None,
    enable_artifact_metadata: Optional[bool] = None,
    enable_artifact_visualization: Optional[bool] = None,
    enable_step_logs: Optional[bool] = None,
    enable_pipeline_logs: Optional[bool] = None,
    settings: Optional[Mapping[str, "SettingsOrDict"]] = None,
    tags: Optional[List[Union[str, "Tag"]]] = None,
    extra: Optional[Dict[str, Any]] = None,
    on_failure: Optional["HookSpecification"] = None,
    on_success: Optional["HookSpecification"] = None,
    model: Optional["Model"] = None,
    substitutions: Optional[Dict[str, str]] = None,
) -> None:
    """Initializes a pipeline.

    Args:
        name: The name of the pipeline.
        entrypoint: The entrypoint function of the pipeline.
        enable_cache: If caching should be enabled for this pipeline.
        enable_artifact_metadata: If artifact metadata should be enabled for
            this pipeline.
        enable_artifact_visualization: If artifact visualization should be
            enabled for this pipeline.
        enable_step_logs: If step logs should be enabled for this pipeline.
        enable_pipeline_logs: If pipeline logs should be enabled for this pipeline.
        settings: Settings for this pipeline.
        tags: Tags to apply to runs of this pipeline.
        extra: Extra configurations for this pipeline.
        on_failure: Callback function in event of failure of the step. Can
            be a function with a single argument of type `BaseException`, or
            a source path to such a function (e.g. `module.my_function`).
        on_success: Callback function in event of success of the step. Can
            be a function with no arguments, or a source path to such a
            function (e.g. `module.my_function`).
        model: configuration of the model in the Model Control Plane.
        substitutions: Extra placeholders to use in the name templates.
    """
    self._invocations: Dict[str, StepInvocation] = {}
    self._run_args: Dict[str, Any] = {}

    self._configuration = PipelineConfiguration(
        name=name,
    )
    self._from_config_file: Dict[str, Any] = {}
    with self.__suppress_configure_warnings__():
        self.configure(
            enable_cache=enable_cache,
            enable_artifact_metadata=enable_artifact_metadata,
            enable_artifact_visualization=enable_artifact_visualization,
            enable_step_logs=enable_step_logs,
            enable_pipeline_logs=enable_pipeline_logs,
            settings=settings,
            tags=tags,
            extra=extra,
            on_failure=on_failure,
            on_success=on_success,
            model=model,
            substitutions=substitutions,
        )
    self.entrypoint = entrypoint
    self._parameters: Dict[str, Any] = {}

    self.__suppress_warnings_flag__ = False
Attributes
configuration: PipelineConfiguration property

The configuration of the pipeline.

Returns:

Type Description
PipelineConfiguration

The configuration of the pipeline.

enable_cache: Optional[bool] property

If caching is enabled for the pipeline.

Returns:

Type Description
Optional[bool]

If caching is enabled for the pipeline.

invocations: Dict[str, StepInvocation] property

Returns the step invocations of this pipeline.

This dictionary will only be populated once the pipeline has been called.

Returns:

Type Description
Dict[str, StepInvocation]

The step invocations.

is_prepared: bool property

If the pipeline is prepared.

Prepared means that the pipeline entrypoint has been called and the pipeline is fully defined.

Returns:

Type Description
bool

If the pipeline is prepared.

missing_parameters: List[str] property

List of missing parameters for the pipeline entrypoint.

Returns:

Type Description
List[str]

List of missing parameters for the pipeline entrypoint.

model: PipelineResponse property

Gets the registered pipeline model for this instance.

Returns:

Type Description
PipelineResponse

The registered pipeline model.

Raises:

Type Description
RuntimeError

If the pipeline has not been registered yet.

name: str property

The name of the pipeline.

Returns:

Type Description
str

The name of the pipeline.

required_parameters: List[str] property

List of required parameters for the pipeline entrypoint.

Returns:

Type Description
List[str]

List of required parameters for the pipeline entrypoint.

source_code: str property

The source code of this pipeline.

Returns:

Type Description
str

The source code of this pipeline.

source_object: Any property

The source object of this pipeline.

Returns:

Type Description
Any

The source object of this pipeline.

Functions
add_step_invocation(step: BaseStep, input_artifacts: Dict[str, StepArtifact], external_artifacts: Dict[str, Union[ExternalArtifact, ArtifactVersionResponse]], model_artifacts_or_metadata: Dict[str, ModelVersionDataLazyLoader], client_lazy_loaders: Dict[str, ClientLazyLoader], parameters: Dict[str, Any], default_parameters: Dict[str, Any], upstream_steps: Set[str], custom_id: Optional[str] = None, allow_id_suffix: bool = True) -> str

Adds a step invocation to the pipeline.

Parameters:

Name Type Description Default
step BaseStep

The step for which to add an invocation.

required
input_artifacts Dict[str, StepArtifact]

The input artifacts for the invocation.

required
external_artifacts Dict[str, Union[ExternalArtifact, ArtifactVersionResponse]]

The external artifacts for the invocation.

required
model_artifacts_or_metadata Dict[str, ModelVersionDataLazyLoader]

The model artifacts or metadata for the invocation.

required
client_lazy_loaders Dict[str, ClientLazyLoader]

The client lazy loaders for the invocation.

required
parameters Dict[str, Any]

The parameters for the invocation.

required
default_parameters Dict[str, Any]

The default parameters for the invocation.

required
upstream_steps Set[str]

The upstream steps for the invocation.

required
custom_id Optional[str]

Custom ID to use for the invocation.

None
allow_id_suffix bool

Whether a suffix can be appended to the invocation ID.

True

Raises:

Type Description
RuntimeError

If the method is called on an inactive pipeline.

RuntimeError

If the invocation was called with an artifact from a different pipeline.

Returns:

Type Description
str

The step invocation ID.

Source code in src/zenml/pipelines/pipeline_definition.py
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
def add_step_invocation(
    self,
    step: "BaseStep",
    input_artifacts: Dict[str, StepArtifact],
    external_artifacts: Dict[
        str, Union["ExternalArtifact", "ArtifactVersionResponse"]
    ],
    model_artifacts_or_metadata: Dict[str, "ModelVersionDataLazyLoader"],
    client_lazy_loaders: Dict[str, "ClientLazyLoader"],
    parameters: Dict[str, Any],
    default_parameters: Dict[str, Any],
    upstream_steps: Set[str],
    custom_id: Optional[str] = None,
    allow_id_suffix: bool = True,
) -> str:
    """Adds a step invocation to the pipeline.

    Args:
        step: The step for which to add an invocation.
        input_artifacts: The input artifacts for the invocation.
        external_artifacts: The external artifacts for the invocation.
        model_artifacts_or_metadata: The model artifacts or metadata for
            the invocation.
        client_lazy_loaders: The client lazy loaders for the invocation.
        parameters: The parameters for the invocation.
        default_parameters: The default parameters for the invocation.
        upstream_steps: The upstream steps for the invocation.
        custom_id: Custom ID to use for the invocation.
        allow_id_suffix: Whether a suffix can be appended to the invocation
            ID.

    Raises:
        RuntimeError: If the method is called on an inactive pipeline.
        RuntimeError: If the invocation was called with an artifact from
            a different pipeline.

    Returns:
        The step invocation ID.
    """
    if Pipeline.ACTIVE_PIPELINE != self:
        raise RuntimeError(
            "A step invocation can only be added to an active pipeline."
        )

    for artifact in input_artifacts.values():
        if artifact.pipeline is not self:
            raise RuntimeError(
                "Got invalid input artifact for invocation of step "
                f"{step.name}: The input artifact was produced by a step "
                f"inside a different pipeline {artifact.pipeline.name}."
            )

    invocation_id = self._compute_invocation_id(
        step=step, custom_id=custom_id, allow_suffix=allow_id_suffix
    )
    invocation = StepInvocation(
        id=invocation_id,
        step=step,
        input_artifacts=input_artifacts,
        external_artifacts=external_artifacts,
        model_artifacts_or_metadata=model_artifacts_or_metadata,
        client_lazy_loaders=client_lazy_loaders,
        parameters=parameters,
        default_parameters=default_parameters,
        upstream_steps=upstream_steps,
        pipeline=self,
    )
    self._invocations[invocation_id] = invocation
    return invocation_id
build(settings: Optional[Mapping[str, SettingsOrDict]] = None, step_configurations: Optional[Mapping[str, StepConfigurationUpdateOrDict]] = None, config_path: Optional[str] = None) -> Optional[PipelineBuildResponse]

Builds Docker images for the pipeline.

Parameters:

Name Type Description Default
settings Optional[Mapping[str, SettingsOrDict]]

Settings for the pipeline.

None
step_configurations Optional[Mapping[str, StepConfigurationUpdateOrDict]]

Configurations for steps of the pipeline.

None
config_path Optional[str]

Path to a yaml configuration file. This file will be parsed as a zenml.config.pipeline_configurations.PipelineRunConfiguration object. Options provided in this file will be overwritten by options provided in code using the other arguments of this method.

None

Returns:

Type Description
Optional[PipelineBuildResponse]

The build output.

Source code in src/zenml/pipelines/pipeline_definition.py
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
def build(
    self,
    settings: Optional[Mapping[str, "SettingsOrDict"]] = None,
    step_configurations: Optional[
        Mapping[str, "StepConfigurationUpdateOrDict"]
    ] = None,
    config_path: Optional[str] = None,
) -> Optional["PipelineBuildResponse"]:
    """Builds Docker images for the pipeline.

    Args:
        settings: Settings for the pipeline.
        step_configurations: Configurations for steps of the pipeline.
        config_path: Path to a yaml configuration file. This file will
            be parsed as a
            `zenml.config.pipeline_configurations.PipelineRunConfiguration`
            object. Options provided in this file will be overwritten by
            options provided in code using the other arguments of this
            method.

    Returns:
        The build output.
    """
    with track_handler(event=AnalyticsEvent.BUILD_PIPELINE):
        self._prepare_if_possible()

        compile_args = self._run_args.copy()
        compile_args.pop("unlisted", None)
        compile_args.pop("prevent_build_reuse", None)
        if config_path:
            compile_args["config_path"] = config_path
        if step_configurations:
            compile_args["step_configurations"] = step_configurations
        if settings:
            compile_args["settings"] = settings

        deployment, _, _ = self._compile(**compile_args)
        pipeline_id = self._register().id

        local_repo = code_repository_utils.find_active_code_repository()
        code_repository = build_utils.verify_local_repository_context(
            deployment=deployment, local_repo_context=local_repo
        )

        return build_utils.create_pipeline_build(
            deployment=deployment,
            pipeline_id=pipeline_id,
            code_repository=code_repository,
        )
configure(enable_cache: Optional[bool] = None, enable_artifact_metadata: Optional[bool] = None, enable_artifact_visualization: Optional[bool] = None, enable_step_logs: Optional[bool] = None, enable_pipeline_logs: Optional[bool] = None, settings: Optional[Mapping[str, SettingsOrDict]] = None, tags: Optional[List[Union[str, Tag]]] = None, extra: Optional[Dict[str, Any]] = None, on_failure: Optional[HookSpecification] = None, on_success: Optional[HookSpecification] = None, model: Optional[Model] = None, parameters: Optional[Dict[str, Any]] = None, merge: bool = True, substitutions: Optional[Dict[str, str]] = None) -> Self

Configures the pipeline.

Configuration merging example: * merge==True: pipeline.configure(extra={"key1": 1}) pipeline.configure(extra={"key2": 2}, merge=True) pipeline.configuration.extra # {"key1": 1, "key2": 2} * merge==False: pipeline.configure(extra={"key1": 1}) pipeline.configure(extra={"key2": 2}, merge=False) pipeline.configuration.extra # {"key2": 2}

Parameters:

Name Type Description Default
enable_cache Optional[bool]

If caching should be enabled for this pipeline.

None
enable_artifact_metadata Optional[bool]

If artifact metadata should be enabled for this pipeline.

None
enable_artifact_visualization Optional[bool]

If artifact visualization should be enabled for this pipeline.

None
enable_step_logs Optional[bool]

If step logs should be enabled for this pipeline.

None
enable_pipeline_logs Optional[bool]

If pipeline logs should be enabled for this pipeline.

None
settings Optional[Mapping[str, SettingsOrDict]]

settings for this pipeline.

None
tags Optional[List[Union[str, Tag]]]

Tags to apply to runs of this pipeline.

None
extra Optional[Dict[str, Any]]

Extra configurations for this pipeline.

None
on_failure Optional[HookSpecification]

Callback function in event of failure of the step. Can be a function with a single argument of type BaseException, or a source path to such a function (e.g. module.my_function).

None
on_success Optional[HookSpecification]

Callback function in event of success of the step. Can be a function with no arguments, or a source path to such a function (e.g. module.my_function).

None
merge bool

If True, will merge the given dictionary configurations like extra and settings with existing configurations. If False the given configurations will overwrite all existing ones. See the general description of this method for an example.

True
model Optional[Model]

configuration of the model version in the Model Control Plane.

None
parameters Optional[Dict[str, Any]]

input parameters for the pipeline.

None
substitutions Optional[Dict[str, str]]

Extra placeholders to use in the name templates.

None

Returns:

Type Description
Self

The pipeline instance that this method was called on.

Source code in src/zenml/pipelines/pipeline_definition.py
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
def configure(
    self,
    enable_cache: Optional[bool] = None,
    enable_artifact_metadata: Optional[bool] = None,
    enable_artifact_visualization: Optional[bool] = None,
    enable_step_logs: Optional[bool] = None,
    enable_pipeline_logs: Optional[bool] = None,
    settings: Optional[Mapping[str, "SettingsOrDict"]] = None,
    tags: Optional[List[Union[str, "Tag"]]] = None,
    extra: Optional[Dict[str, Any]] = None,
    on_failure: Optional["HookSpecification"] = None,
    on_success: Optional["HookSpecification"] = None,
    model: Optional["Model"] = None,
    parameters: Optional[Dict[str, Any]] = None,
    merge: bool = True,
    substitutions: Optional[Dict[str, str]] = None,
) -> Self:
    """Configures the pipeline.

    Configuration merging example:
    * `merge==True`:
        pipeline.configure(extra={"key1": 1})
        pipeline.configure(extra={"key2": 2}, merge=True)
        pipeline.configuration.extra # {"key1": 1, "key2": 2}
    * `merge==False`:
        pipeline.configure(extra={"key1": 1})
        pipeline.configure(extra={"key2": 2}, merge=False)
        pipeline.configuration.extra # {"key2": 2}

    Args:
        enable_cache: If caching should be enabled for this pipeline.
        enable_artifact_metadata: If artifact metadata should be enabled for
            this pipeline.
        enable_artifact_visualization: If artifact visualization should be
            enabled for this pipeline.
        enable_step_logs: If step logs should be enabled for this pipeline.
        enable_pipeline_logs: If pipeline logs should be enabled for this pipeline.
        settings: settings for this pipeline.
        tags: Tags to apply to runs of this pipeline.
        extra: Extra configurations for this pipeline.
        on_failure: Callback function in event of failure of the step. Can
            be a function with a single argument of type `BaseException`, or
            a source path to such a function (e.g. `module.my_function`).
        on_success: Callback function in event of success of the step. Can
            be a function with no arguments, or a source path to such a
            function (e.g. `module.my_function`).
        merge: If `True`, will merge the given dictionary configurations
            like `extra` and `settings` with existing
            configurations. If `False` the given configurations will
            overwrite all existing ones. See the general description of this
            method for an example.
        model: configuration of the model version in the Model Control Plane.
        parameters: input parameters for the pipeline.
        substitutions: Extra placeholders to use in the name templates.

    Returns:
        The pipeline instance that this method was called on.
    """
    failure_hook_source = None
    if on_failure:
        # string of on_failure hook function to be used for this pipeline
        failure_hook_source = resolve_and_validate_hook(on_failure)

    success_hook_source = None
    if on_success:
        # string of on_success hook function to be used for this pipeline
        success_hook_source = resolve_and_validate_hook(on_success)

    if merge and tags and self._configuration.tags:
        # Merge tags explicitly here as the recursive update later only
        # merges dicts
        tags = self._configuration.tags + tags

    values = dict_utils.remove_none_values(
        {
            "enable_cache": enable_cache,
            "enable_artifact_metadata": enable_artifact_metadata,
            "enable_artifact_visualization": enable_artifact_visualization,
            "enable_step_logs": enable_step_logs,
            "enable_pipeline_logs": enable_pipeline_logs,
            "settings": settings,
            "tags": tags,
            "extra": extra,
            "failure_hook_source": failure_hook_source,
            "success_hook_source": success_hook_source,
            "model": model,
            "parameters": parameters,
            "substitutions": substitutions,
        }
    )
    if not self.__suppress_warnings_flag__:
        to_be_reapplied = []
        for param_, value_ in values.items():
            if (
                param_ in PipelineRunConfiguration.model_fields
                and param_ in self._from_config_file
                and value_ != self._from_config_file[param_]
            ):
                to_be_reapplied.append(
                    (param_, self._from_config_file[param_], value_)
                )
        if to_be_reapplied:
            msg = ""
            reapply_during_run_warning = (
                "The value of parameter '{name}' has changed from "
                "'{file_value}' to '{new_value}' set in your configuration "
                "file.\n"
            )
            for name, file_value, new_value in to_be_reapplied:
                msg += reapply_during_run_warning.format(
                    name=name, file_value=file_value, new_value=new_value
                )
            msg += (
                "Configuration file value will be used during pipeline "
                "run, so you change will not be efficient. Consider "
                "updating your configuration file instead."
            )
            logger.warning(msg)

    config = PipelineConfigurationUpdate(**values)
    self._apply_configuration(config, merge=merge)
    return self
copy() -> Pipeline

Copies the pipeline.

Returns:

Type Description
Pipeline

The pipeline copy.

Source code in src/zenml/pipelines/pipeline_definition.py
1433
1434
1435
1436
1437
1438
1439
def copy(self) -> "Pipeline":
    """Copies the pipeline.

    Returns:
        The pipeline copy.
    """
    return copy.deepcopy(self)
create_run_template(name: str, **kwargs: Any) -> RunTemplateResponse

Create a run template for the pipeline.

Parameters:

Name Type Description Default
name str

The name of the run template.

required
**kwargs Any

Keyword arguments for the client method to create a run template.

{}

Returns:

Type Description
RunTemplateResponse

The created run template.

Source code in src/zenml/pipelines/pipeline_definition.py
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
def create_run_template(
    self, name: str, **kwargs: Any
) -> RunTemplateResponse:
    """Create a run template for the pipeline.

    Args:
        name: The name of the run template.
        **kwargs: Keyword arguments for the client method to create a run
            template.

    Returns:
        The created run template.
    """
    self._prepare_if_possible()
    deployment = self._create_deployment(
        **self._run_args, skip_schedule_registration=True
    )

    return Client().create_run_template(
        name=name, deployment_id=deployment.id, **kwargs
    )
log_pipeline_deployment_metadata(deployment_model: PipelineDeploymentResponse) -> None staticmethod

Displays logs based on the deployment model upon running a pipeline.

Parameters:

Name Type Description Default
deployment_model PipelineDeploymentResponse

The model for the pipeline deployment

required
Source code in src/zenml/pipelines/pipeline_definition.py
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
@staticmethod
def log_pipeline_deployment_metadata(
    deployment_model: PipelineDeploymentResponse,
) -> None:
    """Displays logs based on the deployment model upon running a pipeline.

    Args:
        deployment_model: The model for the pipeline deployment
    """
    try:
        # Log about the caching status
        if deployment_model.pipeline_configuration.enable_cache is False:
            logger.info(
                f"Caching is disabled by default for "
                f"`{deployment_model.pipeline_configuration.name}`."
            )

        # Log about the used builds
        if deployment_model.build:
            logger.info("Using a build:")
            logger.info(
                " Image(s): "
                f"{', '.join([i.image for i in deployment_model.build.images.values()])}"
            )

            # Log about version mismatches between local and build
            from zenml import __version__

            if deployment_model.build.zenml_version != __version__:
                logger.info(
                    f"ZenML version (different than the local version): "
                    f"{deployment_model.build.zenml_version}"
                )

            import platform

            if (
                deployment_model.build.python_version
                != platform.python_version()
            ):
                logger.info(
                    f"Python version (different than the local version): "
                    f"{deployment_model.build.python_version}"
                )

        # Log about the user, stack and components
        if deployment_model.user is not None:
            logger.info(f"Using user: `{deployment_model.user.name}`")

        if deployment_model.stack is not None:
            logger.info(f"Using stack: `{deployment_model.stack.name}`")

            for (
                component_type,
                component_models,
            ) in deployment_model.stack.components.items():
                logger.info(
                    f"  {component_type.value}: `{component_models[0].name}`"
                )
    except Exception as e:
        logger.debug(f"Logging pipeline deployment metadata failed: {e}")
prepare(*args: Any, **kwargs: Any) -> None

Prepares the pipeline.

Parameters:

Name Type Description Default
*args Any

Pipeline entrypoint input arguments.

()
**kwargs Any

Pipeline entrypoint input keyword arguments.

{}

Raises:

Type Description
RuntimeError

If the pipeline has parameters configured differently in configuration file and code.

Source code in src/zenml/pipelines/pipeline_definition.py
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
    def prepare(self, *args: Any, **kwargs: Any) -> None:
        """Prepares the pipeline.

        Args:
            *args: Pipeline entrypoint input arguments.
            **kwargs: Pipeline entrypoint input keyword arguments.

        Raises:
            RuntimeError: If the pipeline has parameters configured differently in
                configuration file and code.
        """
        # Clear existing parameters and invocations
        self._parameters = {}
        self._invocations = {}

        conflicting_parameters = {}
        parameters_ = (self.configuration.parameters or {}).copy()
        if from_file_ := self._from_config_file.get("parameters", None):
            parameters_ = dict_utils.recursive_update(parameters_, from_file_)
        if parameters_:
            for k, v_runtime in kwargs.items():
                if k in parameters_:
                    v_config = parameters_[k]
                    if v_config != v_runtime:
                        conflicting_parameters[k] = (v_config, v_runtime)
            if conflicting_parameters:
                is_plural = "s" if len(conflicting_parameters) > 1 else ""
                msg = f"Configured parameter{is_plural} for the pipeline `{self.name}` conflict{'' if not is_plural else 's'} with parameter{is_plural} passed in runtime:\n"
                for key, values in conflicting_parameters.items():
                    msg += f"`{key}`: config=`{values[0]}` | runtime=`{values[1]}`\n"
                msg += """This happens, if you define values for pipeline parameters in configuration file and pass same parameters from the code. Example:
```
# config.yaml
    parameters:
        param_name: value1


# pipeline.py
@pipeline
def pipeline_(param_name: str):
    step_name()

if __name__=="__main__":
    pipeline_.with_options(config_path="config.yaml")(param_name="value2")
```
To avoid this consider setting pipeline parameters only in one place (config or code).
"""
                raise RuntimeError(msg)
            for k, v_config in parameters_.items():
                if k not in kwargs:
                    kwargs[k] = v_config

        with self:
            # Enter the context manager, so we become the active pipeline. This
            # means that all steps that get called while the entrypoint function
            # is executed will be added as invocation to this pipeline instance.
            self._call_entrypoint(*args, **kwargs)
register() -> PipelineResponse

Register the pipeline in the server.

Returns:

Type Description
PipelineResponse

The registered pipeline model.

Source code in src/zenml/pipelines/pipeline_definition.py
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
def register(self) -> "PipelineResponse":
    """Register the pipeline in the server.

    Returns:
        The registered pipeline model.
    """
    # Activating the built-in integrations to load all materializers
    from zenml.integrations.registry import integration_registry

    self._prepare_if_possible()
    integration_registry.activate_integrations()

    if self.configuration.model_dump(
        exclude_defaults=True, exclude={"name"}
    ):
        logger.warning(
            f"The pipeline `{self.name}` that you're registering has "
            "custom configurations applied to it. These will not be "
            "registered with the pipeline and won't be set when you build "
            "images or run the pipeline from the CLI. To provide these "
            "configurations, use the `--config` option of the `zenml "
            "pipeline build/run` commands."
        )

    return self._register()
resolve() -> Source

Resolves the pipeline.

Returns:

Type Description
Source

The pipeline source.

Source code in src/zenml/pipelines/pipeline_definition.py
237
238
239
240
241
242
243
def resolve(self) -> "Source":
    """Resolves the pipeline.

    Returns:
        The pipeline source.
    """
    return source_utils.resolve(self.entrypoint, skip_validation=True)
with_options(run_name: Optional[str] = None, schedule: Optional[Schedule] = None, build: Union[str, UUID, PipelineBuildBase, None] = None, step_configurations: Optional[Mapping[str, StepConfigurationUpdateOrDict]] = None, steps: Optional[Mapping[str, StepConfigurationUpdateOrDict]] = None, config_path: Optional[str] = None, unlisted: bool = False, prevent_build_reuse: bool = False, **kwargs: Any) -> Pipeline

Copies the pipeline and applies the given configurations.

Parameters:

Name Type Description Default
run_name Optional[str]

Name of the pipeline run.

None
schedule Optional[Schedule]

Optional schedule to use for the run.

None
build Union[str, UUID, PipelineBuildBase, None]

Optional build to use for the run.

None
step_configurations Optional[Mapping[str, StepConfigurationUpdateOrDict]]

Configurations for steps of the pipeline.

None
steps Optional[Mapping[str, StepConfigurationUpdateOrDict]]

Configurations for steps of the pipeline. This is equivalent to step_configurations, and will be ignored if step_configurations is set as well.

None
config_path Optional[str]

Path to a yaml configuration file. This file will be parsed as a zenml.config.pipeline_configurations.PipelineRunConfiguration object. Options provided in this file will be overwritten by options provided in code using the other arguments of this method.

None
unlisted bool

Whether the pipeline run should be unlisted (not assigned to any pipeline).

False
prevent_build_reuse bool

DEPRECATED: Use DockerSettings.prevent_build_reuse instead.

False
**kwargs Any

Pipeline configuration options. These will be passed to the pipeline.configure(...) method.

{}

Returns:

Type Description
Pipeline

The copied pipeline instance.

Source code in src/zenml/pipelines/pipeline_definition.py
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
def with_options(
    self,
    run_name: Optional[str] = None,
    schedule: Optional[Schedule] = None,
    build: Union[str, "UUID", "PipelineBuildBase", None] = None,
    step_configurations: Optional[
        Mapping[str, "StepConfigurationUpdateOrDict"]
    ] = None,
    steps: Optional[Mapping[str, "StepConfigurationUpdateOrDict"]] = None,
    config_path: Optional[str] = None,
    unlisted: bool = False,
    prevent_build_reuse: bool = False,
    **kwargs: Any,
) -> "Pipeline":
    """Copies the pipeline and applies the given configurations.

    Args:
        run_name: Name of the pipeline run.
        schedule: Optional schedule to use for the run.
        build: Optional build to use for the run.
        step_configurations: Configurations for steps of the pipeline.
        steps: Configurations for steps of the pipeline. This is equivalent
            to `step_configurations`, and will be ignored if
            `step_configurations` is set as well.
        config_path: Path to a yaml configuration file. This file will
            be parsed as a
            `zenml.config.pipeline_configurations.PipelineRunConfiguration`
            object. Options provided in this file will be overwritten by
            options provided in code using the other arguments of this
            method.
        unlisted: Whether the pipeline run should be unlisted (not assigned
            to any pipeline).
        prevent_build_reuse: DEPRECATED: Use
            `DockerSettings.prevent_build_reuse` instead.
        **kwargs: Pipeline configuration options. These will be passed
            to the `pipeline.configure(...)` method.

    Returns:
        The copied pipeline instance.
    """
    if steps and step_configurations:
        logger.warning(
            "Step configurations were passed using both the "
            "`step_configurations` and `steps` keywords, ignoring the "
            "values passed using the `steps` keyword."
        )

    pipeline_copy = self.copy()

    pipeline_copy._reconfigure_from_file_with_overrides(
        config_path=config_path, **kwargs
    )

    run_args = dict_utils.remove_none_values(
        {
            "run_name": run_name,
            "schedule": schedule,
            "build": build,
            "step_configurations": step_configurations or steps,
            "config_path": config_path,
            "unlisted": unlisted,
            "prevent_build_reuse": prevent_build_reuse,
        }
    )
    pipeline_copy._run_args.update(run_args)
    return pipeline_copy
write_run_configuration_template(path: str, stack: Optional[Stack] = None) -> None

Writes a run configuration yaml template.

Parameters:

Name Type Description Default
path str

The path where the template will be written.

required
stack Optional[Stack]

The stack for which the template should be generated. If not given, the active stack will be used.

None
Source code in src/zenml/pipelines/pipeline_definition.py
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
def write_run_configuration_template(
    self, path: str, stack: Optional["Stack"] = None
) -> None:
    """Writes a run configuration yaml template.

    Args:
        path: The path where the template will be written.
        stack: The stack for which the template should be generated. If
            not given, the active stack will be used.
    """
    from zenml.config.base_settings import ConfigurationLevel
    from zenml.config.step_configurations import (
        PartialArtifactConfiguration,
    )

    self._prepare_if_possible()

    stack = stack or Client().active_stack

    setting_classes = stack.setting_classes
    setting_classes.update(settings_utils.get_general_settings())

    pipeline_settings = {}
    step_settings = {}
    for key, setting_class in setting_classes.items():
        fields = pydantic_utils.TemplateGenerator(setting_class).run()
        if ConfigurationLevel.PIPELINE in setting_class.LEVEL:
            pipeline_settings[key] = fields
        if ConfigurationLevel.STEP in setting_class.LEVEL:
            step_settings[key] = fields

    steps = {}
    for step_name, invocation in self.invocations.items():
        step = invocation.step
        outputs = {
            name: PartialArtifactConfiguration()
            for name in step.entrypoint_definition.outputs
        }
        step_template = StepConfigurationUpdate(
            parameters={},
            settings=step_settings,
            outputs=outputs,
        )
        steps[step_name] = step_template

    run_config = PipelineRunConfiguration(
        settings=pipeline_settings, steps=steps
    )
    template = pydantic_utils.TemplateGenerator(run_config).run()
    yaml_string = yaml.dump(template)
    yaml_string = yaml_utils.comment_out_yaml(yaml_string)

    with open(path, "w") as f:
        f.write(yaml_string)

PipelineBuildBase

Bases: BaseZenModel

Base model for pipeline builds.

Attributes
requires_code_download: bool property

Whether the build requires code download.

Returns:

Type Description
bool

Whether the build requires code download.

Functions
get_image(component_key: str, step: Optional[str] = None) -> str

Get the image built for a specific key.

Parameters:

Name Type Description Default
component_key str

The key for which to get the image.

required
step Optional[str]

The pipeline step for which to get the image. If no image exists for this step, will fall back to the pipeline image for the same key.

None

Returns:

Type Description
str

The image name or digest.

Source code in src/zenml/models/v2/core/pipeline_build.py
107
108
109
110
111
112
113
114
115
116
117
118
119
def get_image(self, component_key: str, step: Optional[str] = None) -> str:
    """Get the image built for a specific key.

    Args:
        component_key: The key for which to get the image.
        step: The pipeline step for which to get the image. If no image
            exists for this step, will fall back to the pipeline image for
            the same key.

    Returns:
        The image name or digest.
    """
    return self._get_item(component_key=component_key, step=step).image
get_image_key(component_key: str, step: Optional[str] = None) -> str staticmethod

Get the image key.

Parameters:

Name Type Description Default
component_key str

The component key.

required
step Optional[str]

The pipeline step for which the image was built.

None

Returns:

Type Description
str

The image key.

Source code in src/zenml/models/v2/core/pipeline_build.py
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
@staticmethod
def get_image_key(component_key: str, step: Optional[str] = None) -> str:
    """Get the image key.

    Args:
        component_key: The component key.
        step: The pipeline step for which the image was built.

    Returns:
        The image key.
    """
    if step:
        return f"{step}.{component_key}"
    else:
        return component_key
get_settings_checksum(component_key: str, step: Optional[str] = None) -> Optional[str]

Get the settings checksum for a specific key.

Parameters:

Name Type Description Default
component_key str

The key for which to get the checksum.

required
step Optional[str]

The pipeline step for which to get the checksum. If no image exists for this step, will fall back to the pipeline image for the same key.

None

Returns:

Type Description
Optional[str]

The settings checksum.

Source code in src/zenml/models/v2/core/pipeline_build.py
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
def get_settings_checksum(
    self, component_key: str, step: Optional[str] = None
) -> Optional[str]:
    """Get the settings checksum for a specific key.

    Args:
        component_key: The key for which to get the checksum.
        step: The pipeline step for which to get the checksum. If no
            image exists for this step, will fall back to the pipeline image
            for the same key.

    Returns:
        The settings checksum.
    """
    return self._get_item(
        component_key=component_key, step=step
    ).settings_checksum

PipelineBuildFilter

Bases: ProjectScopedFilter

Model to enable advanced filtering of all pipeline builds.

Functions
get_custom_filters(table: Type[AnySchema]) -> List[ColumnElement[bool]]

Get custom filters.

Parameters:

Name Type Description Default
table Type[AnySchema]

The query table.

required

Returns:

Type Description
List[ColumnElement[bool]]

A list of custom filters.

Source code in src/zenml/models/v2/core/pipeline_build.py
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
def get_custom_filters(
    self,
    table: Type["AnySchema"],
) -> List["ColumnElement[bool]"]:
    """Get custom filters.

    Args:
        table: The query table.

    Returns:
        A list of custom filters.
    """
    custom_filters = super().get_custom_filters(table)

    from sqlmodel import and_

    from zenml.enums import StackComponentType
    from zenml.zen_stores.schemas import (
        PipelineBuildSchema,
        StackComponentSchema,
        StackCompositionSchema,
        StackSchema,
    )

    if self.container_registry_id:
        container_registry_filter = and_(
            PipelineBuildSchema.stack_id == StackSchema.id,
            StackSchema.id == StackCompositionSchema.stack_id,
            StackCompositionSchema.component_id == StackComponentSchema.id,
            StackComponentSchema.type
            == StackComponentType.CONTAINER_REGISTRY.value,
            StackComponentSchema.id == self.container_registry_id,
        )
        custom_filters.append(container_registry_filter)

    return custom_filters

PipelineFilter

Bases: ProjectScopedFilter, TaggableFilter

Pipeline filter model.

Functions
apply_filter(query: AnyQuery, table: Type[AnySchema]) -> AnyQuery

Applies the filter to a query.

Parameters:

Name Type Description Default
query AnyQuery

The query to which to apply the filter.

required
table Type[AnySchema]

The query table.

required

Returns:

Type Description
AnyQuery

The query with filter applied.

Source code in src/zenml/models/v2/core/pipeline.py
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
def apply_filter(
    self, query: AnyQuery, table: Type["AnySchema"]
) -> AnyQuery:
    """Applies the filter to a query.

    Args:
        query: The query to which to apply the filter.
        table: The query table.

    Returns:
        The query with filter applied.
    """
    query = super().apply_filter(query, table)

    from sqlmodel import and_, col, func, select

    from zenml.zen_stores.schemas import PipelineRunSchema, PipelineSchema

    if self.latest_run_status:
        latest_pipeline_run_subquery = (
            select(
                PipelineRunSchema.pipeline_id,
                func.max(PipelineRunSchema.created).label("created"),
            )
            .where(col(PipelineRunSchema.pipeline_id).is_not(None))
            .group_by(col(PipelineRunSchema.pipeline_id))
            .subquery()
        )

        query = (
            query.join(
                PipelineRunSchema,
                PipelineSchema.id == PipelineRunSchema.pipeline_id,
            )
            .join(
                latest_pipeline_run_subquery,
                and_(
                    PipelineRunSchema.pipeline_id
                    == latest_pipeline_run_subquery.c.pipeline_id,
                    PipelineRunSchema.created
                    == latest_pipeline_run_subquery.c.created,
                ),
            )
            .where(
                self.generate_custom_query_conditions_for_column(
                    value=self.latest_run_status,
                    table=PipelineRunSchema,
                    column="status",
                )
            )
        )

    return query
apply_sorting(query: AnyQuery, table: Type[AnySchema]) -> AnyQuery

Apply sorting to the query.

Parameters:

Name Type Description Default
query AnyQuery

The query to which to apply the sorting.

required
table Type[AnySchema]

The query table.

required

Returns:

Type Description
AnyQuery

The query with sorting applied.

Source code in src/zenml/models/v2/core/pipeline.py
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
def apply_sorting(
    self,
    query: AnyQuery,
    table: Type["AnySchema"],
) -> AnyQuery:
    """Apply sorting to the query.

    Args:
        query: The query to which to apply the sorting.
        table: The query table.

    Returns:
        The query with sorting applied.
    """
    from sqlmodel import asc, case, col, desc, func, select

    from zenml.enums import SorterOps
    from zenml.zen_stores.schemas import PipelineRunSchema, PipelineSchema

    sort_by, operand = self.sorting_params

    if sort_by == SORT_PIPELINES_BY_LATEST_RUN_KEY:
        # Subquery to find the latest run per pipeline
        latest_run_subquery = (
            select(
                PipelineSchema.id,
                case(
                    (
                        func.max(PipelineRunSchema.created).is_(None),
                        PipelineSchema.created,
                    ),
                    else_=func.max(PipelineRunSchema.created),
                ).label("latest_run"),
            )
            .outerjoin(
                PipelineRunSchema,
                PipelineSchema.id == PipelineRunSchema.pipeline_id,  # type: ignore[arg-type]
            )
            .group_by(col(PipelineSchema.id))
            .subquery()
        )

        query = query.add_columns(
            latest_run_subquery.c.latest_run,
        ).where(PipelineSchema.id == latest_run_subquery.c.id)

        if operand == SorterOps.ASCENDING:
            query = query.order_by(
                asc(latest_run_subquery.c.latest_run),
                asc(PipelineSchema.id),
            )
        else:
            query = query.order_by(
                desc(latest_run_subquery.c.latest_run),
                desc(PipelineSchema.id),
            )
        return query
    else:
        return super().apply_sorting(query=query, table=table)

PipelineRunFilter

Bases: ProjectScopedFilter, TaggableFilter, RunMetadataFilterMixin

Model to enable advanced filtering of all pipeline runs.

Functions
apply_sorting(query: AnyQuery, table: Type[AnySchema]) -> AnyQuery

Apply sorting to the query.

Parameters:

Name Type Description Default
query AnyQuery

The query to which to apply the sorting.

required
table Type[AnySchema]

The query table.

required

Returns:

Type Description
AnyQuery

The query with sorting applied.

Source code in src/zenml/models/v2/core/pipeline_run.py
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
def apply_sorting(
    self,
    query: AnyQuery,
    table: Type["AnySchema"],
) -> AnyQuery:
    """Apply sorting to the query.

    Args:
        query: The query to which to apply the sorting.
        table: The query table.

    Returns:
        The query with sorting applied.
    """
    from sqlmodel import asc, desc

    from zenml.enums import SorterOps
    from zenml.zen_stores.schemas import (
        ModelSchema,
        ModelVersionSchema,
        PipelineDeploymentSchema,
        PipelineRunSchema,
        PipelineSchema,
        StackSchema,
    )

    sort_by, operand = self.sorting_params

    if sort_by == "pipeline":
        query = query.outerjoin(
            PipelineSchema,
            PipelineRunSchema.pipeline_id == PipelineSchema.id,
        )
        column = PipelineSchema.name
    elif sort_by == "stack":
        query = query.outerjoin(
            PipelineDeploymentSchema,
            PipelineRunSchema.deployment_id == PipelineDeploymentSchema.id,
        ).outerjoin(
            StackSchema,
            PipelineDeploymentSchema.stack_id == StackSchema.id,
        )
        column = StackSchema.name
    elif sort_by == "model":
        query = query.outerjoin(
            ModelVersionSchema,
            PipelineRunSchema.model_version_id == ModelVersionSchema.id,
        ).outerjoin(
            ModelSchema,
            ModelVersionSchema.model_id == ModelSchema.id,
        )
        column = ModelSchema.name
    elif sort_by == "model_version":
        query = query.outerjoin(
            ModelVersionSchema,
            PipelineRunSchema.model_version_id == ModelVersionSchema.id,
        )
        column = ModelVersionSchema.name
    else:
        return super().apply_sorting(query=query, table=table)

    query = query.add_columns(column)

    if operand == SorterOps.ASCENDING:
        query = query.order_by(asc(column))
    else:
        query = query.order_by(desc(column))

    return query
get_custom_filters(table: Type[AnySchema]) -> List[ColumnElement[bool]]

Get custom filters.

Parameters:

Name Type Description Default
table Type[AnySchema]

The query table.

required

Returns:

Type Description
List[ColumnElement[bool]]

A list of custom filters.

Source code in src/zenml/models/v2/core/pipeline_run.py
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
def get_custom_filters(
    self,
    table: Type["AnySchema"],
) -> List["ColumnElement[bool]"]:
    """Get custom filters.

    Args:
        table: The query table.

    Returns:
        A list of custom filters.
    """
    custom_filters = super().get_custom_filters(table)

    from sqlmodel import and_, col, or_

    from zenml.zen_stores.schemas import (
        CodeReferenceSchema,
        CodeRepositorySchema,
        ModelSchema,
        ModelVersionSchema,
        PipelineBuildSchema,
        PipelineDeploymentSchema,
        PipelineRunSchema,
        PipelineSchema,
        ScheduleSchema,
        StackComponentSchema,
        StackCompositionSchema,
        StackSchema,
    )

    if self.unlisted is not None:
        if self.unlisted is True:
            unlisted_filter = PipelineRunSchema.pipeline_id.is_(None)  # type: ignore[union-attr]
        else:
            unlisted_filter = PipelineRunSchema.pipeline_id.is_not(None)  # type: ignore[union-attr]
        custom_filters.append(unlisted_filter)

    if self.code_repository_id:
        code_repo_filter = and_(
            PipelineRunSchema.deployment_id == PipelineDeploymentSchema.id,
            PipelineDeploymentSchema.code_reference_id
            == CodeReferenceSchema.id,
            CodeReferenceSchema.code_repository_id
            == self.code_repository_id,
        )
        custom_filters.append(code_repo_filter)

    if self.stack_id:
        stack_filter = and_(
            PipelineRunSchema.deployment_id == PipelineDeploymentSchema.id,
            PipelineDeploymentSchema.stack_id == StackSchema.id,
            StackSchema.id == self.stack_id,
        )
        custom_filters.append(stack_filter)

    if self.schedule_id:
        schedule_filter = and_(
            PipelineRunSchema.deployment_id == PipelineDeploymentSchema.id,
            PipelineDeploymentSchema.schedule_id == ScheduleSchema.id,
            ScheduleSchema.id == self.schedule_id,
        )
        custom_filters.append(schedule_filter)

    if self.build_id:
        pipeline_build_filter = and_(
            PipelineRunSchema.deployment_id == PipelineDeploymentSchema.id,
            PipelineDeploymentSchema.build_id == PipelineBuildSchema.id,
            PipelineBuildSchema.id == self.build_id,
        )
        custom_filters.append(pipeline_build_filter)

    if self.template_id:
        run_template_filter = and_(
            PipelineRunSchema.deployment_id == PipelineDeploymentSchema.id,
            PipelineDeploymentSchema.template_id == self.template_id,
        )
        custom_filters.append(run_template_filter)

    if self.pipeline:
        pipeline_filter = and_(
            PipelineRunSchema.pipeline_id == PipelineSchema.id,
            self.generate_name_or_id_query_conditions(
                value=self.pipeline, table=PipelineSchema
            ),
        )
        custom_filters.append(pipeline_filter)

    if self.stack:
        stack_filter = and_(
            PipelineRunSchema.deployment_id == PipelineDeploymentSchema.id,
            PipelineDeploymentSchema.stack_id == StackSchema.id,
            self.generate_name_or_id_query_conditions(
                value=self.stack,
                table=StackSchema,
            ),
        )
        custom_filters.append(stack_filter)

    if self.code_repository:
        code_repo_filter = and_(
            PipelineRunSchema.deployment_id == PipelineDeploymentSchema.id,
            PipelineDeploymentSchema.code_reference_id
            == CodeReferenceSchema.id,
            CodeReferenceSchema.code_repository_id
            == CodeRepositorySchema.id,
            self.generate_name_or_id_query_conditions(
                value=self.code_repository,
                table=CodeRepositorySchema,
            ),
        )
        custom_filters.append(code_repo_filter)

    if self.model:
        model_filter = and_(
            PipelineRunSchema.model_version_id == ModelVersionSchema.id,
            ModelVersionSchema.model_id == ModelSchema.id,
            self.generate_name_or_id_query_conditions(
                value=self.model, table=ModelSchema
            ),
        )
        custom_filters.append(model_filter)

    if self.stack_component:
        component_filter = and_(
            PipelineRunSchema.deployment_id == PipelineDeploymentSchema.id,
            PipelineDeploymentSchema.stack_id == StackSchema.id,
            StackSchema.id == StackCompositionSchema.stack_id,
            StackCompositionSchema.component_id == StackComponentSchema.id,
            self.generate_name_or_id_query_conditions(
                value=self.stack_component,
                table=StackComponentSchema,
            ),
        )
        custom_filters.append(component_filter)

    if self.pipeline_name:
        pipeline_name_filter = and_(
            PipelineRunSchema.pipeline_id == PipelineSchema.id,
            self.generate_custom_query_conditions_for_column(
                value=self.pipeline_name,
                table=PipelineSchema,
                column="name",
            ),
        )
        custom_filters.append(pipeline_name_filter)

    if self.templatable is not None:
        if self.templatable is True:
            templatable_filter = and_(
                # The following condition is not perfect as it does not
                # consider stacks with custom flavor components or local
                # components, but the best we can do currently with our
                # table columns.
                PipelineRunSchema.deployment_id
                == PipelineDeploymentSchema.id,
                PipelineDeploymentSchema.build_id
                == PipelineBuildSchema.id,
                col(PipelineBuildSchema.is_local).is_(False),
                col(PipelineBuildSchema.stack_id).is_not(None),
            )
        else:
            templatable_filter = or_(
                col(PipelineRunSchema.deployment_id).is_(None),
                and_(
                    PipelineRunSchema.deployment_id
                    == PipelineDeploymentSchema.id,
                    col(PipelineDeploymentSchema.build_id).is_(None),
                ),
                and_(
                    PipelineRunSchema.deployment_id
                    == PipelineDeploymentSchema.id,
                    PipelineDeploymentSchema.build_id
                    == PipelineBuildSchema.id,
                    or_(
                        col(PipelineBuildSchema.is_local).is_(True),
                        col(PipelineBuildSchema.stack_id).is_(None),
                    ),
                ),
            )

        custom_filters.append(templatable_filter)

    return custom_filters

ProjectFilter

Bases: BaseFilter

Model to enable advanced filtering of all projects.

ScheduleFilter

Bases: ProjectScopedFilter

Model to enable advanced filtering of all Users.

SecretFilter

Bases: UserScopedFilter

Model to enable advanced secret filtering.

Functions
apply_filter(query: AnyQuery, table: Type[AnySchema]) -> AnyQuery

Applies the filter to a query.

Parameters:

Name Type Description Default
query AnyQuery

The query to which to apply the filter.

required
table Type[AnySchema]

The query table.

required

Returns:

Type Description
AnyQuery

The query with filter applied.

Source code in src/zenml/models/v2/core/secret.py
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
def apply_filter(
    self,
    query: AnyQuery,
    table: Type["AnySchema"],
) -> AnyQuery:
    """Applies the filter to a query.

    Args:
        query: The query to which to apply the filter.
        table: The query table.

    Returns:
        The query with filter applied.
    """
    # The secret user scoping works a bit differently than the other
    # scoped filters. We have to filter out all private secrets that are
    # not owned by the current user.
    if not self.scope_user:
        return super().apply_filter(query=query, table=table)

    scope_user = self.scope_user

    # First we apply the inherited filters without the user scoping
    # applied.
    self.scope_user = None
    query = super().apply_filter(query=query, table=table)
    self.scope_user = scope_user

    # Then we apply the user scoping filter.
    if self.scope_user:
        from sqlmodel import and_, or_

        query = query.where(
            or_(
                and_(
                    getattr(table, "user_id") == self.scope_user,
                    getattr(table, "private") == True,  # noqa: E712
                ),
                getattr(table, "private") == False,  # noqa: E712
            )
        )

    else:
        query = query.where(getattr(table, "private") == False)  # noqa: E712

    return query

SecretResponse

Bases: UserScopedResponse[SecretResponseBody, SecretResponseMetadata, SecretResponseResources]

Response model for secrets.

Attributes
has_missing_values: bool property

Returns True if the secret has missing values (i.e. None).

Values can be missing from a secret for example if the user retrieves a secret but does not have the permission to view the secret values.

Returns:

Type Description
bool

True if the secret has any values set to None.

private: bool property

The private property.

Returns:

Type Description
bool

the value of the property.

secret_values: Dict[str, str] property

A dictionary with all un-obfuscated values stored in this secret.

The values are returned as strings, not SecretStr. If a value is None, it is not included in the returned dictionary. This is to enable the use of None values in the update model to indicate that a secret value should be deleted.

Returns:

Type Description
Dict[str, str]

A dictionary containing the secret's values.

values: Dict[str, Optional[SecretStr]] property

The values property.

Returns:

Type Description
Dict[str, Optional[SecretStr]]

the value of the property.

Functions
add_secret(key: str, value: str) -> None

Adds a secret value to the secret.

Parameters:

Name Type Description Default
key str

The key of the secret value.

required
value str

The secret value.

required
Source code in src/zenml/models/v2/core/secret.py
225
226
227
228
229
230
231
232
def add_secret(self, key: str, value: str) -> None:
    """Adds a secret value to the secret.

    Args:
        key: The key of the secret value.
        value: The secret value.
    """
    self.get_body().values[key] = SecretStr(value)
get_hydrated_version() -> SecretResponse

Get the hydrated version of this secret.

Returns:

Type Description
SecretResponse

an instance of the same entity with the metadata field attached.

Source code in src/zenml/models/v2/core/secret.py
164
165
166
167
168
169
170
171
172
def get_hydrated_version(self) -> "SecretResponse":
    """Get the hydrated version of this secret.

    Returns:
        an instance of the same entity with the metadata field attached.
    """
    from zenml.client import Client

    return Client().zen_store.get_secret(self.id)
remove_secret(key: str) -> None

Removes a secret value from the secret.

Parameters:

Name Type Description Default
key str

The key of the secret value.

required
Source code in src/zenml/models/v2/core/secret.py
234
235
236
237
238
239
240
def remove_secret(self, key: str) -> None:
    """Removes a secret value from the secret.

    Args:
        key: The key of the secret value.
    """
    del self.get_body().values[key]
remove_secrets() -> None

Removes all secret values from the secret but keep the keys.

Source code in src/zenml/models/v2/core/secret.py
242
243
244
def remove_secrets(self) -> None:
    """Removes all secret values from the secret but keep the keys."""
    self.get_body().values = {k: None for k in self.values.keys()}
set_secrets(values: Dict[str, str]) -> None

Sets the secret values of the secret.

Parameters:

Name Type Description Default
values Dict[str, str]

The secret values to set.

required
Source code in src/zenml/models/v2/core/secret.py
246
247
248
249
250
251
252
def set_secrets(self, values: Dict[str, str]) -> None:
    """Sets the secret values of the secret.

    Args:
        values: The secret values to set.
    """
    self.get_body().values = {k: SecretStr(v) for k, v in values.items()}

ServerCredentials

Bases: BaseModel

Cached Server Credentials.

Attributes

Get the hyperlink to the ZenML OpenAPI dashboard for this workspace.

Returns:

Type Description
str

The hyperlink to the ZenML OpenAPI dashboard for this workspace.

auth_status: str property

Get the authentication status.

Returns:

Type Description
str

The authentication status.

Get the hyperlink to the ZenML dashboard for this workspace.

Returns:

Type Description
str

The hyperlink to the ZenML dashboard for this workspace.

dashboard_organization_url: str property

Get the URL to the ZenML Pro dashboard for this workspace's organization.

Returns:

Type Description
str

The URL to the ZenML Pro dashboard for this workspace's organization.

dashboard_url: str property

Get the URL to the ZenML dashboard for this server.

Returns:

Type Description
str

The URL to the ZenML dashboard for this server.

expires_at: str property

Get the expiration time of the token as a string.

Returns:

Type Description
str

The expiration time of the token as a string.

expires_in: str property

Get the time remaining until the token expires.

Returns:

Type Description
str

The time remaining until the token expires.

id: str property

Get the server identifier.

Returns:

Type Description
str

The server identifier.

is_available: bool property

Check if the server is available (running and authenticated).

Returns:

Type Description
bool

True if the server is available, False otherwise.

Get the hyperlink to the ZenML Pro dashboard for this server's organization.

Returns:

Type Description
str

The hyperlink to the ZenML Pro dashboard for this server's

str

organization.

Get the hyperlink to the ZenML Pro dashboard for this workspace's organization using its ID.

Returns:

Type Description
str

The hyperlink to the ZenML Pro dashboard for this workspace's

str

organization using its ID.

Get the hyperlink to the ZenML Pro dashboard for this server's organization using its name.

Returns:

Type Description
str

The hyperlink to the ZenML Pro dashboard for this server's

str

organization using its name.

Get the hyperlink to the ZenML dashboard for this server using its ID.

Returns:

Type Description
str

The hyperlink to the ZenML dashboard for this server using its ID.

Get the hyperlink to the ZenML dashboard for this server using its name.

Returns:

Type Description
str

The hyperlink to the ZenML dashboard for this server using its name.

type: ServerType property

Get the server type.

Returns:

Type Description
ServerType

The server type.

Functions
update_server_info(server_info: Union[ServerModel, WorkspaceRead]) -> None

Update with server information received from the server itself or from a ZenML Pro workspace descriptor.

Parameters:

Name Type Description Default
server_info Union[ServerModel, WorkspaceRead]

The server information to update with.

required
Source code in src/zenml/login/credentials.py
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
def update_server_info(
    self, server_info: Union[ServerModel, WorkspaceRead]
) -> None:
    """Update with server information received from the server itself or from a ZenML Pro workspace descriptor.

    Args:
        server_info: The server information to update with.
    """
    if isinstance(server_info, ServerModel):
        # The server ID doesn't change during the lifetime of the server
        self.server_id = self.server_id or server_info.id
        # All other attributes can change during the lifetime of the server
        self.deployment_type = server_info.deployment_type
        server_name = (
            server_info.pro_workspace_name
            or server_info.metadata.get("workspace_name")
            or server_info.name
        )
        if server_name:
            self.server_name = server_name
        if server_info.pro_organization_id:
            self.organization_id = server_info.pro_organization_id
        if server_info.pro_workspace_id:
            self.server_id = server_info.pro_workspace_id
        if server_info.pro_organization_name:
            self.organization_name = server_info.pro_organization_name
        if server_info.pro_workspace_name:
            self.workspace_name = server_info.pro_workspace_name
        if server_info.pro_api_url:
            self.pro_api_url = server_info.pro_api_url
        if server_info.pro_dashboard_url:
            self.pro_dashboard_url = server_info.pro_dashboard_url
        self.version = server_info.version or self.version
        # The server information was retrieved from the server itself, so we
        # can assume that the server is available
        self.status = "available"
    else:
        self.deployment_type = ServerDeploymentType.CLOUD
        self.server_id = server_info.id
        self.server_name = server_info.name
        self.organization_name = server_info.organization_name
        self.organization_id = server_info.organization_id
        self.workspace_name = server_info.name
        self.workspace_id = server_info.id
        self.status = server_info.status
        self.version = server_info.version

ServerProviderType

Bases: StrEnum

ZenML server providers.

ServerType

Bases: StrEnum

The type of server.

ServiceAccountFilter

Bases: BaseFilter

Model to enable advanced filtering of service accounts.

Functions
apply_filter(query: AnyQuery, table: Type[AnySchema]) -> AnyQuery

Override to filter out user accounts from the query.

Parameters:

Name Type Description Default
query AnyQuery

The query to which to apply the filter.

required
table Type[AnySchema]

The query table.

required

Returns:

Type Description
AnyQuery

The query with filter applied.

Source code in src/zenml/models/v2/core/service_account.py
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
def apply_filter(
    self,
    query: AnyQuery,
    table: Type["AnySchema"],
) -> AnyQuery:
    """Override to filter out user accounts from the query.

    Args:
        query: The query to which to apply the filter.
        table: The query table.

    Returns:
        The query with filter applied.
    """
    query = super().apply_filter(query=query, table=table)
    query = query.where(
        getattr(table, "is_service_account") == True  # noqa: E712
    )

    return query

ServiceConnectorFilter

Bases: UserScopedFilter

Model to enable advanced filtering of service connectors.

Functions
validate_labels() -> ServiceConnectorFilter

Parse the labels string into a label dictionary and vice-versa.

Returns:

Type Description
ServiceConnectorFilter

The validated values.

Source code in src/zenml/models/v2/core/service_connector.py
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
@model_validator(mode="after")
def validate_labels(self) -> "ServiceConnectorFilter":
    """Parse the labels string into a label dictionary and vice-versa.

    Returns:
        The validated values.
    """
    if self.labels_str is not None:
        try:
            self.labels = json.loads(self.labels_str)
        except json.JSONDecodeError:
            # Interpret as comma-separated values instead
            self.labels = {
                label.split("=", 1)[0]: label.split("=", 1)[1]
                if "=" in label
                else None
                for label in self.labels_str.split(",")
            }
    elif self.labels is not None:
        self.labels_str = json.dumps(self.labels)

    return self

ServiceConnectorInfo

Bases: BaseModel

Information about the service connector when creating a full stack.

ServiceConnectorRequest

Bases: UserScopedRequest

Request model for service connectors.

Attributes
emojified_connector_type: str property

Get the emojified connector type.

Returns:

Type Description
str

The emojified connector type.

emojified_resource_types: List[str] property

Get the emojified connector type.

Returns:

Type Description
List[str]

The emojified connector type.

type: str property

Get the connector type.

Returns:

Type Description
str

The connector type.

Functions
get_analytics_metadata() -> Dict[str, Any]

Format the resource types in the analytics metadata.

Returns:

Type Description
Dict[str, Any]

Dict of analytics metadata.

Source code in src/zenml/models/v2/core/service_connector.py
120
121
122
123
124
125
126
127
128
129
130
131
132
def get_analytics_metadata(self) -> Dict[str, Any]:
    """Format the resource types in the analytics metadata.

    Returns:
        Dict of analytics metadata.
    """
    metadata = super().get_analytics_metadata()
    if len(self.resource_types) == 1:
        metadata["resource_types"] = self.resource_types[0]
    else:
        metadata["resource_types"] = ", ".join(self.resource_types)
    metadata["connector_type"] = self.type
    return metadata
validate_and_configure_resources(connector_type: ServiceConnectorTypeModel, resource_types: Optional[Union[str, List[str]]] = None, resource_id: Optional[str] = None, configuration: Optional[Dict[str, Any]] = None, secrets: Optional[Dict[str, Optional[SecretStr]]] = None) -> None

Validate and configure the resources that the connector can be used to access.

Parameters:

Name Type Description Default
connector_type ServiceConnectorTypeModel

The connector type specification used to validate the connector configuration.

required
resource_types Optional[Union[str, List[str]]]

The type(s) of resource that the connector instance can be used to access. If omitted, a multi-type connector is configured.

None
resource_id Optional[str]

Uniquely identifies a specific resource instance that the connector instance can be used to access.

None
configuration Optional[Dict[str, Any]]

The connector configuration.

None
secrets Optional[Dict[str, Optional[SecretStr]]]

The connector secrets.

None
Source code in src/zenml/models/v2/core/service_connector.py
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
def validate_and_configure_resources(
    self,
    connector_type: "ServiceConnectorTypeModel",
    resource_types: Optional[Union[str, List[str]]] = None,
    resource_id: Optional[str] = None,
    configuration: Optional[Dict[str, Any]] = None,
    secrets: Optional[Dict[str, Optional[SecretStr]]] = None,
) -> None:
    """Validate and configure the resources that the connector can be used to access.

    Args:
        connector_type: The connector type specification used to validate
            the connector configuration.
        resource_types: The type(s) of resource that the connector instance
            can be used to access. If omitted, a multi-type connector is
            configured.
        resource_id: Uniquely identifies a specific resource instance that
            the connector instance can be used to access.
        configuration: The connector configuration.
        secrets: The connector secrets.
    """
    _validate_and_configure_resources(
        connector=self,
        connector_type=connector_type,
        resource_types=resource_types,
        resource_id=resource_id,
        configuration=configuration,
        secrets=secrets,
    )

ServiceConnectorResourcesInfo

Bases: BaseModel

Information about the service connector resources needed for CLI and UI.

ServiceConnectorResourcesModel

Bases: BaseModel

Service connector resources list.

Lists the resource types and resource instances that a service connector can provide access to.

Attributes
emojified_connector_type: str property

Get the emojified connector type.

Returns:

Type Description
str

The emojified connector type.

resource_types: List[str] property

Get the resource types.

Returns:

Type Description
List[str]

The resource types.

resources_dict: Dict[str, ServiceConnectorTypedResourcesModel] property

Get the resources as a dictionary indexed by resource type.

Returns:

Type Description
Dict[str, ServiceConnectorTypedResourcesModel]

The resources as a dictionary indexed by resource type.

type: str property

Get the connector type.

Returns:

Type Description
str

The connector type.

Functions
from_connector_model(connector_model: ServiceConnectorResponse, resource_type: Optional[str] = None) -> ServiceConnectorResourcesModel classmethod

Initialize a resource model from a connector model.

Parameters:

Name Type Description Default
connector_model ServiceConnectorResponse

The connector model.

required
resource_type Optional[str]

The resource type to set on the resource model. If omitted, the resource type is set according to the connector model.

None

Returns:

Type Description
ServiceConnectorResourcesModel

A resource list model instance.

Source code in src/zenml/models/v2/misc/service_connector_type.py
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
@classmethod
def from_connector_model(
    cls,
    connector_model: "ServiceConnectorResponse",
    resource_type: Optional[str] = None,
) -> "ServiceConnectorResourcesModel":
    """Initialize a resource model from a connector model.

    Args:
        connector_model: The connector model.
        resource_type: The resource type to set on the resource model. If
            omitted, the resource type is set according to the connector
            model.

    Returns:
        A resource list model instance.
    """
    resources = cls(
        id=connector_model.id,
        name=connector_model.name,
        connector_type=connector_model.type,
    )

    resource_types = resource_type or connector_model.resource_types
    for resource_type in resource_types:
        resources.resources.append(
            ServiceConnectorTypedResourcesModel(
                resource_type=resource_type,
                resource_ids=[connector_model.resource_id]
                if connector_model.resource_id
                else None,
            )
        )

    return resources
get_default_resource_id() -> Optional[str]

Get the default resource ID, if included in the resource list.

The default resource ID is a resource ID supplied by the connector implementation only for resource types that do not support multiple instances.

Returns:

Type Description
Optional[str]

The default resource ID, or None if no resource ID is set.

Source code in src/zenml/models/v2/misc/service_connector_type.py
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
def get_default_resource_id(self) -> Optional[str]:
    """Get the default resource ID, if included in the resource list.

    The default resource ID is a resource ID supplied by the connector
    implementation only for resource types that do not support multiple
    instances.

    Returns:
        The default resource ID, or None if no resource ID is set.
    """
    if len(self.resources) != 1:
        # multi-type connectors do not have a default resource ID
        return None

    if isinstance(self.connector_type, str):
        # can't determine default resource ID for unknown connector types
        return None

    resource_type_spec = self.connector_type.resource_type_dict[
        self.resources[0].resource_type
    ]
    if resource_type_spec.supports_instances:
        # resource types that support multiple instances do not have a
        # default resource ID
        return None

    resource_ids = self.resources[0].resource_ids

    if not resource_ids or len(resource_ids) != 1:
        return None

    return resource_ids[0]
get_emojified_resource_types(resource_type: Optional[str] = None) -> List[str]

Get the emojified resource type.

Parameters:

Name Type Description Default
resource_type Optional[str]

The resource type to get the emojified resource type for. If omitted, the emojified resource type for all resource types is returned.

None

Returns:

Type Description
List[str]

The list of emojified resource types.

Source code in src/zenml/models/v2/misc/service_connector_type.py
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
def get_emojified_resource_types(
    self, resource_type: Optional[str] = None
) -> List[str]:
    """Get the emojified resource type.

    Args:
        resource_type: The resource type to get the emojified resource type
            for. If omitted, the emojified resource type for all resource
            types is returned.


    Returns:
        The list of emojified resource types.
    """
    if not isinstance(self.connector_type, str):
        if resource_type:
            return [
                self.connector_type.resource_type_dict[
                    resource_type
                ].emojified_resource_type
            ]
        return [
            self.connector_type.resource_type_dict[
                resource_type
            ].emojified_resource_type
            for resource_type in self.resources_dict.keys()
        ]
    if resource_type:
        return [resource_type]
    return list(self.resources_dict.keys())
set_error(error: str, resource_type: Optional[str] = None) -> None

Set a global error message or an error for a single resource type.

Parameters:

Name Type Description Default
error str

The error message.

required
resource_type Optional[str]

The resource type to set the error message for. If omitted, or if there is only one resource type involved, the error message is (also) set globally.

None

Raises:

Type Description
KeyError

If the resource type is not found in the resources list.

Source code in src/zenml/models/v2/misc/service_connector_type.py
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
def set_error(
    self, error: str, resource_type: Optional[str] = None
) -> None:
    """Set a global error message or an error for a single resource type.

    Args:
        error: The error message.
        resource_type: The resource type to set the error message for. If
            omitted, or if there is only one resource type involved, the
            error message is (also) set globally.

    Raises:
        KeyError: If the resource type is not found in the resources list.
    """
    if resource_type:
        resource = self.resources_dict.get(resource_type)
        if not resource:
            raise KeyError(
                f"resource type '{resource_type}' not found in "
                "service connector resources list"
            )
        resource.error = error
        resource.resource_ids = None
        if len(self.resources) == 1:
            # If there is only one resource type involved, set the global
            # error message as well.
            self.error = error
    else:
        self.error = error
        for resource in self.resources:
            resource.error = error
            resource.resource_ids = None
set_resource_ids(resource_type: str, resource_ids: List[str]) -> None

Set the resource IDs for a resource type.

Parameters:

Name Type Description Default
resource_type str

The resource type to set the resource IDs for.

required
resource_ids List[str]

The resource IDs to set.

required

Raises:

Type Description
KeyError

If the resource type is not found in the resources list.

Source code in src/zenml/models/v2/misc/service_connector_type.py
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
def set_resource_ids(
    self, resource_type: str, resource_ids: List[str]
) -> None:
    """Set the resource IDs for a resource type.

    Args:
        resource_type: The resource type to set the resource IDs for.
        resource_ids: The resource IDs to set.

    Raises:
        KeyError: If the resource type is not found in the resources list.
    """
    resource = self.resources_dict.get(resource_type)
    if not resource:
        raise KeyError(
            f"resource type '{resource_type}' not found in "
            "service connector resources list"
        )
    resource.resource_ids = resource_ids
    resource.error = None

ServiceConnectorResponse

Bases: UserScopedResponse[ServiceConnectorResponseBody, ServiceConnectorResponseMetadata, ServiceConnectorResponseResources]

Response model for service connectors.

Attributes
auth_method: str property

The auth_method property.

Returns:

Type Description
str

the value of the property.

configuration: Dict[str, Any] property

The configuration property.

Returns:

Type Description
Dict[str, Any]

the value of the property.

connector_type: Union[str, ServiceConnectorTypeModel] property

The connector_type property.

Returns:

Type Description
Union[str, ServiceConnectorTypeModel]

the value of the property.

description: str property

The description property.

Returns:

Type Description
str

the value of the property.

emojified_connector_type: str property

Get the emojified connector type.

Returns:

Type Description
str

The emojified connector type.

emojified_resource_types: List[str] property

Get the emojified connector type.

Returns:

Type Description
List[str]

The emojified connector type.

expiration_seconds: Optional[int] property

The expiration_seconds property.

Returns:

Type Description
Optional[int]

the value of the property.

expires_at: Optional[datetime] property

The expires_at property.

Returns:

Type Description
Optional[datetime]

the value of the property.

expires_skew_tolerance: Optional[int] property

The expires_skew_tolerance property.

Returns:

Type Description
Optional[int]

the value of the property.

full_configuration: Dict[str, str] property

Get the full connector configuration, including secrets.

Returns:

Type Description
Dict[str, str]

The full connector configuration, including secrets.

is_multi_instance: bool property

Checks if the connector is multi-instance.

A multi-instance connector is configured to access multiple instances of the configured resource type.

Returns:

Type Description
bool

True if the connector is multi-instance, False otherwise.

is_multi_type: bool property

Checks if the connector is multi-type.

A multi-type connector can be used to access multiple types of resources.

Returns:

Type Description
bool

True if the connector is multi-type, False otherwise.

is_single_instance: bool property

Checks if the connector is single-instance.

A single-instance connector is configured to access only a single instance of the configured resource type or does not support multiple resource instances.

Returns:

Type Description
bool

True if the connector is single-instance, False otherwise.

labels: Dict[str, str] property

The labels property.

Returns:

Type Description
Dict[str, str]

the value of the property.

resource_id: Optional[str] property

The resource_id property.

Returns:

Type Description
Optional[str]

the value of the property.

resource_types: List[str] property

The resource_types property.

Returns:

Type Description
List[str]

the value of the property.

secret_id: Optional[UUID] property

The secret_id property.

Returns:

Type Description
Optional[UUID]

the value of the property.

secrets: Dict[str, Optional[SecretStr]] property

The secrets property.

Returns:

Type Description
Dict[str, Optional[SecretStr]]

the value of the property.

supports_instances: bool property

The supports_instances property.

Returns:

Type Description
bool

the value of the property.

type: str property

Get the connector type.

Returns:

Type Description
str

The connector type.

Functions
get_analytics_metadata() -> Dict[str, Any]

Add the service connector labels to analytics metadata.

Returns:

Type Description
Dict[str, Any]

Dict of analytics metadata.

Source code in src/zenml/models/v2/core/service_connector.py
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
def get_analytics_metadata(self) -> Dict[str, Any]:
    """Add the service connector labels to analytics metadata.

    Returns:
        Dict of analytics metadata.
    """
    metadata = super().get_analytics_metadata()

    metadata.update(
        {
            label[6:]: value
            for label, value in self.labels.items()
            if label.startswith("zenml:")
        }
    )
    return metadata
get_hydrated_version() -> ServiceConnectorResponse

Get the hydrated version of this service connector.

Returns:

Type Description
ServiceConnectorResponse

an instance of the same entity with the metadata field attached.

Source code in src/zenml/models/v2/core/service_connector.py
515
516
517
518
519
520
521
522
523
def get_hydrated_version(self) -> "ServiceConnectorResponse":
    """Get the hydrated version of this service connector.

    Returns:
        an instance of the same entity with the metadata field attached.
    """
    from zenml.client import Client

    return Client().zen_store.get_service_connector(self.id)
set_connector_type(value: Union[str, ServiceConnectorTypeModel]) -> None

Auxiliary method to set the connector type.

Parameters:

Name Type Description Default
value Union[str, ServiceConnectorTypeModel]

the new value for the connector type.

required
Source code in src/zenml/models/v2/core/service_connector.py
620
621
622
623
624
625
626
627
628
def set_connector_type(
    self, value: Union[str, "ServiceConnectorTypeModel"]
) -> None:
    """Auxiliary method to set the connector type.

    Args:
        value: the new value for the connector type.
    """
    self.get_body().connector_type = value
validate_and_configure_resources(connector_type: ServiceConnectorTypeModel, resource_types: Optional[Union[str, List[str]]] = None, resource_id: Optional[str] = None, configuration: Optional[Dict[str, Any]] = None, secrets: Optional[Dict[str, Optional[SecretStr]]] = None) -> None

Validate and configure the resources that the connector can be used to access.

Parameters:

Name Type Description Default
connector_type ServiceConnectorTypeModel

The connector type specification used to validate the connector configuration.

required
resource_types Optional[Union[str, List[str]]]

The type(s) of resource that the connector instance can be used to access. If omitted, a multi-type connector is configured.

None
resource_id Optional[str]

Uniquely identifies a specific resource instance that the connector instance can be used to access.

None
configuration Optional[Dict[str, Any]]

The connector configuration.

None
secrets Optional[Dict[str, Optional[SecretStr]]]

The connector secrets.

None
Source code in src/zenml/models/v2/core/service_connector.py
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
def validate_and_configure_resources(
    self,
    connector_type: "ServiceConnectorTypeModel",
    resource_types: Optional[Union[str, List[str]]] = None,
    resource_id: Optional[str] = None,
    configuration: Optional[Dict[str, Any]] = None,
    secrets: Optional[Dict[str, Optional[SecretStr]]] = None,
) -> None:
    """Validate and configure the resources that the connector can be used to access.

    Args:
        connector_type: The connector type specification used to validate
            the connector configuration.
        resource_types: The type(s) of resource that the connector instance
            can be used to access. If omitted, a multi-type connector is
            configured.
        resource_id: Uniquely identifies a specific resource instance that
            the connector instance can be used to access.
        configuration: The connector configuration.
        secrets: The connector secrets.
    """
    _validate_and_configure_resources(
        connector=self,
        connector_type=connector_type,
        resource_types=resource_types,
        resource_id=resource_id,
        configuration=configuration,
        secrets=secrets,
    )

ServiceState

Bases: StrEnum

Possible states for the service and service endpoint.

Source

Bases: BaseModel

Source specification.

A source specifies a module name as well as an optional attribute of that module. These values can be used to import the module and get the value of the attribute inside the module.

Example

The source Source(module="zenml.config.source", attribute="Source") references the class that this docstring is describing. This class is defined in the zenml.config.source module and the name of the attribute is the class name Source.

Attributes:

Name Type Description
module str

The module name.

attribute Optional[str]

Optional name of the attribute inside the module.

type SourceType

The type of the source.

Attributes
import_path: str property

The import path of the source.

Returns:

Type Description
str

The import path of the source.

is_internal: bool property

If the source is internal (=from the zenml package).

Returns:

Type Description
bool

True if the source is internal, False otherwise

is_module_source: bool property

If the source is a module source.

Returns:

Type Description
bool

If the source is a module source.

Functions
from_import_path(import_path: str, is_module_path: bool = False) -> Source classmethod

Creates a source from an import path.

Parameters:

Name Type Description Default
import_path str

The import path.

required
is_module_path bool

If the import path points to a module or not.

False

Raises:

Type Description
ValueError

If the import path is empty.

Returns:

Type Description
Source

The source.

Source code in src/zenml/config/source.py
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
@classmethod
def from_import_path(
    cls, import_path: str, is_module_path: bool = False
) -> "Source":
    """Creates a source from an import path.

    Args:
        import_path: The import path.
        is_module_path: If the import path points to a module or not.

    Raises:
        ValueError: If the import path is empty.

    Returns:
        The source.
    """
    if not import_path:
        raise ValueError(
            "Invalid empty import path. The import path needs to refer "
            "to a Python module and an optional attribute of that module."
        )

    # Remove internal version pins for backwards compatibility
    if "@" in import_path:
        import_path = import_path.split("@", 1)[0]

    if is_module_path or "." not in import_path:
        module = import_path
        attribute = None
    else:
        module, attribute = import_path.rsplit(".", maxsplit=1)

    return Source(
        module=module, attribute=attribute, type=SourceType.UNKNOWN
    )
model_dump(**kwargs: Any) -> Dict[str, Any]

Dump the source as a dictionary.

Parameters:

Name Type Description Default
**kwargs Any

Additional keyword arguments.

{}

Returns:

Type Description
Dict[str, Any]

The source as a dictionary.

Source code in src/zenml/config/source.py
143
144
145
146
147
148
149
150
151
152
def model_dump(self, **kwargs: Any) -> Dict[str, Any]:
    """Dump the source as a dictionary.

    Args:
        **kwargs: Additional keyword arguments.

    Returns:
        The source as a dictionary.
    """
    return super().model_dump(serialize_as_any=True, **kwargs)
model_dump_json(**kwargs: Any) -> str

Dump the source as a JSON string.

Parameters:

Name Type Description Default
**kwargs Any

Additional keyword arguments.

{}

Returns:

Type Description
str

The source as a JSON string.

Source code in src/zenml/config/source.py
154
155
156
157
158
159
160
161
162
163
def model_dump_json(self, **kwargs: Any) -> str:
    """Dump the source as a JSON string.

    Args:
        **kwargs: Additional keyword arguments.

    Returns:
        The source as a JSON string.
    """
    return super().model_dump_json(serialize_as_any=True, **kwargs)

StackComponentType

Bases: StrEnum

All possible types a StackComponent can have.

Attributes
plural: str property

Returns the plural of the enum value.

Returns:

Type Description
str

The plural of the enum value.

StackDeploymentProvider

Bases: StrEnum

All possible stack deployment providers.

StackFilter

Bases: UserScopedFilter

Model to enable advanced stack filtering.

Functions
get_custom_filters(table: Type[AnySchema]) -> List[ColumnElement[bool]]

Get custom filters.

Parameters:

Name Type Description Default
table Type[AnySchema]

The query table.

required

Returns:

Type Description
List[ColumnElement[bool]]

A list of custom filters.

Source code in src/zenml/models/v2/core/stack.py
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
def get_custom_filters(
    self, table: Type["AnySchema"]
) -> List["ColumnElement[bool]"]:
    """Get custom filters.

    Args:
        table: The query table.

    Returns:
        A list of custom filters.
    """
    custom_filters = super().get_custom_filters(table)

    from zenml.zen_stores.schemas import (
        StackComponentSchema,
        StackCompositionSchema,
        StackSchema,
    )

    if self.component_id:
        component_id_filter = and_(
            StackCompositionSchema.stack_id == StackSchema.id,
            StackCompositionSchema.component_id == self.component_id,
        )
        custom_filters.append(component_id_filter)

    if self.component:
        component_filter = and_(
            StackCompositionSchema.stack_id == StackSchema.id,
            StackCompositionSchema.component_id == StackComponentSchema.id,
            self.generate_name_or_id_query_conditions(
                value=self.component,
                table=StackComponentSchema,
            ),
        )
        custom_filters.append(component_filter)

    return custom_filters

StackRequest

Bases: UserScopedRequest

Request model for stack creation.

Attributes
is_valid: bool property

Check if the stack is valid.

Returns:

Type Description
bool

True if the stack is valid, False otherwise.

StoreType

Bases: StrEnum

Zen Store Backend Types.

TagFilter

Bases: UserScopedFilter

Model to enable advanced filtering of all tags.

Functions
get_custom_filters(table: Type[AnySchema]) -> List[ColumnElement[bool]]

Get custom filters.

Parameters:

Name Type Description Default
table Type[AnySchema]

The query table.

required

Returns:

Type Description
List[ColumnElement[bool]]

A list of custom filters.

Source code in src/zenml/models/v2/core/tag.py
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
def get_custom_filters(
    self, table: Type["AnySchema"]
) -> List["ColumnElement[bool]"]:
    """Get custom filters.

    Args:
        table: The query table.

    Returns:
        A list of custom filters.
    """
    custom_filters = super().get_custom_filters(table)

    from sqlmodel import exists, select

    from zenml.zen_stores.schemas import (
        TagResourceSchema,
        TagSchema,
    )

    if self.resource_type:
        # Filter for tags that have at least one association with the specified resource type
        resource_type_filter = exists(
            select(TagResourceSchema).where(
                TagResourceSchema.tag_id == TagSchema.id,
                TagResourceSchema.resource_type
                == self.resource_type.value,
            )
        )
        custom_filters.append(resource_type_filter)

    return custom_filters

UserFilter

Bases: BaseFilter

Model to enable advanced filtering of all Users.

Functions
apply_filter(query: AnyQuery, table: Type[AnySchema]) -> AnyQuery

Override to filter out service accounts from the query.

Parameters:

Name Type Description Default
query AnyQuery

The query to which to apply the filter.

required
table Type[AnySchema]

The query table.

required

Returns:

Type Description
AnyQuery

The query with filter applied.

Source code in src/zenml/models/v2/core/user.py
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
def apply_filter(
    self,
    query: AnyQuery,
    table: Type["AnySchema"],
) -> AnyQuery:
    """Override to filter out service accounts from the query.

    Args:
        query: The query to which to apply the filter.
        table: The query table.

    Returns:
        The query with filter applied.
    """
    query = super().apply_filter(query=query, table=table)
    query = query.where(
        getattr(table, "is_service_account") != True  # noqa: E712
    )

    return query

ZenKeyError(message: str)

Bases: KeyError

Specialized key error which allows error messages with line breaks.

Initialization.

Parameters:

Name Type Description Default
message str

str, the error message

required
Source code in src/zenml/exceptions.py
148
149
150
151
152
153
154
def __init__(self, message: str) -> None:
    """Initialization.

    Args:
        message:str, the error message
    """
    self.message = message
Functions

ZenMLProjectTemplateLocation

Bases: BaseModel

A ZenML project template location.

Attributes
copier_github_url: str property

Get the GitHub URL for the copier.

Returns:

Type Description
str

A GitHub URL in copier format.

track_handler(event: AnalyticsEvent, metadata: Optional[Dict[str, Any]] = None)

Bases: object

Context handler to enable tracking the success status of an event.

Initialization of the context manager.

Parameters:

Name Type Description Default
event AnalyticsEvent

The type of the analytics event

required
metadata Optional[Dict[str, Any]]

The metadata of the event.

None
Source code in src/zenml/analytics/utils.py
207
208
209
210
211
212
213
214
215
216
217
218
219
def __init__(
    self,
    event: AnalyticsEvent,
    metadata: Optional[Dict[str, Any]] = None,
):
    """Initialization of the context manager.

    Args:
        event: The type of the analytics event
        metadata: The metadata of the event.
    """
    self.event: AnalyticsEvent = event
    self.metadata: Dict[str, Any] = metadata or {}
Functions

Functions

analytics() -> None

Analytics for opt-in and opt-out.

Source code in src/zenml/cli/config.py
27
28
29
@cli.group(cls=TagGroup, tag=CliCategories.MANAGEMENT_TOOLS)
def analytics() -> None:
    """Analytics for opt-in and opt-out."""

api_key(ctx: click.Context, service_account_name_or_id: str) -> None

List and manage the API keys associated with a service account.

Parameters:

Name Type Description Default
ctx Context

The click context.

required
service_account_name_or_id str

The name or ID of the service account.

required
Source code in src/zenml/cli/service_accounts.py
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
@service_account.group(
    cls=TagGroup,
    help="Commands for interacting with API keys.",
)
@click.pass_context
@click.argument("service_account_name_or_id", type=str, required=True)
def api_key(
    ctx: click.Context,
    service_account_name_or_id: str,
) -> None:
    """List and manage the API keys associated with a service account.

    Args:
        ctx: The click context.
        service_account_name_or_id: The name or ID of the service account.
    """
    ctx.obj = service_account_name_or_id

artifact() -> None

Commands for interacting with artifacts.

Source code in src/zenml/cli/artifact.py
33
34
35
@cli.group(cls=TagGroup, tag=CliCategories.MANAGEMENT_TOOLS)
def artifact() -> None:
    """Commands for interacting with artifacts."""

authorized_device() -> None

Interact with authorized devices.

Source code in src/zenml/cli/authorized_device.py
32
33
34
@cli.group(cls=TagGroup, tag=CliCategories.MANAGEMENT_TOOLS)
def authorized_device() -> None:
    """Interact with authorized devices."""

backup_database(strategy: Optional[str] = None, location: Optional[str] = None, overwrite: bool = False) -> None

Backup the ZenML database.

Parameters:

Name Type Description Default
strategy Optional[str]

Custom backup strategy to use. Defaults to whatever is configured in the store config.

None
location Optional[str]

Custom location to store the backup. Defaults to whatever is configured in the store config. Depending on the strategy, this can be a local path or a database name.

None
overwrite bool

Whether to overwrite the existing backup.

False
Source code in src/zenml/cli/base.py
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
@cli.command("backup-database", help="Create a database backup.", hidden=True)
@click.option(
    "--strategy",
    "-s",
    help="Custom backup strategy to use. Defaults to whatever is configured "
    "in the store config.",
    type=click.Choice(choices=DatabaseBackupStrategy.values()),
    required=False,
    default=None,
)
@click.option(
    "--location",
    default=None,
    help="Custom location to store the backup. Defaults to whatever is "
    "configured in the store config. Depending on the strategy, this can be "
    "a local path or a database name.",
    type=str,
)
@click.option(
    "--overwrite",
    "-o",
    is_flag=True,
    default=False,
    help="Overwrite the existing backup.",
    type=bool,
)
def backup_database(
    strategy: Optional[str] = None,
    location: Optional[str] = None,
    overwrite: bool = False,
) -> None:
    """Backup the ZenML database.

    Args:
        strategy: Custom backup strategy to use. Defaults to whatever is
            configured in the store config.
        location: Custom location to store the backup. Defaults to whatever is
            configured in the store config. Depending on the strategy, this can
            be a local path or a database name.
        overwrite: Whether to overwrite the existing backup.
    """
    from zenml.zen_stores.base_zen_store import BaseZenStore
    from zenml.zen_stores.sql_zen_store import SqlZenStore

    store_config = GlobalConfiguration().store_configuration
    if store_config.type == StoreType.SQL:
        store = BaseZenStore.create_store(
            store_config, skip_default_registrations=True, skip_migrations=True
        )
        assert isinstance(store, SqlZenStore)
        msg, location = store.backup_database(
            strategy=DatabaseBackupStrategy(strategy) if strategy else None,
            location=location,
            overwrite=overwrite,
        )
        cli_utils.declare(f"Database was backed up to {msg}.")
    else:
        cli_utils.warning(
            "Cannot backup database while connected to a ZenML server."
        )

backup_secrets(ignore_errors: bool = True, delete_secrets: bool = False) -> None

Backup all secrets to the backup secrets store.

Parameters:

Name Type Description Default
ignore_errors bool

Whether to ignore individual errors when backing up secrets and continue with the backup operation until all secrets have been backed up.

True
delete_secrets bool

Whether to delete the secrets that have been successfully backed up from the primary secrets store. Setting this flag effectively moves all secrets from the primary secrets store to the backup secrets store.

False
Source code in src/zenml/cli/secret.py
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
@secret.command(
    "backup", help="Backup all secrets to the backup secrets store."
)
@click.option(
    "--ignore-errors",
    "-i",
    type=click.BOOL,
    default=True,
    help="Whether to ignore individual errors when backing up secrets and "
    "continue with the backup operation until all secrets have been backed up.",
)
@click.option(
    "--delete-secrets",
    "-d",
    is_flag=True,
    default=False,
    help="Whether to delete the secrets that have been successfully backed up "
    "from the primary secrets store. Setting this flag effectively moves all "
    "secrets from the primary secrets store to the backup secrets store.",
)
def backup_secrets(
    ignore_errors: bool = True, delete_secrets: bool = False
) -> None:
    """Backup all secrets to the backup secrets store.

    Args:
        ignore_errors: Whether to ignore individual errors when backing up
            secrets and continue with the backup operation until all secrets
            have been backed up.
        delete_secrets: Whether to delete the secrets that have been
            successfully backed up from the primary secrets store. Setting
            this flag effectively moves all secrets from the primary secrets
            store to the backup secrets store.
    """
    client = Client()

    with console.status("Backing up secrets..."):
        try:
            client.backup_secrets(
                ignore_errors=ignore_errors, delete_secrets=delete_secrets
            )
            declare("Secrets successfully backed up.")
        except NotImplementedError as e:
            error(f"Could not backup secrets: {str(e)}")

build_pipeline(source: str, config_path: Optional[str] = None, stack_name_or_id: Optional[str] = None, output_path: Optional[str] = None) -> None

Build Docker images for a pipeline.

Parameters:

Name Type Description Default
source str

Importable source resolving to a pipeline instance.

required
config_path Optional[str]

Path to pipeline configuration file.

None
stack_name_or_id Optional[str]

Name or ID of the stack for which the images should be built.

None
output_path Optional[str]

Optional file path to write the output to.

None
Source code in src/zenml/cli/pipeline.py
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
@pipeline.command(
    "build",
    help="Build Docker images for a pipeline. The SOURCE argument needs to be "
    " an importable source path resolving to a ZenML pipeline instance, e.g. "
    "`my_module.my_pipeline_instance`.",
)
@click.argument("source")
@click.option(
    "--config",
    "-c",
    "config_path",
    type=click.Path(exists=True, dir_okay=False),
    required=False,
    help="Path to configuration file for the build.",
)
@click.option(
    "--stack",
    "-s",
    "stack_name_or_id",
    type=str,
    required=False,
    help="Name or ID of the stack to use for the build.",
)
@click.option(
    "--output",
    "-o",
    "output_path",
    type=click.Path(exists=False, dir_okay=False),
    required=False,
    help="Output path for the build information.",
)
def build_pipeline(
    source: str,
    config_path: Optional[str] = None,
    stack_name_or_id: Optional[str] = None,
    output_path: Optional[str] = None,
) -> None:
    """Build Docker images for a pipeline.

    Args:
        source: Importable source resolving to a pipeline instance.
        config_path: Path to pipeline configuration file.
        stack_name_or_id: Name or ID of the stack for which the images should
            be built.
        output_path: Optional file path to write the output to.
    """
    if not Client().root:
        cli_utils.warning(
            "You're running the `zenml pipeline build` command without a "
            "ZenML repository. Your current working directory will be used "
            "as the source root relative to which the registered step classes "
            "will be resolved. To silence this warning, run `zenml init` at "
            "your source code root."
        )

    with cli_utils.temporary_active_stack(stack_name_or_id=stack_name_or_id):
        pipeline_instance = _import_pipeline(source=source)

        pipeline_instance = pipeline_instance.with_options(
            config_path=config_path
        )
        build = pipeline_instance.build()

    if build:
        cli_utils.declare(f"Created pipeline build `{build.id}`.")

        if output_path:
            cli_utils.declare(
                f"Writing pipeline build output to `{output_path}`."
            )
            write_yaml(output_path, build.to_yaml())
    else:
        cli_utils.declare("No docker builds required.")

builds() -> None

Commands for pipeline builds.

Source code in src/zenml/cli/pipeline.py
573
574
575
@pipeline.group()
def builds() -> None:
    """Commands for pipeline builds."""

change_user_password(password: Optional[str] = None, old_password: Optional[str] = None) -> None

Change the password of the current user.

Parameters:

Name Type Description Default
password Optional[str]

The new password for the current user.

None
old_password Optional[str]

The old password for the current user.

None
Source code in src/zenml/cli/user_management.py
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
@user.command(
    "change-password",
    help="Change the password for the current user account.",
)
@click.option(
    "--password",
    help=(
        "The new user password. If omitted, a prompt will be shown to enter "
        "the password."
    ),
    required=False,
    type=str,
)
@click.option(
    "--old-password",
    help=(
        "The old user password. If omitted, a prompt will be shown to enter "
        "the old password."
    ),
    required=False,
    type=str,
)
def change_user_password(
    password: Optional[str] = None, old_password: Optional[str] = None
) -> None:
    """Change the password of the current user.

    Args:
        password: The new password for the current user.
        old_password: The old password for the current user.
    """
    active_user = Client().active_user

    if old_password is not None or password is not None:
        cli_utils.warning(
            "Supplying password values in the command line is not safe. "
            "Please consider using the prompt option."
        )

    if old_password is None:
        old_password = click.prompt(
            f"Current password for user {active_user.name}",
            hide_input=True,
        )
    if password is None:
        password = click.prompt(
            f"New password for user {active_user.name}",
            hide_input=True,
        )
        password_again = click.prompt(
            f"Please re-enter the new password for user {active_user.name}",
            hide_input=True,
        )
        if password != password_again:
            cli_utils.error("Passwords do not match.")

    try:
        Client().update_user(
            name_id_or_prefix=active_user.id,
            old_password=old_password,
            updated_password=password,
        )
    except (KeyError, IllegalOperationError, AuthorizationException) as err:
        cli_utils.error(str(err))

    cli_utils.declare(
        f"Successfully updated password for active user '{active_user.name}'."
    )

check_zenml_pro_project_availability() -> None

Check if the ZenML Pro project feature is available.

Source code in src/zenml/cli/utils.py
2273
2274
2275
2276
2277
2278
2279
2280
def check_zenml_pro_project_availability() -> None:
    """Check if the ZenML Pro project feature is available."""
    client = Client()
    if not client.zen_store.get_store_info().is_pro_server():
        warning(
            "The ZenML projects feature is available only on ZenML Pro. "
            "Please visit https://zenml.io/pro to learn more."
        )

clean(yes: bool = False, local: bool = False) -> None

Delete all ZenML metadata, artifacts and stacks.

This is a destructive operation, primarily intended for use in development.

Parameters:

Name Type Description Default
yes bool

If you don't want a confirmation prompt.

False
local bool

If you want to delete local files associated with the active stack.

False
Source code in src/zenml/cli/base.py
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
@cli.command(
    "clean",
    hidden=True,
    help="Delete all ZenML metadata, artifacts and stacks.",
)
@click.option(
    "--yes",
    "-y",
    is_flag=True,
    default=False,
    help="Don't ask for confirmation.",
)
@click.option(
    "--local",
    "-l",
    is_flag=True,
    default=False,
    help="Delete local files relating to the active stack.",
)
def clean(yes: bool = False, local: bool = False) -> None:
    """Delete all ZenML metadata, artifacts and stacks.

    This is a destructive operation, primarily intended for use in development.

    Args:
        yes: If you don't want a confirmation prompt.
        local: If you want to delete local files associated with the active
            stack.
    """
    if local:
        curr_version = version.parse(zenml_version)

        global_version = GlobalConfiguration().version
        if global_version is not None:
            config_version = version.parse(global_version)

            if config_version > curr_version:
                error(
                    "Due to this version mismatch, ZenML can not detect and "
                    "shut down any running dashboards or clean any resources "
                    "related to the active stack."
                )
        _delete_local_files(force_delete=yes)
        return

    confirm = None
    if not yes:
        confirm = confirmation(
            "DANGER: This will completely delete all artifacts, metadata and "
            "stacks \never created during the use of ZenML. Pipelines and "
            "stack components running non-\nlocally will still exist. Please "
            "delete those manually. \n\nAre you sure you want to proceed?"
        )

    if yes or confirm:
        server = get_local_server()

        if server:
            from zenml.zen_server.deploy.deployer import LocalServerDeployer

            deployer = LocalServerDeployer()
            deployer.remove_server()
            cli_utils.declare("The local ZenML dashboard has been shut down.")

        # delete the .zen folder
        local_zen_repo_config = Path.cwd() / REPOSITORY_DIRECTORY_NAME
        if fileio.exists(str(local_zen_repo_config)):
            fileio.rmtree(str(local_zen_repo_config))
            declare(
                f"Deleted local ZenML config from {local_zen_repo_config}."
            )

        # delete the zen store and all other files and directories used by ZenML
        # to persist information locally (e.g. artifacts)
        global_zen_config = Path(get_global_config_directory())
        if fileio.exists(str(global_zen_config)):
            gc = GlobalConfiguration()
            for dir_name in fileio.listdir(str(global_zen_config)):
                if fileio.isdir(str(global_zen_config / str(dir_name))):
                    warning(
                        f"Deleting '{str(dir_name)}' directory from global "
                        f"config."
                    )
            fileio.rmtree(str(global_zen_config))
            declare(f"Deleted global ZenML config from {global_zen_config}.")
            GlobalConfiguration._reset_instance()
            fresh_gc = GlobalConfiguration(
                user_id=gc.user_id,
                analytics_opt_in=gc.analytics_opt_in,
                version=zenml_version,
            )
            fresh_gc.set_default_store()
            declare(f"Reinitialized ZenML global config at {Path.cwd()}.")

    else:
        declare("Aborting clean.")

code_repository() -> None

Interact with code repositories.

Source code in src/zenml/cli/code_repository.py
35
36
37
@cli.group(cls=TagGroup, tag=CliCategories.MANAGEMENT_TOOLS)
def code_repository() -> None:
    """Interact with code repositories."""

confirmation(text: str, *args: Any, **kwargs: Any) -> bool

Echo a confirmation string on the CLI.

Parameters:

Name Type Description Default
text str

Input text string.

required
*args Any

Args to be passed to click.confirm().

()
**kwargs Any

Kwargs to be passed to click.confirm().

{}

Returns:

Type Description
bool

Boolean based on user response.

Source code in src/zenml/cli/utils.py
125
126
127
128
129
130
131
132
133
134
135
136
def confirmation(text: str, *args: Any, **kwargs: Any) -> bool:
    """Echo a confirmation string on the CLI.

    Args:
        text: Input text string.
        *args: Args to be passed to click.confirm().
        **kwargs: Kwargs to be passed to click.confirm().

    Returns:
        Boolean based on user response.
    """
    return Confirm.ask(text, console=console)

connect(url: Optional[str] = None, username: Optional[str] = None, password: Optional[str] = None, api_key: Optional[str] = None, no_verify_ssl: bool = False, ssl_ca_cert: Optional[str] = None) -> None

Connect to a remote ZenML server.

Parameters:

Name Type Description Default
url Optional[str]

The URL where the ZenML server is reachable.

None
username Optional[str]

The username that is used to authenticate with the ZenML server.

None
password Optional[str]

The password that is used to authenticate with the ZenML server.

None
api_key Optional[str]

The API key that is used to authenticate with the ZenML server.

None
no_verify_ssl bool

Whether to verify the server's TLS certificate.

False
ssl_ca_cert Optional[str]

A path to a CA bundle to use to verify the server's TLS certificate or the CA bundle value itself.

None
Source code in src/zenml/cli/server.py
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
@cli.command(
    "connect",
    help=(
        """Connect to a remote ZenML server.

    DEPRECATED: Please use `zenml login` instead.

    Examples:

      * to re-login to the current ZenML server or connect to a ZenML Pro server:

        zenml connect

      * to log in to a particular ZenML server:

        zenml connect --url=http://zenml.example.com:8080
    """
    ),
)
@click.option(
    "--url",
    "-u",
    help="The URL where the ZenML server is running.",
    required=False,
    type=str,
)
@click.option(
    "--username",
    help="(Deprecated) The username that is used to authenticate with a ZenML "
    "server. If omitted, the web login will be used.",
    required=False,
    type=str,
)
@click.option(
    "--password",
    help="(Deprecated) The password that is used to authenticate with a ZenML "
    "server. If omitted, a prompt will be shown to enter the password.",
    required=False,
    type=str,
)
@click.option(
    "--api-key",
    help="Use an API key to authenticate with a ZenML server. If "
    "omitted, the web login will be used.",
    required=False,
    type=str,
)
@click.option(
    "--no-verify-ssl",
    is_flag=True,
    help="Whether to verify the server's TLS certificate",
    default=False,
)
@click.option(
    "--ssl-ca-cert",
    help="A path to a CA bundle file to use to verify the server's TLS "
    "certificate or the CA bundle value itself",
    required=False,
    type=str,
)
def connect(
    url: Optional[str] = None,
    username: Optional[str] = None,
    password: Optional[str] = None,
    api_key: Optional[str] = None,
    no_verify_ssl: bool = False,
    ssl_ca_cert: Optional[str] = None,
) -> None:
    """Connect to a remote ZenML server.

    Args:
        url: The URL where the ZenML server is reachable.
        username: The username that is used to authenticate with the ZenML
            server.
        password: The password that is used to authenticate with the ZenML
            server.
        api_key: The API key that is used to authenticate with the ZenML
            server.
        no_verify_ssl: Whether to verify the server's TLS certificate.
        ssl_ca_cert: A path to a CA bundle to use to verify the server's TLS
            certificate or the CA bundle value itself.
    """
    cli_utils.warning(
        "The `zenml connect` command is deprecated and will be removed in a "
        "future release. Please use the `zenml login` command instead. "
    )

    if password is not None or username is not None:
        cli_utils.warning(
            "Connecting to a ZenML server using a username and password is "
            "insecure because the password is locally stored on your "
            "filesystem and is no longer supported. The web login workflow will "
            "be used instead. An alternative for non-interactive environments "
            "is to create and use a service account API key (see "
            "https://docs.zenml.io/how-to/manage-zenml-server/connecting-to-zenml/connect-with-a-service-account "
            "for more information)."
        )

    # Calling the `zenml login` command
    cli_utils.declare("Calling `zenml login`...")
    login.callback(  # type: ignore[misc]
        server=url,
        api_key=api_key,
        no_verify_ssl=no_verify_ssl,
        ssl_ca_cert=ssl_ca_cert,
    )

connect_stack(stack_name_or_id: Optional[str] = None, connector: Optional[str] = None, interactive: bool = False, no_verify: bool = False) -> None

Connect a service-connector to all components of a stack.

Parameters:

Name Type Description Default
stack_name_or_id Optional[str]

Name of the stack to connect.

None
connector Optional[str]

The name, ID or prefix of the connector to use.

None
interactive bool

Configure a service connector resource interactively.

False
no_verify bool

Skip verification of the connector resource.

False
Source code in src/zenml/cli/stack.py
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
@stack.command(
    "connect",
    help="Connect a service-connector to a stack's components. "
    "Note that this only connects the service-connector to the current "
    "components of the stack and not to the stack itself, which means that "
    "you need to rerun the command after adding new components to the stack.",
)
@click.argument("stack_name_or_id", type=str, required=False)
@click.option(
    "--connector",
    "-c",
    "connector",
    help="The name, ID or prefix of the connector to use.",
    required=False,
    type=str,
)
@click.option(
    "--interactive",
    "-i",
    "interactive",
    is_flag=True,
    default=False,
    help="Configure a service connector resource interactively.",
    type=click.BOOL,
)
@click.option(
    "--no-verify",
    "no_verify",
    is_flag=True,
    default=False,
    help="Skip verification of the connector resource.",
    type=click.BOOL,
)
def connect_stack(
    stack_name_or_id: Optional[str] = None,
    connector: Optional[str] = None,
    interactive: bool = False,
    no_verify: bool = False,
) -> None:
    """Connect a service-connector to all components of a stack.

    Args:
        stack_name_or_id: Name of the stack to connect.
        connector: The name, ID or prefix of the connector to use.
        interactive: Configure a service connector resource interactively.
        no_verify: Skip verification of the connector resource.
    """
    from zenml.cli.stack_components import (
        connect_stack_component_with_service_connector,
    )

    client = Client()
    stack_to_connect = client.get_stack(name_id_or_prefix=stack_name_or_id)
    for component in stack_to_connect.components.values():
        connect_stack_component_with_service_connector(
            component_type=component[0].type,
            name_id_or_prefix=component[0].name,
            connector=connector,
            interactive=interactive,
            no_verify=no_verify,
        )

connect_stack_component_with_service_connector(component_type: StackComponentType, name_id_or_prefix: Optional[str] = None, connector: Optional[str] = None, resource_id: Optional[str] = None, interactive: bool = False, no_verify: bool = False) -> None

Connect the stack component to a resource through a service connector.

Parameters:

Name Type Description Default
component_type StackComponentType

Type of the component to generate the command for.

required
name_id_or_prefix Optional[str]

The name of the stack component to connect.

None
connector Optional[str]

The name, ID or prefix of the connector to use.

None
resource_id Optional[str]

The resource ID to use connect to. Only required for multi-instance connectors that are not already configured with a particular resource ID.

None
interactive bool

Configure a service connector resource interactively.

False
no_verify bool

Do not verify whether the resource is accessible.

False
Source code in src/zenml/cli/stack_components.py
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
def connect_stack_component_with_service_connector(
    component_type: StackComponentType,
    name_id_or_prefix: Optional[str] = None,
    connector: Optional[str] = None,
    resource_id: Optional[str] = None,
    interactive: bool = False,
    no_verify: bool = False,
) -> None:
    """Connect the stack component to a resource through a service connector.

    Args:
        component_type: Type of the component to generate the command for.
        name_id_or_prefix: The name of the stack component to connect.
        connector: The name, ID or prefix of the connector to use.
        resource_id: The resource ID to use connect to. Only
            required for multi-instance connectors that are not already
            configured with a particular resource ID.
        interactive: Configure a service connector resource interactively.
        no_verify: Do not verify whether the resource is accessible.
    """
    display_name = _component_display_name(component_type)

    if not connector and not interactive:
        cli_utils.error(
            "Please provide either a connector ID or set the interactive flag."
        )

    if connector and interactive:
        cli_utils.error(
            "Please provide either a connector ID or set the interactive "
            "flag, not both."
        )

    client = Client()

    try:
        component_model = client.get_stack_component(
            name_id_or_prefix=name_id_or_prefix,
            component_type=component_type,
        )
    except KeyError as err:
        cli_utils.error(str(err))

    requirements = component_model.flavor.connector_requirements

    if not requirements:
        cli_utils.error(
            f"The '{component_model.name}' {display_name} implementation "
            "does not support using a service connector to connect to "
            "resources."
        )

    resource_type = requirements.resource_type
    if requirements.resource_id_attr is not None:
        # Check if an attribute is set in the component configuration
        resource_id = component_model.configuration.get(
            requirements.resource_id_attr
        )

    if interactive:
        # Fetch the list of connectors that have resources compatible with
        # the stack component's flavor's resource requirements
        with console.status(
            "Finding all resources matching the stack component "
            "requirements (this could take a while)...\n"
        ):
            resource_list = client.list_service_connector_resources(
                connector_type=requirements.connector_type,
                resource_type=resource_type,
                resource_id=resource_id,
            )

        resource_list = [
            resource
            for resource in resource_list
            if resource.resources[0].resource_ids
        ]

        error_resource_list = [
            resource
            for resource in resource_list
            if not resource.resources[0].resource_ids
        ]

        if not resource_list:
            # No compatible resources were found
            additional_info = ""
            if error_resource_list:
                additional_info = (
                    f"{len(error_resource_list)} connectors can be used "
                    f"to gain access to {resource_type} resources required "
                    "for the stack component, but they are in an error "
                    "state or they didn't list any matching resources. "
                )
            command_args = ""
            if requirements.connector_type:
                command_args += (
                    f" --connector-type {requirements.connector_type}"
                )
            command_args += f" --resource-type {requirements.resource_type}"
            if resource_id:
                command_args += f" --resource-id {resource_id}"

            cli_utils.error(
                f"No compatible valid resources were found for the "
                f"'{component_model.name}' {display_name}. "
                f"{additional_info}You can create a new "
                "connector using the 'zenml service-connector register' "
                "command or list the compatible resources using the "
                f"'zenml service-connector list-resources{command_args}' "
                "command."
            )

        # Prompt the user to select a connector and a resource ID, if
        # applicable
        connector_id, resource_id = prompt_select_resource(resource_list)
        no_verify = False
    else:
        # Non-interactive mode: we need to fetch the connector model first

        assert connector is not None
        try:
            connector_model = client.get_service_connector(connector)
        except KeyError as err:
            cli_utils.error(
                f"Could not find a connector '{connector}': {str(err)}"
            )

        connector_id = connector_model.id

        satisfied, msg = requirements.is_satisfied_by(
            connector_model, component_model
        )
        if not satisfied:
            cli_utils.error(
                f"The connector with ID {connector_id} does not match the "
                f"component's `{name_id_or_prefix}` of type `{component_type}`"
                f" connector requirements: {msg}. Please pick a connector that "
                f"is compatible with the component flavor and try again, or "
                f"use the interactive mode to select a compatible connector."
            )

        if not resource_id:
            if connector_model.resource_id:
                resource_id = connector_model.resource_id
            elif connector_model.supports_instances:
                cli_utils.error(
                    f"Multiple {resource_type} resources are available for "
                    "the selected connector. Please use the "
                    "`--resource-id` command line argument to configure a "
                    f"{resource_type} resource or use the interactive mode "
                    "to select a resource interactively."
                )

    connector_resources: Optional[ServiceConnectorResourcesModel] = None
    if not no_verify:
        with console.status(
            "Validating service connector resource configuration...\n"
        ):
            try:
                connector_resources = client.verify_service_connector(
                    connector_id,
                    resource_type=requirements.resource_type,
                    resource_id=resource_id,
                )
            except (
                KeyError,
                ValueError,
                IllegalOperationError,
                NotImplementedError,
                AuthorizationException,
            ) as e:
                cli_utils.error(
                    f"Access to the resource could not be verified: {e}"
                )
        resources = connector_resources.resources[0]
        if resources.resource_ids:
            if len(resources.resource_ids) > 1:
                cli_utils.error(
                    f"Multiple {resource_type} resources are available for "
                    "the selected connector. Please use the "
                    "`--resource-id` command line argument to configure a "
                    f"{resource_type} resource or use the interactive mode "
                    "to select a resource interactively."
                )
            else:
                resource_id = resources.resource_ids[0]

    with console.status(f"Updating {display_name} '{name_id_or_prefix}'...\n"):
        try:
            client.update_stack_component(
                name_id_or_prefix=name_id_or_prefix,
                component_type=component_type,
                connector_id=connector_id,
                connector_resource_id=resource_id,
            )
        except (KeyError, IllegalOperationError) as err:
            cli_utils.error(str(err))

    if connector_resources is not None:
        cli_utils.declare(
            f"Successfully connected {display_name} "
            f"`{component_model.name}` to the following resources:"
        )

        cli_utils.print_service_connector_resource_table([connector_resources])

    else:
        cli_utils.declare(
            f"Successfully connected {display_name} "
            f"`{component_model.name}` to resource."
        )

connect_to_pro_server(pro_server: Optional[str] = None, api_key: Optional[str] = None, refresh: bool = False, pro_api_url: Optional[str] = None) -> None

Connect the client to a ZenML Pro server.

Parameters:

Name Type Description Default
pro_server Optional[str]

The UUID, name or URL of the ZenML Pro server to connect to. If not provided, the web login flow will be initiated.

None
api_key Optional[str]

The API key to use to authenticate with the ZenML Pro server.

None
refresh bool

Whether to force a new login flow with the ZenML Pro server.

False
pro_api_url Optional[str]

The URL for the ZenML Pro API.

None

Raises:

Type Description
ValueError

If incorrect parameters are provided.

AuthorizationException

If the user does not have access to the ZenML Pro server.

Source code in src/zenml/cli/login.py
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
def connect_to_pro_server(
    pro_server: Optional[str] = None,
    api_key: Optional[str] = None,
    refresh: bool = False,
    pro_api_url: Optional[str] = None,
) -> None:
    """Connect the client to a ZenML Pro server.

    Args:
        pro_server: The UUID, name or URL of the ZenML Pro server to connect to.
            If not provided, the web login flow will be initiated.
        api_key: The API key to use to authenticate with the ZenML Pro server.
        refresh: Whether to force a new login flow with the ZenML Pro server.
        pro_api_url: The URL for the ZenML Pro API.

    Raises:
        ValueError: If incorrect parameters are provided.
        AuthorizationException: If the user does not have access to the ZenML
            Pro server.
    """
    from zenml.login.credentials_store import get_credentials_store
    from zenml.login.pro.client import ZenMLProClient
    from zenml.login.pro.workspace.models import WorkspaceStatus

    pro_api_url = pro_api_url or ZENML_PRO_API_URL
    pro_api_url = pro_api_url.rstrip("/")

    server_id, server_url, server_name = None, None, None
    login = False
    if not pro_server:
        login = True
        if api_key:
            raise ValueError(
                "You must provide the URL of the ZenML Pro server when "
                "connecting with an API key."
            )

    elif not re.match(r"^https?://", pro_server):
        # The server argument is not a URL, so it must be a ZenML Pro server
        # name or UUID.
        try:
            server_id = UUID(pro_server)
        except ValueError:
            # The server argument is not a UUID, so it must be a ZenML Pro
            # server name.
            server_name = pro_server
    else:
        server_url = pro_server

    credentials_store = get_credentials_store()
    if not credentials_store.has_valid_pro_authentication(pro_api_url):
        # Without valid ZenML Pro credentials, we can only connect to a ZenML
        # Pro server with an API key and we also need to know the URL of the
        # server to connect to.
        if api_key:
            if server_url:
                connect_to_server(server_url, api_key=api_key, pro_server=True)
                return
            else:
                raise ValueError(
                    "You must provide the URL of the ZenML Pro server when "
                    "connecting with an API key."
                )
        else:
            login = True

    if login or refresh:
        # If we reached this point, then we need to start a new login flow.
        # We also need to remove all existing API tokens associated with the
        # target ZenML Pro API, otherwise they will continue to be used after
        # the re-login flow.
        credentials_store.clear_all_pro_tokens()
        try:
            token = web_login(
                pro_api_url=pro_api_url,
            )
        except AuthorizationException as e:
            cli_utils.error(f"Authorization error: {e}")

        cli_utils.declare(
            "You can now run 'zenml server list' to view the available ZenML "
            "Pro servers and then 'zenml login <server-url-name-or-id>' to "
            "connect to a specific server without having to log in again until "
            "your session expires."
        )

        workspace_id: Optional[str] = None
        if token.device_metadata:
            # TODO: is this still correct?
            workspace_id = token.device_metadata.get("tenant_id")

        if workspace_id is None and pro_server is None:
            # This is not really supposed to happen, because the implementation
            # of the web login workflow should always return a workspace ID, but
            # we're handling it just in case.
            cli_utils.declare(
                "A valid server was not selected during the login process. "
                "Please run `zenml server list` to display a list of available "
                "servers and then `zenml login <server-url-name-or-id>` to "
                "connect to a server."
            )
            return

        # The server selected during the web login process overrides any
        # server argument passed to the command.
        server_id = UUID(workspace_id)

    client = ZenMLProClient(pro_api_url)

    if server_id:
        server = client.workspace.get(server_id)
    elif server_url:
        servers = client.workspace.list(url=server_url, member_only=True)
        if not servers:
            raise AuthorizationException(
                f"The '{server_url}' URL belongs to a ZenML Pro server, "
                "but it doesn't look like you have access to it. Please "
                "check the server URL and your permissions and try again."
            )

        server = servers[0]
    elif server_name:
        servers = client.workspace.list(
            workspace_name=server_name, member_only=True
        )
        if not servers:
            raise AuthorizationException(
                f"No ZenML Pro server with the name '{server_name}' exists "
                "or you don't have access to it. Please check the server name "
                "and your permissions and try again."
            )
        server = servers[0]
    else:
        raise ValueError(
            "No server ID, URL, or name was provided. Please provide one of "
            "these values to connect to a ZenML Pro server."
        )

    server_id = server.id

    if server.status == WorkspaceStatus.PENDING:
        with console.status(
            f"Waiting for your `{server.name}` ZenML Pro server to be set up..."
        ):
            timeout = 180  # 3 minutes
            while True:
                time.sleep(5)
                server = client.workspace.get(server_id)
                if server.status != WorkspaceStatus.PENDING:
                    break
                timeout -= 5
                if timeout <= 0:
                    cli_utils.error(
                        f"Your `{server.name}` ZenML Pro server is taking "
                        "longer than expected to set up. Please try again "
                        "later or manage the server state by visiting the "
                        f"ZenML Pro dashboard at {server.dashboard_url}."
                    )

    if server.status == WorkspaceStatus.FAILED:
        cli_utils.error(
            f"Your `{server.name}` ZenML Pro server is currently in a "
            "failed state. Please manage the server state by visiting the "
            f"ZenML Pro dashboard at {server.dashboard_url}, or contact "
            "your server administrator."
        )

    elif server.status == WorkspaceStatus.DEACTIVATED:
        cli_utils.error(
            f"Your `{server.name}` ZenML Pro server is currently "
            "deactivated. Please manage the server state by visiting the "
            f"ZenML Pro dashboard at {server.dashboard_url}, or contact "
            "your server administrator."
        )

    elif server.status == WorkspaceStatus.AVAILABLE:
        if not server.url:
            cli_utils.error(
                f"The ZenML Pro server '{server.name}' is not currently "
                f"running. Visit the ZenML Pro dashboard to manage the server "
                f"status at: {server.dashboard_url}"
            )
    else:
        cli_utils.error(
            f"Your `{server.name}` ZenML Pro server is currently "
            "being deleted. Please select a different server or set up a "
            "new server by visiting the ZenML Pro dashboard at "
            f"{server.dashboard_organization_url}."
        )

    cli_utils.declare(
        f"Connecting to ZenML Pro server: {server.name} [{str(server.id)}] "
    )

    connect_to_server(server.url, api_key=api_key, pro_server=True)

    # Update the stored server info with more accurate data taken from the
    # ZenML Pro workspace object.
    credentials_store.update_server_info(server.url, server)

    cli_utils.declare(f"Connected to ZenML Pro server: {server.name}.")

connect_to_server(url: str, api_key: Optional[str] = None, verify_ssl: Union[str, bool] = True, refresh: bool = False, pro_server: bool = False) -> None

Connect the client to a ZenML server or a SQL database.

Parameters:

Name Type Description Default
url str

The URL of the ZenML server or the SQL database to connect to.

required
api_key Optional[str]

The API key to use to authenticate with the ZenML server.

None
verify_ssl Union[str, bool]

Whether to verify the server's TLS certificate. If a string is passed, it is interpreted as the path to a CA bundle file.

True
refresh bool

Whether to force a new login flow with the ZenML server.

False
pro_server bool

Whether the server is a ZenML Pro server.

False
Source code in src/zenml/cli/login.py
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
def connect_to_server(
    url: str,
    api_key: Optional[str] = None,
    verify_ssl: Union[str, bool] = True,
    refresh: bool = False,
    pro_server: bool = False,
) -> None:
    """Connect the client to a ZenML server or a SQL database.

    Args:
        url: The URL of the ZenML server or the SQL database to connect to.
        api_key: The API key to use to authenticate with the ZenML server.
        verify_ssl: Whether to verify the server's TLS certificate. If a string
            is passed, it is interpreted as the path to a CA bundle file.
        refresh: Whether to force a new login flow with the ZenML server.
        pro_server: Whether the server is a ZenML Pro server.
    """
    from zenml.login.credentials_store import get_credentials_store
    from zenml.zen_stores.base_zen_store import BaseZenStore

    url = url.rstrip("/")

    store_type = BaseZenStore.get_store_type(url)
    if store_type == StoreType.REST:
        from zenml.zen_stores.rest_zen_store import RestZenStoreConfiguration

        credentials_store = get_credentials_store()
        if api_key:
            cli_utils.declare(
                f"Authenticating to ZenML server '{url}' using an API key..."
            )
            credentials_store.set_api_key(url, api_key)
        elif pro_server:
            # We don't have to do anything here assuming the user has already
            # logged in to the ZenML Pro server using the ZenML Pro web login
            # flow.
            cli_utils.declare(f"Authenticating to ZenML server '{url}'...")
        else:
            if refresh or not credentials_store.has_valid_authentication(url):
                cli_utils.declare(
                    f"Authenticating to ZenML server '{url}' using the web "
                    "login..."
                )
                web_login(url=url, verify_ssl=verify_ssl)
            else:
                cli_utils.declare(f"Connecting to ZenML server '{url}'...")

        rest_store_config = RestZenStoreConfiguration(
            url=url,
            verify_ssl=verify_ssl,
        )
        try:
            GlobalConfiguration().set_store(rest_store_config)
        except IllegalOperationError:
            cli_utils.error(
                f"You do not have sufficient permissions to "
                f"access the server at '{url}'."
            )
        except CredentialsNotValid as e:
            cli_utils.error(f"Authorization error: {e}")

    else:
        from zenml.zen_stores.sql_zen_store import SqlZenStoreConfiguration

        # Connect to a SQL database
        sql_store_config = SqlZenStoreConfiguration(
            url=url,
        )
        cli_utils.declare(f"Connecting to SQL database '{url}'...")

        try:
            GlobalConfiguration().set_store(sql_store_config)
        except IllegalOperationError:
            cli_utils.warning(
                f"You do not have sufficient permissions to "
                f"access the SQL database at '{url}'."
            )
        except CredentialsNotValid as e:
            cli_utils.warning(f"Authorization error: {e}")

        cli_utils.declare(f"Connected to SQL database '{url}'")

connected_to_local_server() -> bool

Check if the client is connected to a local server.

Returns:

Type Description
bool

True if the client is connected to a local server, False otherwise.

Source code in src/zenml/utils/server_utils.py
43
44
45
46
47
48
49
50
51
52
def connected_to_local_server() -> bool:
    """Check if the client is connected to a local server.

    Returns:
        True if the client is connected to a local server, False otherwise.
    """
    from zenml.zen_server.deploy.deployer import LocalServerDeployer

    deployer = LocalServerDeployer()
    return deployer.is_connected_to_server()

convert_structured_str_to_dict(string: str) -> Dict[str, str]

Convert a structured string (JSON or YAML) into a dict.

Examples:

>>> convert_structured_str_to_dict('{"location": "Nevada", "aliens":"many"}')
{'location': 'Nevada', 'aliens': 'many'}
>>> convert_structured_str_to_dict('location: Nevada \naliens: many')
{'location': 'Nevada', 'aliens': 'many'}
>>> convert_structured_str_to_dict("{'location': 'Nevada', 'aliens': 'many'}")
{'location': 'Nevada', 'aliens': 'many'}

Parameters:

Name Type Description Default
string str

JSON or YAML string value

required

Returns:

Name Type Description
dict_ Dict[str, str]

dict from structured JSON or YAML str

Source code in src/zenml/cli/utils.py
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
def convert_structured_str_to_dict(string: str) -> Dict[str, str]:
    """Convert a structured string (JSON or YAML) into a dict.

    Examples:
        >>> convert_structured_str_to_dict('{"location": "Nevada", "aliens":"many"}')
        {'location': 'Nevada', 'aliens': 'many'}
        >>> convert_structured_str_to_dict('location: Nevada \\naliens: many')
        {'location': 'Nevada', 'aliens': 'many'}
        >>> convert_structured_str_to_dict("{'location': 'Nevada', 'aliens': 'many'}")
        {'location': 'Nevada', 'aliens': 'many'}

    Args:
        string: JSON or YAML string value

    Returns:
        dict_: dict from structured JSON or YAML str
    """
    try:
        dict_: Dict[str, str] = json.loads(string)
        return dict_
    except ValueError:
        pass

    try:
        # Here, Dict type in str is implicitly supported by yaml.safe_load()
        dict_ = yaml.safe_load(string)
        return dict_
    except yaml.YAMLError:
        pass

    error(
        f"Invalid argument: '{string}'. Please provide the value in JSON or YAML format."
    )

copy_dir(source_dir: str, destination_dir: str, overwrite: bool = False) -> None

Copies dir from source to destination.

Parameters:

Name Type Description Default
source_dir str

Path to copy from.

required
destination_dir str

Path to copy to.

required
overwrite bool

Boolean. If false, function throws an error before overwrite.

False
Source code in src/zenml/utils/io_utils.py
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
def copy_dir(
    source_dir: str, destination_dir: str, overwrite: bool = False
) -> None:
    """Copies dir from source to destination.

    Args:
        source_dir: Path to copy from.
        destination_dir: Path to copy to.
        overwrite: Boolean. If false, function throws an error before overwrite.
    """
    for source_file in listdir(source_dir):
        source_path = os.path.join(source_dir, convert_to_str(source_file))
        destination_path = os.path.join(
            destination_dir, convert_to_str(source_file)
        )
        if isdir(source_path):
            if source_path == destination_dir:
                # if the destination is a subdirectory of the source, we skip
                # copying it to avoid an infinite loop.
                continue
            copy_dir(source_path, destination_path, overwrite)
        else:
            create_dir_recursive_if_not_exists(
                os.path.dirname(destination_path)
            )
            copy(str(source_path), str(destination_path), overwrite)

copy_stack(source_stack_name_or_id: str, target_stack: str) -> None

Copy a stack.

Parameters:

Name Type Description Default
source_stack_name_or_id str

The name or id of the stack to copy.

required
target_stack str

Name of the copied stack.

required
Source code in src/zenml/cli/stack.py
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
@stack.command("copy", help="Copy a stack to a new stack name.")
@click.argument("source_stack_name_or_id", type=str, required=True)
@click.argument("target_stack", type=str, required=True)
def copy_stack(source_stack_name_or_id: str, target_stack: str) -> None:
    """Copy a stack.

    Args:
        source_stack_name_or_id: The name or id of the stack to copy.
        target_stack: Name of the copied stack.
    """
    client = Client()

    with console.status(f"Copying stack `{source_stack_name_or_id}`...\n"):
        try:
            stack_to_copy = client.get_stack(
                name_id_or_prefix=source_stack_name_or_id
            )
        except KeyError as err:
            cli_utils.error(str(err))

        component_mapping: Dict[StackComponentType, Union[str, UUID]] = {}

        for c_type, c_list in stack_to_copy.components.items():
            if c_list:
                component_mapping[c_type] = c_list[0].id

        copied_stack = client.create_stack(
            name=target_stack,
            components=component_mapping,
        )

    print_model_url(get_stack_url(copied_stack))

create_api_key(service_account_name_or_id: str, name: str, description: Optional[str], set_key: bool = False, output_file: Optional[str] = None) -> None

Create an API key.

Parameters:

Name Type Description Default
service_account_name_or_id str

The name or ID of the service account to which the API key should be added.

required
name str

Name of the API key

required
description Optional[str]

The API key description.

required
set_key bool

Configure the local client with the generated key.

False
output_file Optional[str]

Output file to write the API key to.

None
Source code in src/zenml/cli/service_accounts.py
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
@api_key.command(
    "create",
    help="Create an API key and print its value.",
)
@click.argument("name", type=click.STRING)
@click.option(
    "--description",
    "-d",
    type=str,
    required=False,
    help="The API key description.",
)
@click.option(
    "--set-key",
    is_flag=True,
    help="Configure the local client with the generated key.",
)
@click.option(
    "--output-file",
    type=str,
    required=False,
    help="File to write the API key to.",
)
@click.pass_obj
def create_api_key(
    service_account_name_or_id: str,
    name: str,
    description: Optional[str],
    set_key: bool = False,
    output_file: Optional[str] = None,
) -> None:
    """Create an API key.

    Args:
        service_account_name_or_id: The name or ID of the service account to
            which the API key should be added.
        name: Name of the API key
        description: The API key description.
        set_key: Configure the local client with the generated key.
        output_file: Output file to write the API key to.
    """
    _create_api_key(
        service_account_name_or_id=service_account_name_or_id,
        name=name,
        description=description,
        set_key=set_key,
        output_file=output_file,
    )

create_run_template(source: str, name: str, config_path: Optional[str] = None, stack_name_or_id: Optional[str] = None) -> None

Create a run template for a pipeline.

Parameters:

Name Type Description Default
source str

Importable source resolving to a pipeline instance.

required
name str

Name of the run template.

required
config_path Optional[str]

Path to pipeline configuration file.

None
stack_name_or_id Optional[str]

Name or ID of the stack for which the template should be created.

None
Source code in src/zenml/cli/pipeline.py
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
@pipeline.command(
    "create-run-template",
    help="Create a run template for a pipeline. The SOURCE argument needs to "
    "be an importable source path resolving to a ZenML pipeline instance, e.g. "
    "`my_module.my_pipeline_instance`.",
)
@click.argument("source")
@click.option(
    "--name",
    "-n",
    type=str,
    required=True,
    help="Name for the template",
)
@click.option(
    "--config",
    "-c",
    "config_path",
    type=click.Path(exists=True, dir_okay=False),
    required=False,
    help="Path to configuration file for the build.",
)
@click.option(
    "--stack",
    "-s",
    "stack_name_or_id",
    type=str,
    required=False,
    help="Name or ID of the stack to use for the build.",
)
def create_run_template(
    source: str,
    name: str,
    config_path: Optional[str] = None,
    stack_name_or_id: Optional[str] = None,
) -> None:
    """Create a run template for a pipeline.

    Args:
        source: Importable source resolving to a pipeline instance.
        name: Name of the run template.
        config_path: Path to pipeline configuration file.
        stack_name_or_id: Name or ID of the stack for which the template should
            be created.
    """
    if not Client().root:
        cli_utils.warning(
            "You're running the `zenml pipeline create-run-template` command "
            "without a ZenML repository. Your current working directory will "
            "be used as the source root relative to which the registered step "
            "classes will be resolved. To silence this warning, run `zenml "
            "init` at your source code root."
        )

    with cli_utils.temporary_active_stack(stack_name_or_id=stack_name_or_id):
        pipeline_instance = _import_pipeline(source=source)

        pipeline_instance = pipeline_instance.with_options(
            config_path=config_path
        )
        template = pipeline_instance.create_run_template(name=name)

    cli_utils.declare(f"Created run template `{template.id}`.")

create_secret(name: str, private: bool, interactive: bool, values: str, args: List[str]) -> None

Create a secret.

Parameters:

Name Type Description Default
name str

The name of the secret to create.

required
private bool

Whether the secret is private.

required
interactive bool

Whether to use interactive mode to enter the secret values.

required
values str

Secret key-value pairs to be passed as JSON or YAML.

required
args List[str]

The arguments to pass to the secret.

required
Source code in src/zenml/cli/secret.py
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
@secret.command(
    "create",
    context_settings={"ignore_unknown_options": True},
    help="Create a new secret.",
)
@click.argument("name", type=click.STRING)
@click.option(
    "--private",
    "-p",
    "private",
    is_flag=True,
    help="Whether the secret is private. A private secret is only accessible "
    "to the user who creates it.",
)
@click.option(
    "--interactive",
    "-i",
    "interactive",
    is_flag=True,
    help="Use interactive mode to enter the secret values.",
    type=click.BOOL,
)
@click.option(
    "--values",
    "-v",
    "values",
    help="Pass one or more values using JSON or YAML format or reference a file by prefixing the filename with the @ "
    "special character.",
    required=False,
    type=str,
)
@click.argument("args", nargs=-1, type=click.UNPROCESSED)
def create_secret(
    name: str, private: bool, interactive: bool, values: str, args: List[str]
) -> None:
    """Create a secret.

    Args:
        name: The name of the secret to create.
        private: Whether the secret is private.
        interactive: Whether to use interactive mode to enter the secret values.
        values: Secret key-value pairs to be passed as JSON or YAML.
        args: The arguments to pass to the secret.
    """
    name, parsed_args = parse_name_and_extra_arguments(  # type: ignore[assignment]
        list(args) + [name], expand_args=True
    )
    if values:
        inline_values = expand_argument_value_from_file(SECRET_VALUES, values)
        inline_values_dict = convert_structured_str_to_dict(inline_values)
        parsed_args.update(inline_values_dict)

    if "name" in parsed_args:
        error("You can't use 'name' as the key for one of your secrets.")
    elif name == "name":
        error("Secret names cannot be named 'name'.")

    try:
        client = Client()
        if interactive:
            if parsed_args:
                error(
                    "Cannot pass secret fields as arguments when using "
                    "interactive mode."
                )
            else:
                click.echo("Entering interactive mode:")
                while True:
                    k = click.prompt("Please enter a secret key")
                    if k in parsed_args:
                        warning(
                            f"Key {k} already in this secret. Please restart "
                            f"this process or use 'zenml "
                            f"secret update {name} --values=<JSON/YAML> or --{k}=...' to update this "
                            f"key after the secret is registered. Skipping ..."
                        )
                    else:
                        v = getpass.getpass(
                            f"Please enter the secret value for the key [{k}]:"
                        )
                        parsed_args[k] = v

                    if not confirmation(
                        "Do you want to add another key-value pair to this "
                        "secret?"
                    ):
                        break
        elif not parsed_args:
            error(
                "Secret fields must be passed as arguments when not using "
                "interactive mode."
            )

        for key in parsed_args:
            validate_keys(key)
        declare("The following secret will be registered.")
        pretty_print_secret(secret=parsed_args, hide_secret=True)

        with console.status(f"Saving secret `{name}`..."):
            try:
                client.create_secret(
                    name=name, values=parsed_args, private=private
                )
                declare(f"Secret '{name}' successfully created.")
            except EntityExistsError as e:
                # should never hit this on account of the check above
                error(f"Secret with name already exists. {str(e)}")
    except NotImplementedError as e:
        error(f"Centralized secrets management is disabled: {str(e)}")

create_service_account(service_account_name: str, description: str = '', create_api_key: bool = True, set_api_key: bool = False, output_file: Optional[str] = None) -> None

Create a new service account.

Parameters:

Name Type Description Default
service_account_name str

The name of the service account to create.

required
description str

The API key description.

''
create_api_key bool

Create an API key for the service account.

True
set_api_key bool

Configure the local client to use the generated API key.

False
output_file Optional[str]

Output file to write the API key to.

None
Source code in src/zenml/cli/service_accounts.py
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
@service_account.command(
    "create", help="Create a new service account and optional API key."
)
@click.argument("service_account_name", type=str, required=True)
@click.option(
    "--description",
    "-d",
    type=str,
    required=False,
    default="",
    help="The API key description.",
)
@click.option(
    "--create-api-key",
    help=("Create an API key for the service account."),
    type=bool,
    default=True,
)
@click.option(
    "--set-api-key",
    help=("Configure the local client to use the generated API key."),
    is_flag=True,
)
@click.option(
    "--output-file",
    type=str,
    required=False,
    help="File to write the API key to.",
)
def create_service_account(
    service_account_name: str,
    description: str = "",
    create_api_key: bool = True,
    set_api_key: bool = False,
    output_file: Optional[str] = None,
) -> None:
    """Create a new service account.

    Args:
        service_account_name: The name of the service account to create.
        description: The API key description.
        create_api_key: Create an API key for the service account.
        set_api_key: Configure the local client to use the generated API key.
        output_file: Output file to write the API key to.
    """
    client = Client()
    try:
        service_account = client.create_service_account(
            name=service_account_name,
            description=description,
        )

        cli_utils.declare(f"Created service account '{service_account.name}'.")
    except EntityExistsError as err:
        cli_utils.error(str(err))

    if create_api_key:
        _create_api_key(
            service_account_name_or_id=service_account.name,
            name="default",
            description="Default API key.",
            set_key=set_api_key,
            output_file=output_file,
        )

create_user(user_name: str, password: Optional[str] = None, is_admin: bool = False) -> None

Create a new user.

Parameters:

Name Type Description Default
user_name str

The name of the user to create.

required
password Optional[str]

The password of the user to create.

None
is_admin bool

Whether the user should be an admin.

False
Source code in src/zenml/cli/user_management.py
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
@user.command(
    "create",
    help="Create a new user. If an empty password is configured, an activation "
    "token is generated and a link to the dashboard is provided where the "
    "user can activate the account.",
)
@click.argument("user_name", type=str, required=True)
@click.option(
    "--password",
    help=(
        "The user password. If omitted, a prompt will be shown to enter the "
        "password. If an empty password is entered, an activation token is "
        "generated and a link to the dashboard is provided where the user can "
        "activate the account."
    ),
    required=False,
    type=str,
)
@click.option(
    "--is_admin",
    is_flag=True,
    help=(
        "Whether the user should be an admin. If not specified, the user will "
        "be a regular user."
    ),
    required=False,
    default=False,
)
def create_user(
    user_name: str,
    password: Optional[str] = None,
    is_admin: bool = False,
) -> None:
    """Create a new user.

    Args:
        user_name: The name of the user to create.
        password: The password of the user to create.
        is_admin: Whether the user should be an admin.
    """
    client = Client()
    if not password:
        if client.zen_store.type != StoreType.REST:
            password = click.prompt(
                f"Password for user {user_name}",
                hide_input=True,
            )
        else:
            password = click.prompt(
                f"Password for user {user_name}. Leave empty to generate an "
                f"activation token",
                default="",
                hide_input=True,
            )
    else:
        cli_utils.warning(
            "Supplying password values in the command line is not safe. "
            "Please consider using the prompt option."
        )

    try:
        new_user = client.create_user(
            name=user_name, password=password, is_admin=is_admin
        )

        cli_utils.declare(f"Created user '{new_user.name}'.")
    except EntityExistsError as err:
        cli_utils.error(str(err))
    else:
        if not new_user.active and new_user.activation_token is not None:
            user_info = f"?user={str(new_user.id)}&username={new_user.name}&token={new_user.activation_token}"
            cli_utils.declare(
                f"The created user account is currently inactive. You can "
                f"activate it by visiting the dashboard at the following URL:\n"
                # TODO: keep only `activate-user` once legacy dashboard is gone
                f"{client.zen_store.url}/activate-user{user_info}\n\n"
                "If you are using Legacy dashboard visit the following URL:\n"
                f"{client.zen_store.url}/signup{user_info}\n"
            )

deactivate_user(user_name_or_id: str) -> None

Reset the password of a user.

Parameters:

Name Type Description Default
user_name_or_id str

The name or ID of the user to reset the password for.

required
Source code in src/zenml/cli/user_management.py
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
@user.command(
    "deactivate",
    help="Generate an activation token to reset the password for a user account",
)
@click.argument("user_name_or_id", type=str, required=True)
def deactivate_user(
    user_name_or_id: str,
) -> None:
    """Reset the password of a user.

    Args:
        user_name_or_id: The name or ID of the user to reset the password for.
    """
    client = Client()

    store = GlobalConfiguration().store_configuration
    if store.type != StoreType.REST:
        cli_utils.error(
            "Deactivating users is only supported when connected to a ZenML "
            "server."
        )

    try:
        if not client.active_user.is_admin:
            cli_utils.error(
                "Only admins can reset the password of other users."
            )

        user = client.deactivate_user(
            name_id_or_prefix=user_name_or_id,
        )
    except (KeyError, IllegalOperationError) as err:
        cli_utils.error(str(err))

    user_info = f"?user={str(user.id)}&username={user.name}&token={user.activation_token}"
    cli_utils.declare(
        f"Successfully deactivated user account '{user.name}'."
        f"To reactivate the account, please visit the dashboard at the "
        "following URL:\n"
        # TODO: keep only `activate-user` once legacy dashboard is gone
        f"{client.zen_store.url}/activate-user{user_info}\n\n"
        "If you are using Legacy dashboard visit the following URL:\n"
        f"{client.zen_store.url}/signup{user_info}\n"
    )

declare(text: Union[str, Text], bold: Optional[bool] = None, italic: Optional[bool] = None, **kwargs: Any) -> None

Echo a declaration on the CLI.

Parameters:

Name Type Description Default
text Union[str, Text]

Input text string.

required
bold Optional[bool]

Optional boolean to bold the text.

None
italic Optional[bool]

Optional boolean to italicize the text.

None
**kwargs Any

Optional kwargs to be passed to console.print().

{}
Source code in src/zenml/cli/utils.py
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
def declare(
    text: Union[str, "Text"],
    bold: Optional[bool] = None,
    italic: Optional[bool] = None,
    **kwargs: Any,
) -> None:
    """Echo a declaration on the CLI.

    Args:
        text: Input text string.
        bold: Optional boolean to bold the text.
        italic: Optional boolean to italicize the text.
        **kwargs: Optional kwargs to be passed to console.print().
    """
    base_style = zenml_style_defaults["info"]
    style = Style.chain(base_style, Style(bold=bold, italic=italic))
    console.print(text, style=style, **kwargs)

delete_api_key(service_account_name_or_id: str, name_or_id: str, yes: bool = False) -> None

Delete an API key.

Parameters:

Name Type Description Default
service_account_name_or_id str

The name or ID of the service account to which the API key belongs.

required
name_or_id str

The name or ID of the API key to delete.

required
yes bool

If set, don't ask for confirmation.

False
Source code in src/zenml/cli/service_accounts.py
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
@api_key.command("delete")
@click.argument("name_or_id", type=str, required=True)
@click.option(
    "--yes",
    "-y",
    is_flag=True,
    help="Don't ask for confirmation.",
)
@click.pass_obj
def delete_api_key(
    service_account_name_or_id: str, name_or_id: str, yes: bool = False
) -> None:
    """Delete an API key.

    Args:
        service_account_name_or_id: The name or ID of the service account to
            which the API key belongs.
        name_or_id: The name or ID of the API key to delete.
        yes: If set, don't ask for confirmation.
    """
    if not yes:
        confirmation = cli_utils.confirmation(
            f"Are you sure you want to delete API key `{name_or_id}`?"
        )
        if not confirmation:
            cli_utils.declare("API key deletion canceled.")
            return

    try:
        Client().delete_api_key(
            service_account_name_id_or_prefix=service_account_name_or_id,
            name_id_or_prefix=name_or_id,
        )
    except KeyError as e:
        cli_utils.error(str(e))
    else:
        cli_utils.declare(f"Deleted API key `{name_or_id}`.")

delete_authorized_device(id: str, yes: bool = False) -> None

Delete an authorized device.

Parameters:

Name Type Description Default
id str

The ID of the authorized device to delete.

required
yes bool

If set, don't ask for confirmation.

False
Source code in src/zenml/cli/authorized_device.py
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
@authorized_device.command("delete")
@click.argument("id", type=str, required=True)
@click.option(
    "--yes",
    "-y",
    is_flag=True,
    help="Don't ask for confirmation.",
)
def delete_authorized_device(id: str, yes: bool = False) -> None:
    """Delete an authorized device.

    Args:
        id: The ID of the authorized device to delete.
        yes: If set, don't ask for confirmation.
    """
    if not yes:
        confirmation = cli_utils.confirmation(
            f"Are you sure you want to delete authorized device `{id}`?"
        )
        if not confirmation:
            cli_utils.declare("Authorized device deletion canceled.")
            return

    try:
        Client().delete_authorized_device(id_or_prefix=id)
    except KeyError as e:
        cli_utils.error(str(e))
    else:
        cli_utils.declare(f"Deleted authorized device `{id}`.")

delete_code_repository(name_or_id: str, yes: bool = False) -> None

Delete a code repository.

Parameters:

Name Type Description Default
name_or_id str

The name or ID of the code repository to delete.

required
yes bool

If set, don't ask for confirmation.

False
Source code in src/zenml/cli/code_repository.py
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
@code_repository.command("delete")
@click.argument("name_or_id", type=str, required=True)
@click.option(
    "--yes",
    "-y",
    is_flag=True,
    help="Don't ask for confirmation.",
)
def delete_code_repository(name_or_id: str, yes: bool = False) -> None:
    """Delete a code repository.

    Args:
        name_or_id: The name or ID of the code repository to delete.
        yes: If set, don't ask for confirmation.
    """
    if not yes:
        confirmation = cli_utils.confirmation(
            f"Are you sure you want to delete code repository `{name_or_id}`?"
        )
        if not confirmation:
            cli_utils.declare("Code repository deletion canceled.")
            return

    try:
        Client().delete_code_repository(name_id_or_prefix=name_or_id)
    except KeyError as e:
        cli_utils.error(str(e))
    else:
        cli_utils.declare(f"Deleted code repository `{name_or_id}`.")

delete_model(model_name_or_id: str, yes: bool = False) -> None

Delete an existing model from the Model Control Plane.

Parameters:

Name Type Description Default
model_name_or_id str

The ID or name of the model to delete.

required
yes bool

If set, don't ask for confirmation.

False
Source code in src/zenml/cli/model.py
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
@model.command("delete", help="Delete an existing model.")
@click.argument("model_name_or_id")
@click.option(
    "--yes",
    "-y",
    is_flag=True,
    help="Don't ask for confirmation.",
)
def delete_model(
    model_name_or_id: str,
    yes: bool = False,
) -> None:
    """Delete an existing model from the Model Control Plane.

    Args:
        model_name_or_id: The ID or name of the model to delete.
        yes: If set, don't ask for confirmation.
    """
    if not yes:
        confirmation = cli_utils.confirmation(
            f"Are you sure you want to delete model '{model_name_or_id}'?"
        )
        if not confirmation:
            cli_utils.declare("Model deletion canceled.")
            return

    try:
        Client().delete_model(
            model_name_or_id=model_name_or_id,
        )
    except (KeyError, ValueError) as e:
        cli_utils.error(str(e))
    else:
        cli_utils.declare(f"Model '{model_name_or_id}' deleted.")

delete_model_version(model_name_or_id: str, model_version_name_or_number_or_id: str, yes: bool = False) -> None

Delete an existing model version in the Model Control Plane.

Parameters:

Name Type Description Default
model_name_or_id str

The ID or name of the model that contains the version.

required
model_version_name_or_number_or_id str

The ID, number or name of the model version.

required
yes bool

If set, don't ask for confirmation.

False
Source code in src/zenml/cli/model.py
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
@version.command("delete", help="Delete an existing model version.")
@click.argument("model_name_or_id")
@click.argument("model_version_name_or_number_or_id")
@click.option(
    "--yes",
    "-y",
    is_flag=True,
    help="Don't ask for confirmation.",
)
def delete_model_version(
    model_name_or_id: str,
    model_version_name_or_number_or_id: str,
    yes: bool = False,
) -> None:
    """Delete an existing model version in the Model Control Plane.

    Args:
        model_name_or_id: The ID or name of the model that contains the version.
        model_version_name_or_number_or_id: The ID, number or name of the model version.
        yes: If set, don't ask for confirmation.
    """
    if not yes:
        confirmation = cli_utils.confirmation(
            f"Are you sure you want to delete model version '{model_version_name_or_number_or_id}' from model '{model_name_or_id}'?"
        )
        if not confirmation:
            cli_utils.declare("Model version deletion canceled.")
            return

    try:
        model_version = Client().get_model_version(
            model_name_or_id=model_name_or_id,
            model_version_name_or_number_or_id=model_version_name_or_number_or_id,
        )
        Client().delete_model_version(
            model_version_id=model_version.id,
        )
    except (KeyError, ValueError) as e:
        cli_utils.error(str(e))
    else:
        cli_utils.declare(
            f"Model version '{model_version_name_or_number_or_id}' deleted from model '{model_name_or_id}'."
        )

delete_pipeline(pipeline_name_or_id: str, yes: bool = False) -> None

Delete a pipeline.

Parameters:

Name Type Description Default
pipeline_name_or_id str

The name or ID of the pipeline to delete.

required
yes bool

If set, don't ask for confirmation.

False
Source code in src/zenml/cli/pipeline.py
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
@pipeline.command("delete")
@click.argument("pipeline_name_or_id", type=str, required=True)
@click.option(
    "--yes",
    "-y",
    is_flag=True,
    help="Don't ask for confirmation.",
)
def delete_pipeline(
    pipeline_name_or_id: str,
    yes: bool = False,
) -> None:
    """Delete a pipeline.

    Args:
        pipeline_name_or_id: The name or ID of the pipeline to delete.
        yes: If set, don't ask for confirmation.
    """
    if not yes:
        confirmation = cli_utils.confirmation(
            f"Are you sure you want to delete pipeline "
            f"`{pipeline_name_or_id}`? This will change all "
            "existing runs of this pipeline to become unlisted."
        )
        if not confirmation:
            cli_utils.declare("Pipeline deletion canceled.")
            return

    try:
        Client().delete_pipeline(
            name_id_or_prefix=pipeline_name_or_id,
        )
    except KeyError as e:
        cli_utils.error(str(e))
    else:
        cli_utils.declare(f"Deleted pipeline `{pipeline_name_or_id}`.")

delete_pipeline_build(build_id: str, yes: bool = False) -> None

Delete a pipeline build.

Parameters:

Name Type Description Default
build_id str

The ID of the pipeline build to delete.

required
yes bool

If set, don't ask for confirmation.

False
Source code in src/zenml/cli/pipeline.py
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
@builds.command("delete")
@click.argument("build_id", type=str, required=True)
@click.option(
    "--yes",
    "-y",
    is_flag=True,
    help="Don't ask for confirmation.",
)
def delete_pipeline_build(
    build_id: str,
    yes: bool = False,
) -> None:
    """Delete a pipeline build.

    Args:
        build_id: The ID of the pipeline build to delete.
        yes: If set, don't ask for confirmation.
    """
    if not yes:
        confirmation = cli_utils.confirmation(
            f"Are you sure you want to delete pipeline build `{build_id}`?"
        )
        if not confirmation:
            cli_utils.declare("Pipeline build deletion canceled.")
            return

    try:
        Client().delete_build(build_id)
    except KeyError as e:
        cli_utils.error(str(e))
    else:
        cli_utils.declare(f"Deleted pipeline build '{build_id}'.")

delete_pipeline_run(run_name_or_id: str, yes: bool = False) -> None

Delete a pipeline run.

Parameters:

Name Type Description Default
run_name_or_id str

The name or ID of the pipeline run to delete.

required
yes bool

If set, don't ask for confirmation.

False
Source code in src/zenml/cli/pipeline.py
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
@runs.command("delete")
@click.argument("run_name_or_id", type=str, required=True)
@click.option(
    "--yes",
    "-y",
    is_flag=True,
    help="Don't ask for confirmation.",
)
def delete_pipeline_run(
    run_name_or_id: str,
    yes: bool = False,
) -> None:
    """Delete a pipeline run.

    Args:
        run_name_or_id: The name or ID of the pipeline run to delete.
        yes: If set, don't ask for confirmation.
    """
    # Ask for confirmation to delete run.
    if not yes:
        confirmation = cli_utils.confirmation(
            f"Are you sure you want to delete pipeline run `{run_name_or_id}`?"
        )
        if not confirmation:
            cli_utils.declare("Pipeline run deletion canceled.")
            return

    # Delete run.
    try:
        Client().delete_pipeline_run(
            name_id_or_prefix=run_name_or_id,
        )
    except KeyError as e:
        cli_utils.error(str(e))
    else:
        cli_utils.declare(f"Deleted pipeline run '{run_name_or_id}'.")

delete_project(project_name_or_id: str) -> None

Delete a project.

Parameters:

Name Type Description Default
project_name_or_id str

The name or ID of the project to delete.

required
Source code in src/zenml/cli/project.py
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
@project.command("delete")
@click.argument("project_name_or_id", type=str, required=True)
def delete_project(project_name_or_id: str) -> None:
    """Delete a project.

    Args:
        project_name_or_id: The name or ID of the project to delete.
    """
    check_zenml_pro_project_availability()
    client = Client()
    with console.status("Deleting project...\n"):
        try:
            client.delete_project(project_name_or_id)
            cli_utils.declare(
                f"Project '{project_name_or_id}' deleted successfully."
            )
        except Exception as e:
            cli_utils.error(str(e))

delete_schedule(schedule_name_or_id: str, yes: bool = False) -> None

Delete a pipeline schedule.

Parameters:

Name Type Description Default
schedule_name_or_id str

The name or ID of the schedule to delete.

required
yes bool

If set, don't ask for confirmation.

False
Source code in src/zenml/cli/pipeline.py
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
@schedule.command("delete", help="Delete a pipeline schedule.")
@click.argument("schedule_name_or_id", type=str, required=True)
@click.option(
    "--yes",
    "-y",
    is_flag=True,
    help="Don't ask for confirmation.",
)
def delete_schedule(schedule_name_or_id: str, yes: bool = False) -> None:
    """Delete a pipeline schedule.

    Args:
        schedule_name_or_id: The name or ID of the schedule to delete.
        yes: If set, don't ask for confirmation.
    """
    if not yes:
        confirmation = cli_utils.confirmation(
            f"Are you sure you want to delete schedule "
            f"`{schedule_name_or_id}`?"
        )
        if not confirmation:
            cli_utils.declare("Schedule deletion canceled.")
            return

    try:
        Client().delete_schedule(name_id_or_prefix=schedule_name_or_id)
    except KeyError as e:
        cli_utils.error(str(e))
    else:
        cli_utils.declare(f"Deleted schedule '{schedule_name_or_id}'.")

delete_secret(name_or_id: str, yes: bool = False) -> None

Delete a secret for a given name or id.

Parameters:

Name Type Description Default
name_or_id str

The name or id of the secret to delete.

required
yes bool

Skip asking for confirmation.

False
Source code in src/zenml/cli/secret.py
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
@secret.command("delete", help="Delete a secret with a given name or id.")
@click.argument(
    "name_or_id",
    type=click.STRING,
)
@click.option(
    "--yes",
    "-y",
    type=click.BOOL,
    default=False,
    is_flag=True,
    help="Skip asking for confirmation.",
)
def delete_secret(name_or_id: str, yes: bool = False) -> None:
    """Delete a secret for a given name or id.

    Args:
        name_or_id: The name or id of the secret to delete.
        yes: Skip asking for confirmation.
    """
    if not yes:
        confirmation_response = confirmation(
            f"This will delete all data associated with the `{name_or_id}` "
            f"secret. Are you sure you want to proceed?"
        )
        if not confirmation_response:
            console.print("Aborting secret deletion...")
            return

    client = Client()

    with console.status(f"Deleting secret `{name_or_id}`..."):
        try:
            client.delete_secret(name_id_or_prefix=name_or_id)
            declare(f"Secret '{name_or_id}' successfully deleted.")
        except KeyError as e:
            error(
                f"Secret with name or id `{name_or_id}` does not exist or "
                f"could not be loaded: {str(e)}."
            )
        except NotImplementedError as e:
            error(f"Centralized secrets management is disabled: {str(e)}")

delete_service_account(service_account_name_or_id: str) -> None

Delete a service account.

Parameters:

Name Type Description Default
service_account_name_or_id str

The name or ID of the service account.

required
Source code in src/zenml/cli/service_accounts.py
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
@service_account.command("delete")
@click.argument("service_account_name_or_id", type=str, required=True)
def delete_service_account(service_account_name_or_id: str) -> None:
    """Delete a service account.

    Args:
        service_account_name_or_id: The name or ID of the service account.
    """
    client = Client()
    try:
        client.delete_service_account(service_account_name_or_id)
    except (KeyError, IllegalOperationError) as err:
        cli_utils.error(str(err))

    cli_utils.declare(
        f"Deleted service account '{service_account_name_or_id}'."
    )

delete_service_connector(name_id_or_prefix: str) -> None

Deletes a service connector.

Parameters:

Name Type Description Default
name_id_or_prefix str

The name of the service connector to delete.

required
Source code in src/zenml/cli/service_connectors.py
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
@service_connector.command(
    "delete",
    help="""Delete a service connector.
""",
)
@click.argument("name_id_or_prefix", type=str)
def delete_service_connector(name_id_or_prefix: str) -> None:
    """Deletes a service connector.

    Args:
        name_id_or_prefix: The name of the service connector to delete.
    """
    client = Client()

    with console.status(
        f"Deleting service connector '{name_id_or_prefix}'...\n"
    ):
        try:
            client.delete_service_connector(
                name_id_or_prefix=name_id_or_prefix,
            )
        except (KeyError, IllegalOperationError) as err:
            cli_utils.error(str(err))
        cli_utils.declare(f"Deleted service connector: {name_id_or_prefix}")

delete_stack(stack_name_or_id: str, yes: bool = False, recursive: bool = False) -> None

Delete a stack.

Parameters:

Name Type Description Default
stack_name_or_id str

Name or id of the stack to delete.

required
yes bool

Stack will be deleted without prompting for confirmation.

False
recursive bool

The stack will be deleted along with the corresponding stack associated with it.

False
Source code in src/zenml/cli/stack.py
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
@stack.command("delete", help="Delete a stack given its name.")
@click.argument("stack_name_or_id", type=str)
@click.option("--yes", "-y", is_flag=True, required=False)
@click.option(
    "--recursive",
    "-r",
    is_flag=True,
    help="Recursively delete all stack components",
)
def delete_stack(
    stack_name_or_id: str, yes: bool = False, recursive: bool = False
) -> None:
    """Delete a stack.

    Args:
        stack_name_or_id: Name or id of the stack to delete.
        yes: Stack will be deleted without prompting for
            confirmation.
        recursive: The stack will be deleted along with the corresponding stack
            associated with it.
    """
    recursive_confirmation = False
    if recursive:
        recursive_confirmation = yes or cli_utils.confirmation(
            "If there are stack components present in another stack, "
            "those stack components will be ignored for removal \n"
            "Do you want to continue ?"
        )

        if not recursive_confirmation:
            cli_utils.declare("Stack deletion canceled.")
            return

    confirmation = (
        recursive_confirmation
        or yes
        or cli_utils.confirmation(
            f"This will delete stack '{stack_name_or_id}'. \n"
            "Are you sure you want to proceed?"
        )
    )

    if not confirmation:
        cli_utils.declare("Stack deletion canceled.")
        return

    with console.status(f"Deleting stack '{stack_name_or_id}'...\n"):
        client = Client()

        if recursive and recursive_confirmation:
            client.delete_stack(stack_name_or_id, recursive=True)
            return

        try:
            client.delete_stack(stack_name_or_id)
        except (KeyError, ValueError, IllegalOperationError) as err:
            cli_utils.error(str(err))
        cli_utils.declare(f"Deleted stack '{stack_name_or_id}'.")

delete_tag(tag_name_or_id: Union[str, UUID], yes: bool = False) -> None

Delete an existing tag.

Parameters:

Name Type Description Default
tag_name_or_id Union[str, UUID]

The ID or name of the tag to delete.

required
yes bool

If set, don't ask for confirmation.

False
Source code in src/zenml/cli/tag.py
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
@tag.command("delete", help="Delete an existing tag.")
@click.argument("tag_name_or_id")
@click.option(
    "--yes",
    "-y",
    is_flag=True,
    help="Don't ask for confirmation.",
)
def delete_tag(
    tag_name_or_id: Union[str, UUID],
    yes: bool = False,
) -> None:
    """Delete an existing tag.

    Args:
        tag_name_or_id: The ID or name of the tag to delete.
        yes: If set, don't ask for confirmation.
    """
    try:
        tagged_count = Client().get_tag(tag_name_or_id).tagged_count
    except (KeyError, ValueError) as e:
        cli_utils.error(str(e))

    if not yes or tagged_count > 0:
        confirmation = cli_utils.confirmation(
            f"Are you sure you want to delete tag '{tag_name_or_id}'?"
            + (
                ""
                if tagged_count == 0
                else f"\n{tagged_count} objects are tagged with it."
            )
        )
        if not confirmation:
            cli_utils.declare("Tag deletion canceled.")
            return

    try:
        Client().delete_tag(
            tag_name_or_id=tag_name_or_id,
        )
    except (KeyError, ValueError) as e:
        cli_utils.error(str(e))
    else:
        cli_utils.declare(f"Tag '{tag_name_or_id}' deleted.")

delete_user(user_name_or_id: str) -> None

Delete a user.

Parameters:

Name Type Description Default
user_name_or_id str

The name or ID of the user to delete.

required
Source code in src/zenml/cli/user_management.py
417
418
419
420
421
422
423
424
425
426
427
428
429
@user.command("delete")
@click.argument("user_name_or_id", type=str, required=True)
def delete_user(user_name_or_id: str) -> None:
    """Delete a user.

    Args:
        user_name_or_id: The name or ID of the user to delete.
    """
    try:
        Client().delete_user(user_name_or_id)
    except (KeyError, IllegalOperationError) as err:
        cli_utils.error(str(err))
    cli_utils.declare(f"Deleted user '{user_name_or_id}'.")

depaginate(list_method: Callable[..., Page[AnyResponse]], **kwargs: Any) -> List[AnyResponse]

Depaginate the results from a client or store method that returns pages.

Parameters:

Name Type Description Default
list_method Callable[..., Page[AnyResponse]]

The list method to depaginate.

required
**kwargs Any

Arguments for the list method.

{}

Returns:

Type Description
List[AnyResponse]

A list of the corresponding Response Models.

Source code in src/zenml/utils/pagination_utils.py
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
def depaginate(
    list_method: Callable[..., Page[AnyResponse]], **kwargs: Any
) -> List[AnyResponse]:
    """Depaginate the results from a client or store method that returns pages.

    Args:
        list_method: The list method to depaginate.
        **kwargs: Arguments for the list method.

    Returns:
        A list of the corresponding Response Models.
    """
    page = list_method(**kwargs)
    items = list(page.items)
    while page.index < page.total_pages:
        kwargs["page"] = page.index + 1
        page = list_method(**kwargs)
        items += list(page.items)

    return items

deploy(ctx: click.Context, provider: str, stack_name: Optional[str] = None, location: Optional[str] = None, set_stack: bool = False) -> None

Deploy and register a fully functional cloud ZenML stack.

Parameters:

Name Type Description Default
ctx Context

The click context.

required
provider str

The cloud provider to deploy the stack to.

required
stack_name Optional[str]

A name for the ZenML stack that gets imported as a result of the recipe deployment.

None
location Optional[str]

The location to deploy the stack to.

None
set_stack bool

Immediately set the deployed stack as active.

False

Raises:

Type Description
Abort

If the user aborts the deployment.

KeyboardInterrupt

If the user interrupts the deployment.

Source code in src/zenml/cli/stack.py
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
@stack.command(
    help="""Deploy a fully functional ZenML stack in one of the cloud providers.

Running this command will initiate an assisted process that will walk you
through automatically provisioning all the cloud infrastructure resources
necessary for a fully functional ZenML stack in the cloud provider of your
choice. A corresponding ZenML stack will also be automatically registered along
with all the necessary components and properly authenticated through service
connectors.
"""
)
@click.option(
    "--provider",
    "-p",
    "provider",
    required=True,
    type=click.Choice(StackDeploymentProvider.values()),
)
@click.option(
    "--name",
    "-n",
    "stack_name",
    type=click.STRING,
    required=False,
    help="Custom string to use as a prefix to generate names for the ZenML "
    "stack, its components service connectors as well as provisioned cloud "
    "infrastructure resources. May only contain alphanumeric characters and "
    "hyphens and have a maximum length of 16 characters.",
    callback=validate_name,
)
@click.option(
    "--location",
    "-l",
    type=click.STRING,
    required=False,
    help="The location to deploy the stack to.",
)
@click.option(
    "--set",
    "set_stack",
    is_flag=True,
    help="Immediately set this stack as active.",
    type=click.BOOL,
)
@click.pass_context
def deploy(
    ctx: click.Context,
    provider: str,
    stack_name: Optional[str] = None,
    location: Optional[str] = None,
    set_stack: bool = False,
) -> None:
    """Deploy and register a fully functional cloud ZenML stack.

    Args:
        ctx: The click context.
        provider: The cloud provider to deploy the stack to.
        stack_name: A name for the ZenML stack that gets imported as a result
            of the recipe deployment.
        location: The location to deploy the stack to.
        set_stack: Immediately set the deployed stack as active.

    Raises:
        Abort: If the user aborts the deployment.
        KeyboardInterrupt: If the user interrupts the deployment.
    """
    stack_name = stack_name or f"zenml-{provider}-stack"

    # Set up the markdown renderer to use the old-school markdown heading
    Markdown.elements.update(
        {
            "heading_open": OldSchoolMarkdownHeading,
        }
    )

    client = Client()
    if client.zen_store.is_local_store():
        cli_utils.error(
            "This feature cannot be used with a local ZenML deployment. "
            "ZenML needs to be accessible from the cloud provider to allow the "
            "stack and its components to be registered automatically. "
            "Please deploy ZenML in a remote environment as described in the "
            "documentation: https://docs.zenml.io/getting-started/deploying-zenml "
            "or use a managed ZenML Pro server instance for quick access to "
            "this feature and more: https://www.zenml.io/pro"
        )

    with track_handler(
        event=AnalyticsEvent.DEPLOY_FULL_STACK,
    ) as analytics_handler:
        analytics_handler.metadata = {
            "provider": provider,
        }

        deployment = client.zen_store.get_stack_deployment_info(
            provider=StackDeploymentProvider(provider),
        )

        if location and location not in deployment.locations.values():
            cli_utils.error(
                f"Invalid location '{location}' for provider '{provider}'. "
                f"Valid locations are: {', '.join(deployment.locations.values())}"
            )

        console.print(
            Markdown(
                f"# {provider.upper()} ZenML Cloud Stack Deployment\n"
                + deployment.description
            )
        )
        console.print(Markdown("## Details\n" + deployment.instructions))

        deployment_config = client.zen_store.get_stack_deployment_config(
            provider=StackDeploymentProvider(provider),
            stack_name=stack_name,
            location=location,
        )

        if deployment_config.instructions:
            console.print(
                Markdown("## Instructions\n" + deployment_config.instructions),
                "\n",
            )

        if deployment_config.configuration:
            console.print(
                deployment_config.configuration,
                no_wrap=True,
                overflow="ignore",
                crop=False,
                style=Style(bgcolor="grey15"),
            )

        if not cli_utils.confirmation(
            "\n\nProceed to continue with the deployment. You will be "
            f"automatically redirected to "
            f"{deployment_config.deployment_url_text} in your browser.",
        ):
            raise click.Abort()

        date_start = utc_now_tz_aware()

        webbrowser.open(deployment_config.deployment_url)
        console.print(
            Markdown(
                f"If your browser did not open automatically, please open "
                f"the following URL into your browser to deploy the stack to "
                f"{provider.upper()}: "
                f"[{deployment_config.deployment_url_text}]"
                f"({deployment_config.deployment_url}).\n\n"
            )
        )

        try:
            cli_utils.declare(
                "\n\nWaiting for the deployment to complete and the stack to be "
                "registered. Press CTRL+C to abort...\n"
            )

            while True:
                deployed_stack = client.zen_store.get_stack_deployment_stack(
                    provider=StackDeploymentProvider(provider),
                    stack_name=stack_name,
                    location=location,
                    date_start=date_start,
                )
                if deployed_stack:
                    break
                time.sleep(10)

            analytics_handler.metadata.update(
                {
                    "stack_id": deployed_stack.stack.id,
                }
            )

        except KeyboardInterrupt:
            cli_utils.declare("Stack deployment aborted.")
            raise

    stack_desc = f"""## Stack successfully registered! 🚀
Stack [{deployed_stack.stack.name}]({get_stack_url(deployed_stack.stack)}):\n"""

    for component_type, components in deployed_stack.stack.components.items():
        if components:
            component = components[0]
            stack_desc += (
                f" * `{component.flavor_name}` {component_type.value}: "
                f"[{component.name}]({get_component_url(component)})\n"
            )

    if deployed_stack.service_connector:
        stack_desc += (
            f" * Service Connector: {deployed_stack.service_connector.name}\n"
        )

    console.print(Markdown(stack_desc))

    follow_up = f"""
## Follow-up

{deployment.post_deploy_instructions}

To use the `{deployed_stack.stack.name}` stack to run pipelines:

* install the required ZenML integrations by running: `zenml integration install {" ".join(deployment.integrations)}`
"""
    if set_stack:
        client.activate_stack(deployed_stack.stack.id)
        follow_up += f"""
* the `{deployed_stack.stack.name}` stack has already been set as active
"""
    else:
        follow_up += f"""
* set the `{deployed_stack.stack.name}` stack as active by running: `zenml stack set {deployed_stack.stack.name}`
"""

    console.print(
        Markdown(follow_up),
    )

describe_api_key(service_account_name_or_id: str, name_or_id: str) -> None

Describe an API key.

Parameters:

Name Type Description Default
service_account_name_or_id str

The name or ID of the service account to which the API key belongs.

required
name_or_id str

The name or ID of the API key to describe.

required
Source code in src/zenml/cli/service_accounts.py
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
@api_key.command("describe", help="Describe an API key.")
@click.argument("name_or_id", type=str, required=True)
@click.pass_obj
def describe_api_key(service_account_name_or_id: str, name_or_id: str) -> None:
    """Describe an API key.

    Args:
        service_account_name_or_id: The name or ID of the service account to
            which the API key belongs.
        name_or_id: The name or ID of the API key to describe.
    """
    with console.status(f"Getting API key `{name_or_id}`...\n"):
        try:
            api_key = Client().get_api_key(
                service_account_name_id_or_prefix=service_account_name_or_id,
                name_id_or_prefix=name_or_id,
            )
        except KeyError as e:
            cli_utils.error(str(e))

        cli_utils.print_pydantic_model(
            title=f"API key '{api_key.name}'",
            model=api_key,
            exclude_columns={
                "key",
            },
        )

describe_authorized_device(id_or_prefix: str) -> None

Fetch an authorized device.

Parameters:

Name Type Description Default
id_or_prefix str

The ID of the authorized device to fetch.

required
Source code in src/zenml/cli/authorized_device.py
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
@authorized_device.command("describe")
@click.argument("id_or_prefix", type=str, required=True)
def describe_authorized_device(id_or_prefix: str) -> None:
    """Fetch an authorized device.

    Args:
        id_or_prefix: The ID of the authorized device to fetch.
    """
    try:
        device = Client().get_authorized_device(
            id_or_prefix=id_or_prefix,
        )
    except KeyError as e:
        cli_utils.error(str(e))

    cli_utils.print_pydantic_model(
        title=f"Authorized device `{device.id}`",
        model=device,
        exclude_columns={"user"},
    )

describe_code_repository(name_id_or_prefix: str) -> None

Describe a code repository.

Parameters:

Name Type Description Default
name_id_or_prefix str

Name, ID or prefix of the code repository.

required
Source code in src/zenml/cli/code_repository.py
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
@code_repository.command("describe", help="Describe a code repository.")
@click.argument(
    "name_id_or_prefix",
    type=str,
    required=True,
)
def describe_code_repository(name_id_or_prefix: str) -> None:
    """Describe a code repository.

    Args:
        name_id_or_prefix: Name, ID or prefix of the code repository.
    """
    client = Client()
    try:
        code_repository = client.get_code_repository(
            name_id_or_prefix=name_id_or_prefix,
        )
    except KeyError as err:
        cli_utils.error(str(err))
    else:
        cli_utils.print_pydantic_model(
            title=f"Code repository '{code_repository.name}'",
            model=code_repository,
        )

describe_project(project_name_or_id: Optional[str] = None) -> None

Get the project.

Parameters:

Name Type Description Default
project_name_or_id Optional[str]

The name or ID of the project to set as active.

None
Source code in src/zenml/cli/project.py
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
@project.command("describe")
@click.argument("project_name_or_id", type=str, required=False)
def describe_project(project_name_or_id: Optional[str] = None) -> None:
    """Get the project.

    Args:
        project_name_or_id: The name or ID of the project to set as active.
    """
    check_zenml_pro_project_availability()
    client = Client()
    if not project_name_or_id:
        active_project = client.active_project
        cli_utils.print_pydantic_models(
            [active_project], exclude_columns=["created", "updated"]
        )
    else:
        try:
            project_ = client.get_project(project_name_or_id)
        except KeyError as err:
            cli_utils.error(str(err))
        else:
            cli_utils.print_pydantic_models(
                [project_], exclude_columns=["created", "updated"]
            )

describe_service_account(service_account_name_or_id: str) -> None

Describe a service account.

Parameters:

Name Type Description Default
service_account_name_or_id str

The name or ID of the service account.

required
Source code in src/zenml/cli/service_accounts.py
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
@service_account.command("describe")
@click.argument("service_account_name_or_id", type=str, required=True)
def describe_service_account(service_account_name_or_id: str) -> None:
    """Describe a service account.

    Args:
        service_account_name_or_id: The name or ID of the service account.
    """
    client = Client()
    try:
        service_account = client.get_service_account(
            service_account_name_or_id
        )
    except KeyError as err:
        cli_utils.error(str(err))
    else:
        cli_utils.print_pydantic_model(
            title=f"Service account '{service_account.name}'",
            model=service_account,
        )

describe_service_connector(name_id_or_prefix: str, show_secrets: bool = False, describe_client: bool = False, resource_type: Optional[str] = None, resource_id: Optional[str] = None) -> None

Prints details about a service connector.

Parameters:

Name Type Description Default
name_id_or_prefix str

Name or id of the service connector to describe.

required
show_secrets bool

Whether to show security sensitive configuration attributes in the terminal.

False
describe_client bool

Fetch and describe a service connector client instead of the base connector if possible.

False
resource_type Optional[str]

Resource type to use when fetching the service connector client.

None
resource_id Optional[str]

Resource ID to use when fetching the service connector client.

None
Source code in src/zenml/cli/service_connectors.py
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
@service_connector.command(
    "describe",
    help="""Show detailed information about a service connector.

Display detailed information about a service connector configuration, or about
a service connector client generated from it to access a specific resource
(explained below).

Service connector clients are connector configurations generated from the
original service connectors that are actually used by clients to access a
specific target resource (e.g. an AWS connector generates a Kubernetes connector
client to access a specific EKS Kubernetes cluster). Unlike main service
connectors, connector clients are not persisted in the database. They have a
limited lifetime and may contain temporary credentials to access the target
resource (e.g. an AWS connector configured with an AWS secret key and IAM role
generates a connector client containing temporary STS credentials).

Asking to see service connector client details is equivalent to asking to see
the final configuration that the client sees, as opposed to the configuration
that was configured by the user. In some cases, they are the same, in others
they are completely different.

To show the details of a service connector client instead of the base connector
use the `--client` flag. If the service connector is configured to provide
access to multiple resources, you also need to use the `--resource-type` and
`--resource-id` flags to specify the scope of the connector client.

Secret configuration attributes are not shown by default. Use the
`-x|--show-secrets` flag to show them.
""",
)
@click.argument(
    "name_id_or_prefix",
    type=str,
    required=True,
)
@click.option(
    "--show-secrets",
    "-x",
    "show_secrets",
    is_flag=True,
    default=False,
    help="Show security sensitive configuration attributes in the terminal.",
    type=click.BOOL,
)
@click.option(
    "--client",
    "-c",
    "describe_client",
    is_flag=True,
    default=False,
    help="Fetch and describe a service connector client instead of the base "
    "connector.",
    type=click.BOOL,
)
@click.option(
    "--resource-type",
    "-r",
    "resource_type",
    help="Resource type to use when fetching the service connector client.",
    required=False,
    type=str,
)
@click.option(
    "--resource-id",
    "-ri",
    "resource_id",
    help="Resource ID to use when fetching the service connector client.",
    required=False,
    type=str,
)
def describe_service_connector(
    name_id_or_prefix: str,
    show_secrets: bool = False,
    describe_client: bool = False,
    resource_type: Optional[str] = None,
    resource_id: Optional[str] = None,
) -> None:
    """Prints details about a service connector.

    Args:
        name_id_or_prefix: Name or id of the service connector to describe.
        show_secrets: Whether to show security sensitive configuration
            attributes in the terminal.
        describe_client: Fetch and describe a service connector client
            instead of the base connector if possible.
        resource_type: Resource type to use when fetching the service connector
            client.
        resource_id: Resource ID to use when fetching the service connector
            client.
    """
    client = Client()

    if resource_type or resource_id:
        describe_client = True

    if describe_client:
        try:
            connector_client = client.get_service_connector_client(
                name_id_or_prefix=name_id_or_prefix,
                resource_type=resource_type,
                resource_id=resource_id,
                verify=True,
            )
        except (
            KeyError,
            ValueError,
            IllegalOperationError,
            NotImplementedError,
            AuthorizationException,
        ) as e:
            resource_type = resource_type or "<unspecified>"
            resource_id = resource_id or "<unspecified>"
            cli_utils.error(
                f"Failed fetching a service connector client for connector "
                f"'{name_id_or_prefix}', resource type '{resource_type}' and "
                f"resource ID '{resource_id}': {e}"
            )

        connector = connector_client.to_response_model(
            user=client.active_user,
        )
    else:
        try:
            connector = client.get_service_connector(
                name_id_or_prefix=name_id_or_prefix,
                load_secrets=True,
            )
        except KeyError as err:
            cli_utils.error(str(err))

    with console.status(f"Describing connector '{connector.name}'..."):
        active_stack = client.active_stack_model
        active_connector_ids: List[UUID] = []
        for components in active_stack.components.values():
            active_connector_ids.extend(
                [
                    component.connector.id
                    for component in components
                    if component.connector
                ]
            )

        cli_utils.print_service_connector_configuration(
            connector=connector,
            active_status=connector.id in active_connector_ids,
            show_secrets=show_secrets,
        )

describe_service_connector_type(type: str, resource_type: Optional[str] = None, auth_method: Optional[str] = None) -> None

Describes a service connector type.

Parameters:

Name Type Description Default
type str

The connector type to describe.

required
resource_type Optional[str]

The resource type to describe.

None
auth_method Optional[str]

The authentication method to describe.

None
Source code in src/zenml/cli/service_connectors.py
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
@service_connector.command(
    "describe-type",
    help="""Describe a service connector type.
""",
)
@click.argument(
    "type",
    type=str,
    required=True,
)
@click.option(
    "--resource-type",
    "-r",
    "resource_type",
    help="Resource type to describe.",
    required=False,
    type=str,
)
@click.option(
    "--auth-method",
    "-a",
    "auth_method",
    help="Authentication method to describe.",
    required=False,
    type=str,
)
def describe_service_connector_type(
    type: str,
    resource_type: Optional[str] = None,
    auth_method: Optional[str] = None,
) -> None:
    """Describes a service connector type.

    Args:
        type: The connector type to describe.
        resource_type: The resource type to describe.
        auth_method: The authentication method to describe.
    """
    client = Client()

    try:
        connector_type = client.get_service_connector_type(type)
    except KeyError:
        cli_utils.error(f"Service connector type '{type}' not found.")

    if resource_type:
        if resource_type not in connector_type.resource_type_dict:
            cli_utils.error(
                f"Resource type '{resource_type}' not found for service "
                f"connector type '{type}'."
            )
        cli_utils.print_service_connector_resource_type(
            connector_type.resource_type_dict[resource_type]
        )
    elif auth_method:
        if auth_method not in connector_type.auth_method_dict:
            cli_utils.error(
                f"Authentication method '{auth_method}' not found for service"
                f" connector type '{type}'."
            )
        cli_utils.print_service_connector_auth_method(
            connector_type.auth_method_dict[auth_method]
        )
    else:
        cli_utils.print_service_connector_type(
            connector_type,
            include_resource_types=False,
            include_auth_methods=False,
        )

describe_stack(stack_name_or_id: Optional[str] = None) -> None

Show details about a named stack or the active stack.

Parameters:

Name Type Description Default
stack_name_or_id Optional[str]

Name of the stack to describe.

None
Source code in src/zenml/cli/stack.py
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
@stack.command(
    "describe",
    help="Show details about the current active stack.",
)
@click.argument(
    "stack_name_or_id",
    type=click.STRING,
    required=False,
)
def describe_stack(stack_name_or_id: Optional[str] = None) -> None:
    """Show details about a named stack or the active stack.

    Args:
        stack_name_or_id: Name of the stack to describe.
    """
    client = Client()

    with console.status("Describing the stack...\n"):
        try:
            stack_: "StackResponse" = client.get_stack(
                name_id_or_prefix=stack_name_or_id
            )
        except KeyError as err:
            cli_utils.error(str(err))

        cli_utils.print_stack_configuration(
            stack=stack_,
            active=stack_.id == client.active_stack_model.id,
        )

    print_model_url(get_stack_url(stack_))

describe_user(user_name_or_id: Optional[str] = None) -> None

Get the user.

Parameters:

Name Type Description Default
user_name_or_id Optional[str]

The name or ID of the user.

None
Source code in src/zenml/cli/user_management.py
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
@user.command("describe")
@click.argument("user_name_or_id", type=str, required=False)
def describe_user(user_name_or_id: Optional[str] = None) -> None:
    """Get the user.

    Args:
        user_name_or_id: The name or ID of the user.
    """
    client = Client()
    if not user_name_or_id:
        active_user = client.active_user
        cli_utils.print_pydantic_models(
            [active_user],
            exclude_columns=[
                "created",
                "updated",
                "email",
                "email_opted_in",
                "activation_token",
            ],
        )
    else:
        try:
            user = client.get_user(user_name_or_id)
        except KeyError as err:
            cli_utils.error(str(err))
        else:
            cli_utils.print_pydantic_models(
                [user],
                exclude_columns=[
                    "created",
                    "updated",
                    "email",
                    "email_opted_in",
                    "activation_token",
                ],
            )

disconnect_server() -> None

Disconnect from a ZenML server.

Source code in src/zenml/cli/server.py
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
@cli.command(
    "disconnect",
    help="""Disconnect from a ZenML server.

DEPRECATED: Please use `zenml logout` instead.
""",
)
def disconnect_server() -> None:
    """Disconnect from a ZenML server."""
    cli_utils.warning(
        "The `zenml disconnect` command is deprecated and will be removed in a "
        "future release. Please use the `zenml logout` command instead."
    )

    # Calling the `zenml logout` command
    cli_utils.declare("Calling `zenml logout`...")
    logout.callback()  # type: ignore[misc]

down() -> None

Shut down the local ZenML dashboard.

Source code in src/zenml/cli/server.py
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
@cli.command(
    "down",
    help="""Shut down the local ZenML dashboard.

DEPRECATED: Please use `zenml logout local` instead.
""",
)
def down() -> None:
    """Shut down the local ZenML dashboard."""
    cli_utils.warning(
        "The `zenml down` command is deprecated and will be removed in a "
        "future release. Please use the `zenml logout --local` command instead."
    )

    # Calling the `zenml logout` command
    cli_utils.declare("Calling `zenml logout --local`...")
    logout.callback(  # type: ignore[misc]
        local=True
    )

email_opt_int(opted_in: bool, email: Optional[str], source: str) -> None

Track the event of the users response to the email prompt, identify them.

Parameters:

Name Type Description Default
opted_in bool

Did the user decide to opt-in

required
email Optional[str]

The email the user optionally provided

required
source str

Location when the user replied ["zenml go", "zenml server"]

required
Source code in src/zenml/analytics/utils.py
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
def email_opt_int(opted_in: bool, email: Optional[str], source: str) -> None:
    """Track the event of the users response to the email prompt, identify them.

    Args:
        opted_in: Did the user decide to opt-in
        email: The email the user optionally provided
        source: Location when the user replied ["zenml go", "zenml server"]
    """
    # If the user opted in, associate email with the anonymous distinct ID
    if opted_in and email is not None and email != "":
        identify(metadata={"email": email, "source": source})

    # Track that the user answered the prompt
    track(
        AnalyticsEvent.OPT_IN_OUT_EMAIL,
        {"opted_in": opted_in, "source": source},
    )

error(text: str) -> NoReturn

Echo an error string on the CLI.

Parameters:

Name Type Description Default
text str

Input text string.

required

Raises:

Type Description
ClickException

when called.

Source code in src/zenml/cli/utils.py
158
159
160
161
162
163
164
165
166
167
def error(text: str) -> NoReturn:
    """Echo an error string on the CLI.

    Args:
        text: Input text string.

    Raises:
        ClickException: when called.
    """
    raise click.ClickException(message=click.style(text, fg="red", bold=True))

expand_argument_value_from_file(name: str, value: str) -> str

Expands the value of an argument pointing to a file into the contents of that file.

Parameters:

Name Type Description Default
name str

Name of the argument. Used solely for logging purposes.

required
value str

The value of the argument. This is to be interpreted as a filename if it begins with a @ character.

required

Returns:

Type Description
str

The argument value expanded into the contents of the file, if the

str

argument value begins with a @ character. Otherwise, the argument

str

value is returned unchanged.

Raises:

Type Description
ValueError

If the argument value points to a file that doesn't exist, that cannot be read, or is too long(i.e. exceeds MAX_ARGUMENT_VALUE_SIZE bytes).

Source code in src/zenml/cli/utils.py
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
def expand_argument_value_from_file(name: str, value: str) -> str:
    """Expands the value of an argument pointing to a file into the contents of that file.

    Args:
        name: Name of the argument. Used solely for logging purposes.
        value: The value of the argument. This is to be interpreted as a
            filename if it begins with a `@` character.

    Returns:
        The argument value expanded into the contents of the file, if the
        argument value begins with a `@` character. Otherwise, the argument
        value is returned unchanged.

    Raises:
        ValueError: If the argument value points to a file that doesn't exist,
            that cannot be read, or is too long(i.e. exceeds
            `MAX_ARGUMENT_VALUE_SIZE` bytes).
    """
    if value.startswith("@@"):
        return value[1:]
    if not value.startswith("@"):
        return value
    filename = os.path.abspath(os.path.expanduser(value[1:]))
    logger.info(
        f"Expanding argument value `{name}` to contents of file `{filename}`."
    )
    if not os.path.isfile(filename):
        raise ValueError(
            f"Could not load argument '{name}' value: file "
            f"'{filename}' does not exist or is not readable."
        )
    try:
        if os.path.getsize(filename) > MAX_ARGUMENT_VALUE_SIZE:
            raise ValueError(
                f"Could not load argument '{name}' value: file "
                f"'{filename}' is too large (max size is "
                f"{MAX_ARGUMENT_VALUE_SIZE} bytes)."
            )

        with open(filename, "r") as f:
            return f.read()
    except OSError as e:
        raise ValueError(
            f"Could not load argument '{name}' value: file "
            f"'{filename}' could not be accessed: {str(e)}"
        )

export_requirements(stack_name_or_id: Optional[str] = None, output_file: Optional[str] = None, overwrite: bool = False) -> None

Exports stack requirements so they can be installed using pip.

Parameters:

Name Type Description Default
stack_name_or_id Optional[str]

Stack name or ID. If not given, the active stack will be used.

None
output_file Optional[str]

Optional path to the requirements output file.

None
overwrite bool

Overwrite the output file if it already exists. This option is only valid if the output file is provided.

False
Source code in src/zenml/cli/stack.py
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
@stack.command(
    name="export-requirements", help="Export the stack requirements."
)
@click.argument(
    "stack_name_or_id",
    type=click.STRING,
    required=False,
)
@click.option(
    "--output-file",
    "-o",
    "output_file",
    type=str,
    required=False,
    help="File to which to export the stack requirements. If not "
    "provided, the requirements will be printed to stdout instead.",
)
@click.option(
    "--overwrite",
    "-ov",
    "overwrite",
    type=bool,
    required=False,
    is_flag=True,
    help="Overwrite the output file if it already exists. This option is "
    "only valid if the output file is provided.",
)
def export_requirements(
    stack_name_or_id: Optional[str] = None,
    output_file: Optional[str] = None,
    overwrite: bool = False,
) -> None:
    """Exports stack requirements so they can be installed using pip.

    Args:
        stack_name_or_id: Stack name or ID. If not given, the active stack will
            be used.
        output_file: Optional path to the requirements output file.
        overwrite: Overwrite the output file if it already exists. This option
            is only valid if the output file is provided.
    """
    try:
        stack_model: "StackResponse" = Client().get_stack(
            name_id_or_prefix=stack_name_or_id
        )
    except KeyError as err:
        cli_utils.error(str(err))

    requirements, _ = requirements_utils.get_requirements_for_stack(
        stack_model
    )

    if not requirements:
        cli_utils.declare(f"Stack `{stack_model.name}` has no requirements.")
        return

    if output_file:
        try:
            with open(output_file, "x") as f:
                f.write("\n".join(requirements))
        except FileExistsError:
            if overwrite or cli_utils.confirmation(
                "A file already exists at the specified path. "
                "Would you like to overwrite it?"
            ):
                with open(output_file, "w") as f:
                    f.write("\n".join(requirements))
        cli_utils.declare(
            f"Requirements for stack `{stack_model.name}` exported to {output_file}."
        )
    else:
        click.echo(" ".join(requirements), nl=False)

export_secret(name_id_or_prefix: str, private: Optional[bool] = None, filename: Optional[str] = None) -> None

Export a secret as a YAML file.

The resulting YAML file can then be imported as a new secret using the zenml secret create <new_secret_name> -v @<filename> command.

Parameters:

Name Type Description Default
name_id_or_prefix str

The name of the secret to export.

required
private Optional[bool]

Private status of the secret to export.

None
filename Optional[str]

The name of the file to export the secret to.

None
Source code in src/zenml/cli/secret.py
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
@secret.command("export", help="Export a secret as a YAML file.")
@click.argument(
    "name_id_or_prefix",
    type=click.STRING,
)
@click.option(
    "--private",
    "-p",
    "private",
    type=click.BOOL,
    required=False,
    help="Use this flag to explicitly fetch a private secret or a public secret.",
)
@click.option(
    "--filename",
    "-f",
    type=click.STRING,
    default=None,
    help=(
        "The name of the file to export the secret to. Defaults to "
        "<secret_name>.yaml."
    ),
)
def export_secret(
    name_id_or_prefix: str,
    private: Optional[bool] = None,
    filename: Optional[str] = None,
) -> None:
    """Export a secret as a YAML file.

    The resulting YAML file can then be imported as a new secret using the
    `zenml secret create <new_secret_name> -v @<filename>` command.

    Args:
        name_id_or_prefix: The name of the secret to export.
        private: Private status of the secret to export.
        filename: The name of the file to export the secret to.
    """
    from zenml.utils.yaml_utils import write_yaml

    secret = _get_secret(name_id_or_prefix=name_id_or_prefix, private=private)
    if not secret.secret_values:
        warning(f"Secret with name `{name_id_or_prefix}` is empty.")
        return

    filename = filename or f"{secret.name}.yaml"
    write_yaml(filename, secret.secret_values)
    declare(f"Secret '{secret.name}' successfully exported to '{filename}'.")

export_stack(stack_name_or_id: Optional[str] = None, filename: Optional[str] = None) -> None

Export a stack to YAML.

Parameters:

Name Type Description Default
stack_name_or_id Optional[str]

The name of the stack to export.

None
filename Optional[str]

The filename to export the stack to.

None
Source code in src/zenml/cli/stack.py
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
@stack.command("export", help="Exports a stack to a YAML file.")
@click.argument("stack_name_or_id", type=str, required=False)
@click.argument("filename", type=str, required=False)
def export_stack(
    stack_name_or_id: Optional[str] = None,
    filename: Optional[str] = None,
) -> None:
    """Export a stack to YAML.

    Args:
        stack_name_or_id: The name of the stack to export.
        filename: The filename to export the stack to.
    """
    # Get configuration of given stack
    client = Client()
    try:
        stack_to_export = client.get_stack(name_id_or_prefix=stack_name_or_id)
    except KeyError as err:
        cli_utils.error(str(err))

    # write zenml version and stack dict to YAML
    yaml_data = stack_to_export.to_yaml()
    yaml_data["zenml_version"] = zenml.__version__

    if filename is None:
        filename = stack_to_export.name + ".yaml"
    write_yaml(filename, yaml_data)

    cli_utils.declare(
        f"Exported stack '{stack_to_export.name}' to file '{filename}'."
    )

format_integration_list(integrations: List[Tuple[str, Type[Integration]]]) -> List[Dict[str, str]]

Formats a list of integrations into a List of Dicts.

This list of dicts can then be printed in a table style using cli_utils.print_table.

Parameters:

Name Type Description Default
integrations List[Tuple[str, Type[Integration]]]

List of tuples containing the name of the integration and the integration metadata.

required

Returns:

Type Description
List[Dict[str, str]]

List of Dicts containing the name of the integration and the integration

Source code in src/zenml/cli/utils.py
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
def format_integration_list(
    integrations: List[Tuple[str, Type["Integration"]]],
) -> List[Dict[str, str]]:
    """Formats a list of integrations into a List of Dicts.

    This list of dicts can then be printed in a table style using
    cli_utils.print_table.

    Args:
        integrations: List of tuples containing the name of the integration and
            the integration metadata.

    Returns:
        List of Dicts containing the name of the integration and the integration
    """
    list_of_dicts = []
    for name, integration_impl in integrations:
        is_installed = integration_impl.check_installation()
        list_of_dicts.append(
            {
                "INSTALLED": ":white_check_mark:" if is_installed else ":x:",
                "INTEGRATION": name,
                "REQUIRED_PACKAGES": ", ".join(
                    integration_impl.get_requirements()
                ),
            }
        )
    return list_of_dicts

generate_stack_component_connect_command(component_type: StackComponentType) -> Callable[[str, str], None]

Generates a connect command for the specific stack component type.

Parameters:

Name Type Description Default
component_type StackComponentType

Type of the component to generate the command for.

required

Returns:

Type Description
Callable[[str, str], None]

A function that can be used as a click command.

Source code in src/zenml/cli/stack_components.py
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
def generate_stack_component_connect_command(
    component_type: StackComponentType,
) -> Callable[[str, str], None]:
    """Generates a `connect` command for the specific stack component type.

    Args:
        component_type: Type of the component to generate the command for.

    Returns:
        A function that can be used as a `click` command.
    """
    _component_display_name(component_type)

    @click.argument(
        "name_id_or_prefix",
        type=str,
        required=False,
    )
    @click.option(
        "--connector",
        "-c",
        "connector",
        help="The name, ID or prefix of the connector to use.",
        required=False,
        type=str,
    )
    @click.option(
        "--resource-id",
        "-r",
        "resource_id",
        help="The resource ID to use with the connector. Only required for "
        "multi-instance connectors that are not already configured with a "
        "particular resource ID.",
        required=False,
        type=str,
    )
    @click.option(
        "--interactive",
        "-i",
        "interactive",
        is_flag=True,
        default=False,
        help="Configure a service connector resource interactively.",
        type=click.BOOL,
    )
    @click.option(
        "--no-verify",
        "no_verify",
        is_flag=True,
        default=False,
        help="Skip verification of the connector resource.",
        type=click.BOOL,
    )
    def connect_stack_component_command(
        name_id_or_prefix: Optional[str],
        connector: Optional[str] = None,
        resource_id: Optional[str] = None,
        interactive: bool = False,
        no_verify: bool = False,
    ) -> None:
        """Connect the stack component to a resource through a service connector.

        Args:
            name_id_or_prefix: The name of the stack component to connect.
            connector: The name, ID or prefix of the connector to use.
            resource_id: The resource ID to use connect to. Only
                required for multi-instance connectors that are not already
                configured with a particular resource ID.
            interactive: Configure a service connector resource interactively.
            no_verify: Do not verify whether the resource is accessible.
        """
        connect_stack_component_with_service_connector(
            component_type=component_type,
            name_id_or_prefix=name_id_or_prefix,
            connector=connector,
            resource_id=resource_id,
            interactive=interactive,
            no_verify=no_verify,
        )

    return connect_stack_component_command

generate_stack_component_copy_command(component_type: StackComponentType) -> Callable[[str, str], None]

Generates a copy command for the specific stack component type.

Parameters:

Name Type Description Default
component_type StackComponentType

Type of the component to generate the command for.

required

Returns:

Type Description
Callable[[str, str], None]

A function that can be used as a click command.

Source code in src/zenml/cli/stack_components.py
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
def generate_stack_component_copy_command(
    component_type: StackComponentType,
) -> Callable[[str, str], None]:
    """Generates a `copy` command for the specific stack component type.

    Args:
        component_type: Type of the component to generate the command for.

    Returns:
        A function that can be used as a `click` command.
    """
    display_name = _component_display_name(component_type)

    @click.argument(
        "source_component_name_id_or_prefix", type=str, required=True
    )
    @click.argument("target_component", type=str, required=True)
    def copy_stack_component_command(
        source_component_name_id_or_prefix: str,
        target_component: str,
    ) -> None:
        """Copies a stack component.

        Args:
            source_component_name_id_or_prefix: Name or id prefix of the
                                         component to copy.
            target_component: Name of the copied component.
        """
        client = Client()

        with console.status(
            f"Copying {display_name} "
            f"`{source_component_name_id_or_prefix}`..\n"
        ):
            try:
                component_to_copy = client.get_stack_component(
                    name_id_or_prefix=source_component_name_id_or_prefix,
                    component_type=component_type,
                )
            except KeyError as err:
                cli_utils.error(str(err))

            copied_component = client.create_stack_component(
                name=target_component,
                flavor=component_to_copy.flavor_name,
                component_type=component_to_copy.type,
                configuration=component_to_copy.configuration,
                labels=component_to_copy.labels,
            )
            print_model_url(get_component_url(copied_component))

    return copy_stack_component_command

generate_stack_component_delete_command(component_type: StackComponentType) -> Callable[[str], None]

Generates a delete command for the specific stack component type.

Parameters:

Name Type Description Default
component_type StackComponentType

Type of the component to generate the command for.

required

Returns:

Type Description
Callable[[str], None]

A function that can be used as a click command.

Source code in src/zenml/cli/stack_components.py
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
def generate_stack_component_delete_command(
    component_type: StackComponentType,
) -> Callable[[str], None]:
    """Generates a `delete` command for the specific stack component type.

    Args:
        component_type: Type of the component to generate the command for.

    Returns:
        A function that can be used as a `click` command.
    """
    display_name = _component_display_name(component_type)

    @click.argument("name_id_or_prefix", type=str)
    def delete_stack_component_command(name_id_or_prefix: str) -> None:
        """Deletes a stack component.

        Args:
            name_id_or_prefix: The name of the stack component to delete.
        """
        client = Client()

        with console.status(
            f"Deleting {display_name} '{name_id_or_prefix}'...\n"
        ):
            try:
                client.delete_stack_component(
                    name_id_or_prefix=name_id_or_prefix,
                    component_type=component_type,
                )
            except (KeyError, IllegalOperationError) as err:
                cli_utils.error(str(err))
            cli_utils.declare(f"Deleted {display_name}: {name_id_or_prefix}")

    return delete_stack_component_command

generate_stack_component_describe_command(component_type: StackComponentType) -> Callable[[str], None]

Generates a describe command for the specific stack component type.

Parameters:

Name Type Description Default
component_type StackComponentType

Type of the component to generate the command for.

required

Returns:

Type Description
Callable[[str], None]

A function that can be used as a click command.

Source code in src/zenml/cli/stack_components.py
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
def generate_stack_component_describe_command(
    component_type: StackComponentType,
) -> Callable[[str], None]:
    """Generates a `describe` command for the specific stack component type.

    Args:
        component_type: Type of the component to generate the command for.

    Returns:
        A function that can be used as a `click` command.
    """

    @click.argument(
        "name_id_or_prefix",
        type=str,
        required=False,
    )
    def describe_stack_component_command(name_id_or_prefix: str) -> None:
        """Prints details about the active/specified component.

        Args:
            name_id_or_prefix: Name or id of the component to describe.
        """
        client = Client()
        try:
            component_ = client.get_stack_component(
                name_id_or_prefix=name_id_or_prefix,
                component_type=component_type,
            )
        except KeyError as err:
            cli_utils.error(str(err))

        with console.status(f"Describing component '{component_.name}'..."):
            active_component_id = None
            active_components = client.active_stack_model.components.get(
                component_type, None
            )
            if active_components:
                active_component_id = active_components[0].id

            if component_.connector:
                connector_requirements = (
                    component_.flavor.connector_requirements
                )
            else:
                connector_requirements = None

            cli_utils.print_stack_component_configuration(
                component=component_,
                active_status=component_.id == active_component_id,
                connector_requirements=connector_requirements,
            )

            print_model_url(get_component_url(component_))

    return describe_stack_component_command

generate_stack_component_disconnect_command(component_type: StackComponentType) -> Callable[[str], None]

Generates a disconnect command for the specific stack component type.

Parameters:

Name Type Description Default
component_type StackComponentType

Type of the component to generate the command for.

required

Returns:

Type Description
Callable[[str], None]

A function that can be used as a click command.

Source code in src/zenml/cli/stack_components.py
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
def generate_stack_component_disconnect_command(
    component_type: StackComponentType,
) -> Callable[[str], None]:
    """Generates a `disconnect` command for the specific stack component type.

    Args:
        component_type: Type of the component to generate the command for.

    Returns:
        A function that can be used as a `click` command.
    """
    display_name = _component_display_name(component_type)

    @click.argument(
        "name_id_or_prefix",
        type=str,
        required=True,
    )
    def disconnect_stack_component_command(name_id_or_prefix: str) -> None:
        """Disconnect a stack component from a service connector.

        Args:
            name_id_or_prefix: The name of the stack component to disconnect.
        """
        client = Client()

        with console.status(
            f"Disconnecting service-connector from {display_name} '{name_id_or_prefix}'...\n"
        ):
            try:
                updated_component = client.update_stack_component(
                    name_id_or_prefix=name_id_or_prefix,
                    component_type=component_type,
                    disconnect=True,
                )
            except (KeyError, IllegalOperationError) as err:
                cli_utils.error(str(err))

            cli_utils.declare(
                f"Successfully disconnected the service-connector from {display_name} `{name_id_or_prefix}`."
            )
            print_model_url(get_component_url(updated_component))

    return disconnect_stack_component_command

generate_stack_component_explain_command(component_type: StackComponentType) -> Callable[[], None]

Generates an explain command for the specific stack component type.

Parameters:

Name Type Description Default
component_type StackComponentType

Type of the component to generate the command for.

required

Returns:

Type Description
Callable[[], None]

A function that can be used as a click command.

Source code in src/zenml/cli/stack_components.py
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
def generate_stack_component_explain_command(
    component_type: StackComponentType,
) -> Callable[[], None]:
    """Generates an `explain` command for the specific stack component type.

    Args:
        component_type: Type of the component to generate the command for.

    Returns:
        A function that can be used as a `click` command.
    """

    def explain_stack_components_command() -> None:
        """Explains the concept of the stack component."""
        component_module = import_module(f"zenml.{component_type.plural}")

        if component_module.__doc__ is not None:
            md = Markdown(component_module.__doc__)
            console.print(md)
        else:
            console.print(
                "The explain subcommand is yet not available for "
                "this stack component. For more information, you can "
                "visit our docs page: https://docs.zenml.io/ and "
                "stay tuned for future releases."
            )

    return explain_stack_components_command

generate_stack_component_flavor_delete_command(component_type: StackComponentType) -> Callable[[str], None]

Generates a delete command for a single flavor of a component.

Parameters:

Name Type Description Default
component_type StackComponentType

Type of the component to generate the command for.

required

Returns:

Type Description
Callable[[str], None]

A function that can be used as a click command.

Source code in src/zenml/cli/stack_components.py
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
def generate_stack_component_flavor_delete_command(
    component_type: StackComponentType,
) -> Callable[[str], None]:
    """Generates a `delete` command for a single flavor of a component.

    Args:
        component_type: Type of the component to generate the command for.

    Returns:
        A function that can be used as a `click` command.
    """
    display_name = _component_display_name(component_type)

    @click.argument(
        "name_or_id",
        type=str,
        required=True,
    )
    def delete_stack_component_flavor_command(name_or_id: str) -> None:
        """Deletes a flavor.

        Args:
            name_or_id: The name of the flavor.
        """
        client = Client()

        with console.status(
            f"Deleting a {display_name} flavor: {name_or_id}`...\n"
        ):
            client.delete_flavor(name_or_id)

            cli_utils.declare(f"Successfully deleted flavor '{name_or_id}'.")

    return delete_stack_component_flavor_command

generate_stack_component_flavor_describe_command(component_type: StackComponentType) -> Callable[[str], None]

Generates a describe command for a single flavor of a component.

Parameters:

Name Type Description Default
component_type StackComponentType

Type of the component to generate the command for.

required

Returns:

Type Description
Callable[[str], None]

A function that can be used as a click command.

Source code in src/zenml/cli/stack_components.py
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
def generate_stack_component_flavor_describe_command(
    component_type: StackComponentType,
) -> Callable[[str], None]:
    """Generates a `describe` command for a single flavor of a component.

    Args:
        component_type: Type of the component to generate the command for.

    Returns:
        A function that can be used as a `click` command.
    """
    display_name = _component_display_name(component_type)

    @click.argument(
        "name",
        type=str,
        required=True,
    )
    def describe_stack_component_flavor_command(name: str) -> None:
        """Describes a flavor based on its config schema.

        Args:
            name: The name of the flavor.
        """
        client = Client()

        with console.status(f"Describing {display_name} flavor: {name}`...\n"):
            flavor_model = client.get_flavor_by_name_and_type(
                name=name, component_type=component_type
            )

            cli_utils.describe_pydantic_object(flavor_model.config_schema)
            resources = flavor_model.connector_requirements
            if resources:
                resources_str = f"a '{resources.resource_type}' resource"
                cli_args = f"--resource-type {resources.resource_type}"
                if resources.connector_type:
                    resources_str += (
                        f" provided by a '{resources.connector_type}' "
                        "connector"
                    )
                    cli_args += f"--connector-type {resources.connector_type}"

                cli_utils.declare(
                    f"This flavor supports connecting to external resources "
                    f"with a Service Connector. It requires {resources_str}. "
                    "You can get a list of all available connectors and the "
                    "compatible resources that they can access by running:\n\n"
                    f"'zenml service-connector list-resources {cli_args}'\n"
                    "If no compatible Service Connectors are yet registered, "
                    "you can can register a new one by running:\n\n"
                    f"'zenml service-connector register -i'"
                )
            else:
                cli_utils.declare(
                    "This flavor does not support connecting to external "
                    "resources with a Service Connector."
                )

    return describe_stack_component_flavor_command

generate_stack_component_flavor_list_command(component_type: StackComponentType) -> Callable[[], None]

Generates a list command for the flavors of a stack component.

Parameters:

Name Type Description Default
component_type StackComponentType

Type of the component to generate the command for.

required

Returns:

Type Description
Callable[[], None]

A function that can be used as a click command.

Source code in src/zenml/cli/stack_components.py
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
def generate_stack_component_flavor_list_command(
    component_type: StackComponentType,
) -> Callable[[], None]:
    """Generates a `list` command for the flavors of a stack component.

    Args:
        component_type: Type of the component to generate the command for.

    Returns:
        A function that can be used as a `click` command.
    """
    display_name = _component_display_name(component_type)

    def list_stack_component_flavor_command() -> None:
        """Lists the flavors for a single type of stack component."""
        client = Client()

        with console.status(f"Listing {display_name} flavors`...\n"):
            flavors = client.get_flavors_by_type(component_type=component_type)

            cli_utils.print_flavor_list(flavors=flavors)
            cli_utils.print_page_info(flavors)

    return list_stack_component_flavor_command

generate_stack_component_flavor_register_command(component_type: StackComponentType) -> Callable[[str], None]

Generates a register command for the flavors of a stack component.

Parameters:

Name Type Description Default
component_type StackComponentType

Type of the component to generate the command for.

required

Returns:

Type Description
Callable[[str], None]

A function that can be used as a click command.

Source code in src/zenml/cli/stack_components.py
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
def generate_stack_component_flavor_register_command(
    component_type: StackComponentType,
) -> Callable[[str], None]:
    """Generates a `register` command for the flavors of a stack component.

    Args:
        component_type: Type of the component to generate the command for.

    Returns:
        A function that can be used as a `click` command.
    """
    command_name = component_type.value.replace("_", "-")
    display_name = _component_display_name(component_type)

    @click.argument(
        "source",
        type=str,
        required=True,
    )
    def register_stack_component_flavor_command(source: str) -> None:
        """Adds a flavor for a stack component type.

        Example:
            Let's say you create an artifact store flavor class `MyArtifactStoreFlavor`
            in the file path `flavors/my_flavor.py`. You would register it as:

            ```shell
            zenml artifact-store flavor register flavors.my_flavor.MyArtifactStoreFlavor
            ```

        Args:
            source: The source path of the flavor class in dot notation format.
        """
        client = Client()

        if not client.root:
            cli_utils.warning(
                f"You're running the `zenml {command_name} flavor register` "
                "command without a ZenML repository. Your current working "
                "directory will be used as the source root relative to which "
                "the `source` argument is expected. To silence this warning, "
                "run `zenml init` at your source code root."
            )

        with console.status(f"Registering a new {display_name} flavor`...\n"):
            try:
                # Register the new model
                new_flavor = client.create_flavor(
                    source=source,
                    component_type=component_type,
                )
            except ValueError as e:
                source_root = source_utils.get_source_root()

                cli_utils.error(
                    f"Flavor registration failed! ZenML tried loading the "
                    f"module `{source}` from path `{source_root}`. If this is "
                    "not what you expect, then please ensure you have run "
                    "`zenml init` at the root of your repository.\n\n"
                    f"Original exception: {str(e)}"
                )

            cli_utils.declare(
                f"Successfully registered new flavor '{new_flavor.name}' "
                f"for stack component '{new_flavor.type}'."
            )

    return register_stack_component_flavor_command

generate_stack_component_get_command(component_type: StackComponentType) -> Callable[[], None]

Generates a get command for the specific stack component type.

Parameters:

Name Type Description Default
component_type StackComponentType

Type of the component to generate the command for.

required

Returns:

Type Description
Callable[[], None]

A function that can be used as a click command.

Source code in src/zenml/cli/stack_components.py
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
def generate_stack_component_get_command(
    component_type: StackComponentType,
) -> Callable[[], None]:
    """Generates a `get` command for the specific stack component type.

    Args:
        component_type: Type of the component to generate the command for.

    Returns:
        A function that can be used as a `click` command.
    """

    def get_stack_component_command() -> None:
        """Prints the name of the active component."""
        client = Client()
        display_name = _component_display_name(component_type)

        with console.status(f"Getting the active `{display_name}`...\n"):
            active_stack = client.active_stack_model
            components = active_stack.components.get(component_type, None)

            if components:
                cli_utils.declare(
                    f"Active {display_name}: '{components[0].name}'"
                )
                print_model_url(get_component_url(components[0]))
            else:
                cli_utils.warning(
                    f"No {display_name} set for active stack "
                    f"('{active_stack.name}')."
                )

    return get_stack_component_command

generate_stack_component_list_command(component_type: StackComponentType) -> Callable[..., None]

Generates a list command for the specific stack component type.

Parameters:

Name Type Description Default
component_type StackComponentType

Type of the component to generate the command for.

required

Returns:

Type Description
Callable[..., None]

A function that can be used as a click command.

Source code in src/zenml/cli/stack_components.py
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
def generate_stack_component_list_command(
    component_type: StackComponentType,
) -> Callable[..., None]:
    """Generates a `list` command for the specific stack component type.

    Args:
        component_type: Type of the component to generate the command for.

    Returns:
        A function that can be used as a `click` command.
    """

    @list_options(ComponentFilter)
    @click.pass_context
    def list_stack_components_command(
        ctx: click.Context, /, **kwargs: Any
    ) -> None:
        """Prints a table of stack components.

        Args:
            ctx: The click context object
            kwargs: Keyword arguments to filter the components.
        """
        client = Client()
        with console.status(f"Listing {component_type.plural}..."):
            kwargs["type"] = component_type
            components = client.list_stack_components(**kwargs)
            if not components:
                cli_utils.declare("No components found for the given filters.")
                return

            cli_utils.print_components_table(
                client=client,
                component_type=component_type,
                components=components.items,
                show_active=not is_sorted_or_filtered(ctx),
            )
            print_page_info(components)

    return list_stack_components_command

generate_stack_component_logs_command(component_type: StackComponentType) -> Callable[[str, bool], None]

Generates a logs command for the specific stack component type.

Parameters:

Name Type Description Default
component_type StackComponentType

Type of the component to generate the command for.

required

Returns:

Type Description
Callable[[str, bool], None]

A function that can be used as a click command.

Source code in src/zenml/cli/stack_components.py
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
def generate_stack_component_logs_command(
    component_type: StackComponentType,
) -> Callable[[str, bool], None]:
    """Generates a `logs` command for the specific stack component type.

    Args:
        component_type: Type of the component to generate the command for.

    Returns:
        A function that can be used as a `click` command.
    """
    display_name = _component_display_name(component_type)

    @click.argument("name_id_or_prefix", type=str, required=False)
    @click.option(
        "--follow",
        "-f",
        is_flag=True,
        help="Follow the log file instead of just displaying the current logs.",
    )
    def stack_component_logs_command(
        name_id_or_prefix: str, follow: bool = False
    ) -> None:
        """Displays stack component logs.

        Args:
            name_id_or_prefix: The name of the stack component to display logs
                for.
            follow: Follow the log file instead of just displaying the current
                logs.
        """
        client = Client()

        with console.status(
            f"Fetching the logs for the {display_name} "
            f"'{name_id_or_prefix}'...\n"
        ):
            try:
                component_model = client.get_stack_component(
                    name_id_or_prefix=name_id_or_prefix,
                    component_type=component_type,
                )
            except KeyError as err:
                cli_utils.error(str(err))

            from zenml.stack import StackComponent

            component = StackComponent.from_model(
                component_model=component_model
            )
            log_file = component.log_file

            if not log_file or not fileio.exists(log_file):
                cli_utils.warning(
                    f"Unable to find log file for {display_name} "
                    f"'{name_id_or_prefix}'."
                )
                return

        if not log_file or not fileio.exists(log_file):
            cli_utils.warning(
                f"Unable to find log file for {display_name} "
                f"'{component.name}'."
            )
            return

        if follow:
            try:
                with open(log_file, "r") as f:
                    # seek to the end of the file
                    f.seek(0, 2)

                    while True:
                        line = f.readline()
                        if not line:
                            time.sleep(0.1)
                            continue
                        line = line.rstrip("\n")
                        click.echo(line)
            except KeyboardInterrupt:
                cli_utils.declare(f"Stopped following {display_name} logs.")
        else:
            with open(log_file, "r") as f:
                click.echo(f.read())

    return stack_component_logs_command

generate_stack_component_register_command(component_type: StackComponentType) -> Callable[[str, str, List[str]], None]

Generates a register command for the specific stack component type.

Parameters:

Name Type Description Default
component_type StackComponentType

Type of the component to generate the command for.

required

Returns:

Type Description
Callable[[str, str, List[str]], None]

A function that can be used as a click command.

Source code in src/zenml/cli/stack_components.py
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
def generate_stack_component_register_command(
    component_type: StackComponentType,
) -> Callable[[str, str, List[str]], None]:
    """Generates a `register` command for the specific stack component type.

    Args:
        component_type: Type of the component to generate the command for.

    Returns:
        A function that can be used as a `click` command.
    """
    display_name = _component_display_name(component_type)

    @click.argument(
        "name",
        type=str,
    )
    @click.option(
        "--flavor",
        "-f",
        "flavor",
        help=f"The flavor of the {display_name} to register.",
        required=True,
        type=str,
    )
    @click.option(
        "--label",
        "-l",
        "labels",
        help="Labels to be associated with the component, in the form "
        "-l key1=value1 -l key2=value2.",
        multiple=True,
    )
    @click.option(
        "--connector",
        "-c",
        "connector",
        help="Use this flag to connect this stack component to a service connector.",
        type=str,
    )
    @click.option(
        "--resource-id",
        "-r",
        "resource_id",
        help="The resource ID to use with the connector. Only required for "
        "multi-instance connectors that are not already configured with a "
        "particular resource ID.",
        required=False,
        type=str,
    )
    @click.argument("args", nargs=-1, type=click.UNPROCESSED)
    def register_stack_component_command(
        name: str,
        flavor: str,
        args: List[str],
        labels: Optional[List[str]] = None,
        connector: Optional[str] = None,
        resource_id: Optional[str] = None,
    ) -> None:
        """Registers a stack component.

        Args:
            name: Name of the component to register.
            flavor: Flavor of the component to register.
            args: Additional arguments to pass to the component.
            labels: Labels to be associated with the component.
            connector: Name of the service connector to connect the component to.
            resource_id: The resource ID to use with the connector.
        """
        client = Client()

        # Parse the given args
        # name is guaranteed to be set by parse_name_and_extra_arguments
        name, parsed_args = cli_utils.parse_name_and_extra_arguments(  # type: ignore[assignment]
            list(args) + [name], expand_args=True
        )

        parsed_labels = cli_utils.get_parsed_labels(labels)

        if connector:
            try:
                client.get_service_connector(connector)
            except KeyError as err:
                cli_utils.error(
                    f"Could not find a connector '{connector}': {str(err)}"
                )

        with console.status(f"Registering {display_name} '{name}'...\n"):
            # Create a new stack component model
            component = client.create_stack_component(
                name=name,
                flavor=flavor,
                component_type=component_type,
                configuration=parsed_args,
                labels=parsed_labels,
            )

            cli_utils.declare(
                f"Successfully registered {component.type} `{component.name}`."
            )
            print_model_url(get_component_url(component))

        if connector:
            connect_stack_component_with_service_connector(
                component_type=component_type,
                name_id_or_prefix=name,
                connector=connector,
                interactive=False,
                no_verify=False,
                resource_id=resource_id,
            )

    return register_stack_component_command

generate_stack_component_remove_attribute_command(component_type: StackComponentType) -> Callable[[str, List[str]], None]

Generates remove_attribute command for a specific stack component type.

Parameters:

Name Type Description Default
component_type StackComponentType

Type of the component to generate the command for.

required

Returns:

Type Description
Callable[[str, List[str]], None]

A function that can be used as a click command.

Source code in src/zenml/cli/stack_components.py
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
def generate_stack_component_remove_attribute_command(
    component_type: StackComponentType,
) -> Callable[[str, List[str]], None]:
    """Generates `remove_attribute` command for a specific stack component type.

    Args:
        component_type: Type of the component to generate the command for.

    Returns:
        A function that can be used as a `click` command.
    """
    display_name = _component_display_name(component_type)

    @click.argument(
        "name_id_or_prefix",
        type=str,
        required=True,
    )
    @click.option(
        "--label",
        "-l",
        "labels",
        help="Labels to be removed from the component.",
        multiple=True,
    )
    @click.argument("args", nargs=-1, type=click.UNPROCESSED)
    def remove_attribute_stack_component_command(
        name_id_or_prefix: str,
        args: List[str],
        labels: Optional[List[str]] = None,
    ) -> None:
        """Removes one or more attributes from a stack component.

        Args:
            name_id_or_prefix: The name of the stack component to remove the
                attribute from.
            args: Additional arguments to pass to the remove_attribute command.
            labels: Labels to be removed from the component.
        """
        client = Client()

        with console.status(
            f"Updating {display_name} '{name_id_or_prefix}'...\n"
        ):
            try:
                updated_component = client.update_stack_component(
                    name_id_or_prefix=name_id_or_prefix,
                    component_type=component_type,
                    configuration={k: None for k in args},
                    labels={k: None for k in labels} if labels else None,
                )
            except (KeyError, IllegalOperationError) as err:
                cli_utils.error(str(err))

            cli_utils.declare(
                f"Successfully updated {display_name} `{name_id_or_prefix}`."
            )
            print_model_url(get_component_url(updated_component))

    return remove_attribute_stack_component_command

generate_stack_component_rename_command(component_type: StackComponentType) -> Callable[[str, str], None]

Generates a rename command for the specific stack component type.

Parameters:

Name Type Description Default
component_type StackComponentType

Type of the component to generate the command for.

required

Returns:

Type Description
Callable[[str, str], None]

A function that can be used as a click command.

Source code in src/zenml/cli/stack_components.py
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
def generate_stack_component_rename_command(
    component_type: StackComponentType,
) -> Callable[[str, str], None]:
    """Generates a `rename` command for the specific stack component type.

    Args:
        component_type: Type of the component to generate the command for.

    Returns:
        A function that can be used as a `click` command.
    """
    display_name = _component_display_name(component_type)

    @click.argument(
        "name_id_or_prefix",
        type=str,
        required=True,
    )
    @click.argument(
        "new_name",
        type=str,
        required=True,
    )
    def rename_stack_component_command(
        name_id_or_prefix: str, new_name: str
    ) -> None:
        """Rename a stack component.

        Args:
            name_id_or_prefix: The name of the stack component to rename.
            new_name: The new name of the stack component.
        """
        client = Client()

        with console.status(
            f"Renaming {display_name} '{name_id_or_prefix}'...\n"
        ):
            try:
                updated_component = client.update_stack_component(
                    name_id_or_prefix=name_id_or_prefix,
                    component_type=component_type,
                    name=new_name,
                )
            except (KeyError, IllegalOperationError) as err:
                cli_utils.error(str(err))

            cli_utils.declare(
                f"Successfully renamed {display_name} `{name_id_or_prefix}` to"
                f" `{new_name}`."
            )
            print_model_url(get_component_url(updated_component))

    return rename_stack_component_command

generate_stack_component_update_command(component_type: StackComponentType) -> Callable[[str, List[str]], None]

Generates an update command for the specific stack component type.

Parameters:

Name Type Description Default
component_type StackComponentType

Type of the component to generate the command for.

required

Returns:

Type Description
Callable[[str, List[str]], None]

A function that can be used as a click command.

Source code in src/zenml/cli/stack_components.py
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
def generate_stack_component_update_command(
    component_type: StackComponentType,
) -> Callable[[str, List[str]], None]:
    """Generates an `update` command for the specific stack component type.

    Args:
        component_type: Type of the component to generate the command for.

    Returns:
        A function that can be used as a `click` command.
    """
    display_name = _component_display_name(component_type)

    @click.argument(
        "name_id_or_prefix",
        type=str,
        required=False,
    )
    @click.option(
        "--label",
        "-l",
        "labels",
        help="Labels to be associated with the component, in the form "
        "-l key1=value1 -l key2=value2.",
        multiple=True,
    )
    @click.argument("args", nargs=-1, type=click.UNPROCESSED)
    def update_stack_component_command(
        name_id_or_prefix: Optional[str],
        args: List[str],
        labels: Optional[List[str]] = None,
    ) -> None:
        """Updates a stack component.

        Args:
            name_id_or_prefix: The name or id of the stack component to update.
            args: Additional arguments to pass to the update command.
            labels: Labels to be associated with the component.
        """
        client = Client()

        # Parse the given args
        args = list(args)
        if name_id_or_prefix:
            args.append(name_id_or_prefix)

        name_or_id, parsed_args = cli_utils.parse_name_and_extra_arguments(
            args,
            expand_args=True,
            name_mandatory=False,
        )

        parsed_labels = cli_utils.get_parsed_labels(labels)

        with console.status(f"Updating {display_name}...\n"):
            try:
                updated_component = client.update_stack_component(
                    name_id_or_prefix=name_or_id,
                    component_type=component_type,
                    configuration=parsed_args,
                    labels=parsed_labels,
                )
            except KeyError as err:
                cli_utils.error(str(err))

            cli_utils.declare(
                f"Successfully updated {display_name} "
                f"`{updated_component.name}`."
            )
            print_model_url(get_component_url(updated_component))

    return update_stack_component_command

get_active_stack() -> None

Gets the active stack.

Source code in src/zenml/cli/stack.py
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
@stack.command("get")
def get_active_stack() -> None:
    """Gets the active stack."""
    scope = "repository" if Client().uses_local_configuration else "global"

    with console.status("Getting the active stack..."):
        client = Client()
        try:
            cli_utils.declare(
                f"The {scope} active stack is: '{client.active_stack_model.name}'"
            )
        except KeyError as err:
            cli_utils.error(str(err))

get_component_url(component: ComponentResponse) -> Optional[str]

Function to get the dashboard URL of a given component model.

Parameters:

Name Type Description Default
component ComponentResponse

the response model of the given component.

required

Returns:

Type Description
Optional[str]

the URL to the component if the dashboard is available, else None.

Source code in src/zenml/utils/dashboard_utils.py
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
def get_component_url(component: ComponentResponse) -> Optional[str]:
    """Function to get the dashboard URL of a given component model.

    Args:
        component: the response model of the given component.

    Returns:
        the URL to the component if the dashboard is available, else None.
    """
    cloud_url = get_cloud_dashboard_url()
    if cloud_url:
        return f"{cloud_url}{constants.STACK_COMPONENTS}/{component.id}"

    base_url = get_server_dashboard_url()

    if base_url:
        return f"{base_url}{constants.STACK_COMPONENTS}/{component.id}"

    return None

get_environment() -> str

Returns a string representing the execution environment of the pipeline.

Returns:

Name Type Description
str str

the execution environment

Source code in src/zenml/environment.py
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
def get_environment() -> str:
    """Returns a string representing the execution environment of the pipeline.

    Returns:
        str: the execution environment
    """
    # Order is important here
    if Environment.in_kubernetes():
        return EnvironmentType.KUBERNETES
    elif Environment.in_github_actions():
        return EnvironmentType.GITHUB_ACTION
    elif Environment.in_gitlab_ci():
        return EnvironmentType.GITLAB_CI
    elif Environment.in_circle_ci():
        return EnvironmentType.CIRCLE_CI
    elif Environment.in_bitbucket_ci():
        return EnvironmentType.BITBUCKET_CI
    elif Environment.in_ci():
        return EnvironmentType.GENERIC_CI
    elif Environment.in_github_codespaces():
        return EnvironmentType.GITHUB_CODESPACES
    elif Environment.in_vscode_remote_container():
        return EnvironmentType.VSCODE_REMOTE_CONTAINER
    elif Environment.in_lightning_ai_studio():
        return EnvironmentType.LIGHTNING_AI_STUDIO
    elif Environment.in_docker():
        return EnvironmentType.DOCKER
    elif Environment.in_container():
        return EnvironmentType.CONTAINER
    elif Environment.in_google_colab():
        return EnvironmentType.COLAB
    elif Environment.in_paperspace_gradient():
        return EnvironmentType.PAPERSPACE
    elif Environment.in_notebook():
        return EnvironmentType.NOTEBOOK
    elif Environment.in_wsl():
        return EnvironmentType.WSL
    else:
        return EnvironmentType.NATIVE

get_global_config_directory() -> str

Gets the global config directory for ZenML.

Returns:

Type Description
str

The global config directory for ZenML.

Source code in src/zenml/utils/io_utils.py
53
54
55
56
57
58
59
60
61
62
def get_global_config_directory() -> str:
    """Gets the global config directory for ZenML.

    Returns:
        The global config directory for ZenML.
    """
    env_var_path = os.getenv(ENV_ZENML_CONFIG_PATH)
    if env_var_path:
        return str(Path(env_var_path).resolve())
    return click.get_app_dir(APP_NAME)

get_local_server() -> Optional[LocalServerDeployment]

Get the active local server.

Call this function to retrieve the local server deployed on this machine.

Returns:

Type Description
Optional[LocalServerDeployment]

The local server deployment or None, if no local server deployment was

Optional[LocalServerDeployment]

found.

Source code in src/zenml/utils/server_utils.py
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
def get_local_server() -> Optional["LocalServerDeployment"]:
    """Get the active local server.

    Call this function to retrieve the local server deployed on this machine.

    Returns:
        The local server deployment or None, if no local server deployment was
        found.
    """
    from zenml.zen_server.deploy.deployer import LocalServerDeployer
    from zenml.zen_server.deploy.exceptions import (
        ServerDeploymentNotFoundError,
    )

    deployer = LocalServerDeployer()
    try:
        return deployer.get_server()
    except ServerDeploymentNotFoundError:
        return None

get_logger(logger_name: str) -> logging.Logger

Main function to get logger name,.

Parameters:

Name Type Description Default
logger_name str

Name of logger to initialize.

required

Returns:

Type Description
Logger

A logger object.

Source code in src/zenml/logger.py
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
def get_logger(logger_name: str) -> logging.Logger:
    """Main function to get logger name,.

    Args:
        logger_name: Name of logger to initialize.

    Returns:
        A logger object.
    """
    logger = logging.getLogger(logger_name)
    logger.setLevel(get_logging_level().value)
    logger.addHandler(get_console_handler())

    logger.propagate = False
    return logger

get_requirements(integration_name: Optional[str] = None) -> None

List all requirements for the chosen integration.

Parameters:

Name Type Description Default
integration_name Optional[str]

The name of the integration to list the requirements for.

None
Source code in src/zenml/cli/integration.py
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
@integration.command(
    name="requirements", help="List all requirements for an integration."
)
@click.argument("integration_name", required=False, default=None)
def get_requirements(integration_name: Optional[str] = None) -> None:
    """List all requirements for the chosen integration.

    Args:
        integration_name: The name of the integration to list the requirements
            for.
    """
    from zenml.integrations.registry import integration_registry

    try:
        requirements = integration_registry.select_integration_requirements(
            integration_name
        )
    except KeyError as e:
        error(str(e))
    else:
        if requirements:
            title(
                f"Requirements for {integration_name or 'all integrations'}:\n"
            )
            declare(f"{requirements}")
            warning(
                "\n" + "To install the dependencies of a "
                "specific integration, type: "
            )
            warning("zenml integration install INTEGRATION_NAME")

get_resources_options_from_resource_model_for_full_stack(connector_details: Union[UUID, ServiceConnectorInfo]) -> ServiceConnectorResourcesInfo

Get the resource options from the resource model for the full stack.

Parameters:

Name Type Description Default
connector_details Union[UUID, ServiceConnectorInfo]

The service connector details (UUID or Info).

required

Returns:

Type Description
ServiceConnectorResourcesInfo

All available service connector resource options.

Source code in src/zenml/service_connectors/service_connector_utils.py
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
def get_resources_options_from_resource_model_for_full_stack(
    connector_details: Union[UUID, ServiceConnectorInfo],
) -> ServiceConnectorResourcesInfo:
    """Get the resource options from the resource model for the full stack.

    Args:
        connector_details: The service connector details (UUID or Info).

    Returns:
        All available service connector resource options.
    """
    client = Client()
    zen_store = client.zen_store

    if isinstance(connector_details, UUID):
        resource_model = zen_store.verify_service_connector(
            connector_details,
            list_resources=True,
        )
    else:
        resource_model = zen_store.verify_service_connector_config(
            service_connector=ServiceConnectorRequest(
                name="fake",
                connector_type=connector_details.type,
                auth_method=connector_details.auth_method,
                configuration=connector_details.configuration,
                secrets={},
                labels={},
            ),
            list_resources=True,
        )

    resources = resource_model.resources

    if isinstance(
        resource_model.connector_type,
        str,
    ):
        connector_type = resource_model.connector_type
    else:
        connector_type = resource_model.connector_type.connector_type

    artifact_stores: List[ResourcesInfo] = []
    orchestrators: List[ResourcesInfo] = []
    container_registries: List[ResourcesInfo] = []

    if connector_type == "aws":
        for each in resources:
            if each.resource_ids:
                if each.resource_type == "s3-bucket":
                    artifact_stores.append(
                        _prepare_resource_info(
                            connector_details=connector_details,
                            resource_ids=each.resource_ids,
                            stack_component_type=StackComponentType.ARTIFACT_STORE,
                            flavor="s3",
                            required_configuration={"path": "Path"},
                            use_resource_value_as_fixed_config=True,
                            flavor_display_name="S3 Bucket",
                        )
                    )
                if each.resource_type == "aws-generic":
                    orchestrators.append(
                        _prepare_resource_info(
                            connector_details=connector_details,
                            resource_ids=each.resource_ids,
                            stack_component_type=StackComponentType.ORCHESTRATOR,
                            flavor="sagemaker",
                            required_configuration={
                                "execution_role": "execution role ARN"
                            },
                            flavor_display_name="AWS Sagemaker",
                        )
                    )
                    orchestrators.append(
                        _prepare_resource_info(
                            connector_details=connector_details,
                            resource_ids=each.resource_ids,
                            stack_component_type=StackComponentType.ORCHESTRATOR,
                            flavor="vm_aws",
                            required_configuration={"region": "region"},
                            use_resource_value_as_fixed_config=True,
                            flavor_display_name="Skypilot (EC2)",
                        )
                    )

                if each.resource_type == "kubernetes-cluster":
                    orchestrators.append(
                        _prepare_resource_info(
                            connector_details=connector_details,
                            resource_ids=each.resource_ids,
                            stack_component_type=StackComponentType.ORCHESTRATOR,
                            flavor="kubernetes",
                            required_configuration={},
                            flavor_display_name="Kubernetes",
                        )
                    )
                if each.resource_type == "docker-registry":
                    container_registries.append(
                        _prepare_resource_info(
                            connector_details=connector_details,
                            resource_ids=each.resource_ids,
                            stack_component_type=StackComponentType.CONTAINER_REGISTRY,
                            flavor="aws",
                            required_configuration={"uri": "URI"},
                            use_resource_value_as_fixed_config=True,
                            flavor_display_name="ECR",
                        )
                    )

    elif connector_type == "gcp":
        for each in resources:
            if each.resource_ids:
                if each.resource_type == "gcs-bucket":
                    artifact_stores.append(
                        _prepare_resource_info(
                            connector_details=connector_details,
                            resource_ids=each.resource_ids,
                            stack_component_type=StackComponentType.ARTIFACT_STORE,
                            flavor="gcp",
                            required_configuration={"path": "Path"},
                            use_resource_value_as_fixed_config=True,
                            flavor_display_name="GCS Bucket",
                        )
                    )
                if each.resource_type == "gcp-generic":
                    orchestrators.append(
                        _prepare_resource_info(
                            connector_details=connector_details,
                            resource_ids=each.resource_ids,
                            stack_component_type=StackComponentType.ORCHESTRATOR,
                            flavor="vertex",
                            required_configuration={"location": "region name"},
                            flavor_display_name="Vertex AI",
                        )
                    )
                    orchestrators.append(
                        _prepare_resource_info(
                            connector_details=connector_details,
                            resource_ids=each.resource_ids,
                            stack_component_type=StackComponentType.ORCHESTRATOR,
                            flavor="vm_gcp",
                            required_configuration={"region": "region name"},
                            flavor_display_name="Skypilot (Compute)",
                        )
                    )

                if each.resource_type == "kubernetes-cluster":
                    orchestrators.append(
                        _prepare_resource_info(
                            connector_details=connector_details,
                            resource_ids=each.resource_ids,
                            stack_component_type=StackComponentType.ORCHESTRATOR,
                            flavor="kubernetes",
                            required_configuration={},
                            flavor_display_name="Kubernetes",
                        )
                    )
                if each.resource_type == "docker-registry":
                    container_registries.append(
                        _prepare_resource_info(
                            connector_details=connector_details,
                            resource_ids=each.resource_ids,
                            stack_component_type=StackComponentType.CONTAINER_REGISTRY,
                            flavor="gcp",
                            required_configuration={"uri": "URI"},
                            use_resource_value_as_fixed_config=True,
                            flavor_display_name="GCR",
                        )
                    )

    elif connector_type == "azure":
        for each in resources:
            if each.resource_ids:
                if each.resource_type == "blob-container":
                    artifact_stores.append(
                        _prepare_resource_info(
                            connector_details=connector_details,
                            resource_ids=each.resource_ids,
                            stack_component_type=StackComponentType.ARTIFACT_STORE,
                            flavor="azure",
                            required_configuration={"path": "Path"},
                            use_resource_value_as_fixed_config=True,
                            flavor_display_name="Blob container",
                        )
                    )
                if each.resource_type == "azure-generic":
                    # No native orchestrator ATM
                    orchestrators.append(
                        _prepare_resource_info(
                            connector_details=connector_details,
                            resource_ids=each.resource_ids,
                            stack_component_type=StackComponentType.ORCHESTRATOR,
                            flavor="vm_azure",
                            required_configuration={"region": "region name"},
                            flavor_display_name="Skypilot (VM)",
                        )
                    )
                    orchestrators.append(
                        _prepare_resource_info(
                            connector_details=connector_details,
                            resource_ids=each.resource_ids,
                            stack_component_type=StackComponentType.ORCHESTRATOR,
                            flavor="azureml",
                            required_configuration={
                                "subscription_id": "subscription ID",
                                "resource_group": "resource group",
                                "workspace": "workspace",
                            },
                            flavor_display_name="AzureML",
                        )
                    )

                if each.resource_type == "kubernetes-cluster":
                    orchestrators.append(
                        _prepare_resource_info(
                            connector_details=connector_details,
                            resource_ids=each.resource_ids,
                            stack_component_type=StackComponentType.ORCHESTRATOR,
                            flavor="kubernetes",
                            required_configuration={},
                            flavor_display_name="Kubernetes",
                        )
                    )
                if each.resource_type == "docker-registry":
                    container_registries.append(
                        _prepare_resource_info(
                            connector_details=connector_details,
                            resource_ids=each.resource_ids,
                            stack_component_type=StackComponentType.CONTAINER_REGISTRY,
                            flavor="azure",
                            required_configuration={"uri": "URI"},
                            use_resource_value_as_fixed_config=True,
                            flavor_display_name="ACR",
                        )
                    )

    _raise_specific_cloud_exception_if_needed(
        cloud_provider=connector_type,
        artifact_stores=artifact_stores,
        orchestrators=orchestrators,
        container_registries=container_registries,
    )

    return ServiceConnectorResourcesInfo(
        connector_type=connector_type,
        components_resources_info={
            StackComponentType.ARTIFACT_STORE: artifact_stores,
            StackComponentType.ORCHESTRATOR: orchestrators,
            StackComponentType.CONTAINER_REGISTRY: container_registries,
        },
    )

get_secret(name_id_or_prefix: str, private: Optional[bool] = None) -> None

Get a secret and print it to the console.

Parameters:

Name Type Description Default
name_id_or_prefix str

The name of the secret to get.

required
private Optional[bool]

Private status of the secret to filter for.

None
Source code in src/zenml/cli/secret.py
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
@secret.command("get", help="Get a secret with a given name, prefix or id.")
@click.argument(
    "name_id_or_prefix",
    type=click.STRING,
)
@click.option(
    "--private",
    "-p",
    "private",
    type=click.BOOL,
    required=False,
    help="Use this flag to explicitly fetch a private secret or a public secret.",
)
def get_secret(name_id_or_prefix: str, private: Optional[bool] = None) -> None:
    """Get a secret and print it to the console.

    Args:
        name_id_or_prefix: The name of the secret to get.
        private: Private status of the secret to filter for.
    """
    secret = _get_secret(name_id_or_prefix, private)
    scope = ""
    if private is not None:
        scope = "private " if private else "public "
    declare(
        f"Fetched {scope}secret with name `{secret.name}` and ID `{secret.id}`:"
    )
    if not secret.secret_values:
        warning(f"Secret with name `{name_id_or_prefix}` is empty.")
    else:
        pretty_print_secret(secret.secret_values, hide_secret=False)

get_stack_url(stack: StackResponse) -> Optional[str]

Function to get the dashboard URL of a given stack model.

Parameters:

Name Type Description Default
stack StackResponse

the response model of the given stack.

required

Returns:

Type Description
Optional[str]

the URL to the stack if the dashboard is available, else None.

Source code in src/zenml/utils/dashboard_utils.py
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
def get_stack_url(stack: StackResponse) -> Optional[str]:
    """Function to get the dashboard URL of a given stack model.

    Args:
        stack: the response model of the given stack.

    Returns:
        the URL to the stack if the dashboard is available, else None.
    """
    cloud_url = get_cloud_dashboard_url()
    if cloud_url:
        # We don't have a stack detail page here, so just link to the filtered
        # list of stacks.
        return f"{cloud_url}{constants.STACKS}?id={stack.id}"

    base_url = get_server_dashboard_url()

    if base_url:
        # There is no filtering in OSS, we just link to the stack list.
        return f"{base_url}{constants.STACKS}"

    return None

go() -> None

Quickly explore ZenML with this walk-through.

Raises:

Type Description
GitNotFoundError

If git is not installed.

e

when Jupyter Notebook fails to launch.

Source code in src/zenml/cli/base.py
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
@cli.command("go")
def go() -> None:
    """Quickly explore ZenML with this walk-through.

    Raises:
        GitNotFoundError: If git is not installed.
        e: when Jupyter Notebook fails to launch.
    """
    from zenml.cli.text_utils import (
        zenml_cli_privacy_message,
        zenml_cli_welcome_message,
        zenml_go_notebook_tutorial_message,
    )

    metadata = {}

    console.print(zenml_cli_welcome_message, width=80)

    client = Client()

    # Only ask them if they haven't been asked before and the email
    # hasn't been supplied by other means
    if (
        not GlobalConfiguration().user_email
        and client.active_user.email_opted_in is None
    ):
        gave_email = _prompt_email(AnalyticsEventSource.ZENML_GO)
        metadata = {"gave_email": gave_email}

    zenml_tutorial_path = os.path.join(os.getcwd(), "zenml_tutorial")

    if not is_jupyter_installed():
        cli_utils.error(
            "Jupyter Notebook or JupyterLab is not installed. "
            "Please install the 'notebook' package with `pip` "
            "first so you can run the tutorial notebooks."
        )

    with track_handler(event=AnalyticsEvent.RUN_ZENML_GO, metadata=metadata):
        console.print(zenml_cli_privacy_message, width=80)

        if not os.path.isdir(zenml_tutorial_path):
            try:
                from git.repo.base import Repo
            except ImportError as e:
                cli_utils.error(
                    "At this point we would want to clone our tutorial repo "
                    "onto your machine to let you dive right into our code. "
                    "However, this machine has no installation of Git. Feel "
                    "free to install git and rerun this command. Alternatively "
                    "you can also download the repo manually here: "
                    f"{TUTORIAL_REPO}. The tutorial is in the "
                    f"'examples/quickstart/notebooks' directory."
                )
                raise GitNotFoundError(e)

            with tempfile.TemporaryDirectory() as tmpdirname:
                tmp_cloned_dir = os.path.join(tmpdirname, "zenml_repo")
                with console.status(
                    "Cloning tutorial. This sometimes takes a minute..."
                ):
                    Repo.clone_from(
                        TUTORIAL_REPO,
                        tmp_cloned_dir,
                        branch=f"release/{zenml_version}",
                        depth=1,  # to prevent timeouts when downloading
                    )
                example_dir = os.path.join(
                    tmp_cloned_dir, "examples/quickstart"
                )
                copy_dir(example_dir, zenml_tutorial_path)
        else:
            cli_utils.warning(
                f"{zenml_tutorial_path} already exists! Continuing without "
                "cloning."
            )

        # get list of all .ipynb files in zenml_tutorial_path
        ipynb_files = []
        for dirpath, _, filenames in os.walk(zenml_tutorial_path):
            for filename in filenames:
                if filename.endswith(".ipynb"):
                    ipynb_files.append(os.path.join(dirpath, filename))

        ipynb_files.sort()
        console.print(
            zenml_go_notebook_tutorial_message(ipynb_files), width=80
        )
        input("Press ENTER to continue...")

    try:
        subprocess.check_call(
            ["jupyter", "notebook", "--ContentsManager.allow_hidden=True"],
            cwd=zenml_tutorial_path,
        )
    except subprocess.CalledProcessError as e:
        cli_utils.error(
            "An error occurred while launching Jupyter Notebook. "
            "Please make sure Jupyter is properly installed and try again."
        )
        raise e

import_stack(stack_name: str, filename: Optional[str], ignore_version_mismatch: bool = False) -> None

Import a stack from YAML.

Parameters:

Name Type Description Default
stack_name str

The name of the stack to import.

required
filename Optional[str]

The filename to import the stack from.

required
ignore_version_mismatch bool

Import stack components even if the installed version of ZenML is different from the one specified in the stack YAML file.

False
Source code in src/zenml/cli/stack.py
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
@stack.command("import", help="Import a stack from YAML.")
@click.argument("stack_name", type=str, required=True)
@click.option("--filename", "-f", type=str, required=False)
@click.option(
    "--ignore-version-mismatch",
    is_flag=True,
    help="Import stack components even if the installed version of ZenML "
    "is different from the one specified in the stack YAML file",
)
def import_stack(
    stack_name: str,
    filename: Optional[str],
    ignore_version_mismatch: bool = False,
) -> None:
    """Import a stack from YAML.

    Args:
        stack_name: The name of the stack to import.
        filename: The filename to import the stack from.
        ignore_version_mismatch: Import stack components even if
            the installed version of ZenML is different from the
            one specified in the stack YAML file.
    """
    # handle 'zenml stack import file.yaml' calls
    if stack_name.endswith(".yaml") and filename is None:
        filename = stack_name
        data = read_yaml(filename)
        stack_name = data["stack_name"]  # read stack_name from export

    # standard 'zenml stack import stack_name [file.yaml]' calls
    else:
        # if filename is not given, assume default export name
        # "<stack_name>.yaml"
        if filename is None:
            filename = stack_name + ".yaml"
        data = read_yaml(filename)
        cli_utils.declare(
            f"Using '{filename}' to import '{stack_name}' stack."
        )

    # assert zenml version is the same if force is false
    if data["zenml_version"] != zenml.__version__:
        if ignore_version_mismatch:
            cli_utils.warning(
                f"The stack that will be installed is using ZenML version "
                f"{data['zenml_version']}. You have version "
                f"{zenml.__version__} installed. Some components might not "
                "work as expected."
            )
        else:
            cli_utils.error(
                f"Cannot import stacks from other ZenML versions. "
                f"The stack was created using ZenML version "
                f"{data['zenml_version']}, you have version "
                f"{zenml.__version__} installed. You can "
                "retry using the `--ignore-version-mismatch` "
                "flag. However, be aware that this might "
                "fail or lead to other unexpected behavior."
            )

    # ask user for a new stack_name if current one already exists
    client = Client()
    if client.list_stacks(name=stack_name):
        stack_name = click.prompt(
            f"Stack `{stack_name}` already exists. Please choose a different "
            f"name",
            type=str,
        )

    # import stack components
    component_ids = {}
    for component_type_str, component_config in data["components"].items():
        component_type = StackComponentType(component_type_str)

        component_id = _import_stack_component(
            component_type=component_type,
            component_dict=component_config,
        )
        component_ids[component_type] = component_id

    imported_stack = Client().create_stack(
        name=stack_name, components=component_ids
    )

    print_model_url(get_stack_url(imported_stack))

info(packages: Tuple[str], all: bool = False, file: str = '', stack: bool = False) -> None

Show information about the current user setup.

Parameters:

Name Type Description Default
packages Tuple[str]

List of packages to show information about.

required
all bool

Flag to show information about all installed packages.

False
file str

Flag to output to a file.

''
stack bool

Flag to output information about active stack and components

False
Source code in src/zenml/cli/base.py
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
@cli.command(
    "info", help="Show information about the current user setup.", hidden=True
)
@click.option(
    "--all",
    "-a",
    is_flag=True,
    default=False,
    help="Output information about all installed packages.",
    type=bool,
)
@click.option(
    "--file",
    "-f",
    default="",
    help="Path to export to a .yaml file.",
    type=click.Path(exists=False, dir_okay=False),
)
@click.option(
    "--packages",
    "-p",
    multiple=True,
    help="Select specific installed packages.",
    type=str,
)
@click.option(
    "--stack",
    "-s",
    is_flag=True,
    default=False,
    help="Output information about active stack and components.",
    type=bool,
)
def info(
    packages: Tuple[str],
    all: bool = False,
    file: str = "",
    stack: bool = False,
) -> None:
    """Show information about the current user setup.

    Args:
        packages: List of packages to show information about.
        all: Flag to show information about all installed packages.
        file: Flag to output to a file.
        stack: Flag to output information about active stack and components
    """
    gc = GlobalConfiguration()
    environment = Environment()
    client = Client()
    store_info = client.zen_store.get_store_info()

    store_cfg = gc.store_configuration

    user_info = {
        "zenml_local_version": zenml_version,
        "zenml_server_version": store_info.version,
        "zenml_server_database": str(store_info.database_type),
        "zenml_server_deployment_type": str(store_info.deployment_type),
        "zenml_config_dir": gc.config_directory,
        "zenml_local_store_dir": gc.local_stores_path,
        "zenml_server_url": store_cfg.url,
        "zenml_active_repository_root": str(client.root),
        "python_version": environment.python_version(),
        "environment": get_environment(),
        "system_info": environment.get_system_info(),
        "active_project": client.active_project.name,
        "active_stack": client.active_stack_model.name,
        "active_user": client.active_user.name,
        "telemetry_status": "enabled" if gc.analytics_opt_in else "disabled",
        "analytics_client_id": str(gc.user_id),
        "analytics_user_id": str(client.active_user.id),
        "analytics_server_id": str(client.zen_store.get_store_info().id),
        "integrations": integration_registry.get_installed_integrations(),
        "packages": {},
        "query_packages": {},
    }

    if all:
        user_info["packages"] = cli_utils.get_package_information()
    if packages:
        if user_info.get("packages"):
            if isinstance(user_info["packages"], dict):
                user_info["query_packages"] = {
                    p: v
                    for p, v in user_info["packages"].items()
                    if p in packages
                }
        else:
            user_info["query_packages"] = cli_utils.get_package_information(
                list(packages)
            )
    if file:
        file_write_path = os.path.abspath(file)
        write_yaml(file, user_info)
        declare(f"Wrote user debug info to file at '{file_write_path}'.")
    else:
        cli_utils.print_user_info(user_info)

    if stack:
        try:
            cli_utils.print_debug_stack()
        except ModuleNotFoundError as e:
            cli_utils.warning(
                "Could not print debug stack information. Please make sure "
                "you have the necessary dependencies and integrations "
                "installed for all your stack components."
            )
            cli_utils.warning(f"The missing package is: '{e.name}'")

init(path: Optional[Path], template: Optional[str] = None, template_tag: Optional[str] = None, template_with_defaults: bool = False, test: bool = False) -> None

Initialize ZenML on given path.

Parameters:

Name Type Description Default
path Optional[Path]

Path to the repository.

required
template Optional[str]

Optional name or URL of the ZenML project template to use to initialize the repository. Can be a string like e2e_batch, nlp, starter or a copier URL like gh:owner/repo_name. If not specified, no template is used.

None
template_tag Optional[str]

Optional tag of the ZenML project template to use to initialize the repository. If template is a pre-defined template, then this is ignored.

None
template_with_defaults bool

Whether to use default parameters of the ZenML project template

False
test bool

Whether to skip interactivity when testing.

False
Source code in src/zenml/cli/base.py
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
@cli.command("init", help="Initialize a ZenML repository.")
@click.option(
    "--path",
    type=click.Path(
        exists=True, file_okay=False, dir_okay=True, path_type=Path
    ),
)
@click.option(
    "--template",
    type=str,
    required=False,
    help="Name or URL of the ZenML project template to use to initialize the "
    "repository, Can be a string like `e2e_batch`, `nlp`, `llm_finetuning`, "
    "`starter` etc. or a copier URL like gh:owner/repo_name. If not specified, "
    "no template is used.",
)
@click.option(
    "--template-tag",
    type=str,
    required=False,
    help="Optional tag of the ZenML project template to use to initialize the "
    "repository.",
)
@click.option(
    "--template-with-defaults",
    is_flag=True,
    default=False,
    required=False,
    help="Whether to use default parameters of the ZenML project template",
)
@click.option(
    "--test",
    is_flag=True,
    default=False,
    help="To skip interactivity when testing.",
    hidden=True,
)
def init(
    path: Optional[Path],
    template: Optional[str] = None,
    template_tag: Optional[str] = None,
    template_with_defaults: bool = False,
    test: bool = False,
) -> None:
    """Initialize ZenML on given path.

    Args:
        path: Path to the repository.
        template: Optional name or URL of the ZenML project template to use to
            initialize the repository. Can be a string like `e2e_batch`,
            `nlp`, `starter` or a copier URL like `gh:owner/repo_name`. If
            not specified, no template is used.
        template_tag: Optional tag of the ZenML project template to use to
            initialize the repository. If template is a pre-defined template,
            then this is ignored.
        template_with_defaults: Whether to use default parameters of
            the ZenML project template
        test: Whether to skip interactivity when testing.
    """
    if path is None:
        path = Path.cwd()

    os.environ[ENV_ZENML_ENABLE_REPO_INIT_WARNINGS] = "False"

    if template:
        try:
            from copier import Worker
        except ImportError:
            error(
                "You need to install the ZenML project template requirements "
                "to use templates. Please run `pip install zenml[templates]` "
                "and try again."
            )
            return

        from zenml.cli.text_utils import (
            zenml_cli_privacy_message,
            zenml_cli_welcome_message,
        )

        console.print(zenml_cli_welcome_message, width=80)

        client = Client()
        # Only ask them if they haven't been asked before and the email
        # hasn't been supplied by other means
        if (
            not GlobalConfiguration().user_email
            and client.active_user.email_opted_in is None
            and not test
        ):
            _prompt_email(AnalyticsEventSource.ZENML_INIT)

        email = GlobalConfiguration().user_email or ""
        metadata = {
            "email": email,
            "template": template,
            "prompt": not template_with_defaults,
        }

        with track_handler(
            event=AnalyticsEvent.GENERATE_TEMPLATE,
            metadata=metadata,
        ):
            console.print(zenml_cli_privacy_message, width=80)

            if not template_with_defaults:
                from rich.markdown import Markdown

                prompt_message = Markdown(
                    """
## 🧑‍🏫 Project template parameters
"""
                )

                console.print(prompt_message, width=80)

            # Check if template is a URL or a preset template name
            vcs_ref: Optional[str] = None
            if template in ZENML_PROJECT_TEMPLATES:
                declare(f"Using the {template} template...")
                zenml_project_template = ZENML_PROJECT_TEMPLATES[template]
                src_path = zenml_project_template.copier_github_url
                # template_tag is ignored in this case
                vcs_ref = zenml_project_template.github_tag
            else:
                declare(
                    f"List of known templates is: {', '.join(ZENML_PROJECT_TEMPLATES.keys())}"
                )
                declare(
                    f"No known templates specified. Using `{template}` as URL."
                    "If this is not a valid copier template URL, this will "
                    "fail."
                )

                src_path = template
                vcs_ref = template_tag

            with Worker(
                src_path=src_path,
                vcs_ref=vcs_ref,
                dst_path=path,
                data=dict(
                    email=email,
                    template=template,
                ),
                defaults=template_with_defaults,
                user_defaults=dict(
                    email=email,
                ),
                overwrite=template_with_defaults,
                unsafe=True,
            ) as worker:
                worker.run_copy()

    with console.status(f"Initializing ZenML repository at {path}.\n"):
        try:
            Client.initialize(root=path)
            declare(f"ZenML repository initialized at {path}.")
        except InitializationException as e:
            declare(f"{e}")
            return

    declare(
        f"The local active stack was initialized to "
        f"'{Client().active_stack_model.name}'. This local configuration "
        f"will only take effect when you're running ZenML from the initialized "
        f"repository root, or from a subdirectory. For more information on "
        f"repositories and configurations, please visit "
        f"https://docs.zenml.io/user-guides/production-guide/understand-stacks."
    )

install(integrations: Tuple[str], ignore_integration: Tuple[str], force: bool = False, uv: bool = False) -> None

Installs the required packages for a given integration.

If no integration is specified all required packages for all integrations are installed using pip or uv.

Parameters:

Name Type Description Default
integrations Tuple[str]

The name of the integration to install the requirements for.

required
ignore_integration Tuple[str]

Integrations to ignore explicitly (passed in separately).

required
force bool

Force the installation of the required packages.

False
uv bool

Use uv for package installation (experimental).

False
Source code in src/zenml/cli/integration.py
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
@integration.command(
    help="Install the required packages for the integration of choice."
)
@click.argument("integrations", nargs=-1, required=False)
@click.option(
    "--ignore-integration",
    "-i",
    multiple=True,
    help="Integrations to ignore explicitly (passed in separately).",
)
@click.option(
    "--yes",
    "-y",
    "force",
    is_flag=True,
    help="Force the installation of the required packages. This will skip the "
    "confirmation step and reinstall existing packages as well",
)
@click.option(
    "--uv",
    "uv",
    is_flag=True,
    help="Experimental: Use uv for package installation.",
    default=False,
)
def install(
    integrations: Tuple[str],
    ignore_integration: Tuple[str],
    force: bool = False,
    uv: bool = False,
) -> None:
    """Installs the required packages for a given integration.

    If no integration is specified all required packages for all integrations
    are installed using pip or uv.

    Args:
        integrations: The name of the integration to install the requirements
            for.
        ignore_integration: Integrations to ignore explicitly (passed in
            separately).
        force: Force the installation of the required packages.
        uv: Use uv for package installation (experimental).
    """
    from zenml.cli.utils import is_pip_installed, is_uv_installed
    from zenml.integrations.registry import integration_registry

    if uv and not is_uv_installed():
        error(
            "UV is not installed but the uv flag was passed in. Please install "
            "uv or remove the uv flag."
        )

    if not uv and not is_pip_installed():
        error(
            "Pip is not installed. Please install pip or use the uv flag "
            "(--uv) for package installation."
        )

    if not integrations:
        # no integrations specified, use all registered integrations
        integration_set = set(integration_registry.integrations.keys())

        for i in ignore_integration:
            try:
                integration_set.remove(i)
            except KeyError:
                error(
                    f"Integration {i} does not exist. Available integrations: "
                    f"{list(integration_registry.integrations.keys())}"
                )
    else:
        integration_set = set(integrations)

    if sys.version_info.minor == 12 and "tensorflow" in integration_set:
        warning(
            "The TensorFlow integration is not yet compatible with Python "
            "3.12, thus its installation is skipped. Consider using a "
            "different version of Python and stay in touch for further updates."
        )
        integration_set.remove("tensorflow")

    if sys.version_info.minor == 12 and "deepchecks" in integration_set:
        warning(
            "The Deepchecks integration is not yet compatible with Python "
            "3.12, thus its installation is skipped. Consider using a "
            "different version of Python and stay in touch for further updates."
        )
        integration_set.remove("deepchecks")

    requirements = []
    integrations_to_install = []
    for integration_name in integration_set:
        try:
            if force or not integration_registry.is_installed(
                integration_name
            ):
                requirements += (
                    integration_registry.select_integration_requirements(
                        integration_name
                    )
                )
                integrations_to_install.append(integration_name)
            else:
                declare(
                    f"All required packages for integration "
                    f"'{integration_name}' are already installed."
                )
        except KeyError:
            warning(f"Unable to find integration '{integration_name}'.")

    if requirements and (
        force
        or confirmation(
            "Are you sure you want to install the following "
            "packages to the current environment?\n"
            f"{requirements}"
        )
    ):
        with console.status("Installing integrations..."):
            install_packages(requirements, use_uv=uv)

install_packages(packages: List[str], upgrade: bool = False, use_uv: bool = False) -> None

Installs pypi packages into the current environment with pip or uv.

When using with uv, a virtual environment is required.

Parameters:

Name Type Description Default
packages List[str]

List of packages to install.

required
upgrade bool

Whether to upgrade the packages if they are already installed.

False
use_uv bool

Whether to use uv for package installation.

False

Raises:

Type Description
e

If the package installation fails.

Source code in src/zenml/cli/utils.py
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
def install_packages(
    packages: List[str],
    upgrade: bool = False,
    use_uv: bool = False,
) -> None:
    """Installs pypi packages into the current environment with pip or uv.

    When using with `uv`, a virtual environment is required.

    Args:
        packages: List of packages to install.
        upgrade: Whether to upgrade the packages if they are already installed.
        use_uv: Whether to use uv for package installation.

    Raises:
        e: If the package installation fails.
    """
    if "neptune" in packages:
        declare(
            "Uninstalling legacy `neptune-client` package to avoid version "
            "conflicts with new `neptune` package..."
        )
        uninstall_package("neptune-client")

    if "prodigy" in packages:
        packages.remove("prodigy")
        declare(
            "The `prodigy` package should be installed manually using your "
            "license key. Please visit https://prodi.gy/docs/install for more "
            "information."
        )
    if not packages:
        # if user only tried to install prodigy, we can
        # just return without doing anything
        return

    if use_uv and not is_installed_in_python_environment("uv"):
        # If uv is installed globally, don't run as a python module
        command = []
    else:
        command = [sys.executable, "-m"]

    command += ["uv", "pip", "install"] if use_uv else ["pip", "install"]

    if upgrade:
        command += ["--upgrade"]

    command += packages

    if not IS_DEBUG_ENV:
        quiet_flag = "-q" if use_uv else "-qqq"
        command.append(quiet_flag)
        if not use_uv:
            command.append("--no-warn-conflicts")

    try:
        subprocess.check_call(command)
    except subprocess.CalledProcessError as e:
        if (
            use_uv
            and "Failed to locate a virtualenv or Conda environment" in str(e)
        ):
            error(
                "Failed to locate a virtualenv or Conda environment. "
                "When using uv, a virtual environment is required. "
                "Run `uv venv` to create a virtualenv and retry."
            )
        else:
            raise e

integration() -> None

Interact with external integrations.

Source code in src/zenml/cli/integration.py
43
44
45
46
47
48
@cli.group(
    cls=TagGroup,
    tag=CliCategories.INTEGRATIONS,
)
def integration() -> None:
    """Interact with external integrations."""

is_analytics_opted_in() -> None

Check whether user is opt-in or opt-out of analytics.

Source code in src/zenml/cli/config.py
32
33
34
35
36
@analytics.command("get")
def is_analytics_opted_in() -> None:
    """Check whether user is opt-in or opt-out of analytics."""
    gc = GlobalConfiguration()
    cli_utils.declare(f"Analytics opt-in: {gc.analytics_opt_in}")

is_jupyter_installed() -> bool

Checks if Jupyter notebook is installed.

Returns:

Name Type Description
bool bool

True if Jupyter notebook is installed, False otherwise.

Source code in src/zenml/cli/utils.py
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
def is_jupyter_installed() -> bool:
    """Checks if Jupyter notebook is installed.

    Returns:
        bool: True if Jupyter notebook is installed, False otherwise.
    """
    try:
        pkg_resources.get_distribution("notebook")
        return True
    except pkg_resources.DistributionNotFound:
        return False

is_pro_server(url: str) -> Tuple[Optional[bool], Optional[str]]

Check if the server at the given URL is a ZenML Pro server.

Parameters:

Name Type Description Default
url str

The URL of the server to check.

required

Returns:

Type Description
Optional[bool]

True if the server is a ZenML Pro server, False otherwise, and the

Optional[str]

extracted pro API URL if the server is a ZenML Pro server, or None if

Tuple[Optional[bool], Optional[str]]

no information could be extracted.

Source code in src/zenml/cli/login.py
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
def is_pro_server(
    url: str,
) -> Tuple[Optional[bool], Optional[str]]:
    """Check if the server at the given URL is a ZenML Pro server.

    Args:
        url: The URL of the server to check.

    Returns:
        True if the server is a ZenML Pro server, False otherwise, and the
        extracted pro API URL if the server is a ZenML Pro server, or None if
        no information could be extracted.
    """
    from zenml.login.credentials_store import get_credentials_store
    from zenml.login.server_info import get_server_info

    url = url.rstrip("/")
    # First, check the credentials store
    credentials_store = get_credentials_store()
    credentials = credentials_store.get_credentials(url)
    if credentials:
        if credentials.type == ServerType.PRO:
            return True, credentials.pro_api_url
        else:
            return False, None

    # Next, make a request to the server itself
    server_info = get_server_info(url)
    if not server_info:
        return None, None

    if server_info.is_pro_server():
        return True, server_info.pro_api_url

    return False, None

is_sorted_or_filtered(ctx: click.Context) -> bool

Decides whether any filtering/sorting happens during a 'list' CLI call.

Parameters:

Name Type Description Default
ctx Context

the Click context of the CLI call.

required

Returns:

Type Description
bool

a boolean indicating whether any sorting or filtering parameters were

bool

used during the list CLI call.

Source code in src/zenml/cli/utils.py
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
def is_sorted_or_filtered(ctx: click.Context) -> bool:
    """Decides whether any filtering/sorting happens during a 'list' CLI call.

    Args:
        ctx: the Click context of the CLI call.

    Returns:
        a boolean indicating whether any sorting or filtering parameters were
        used during the list CLI call.
    """
    try:
        for _, source in ctx._parameter_source.items():
            if source != click.core.ParameterSource.DEFAULT:
                return True
        return False

    except Exception as e:
        logger.debug(
            f"There was a problem accessing the parameter source for "
            f'the "sort_by" option: {e}'
        )
        return False

legacy_show(ngrok_token: Optional[str] = None) -> None

Show the ZenML dashboard.

Parameters:

Name Type Description Default
ngrok_token Optional[str]

An ngrok auth token to use for exposing the ZenML dashboard on a public domain. Primarily used for accessing the dashboard in Colab.

None
Source code in src/zenml/cli/server.py
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
@cli.command(
    "show",
    help="""Show the ZenML dashboard.

DEPRECATED: Please use `zenml server show` instead.             
""",
)
@click.option(
    "--ngrok-token",
    type=str,
    default=None,
    help="Specify an ngrok auth token to use for exposing the ZenML server.",
)
def legacy_show(ngrok_token: Optional[str] = None) -> None:
    """Show the ZenML dashboard.

    Args:
        ngrok_token: An ngrok auth token to use for exposing the ZenML dashboard
            on a public domain. Primarily used for accessing the dashboard in
            Colab.
    """
    cli_utils.warning(
        "The `zenml show` command is deprecated and will be removed in a "
        "future release. Please use the `zenml server show` command "
        "instead."
    )

    # Calling the `zenml server show` command
    cli_utils.declare("Calling `zenml server show`...")
    show(local=False, ngrok_token=ngrok_token)

list_api_keys(service_account_name_or_id: str, /, **kwargs: Any) -> None

List all API keys.

Parameters:

Name Type Description Default
service_account_name_or_id str

The name or ID of the service account for which to list the API keys.

required
**kwargs Any

Keyword arguments to filter API keys.

{}
Source code in src/zenml/cli/service_accounts.py
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
@api_key.command("list", help="List all API keys.")
@list_options(APIKeyFilter)
@click.pass_obj
def list_api_keys(service_account_name_or_id: str, /, **kwargs: Any) -> None:
    """List all API keys.

    Args:
        service_account_name_or_id: The name or ID of the service account for
            which to list the API keys.
        **kwargs: Keyword arguments to filter API keys.
    """
    with console.status("Listing API keys...\n"):
        try:
            api_keys = Client().list_api_keys(
                service_account_name_id_or_prefix=service_account_name_or_id,
                **kwargs,
            )
        except KeyError as e:
            cli_utils.error(str(e))

        if not api_keys.items:
            cli_utils.declare("No API keys found for this filter.")
            return

        cli_utils.print_pydantic_models(
            api_keys,
            exclude_columns=[
                "created",
                "updated",
                "key",
                "retain_period_minutes",
            ],
        )

list_artifact_versions(**kwargs: Any) -> None

List all artifact versions.

Parameters:

Name Type Description Default
**kwargs Any

Keyword arguments to filter artifact versions by.

{}
Source code in src/zenml/cli/artifact.py
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
@cli_utils.list_options(ArtifactVersionFilter)
@version.command("list", help="List all artifact versions.")
def list_artifact_versions(**kwargs: Any) -> None:
    """List all artifact versions.

    Args:
        **kwargs: Keyword arguments to filter artifact versions by.
    """
    artifact_versions = Client().list_artifact_versions(**kwargs)

    if not artifact_versions:
        cli_utils.declare("No artifact versions found.")
        return

    to_print = []
    for artifact_version in artifact_versions:
        to_print.append(_artifact_version_to_print(artifact_version))

    cli_utils.print_table(to_print)

list_artifacts(**kwargs: Any) -> None

List all artifacts.

Parameters:

Name Type Description Default
**kwargs Any

Keyword arguments to filter artifacts by.

{}
Source code in src/zenml/cli/artifact.py
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
@cli_utils.list_options(ArtifactFilter)
@artifact.command("list", help="List all artifacts.")
def list_artifacts(**kwargs: Any) -> None:
    """List all artifacts.

    Args:
        **kwargs: Keyword arguments to filter artifacts by.
    """
    artifacts = Client().list_artifacts(**kwargs)

    if not artifacts:
        cli_utils.declare("No artifacts found.")
        return

    to_print = []
    for artifact in artifacts:
        to_print.append(_artifact_to_print(artifact))

    cli_utils.print_table(to_print)

list_authorized_devices(**kwargs: Any) -> None

List all authorized devices.

Parameters:

Name Type Description Default
**kwargs Any

Keyword arguments to filter authorized devices.

{}
Source code in src/zenml/cli/authorized_device.py
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
@authorized_device.command(
    "list", help="List all authorized devices for the current user."
)
@list_options(OAuthDeviceFilter)
def list_authorized_devices(**kwargs: Any) -> None:
    """List all authorized devices.

    Args:
        **kwargs: Keyword arguments to filter authorized devices.
    """
    with console.status("Listing authorized devices...\n"):
        devices = Client().list_authorized_devices(**kwargs)

        if not devices.items:
            cli_utils.declare("No authorized devices found for this filter.")
            return

        cli_utils.print_pydantic_models(
            devices,
            columns=["id", "status", "ip_address", "hostname", "os"],
        )

list_code_repositories(**kwargs: Any) -> None

List all connected code repositories.

Parameters:

Name Type Description Default
**kwargs Any

Keyword arguments to filter code repositories.

{}
Source code in src/zenml/cli/code_repository.py
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
@code_repository.command("list", help="List all connected code repositories.")
@list_options(CodeRepositoryFilter)
def list_code_repositories(**kwargs: Any) -> None:
    """List all connected code repositories.

    Args:
        **kwargs: Keyword arguments to filter code repositories.
    """
    with console.status("Listing code repositories...\n"):
        repos = Client().list_code_repositories(**kwargs)

        if not repos.items:
            cli_utils.declare("No code repositories found for this filter.")
            return

        cli_utils.print_pydantic_models(
            repos,
            exclude_columns=["created", "updated", "user", "project"],
        )

list_integrations() -> None

List all available integrations with their installation status.

Source code in src/zenml/cli/integration.py
51
52
53
54
55
56
57
58
59
60
61
62
63
@integration.command(name="list", help="List the available integrations.")
def list_integrations() -> None:
    """List all available integrations with their installation status."""
    from zenml.integrations.registry import integration_registry

    formatted_table = format_integration_list(
        sorted(list(integration_registry.integrations.items()))
    )
    print_table(formatted_table)
    warning(
        "\n" + "To install the dependencies of a specific integration, type: "
    )
    warning("zenml integration install INTEGRATION_NAME")

list_model_version_data_artifacts(model_name: str, model_version: Optional[str] = None, **kwargs: Any) -> None

List data artifacts linked to a model version in the Model Control Plane.

Parameters:

Name Type Description Default
model_name str

The ID or name of the model containing version.

required
model_version Optional[str]

The name, number or ID of the model version. If not provided, the latest version is used.

None
**kwargs Any

Keyword arguments to filter models.

{}
Source code in src/zenml/cli/model.py
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
@model.command(
    "data_artifacts",
    help="List data artifacts linked to a model version.",
)
@click.argument("model_name")
@click.option("--model_version", "-v", default=None)
@cli_utils.list_options(ModelVersionArtifactFilter)
def list_model_version_data_artifacts(
    model_name: str,
    model_version: Optional[str] = None,
    **kwargs: Any,
) -> None:
    """List data artifacts linked to a model version in the Model Control Plane.

    Args:
        model_name: The ID or name of the model containing version.
        model_version: The name, number or ID of the model version. If not
            provided, the latest version is used.
        **kwargs: Keyword arguments to filter models.
    """
    _print_artifacts_links_generic(
        model_name_or_id=model_name,
        model_version_name_or_number_or_id=model_version,
        only_data_artifacts=True,
        **kwargs,
    )

list_model_version_deployment_artifacts(model_name: str, model_version: Optional[str] = None, **kwargs: Any) -> None

List deployment artifacts linked to a model version in the Model Control Plane.

Parameters:

Name Type Description Default
model_name str

The ID or name of the model containing version.

required
model_version Optional[str]

The name, number or ID of the model version. If not provided, the latest version is used.

None
**kwargs Any

Keyword arguments to filter models.

{}
Source code in src/zenml/cli/model.py
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
@model.command(
    "deployment_artifacts",
    help="List deployment artifacts linked to a model version.",
)
@click.argument("model_name")
@click.option("--model_version", "-v", default=None)
@cli_utils.list_options(ModelVersionArtifactFilter)
def list_model_version_deployment_artifacts(
    model_name: str,
    model_version: Optional[str] = None,
    **kwargs: Any,
) -> None:
    """List deployment artifacts linked to a model version in the Model Control Plane.

    Args:
        model_name: The ID or name of the model containing version.
        model_version: The name, number or ID of the model version. If not
            provided, the latest version is used.
        **kwargs: Keyword arguments to filter models.
    """
    _print_artifacts_links_generic(
        model_name_or_id=model_name,
        model_version_name_or_number_or_id=model_version,
        only_deployment_artifacts=True,
        **kwargs,
    )

list_model_version_model_artifacts(model_name: str, model_version: Optional[str] = None, **kwargs: Any) -> None

List model artifacts linked to a model version in the Model Control Plane.

Parameters:

Name Type Description Default
model_name str

The ID or name of the model containing version.

required
model_version Optional[str]

The name, number or ID of the model version. If not provided, the latest version is used.

None
**kwargs Any

Keyword arguments to filter models.

{}
Source code in src/zenml/cli/model.py
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
@model.command(
    "model_artifacts",
    help="List model artifacts linked to a model version.",
)
@click.argument("model_name")
@click.option("--model_version", "-v", default=None)
@cli_utils.list_options(ModelVersionArtifactFilter)
def list_model_version_model_artifacts(
    model_name: str,
    model_version: Optional[str] = None,
    **kwargs: Any,
) -> None:
    """List model artifacts linked to a model version in the Model Control Plane.

    Args:
        model_name: The ID or name of the model containing version.
        model_version: The name, number or ID of the model version. If not
            provided, the latest version is used.
        **kwargs: Keyword arguments to filter models.
    """
    _print_artifacts_links_generic(
        model_name_or_id=model_name,
        model_version_name_or_number_or_id=model_version,
        only_model_artifacts=True,
        **kwargs,
    )

list_model_version_pipeline_runs(model_name: str, model_version: Optional[str] = None, **kwargs: Any) -> None

List pipeline runs of a model version in the Model Control Plane.

Parameters:

Name Type Description Default
model_name str

The ID or name of the model containing version.

required
model_version Optional[str]

The name, number or ID of the model version. If not provided, the latest version is used.

None
**kwargs Any

Keyword arguments to filter models.

{}
Source code in src/zenml/cli/model.py
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
@model.command(
    "runs",
    help="List pipeline runs of a model version.",
)
@click.argument("model_name")
@click.option("--model_version", "-v", default=None)
@cli_utils.list_options(ModelVersionPipelineRunFilter)
def list_model_version_pipeline_runs(
    model_name: str,
    model_version: Optional[str] = None,
    **kwargs: Any,
) -> None:
    """List pipeline runs of a model version in the Model Control Plane.

    Args:
        model_name: The ID or name of the model containing version.
        model_version: The name, number or ID of the model version. If not
            provided, the latest version is used.
        **kwargs: Keyword arguments to filter models.
    """
    model_version_response_model = Client().get_model_version(
        model_name_or_id=model_name,
        model_version_name_or_number_or_id=model_version,
    )

    if not model_version_response_model.pipeline_run_ids:
        cli_utils.declare("No pipeline runs attached to model version found.")
        return
    cli_utils.title(
        f"Pipeline runs linked to the model version `{model_version_response_model.name}[{model_version_response_model.number}]`:"
    )

    links = Client().list_model_version_pipeline_run_links(
        model_version_id=model_version_response_model.id,
        **kwargs,
    )

    cli_utils.print_pydantic_models(
        links,
        columns=[
            "pipeline_run",
            "created",
        ],
    )

list_model_versions(**kwargs: Any) -> None

List model versions with filter in the Model Control Plane.

Parameters:

Name Type Description Default
**kwargs Any

Keyword arguments to filter models.

{}
Source code in src/zenml/cli/model.py
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
@cli_utils.list_options(ModelVersionFilter)
@version.command("list", help="List model versions with filter.")
def list_model_versions(**kwargs: Any) -> None:
    """List model versions with filter in the Model Control Plane.

    Args:
        **kwargs: Keyword arguments to filter models.
    """
    model_versions = Client().list_model_versions(**kwargs)

    if not model_versions:
        cli_utils.declare("No model versions found.")
        return

    to_print = []
    for model_version in model_versions:
        to_print.append(_model_version_to_print(model_version))

    cli_utils.print_table(to_print)

list_models(**kwargs: Any) -> None

List models with filter in the Model Control Plane.

Parameters:

Name Type Description Default
**kwargs Any

Keyword arguments to filter models.

{}
Source code in src/zenml/cli/model.py
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
@cli_utils.list_options(ModelFilter)
@model.command("list", help="List models with filter.")
def list_models(**kwargs: Any) -> None:
    """List models with filter in the Model Control Plane.

    Args:
        **kwargs: Keyword arguments to filter models.
    """
    models = Client().list_models(**kwargs)

    if not models:
        cli_utils.declare("No models found.")
        return
    to_print = []
    for model in models:
        to_print.append(_model_to_print(model))
    cli_utils.print_table(to_print)

list_options(filter_model: Type[BaseFilter]) -> Callable[[F], F]

Create a decorator to generate the correct list of filter parameters.

The Outer decorator (list_options) is responsible for creating the inner decorator. This is necessary so that the type of FilterModel can be passed in as a parameter.

Based on the filter model, the inner decorator extracts all the click options that should be added to the decorated function (wrapper).

Parameters:

Name Type Description Default
filter_model Type[BaseFilter]

The filter model based on which to decorate the function.

required

Returns:

Type Description
Callable[[F], F]

The inner decorator.

Source code in src/zenml/cli/utils.py
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
def list_options(filter_model: Type[BaseFilter]) -> Callable[[F], F]:
    """Create a decorator to generate the correct list of filter parameters.

    The Outer decorator (`list_options`) is responsible for creating the inner
    decorator. This is necessary so that the type of `FilterModel` can be passed
    in as a parameter.

    Based on the filter model, the inner decorator extracts all the click
    options that should be added to the decorated function (wrapper).

    Args:
        filter_model: The filter model based on which to decorate the function.

    Returns:
        The inner decorator.
    """

    def inner_decorator(func: F) -> F:
        options = []
        data_type_descriptors = set()
        for k, v in filter_model.model_fields.items():
            if k not in filter_model.CLI_EXCLUDE_FIELDS:
                options.append(
                    click.option(
                        f"--{k}",
                        type=str,
                        default=v.default,
                        required=False,
                        multiple=_is_list_field(v),
                        help=create_filter_help_text(filter_model, k),
                    )
                )
            if k not in filter_model.FILTER_EXCLUDE_FIELDS:
                data_type_descriptors.add(
                    create_data_type_help_text(filter_model, k)
                )

        def wrapper(function: F) -> F:
            for option in reversed(options):
                function = option(function)
            return function

        func.__doc__ = (
            f"{func.__doc__} By default all filters are "
            f"interpreted as a check for equality. However advanced "
            f"filter operators can be used to tune the filtering by "
            f"writing the operator and separating it from the "
            f"query parameter with a colon `:`, e.g. "
            f"--field='operator:query'."
        )

        if data_type_descriptors:
            joined_data_type_descriptors = "\n\n".join(data_type_descriptors)

            func.__doc__ = (
                f"{func.__doc__} \n\n"
                f"\b Each datatype supports a specific "
                f"set of filter operations, here are the relevant "
                f"ones for the parameters of this command: \n\n"
                f"{joined_data_type_descriptors}"
            )

        return wrapper(func)

    return inner_decorator

list_pipeline_builds(**kwargs: Any) -> None

List all pipeline builds for the filter.

Parameters:

Name Type Description Default
**kwargs Any

Keyword arguments to filter pipeline builds.

{}
Source code in src/zenml/cli/pipeline.py
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
@builds.command("list", help="List all pipeline builds.")
@list_options(PipelineBuildFilter)
def list_pipeline_builds(**kwargs: Any) -> None:
    """List all pipeline builds for the filter.

    Args:
        **kwargs: Keyword arguments to filter pipeline builds.
    """
    client = Client()
    try:
        with console.status("Listing pipeline builds...\n"):
            pipeline_builds = client.list_builds(hydrate=True, **kwargs)
    except KeyError as err:
        cli_utils.error(str(err))
    else:
        if not pipeline_builds.items:
            cli_utils.declare("No pipeline builds found for this filter.")
            return

        cli_utils.print_pydantic_models(
            pipeline_builds,
            exclude_columns=[
                "created",
                "updated",
                "user",
                "project",
                "images",
                "stack_checksum",
            ],
        )

list_pipeline_runs(**kwargs: Any) -> None

List all registered pipeline runs for the filter.

Parameters:

Name Type Description Default
**kwargs Any

Keyword arguments to filter pipeline runs.

{}
Source code in src/zenml/cli/pipeline.py
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
@runs.command("list", help="List all registered pipeline runs.")
@list_options(PipelineRunFilter)
def list_pipeline_runs(**kwargs: Any) -> None:
    """List all registered pipeline runs for the filter.

    Args:
        **kwargs: Keyword arguments to filter pipeline runs.
    """
    client = Client()
    try:
        with console.status("Listing pipeline runs...\n"):
            pipeline_runs = client.list_pipeline_runs(**kwargs)
    except KeyError as err:
        cli_utils.error(str(err))
    else:
        if not pipeline_runs.items:
            cli_utils.declare("No pipeline runs found for this filter.")
            return

        cli_utils.print_pipeline_runs_table(pipeline_runs=pipeline_runs.items)
        cli_utils.print_page_info(pipeline_runs)

list_pipelines(**kwargs: Any) -> None

List all registered pipelines.

Parameters:

Name Type Description Default
**kwargs Any

Keyword arguments to filter pipelines.

{}
Source code in src/zenml/cli/pipeline.py
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
@pipeline.command("list", help="List all registered pipelines.")
@list_options(PipelineFilter)
def list_pipelines(**kwargs: Any) -> None:
    """List all registered pipelines.

    Args:
        **kwargs: Keyword arguments to filter pipelines.
    """
    client = Client()
    with console.status("Listing pipelines...\n"):
        pipelines = client.list_pipelines(**kwargs)

        if not pipelines.items:
            cli_utils.declare("No pipelines found for this filter.")
            return

        cli_utils.print_pydantic_models(
            pipelines,
            exclude_columns=["id", "created", "updated", "user", "project"],
        )

list_projects(ctx: click.Context, /, **kwargs: Any) -> None

List all projects.

Parameters:

Name Type Description Default
ctx Context

The click context object

required
**kwargs Any

Keyword arguments to filter the list of projects.

{}
Source code in src/zenml/cli/project.py
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
@project.command("list")
@list_options(ProjectFilter)
@click.pass_context
def list_projects(ctx: click.Context, /, **kwargs: Any) -> None:
    """List all projects.

    Args:
        ctx: The click context object
        **kwargs: Keyword arguments to filter the list of projects.
    """
    check_zenml_pro_project_availability()
    client = Client()
    with console.status("Listing projects...\n"):
        projects = client.list_projects(**kwargs)
        if projects:
            try:
                active_project = [client.active_project]
            except Exception:
                active_project = []
            cli_utils.print_pydantic_models(
                projects,
                exclude_columns=["id", "created", "updated"],
                active_models=active_project,
                show_active=not is_sorted_or_filtered(ctx),
            )
        else:
            cli_utils.declare("No projects found for the given filter.")

list_schedules(**kwargs: Any) -> None

List all pipeline schedules.

Parameters:

Name Type Description Default
**kwargs Any

Keyword arguments to filter schedules.

{}
Source code in src/zenml/cli/pipeline.py
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
@schedule.command("list", help="List all pipeline schedules.")
@list_options(ScheduleFilter)
def list_schedules(**kwargs: Any) -> None:
    """List all pipeline schedules.

    Args:
        **kwargs: Keyword arguments to filter schedules.
    """
    client = Client()

    schedules = client.list_schedules(**kwargs)

    if not schedules:
        cli_utils.declare("No schedules found for this filter.")
        return

    cli_utils.print_pydantic_models(
        schedules,
        exclude_columns=["id", "created", "updated", "user", "project"],
    )

list_secrets(**kwargs: Any) -> None

List all secrets that fulfill the filter criteria.

Parameters:

Name Type Description Default
kwargs Any

Keyword arguments to filter the secrets.

{}
Source code in src/zenml/cli/secret.py
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
@secret.command(
    "list", help="List all registered secrets that match the filter criteria."
)
@list_options(SecretFilter)
def list_secrets(**kwargs: Any) -> None:
    """List all secrets that fulfill the filter criteria.

    Args:
        kwargs: Keyword arguments to filter the secrets.
    """
    client = Client()
    with console.status("Listing secrets..."):
        try:
            secrets = client.list_secrets(**kwargs)
        except NotImplementedError as e:
            error(f"Centralized secrets management is disabled: {str(e)}")
        if not secrets.items:
            warning("No secrets found for the given filters.")
            return

        secret_rows = [
            dict(
                name=secret.name,
                id=str(secret.id),
                private=secret.private,
            )
            for secret in secrets.items
        ]
        print_table(secret_rows)
        print_page_info(secrets)

list_service_accounts(ctx: click.Context, /, **kwargs: Any) -> None

List all users.

Parameters:

Name Type Description Default
ctx Context

The click context object

required
kwargs Any

Keyword arguments to filter the list of users.

{}
Source code in src/zenml/cli/service_accounts.py
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
@service_account.command("list")
@list_options(ServiceAccountFilter)
@click.pass_context
def list_service_accounts(ctx: click.Context, /, **kwargs: Any) -> None:
    """List all users.

    Args:
        ctx: The click context object
        kwargs: Keyword arguments to filter the list of users.
    """
    client = Client()
    with console.status("Listing service accounts...\n"):
        service_accounts = client.list_service_accounts(**kwargs)
        if not service_accounts:
            cli_utils.declare(
                "No service accounts found for the given filters."
            )
            return

        cli_utils.print_pydantic_models(
            service_accounts,
            exclude_columns=[
                "created",
                "updated",
            ],
        )

list_service_connector_resources(connector_type: Optional[str] = None, resource_type: Optional[str] = None, resource_id: Optional[str] = None, exclude_errors: bool = False) -> None

List resources that can be accessed by service connectors.

Parameters:

Name Type Description Default
connector_type Optional[str]

The type of service connector to filter by.

None
resource_type Optional[str]

The type of resource to filter by.

None
resource_id Optional[str]

The name of a resource to filter by.

None
exclude_errors bool

Exclude resources that cannot be accessed due to errors.

False
Source code in src/zenml/cli/service_connectors.py
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
@service_connector.command(
    "list-resources",
    help="""List all resources accessible by service connectors.

This command can be used to list all resources that can be accessed by the
currently registered service connectors. You can filter the list by connector
type and/or resource type.

Use this command to answer questions like:

- show a list of all Kubernetes clusters that can be accessed by way of service
connectors
- show a list of all connectors along with all the resources they can access or
the error state they are in, if any

NOTE: since this command exercises all service connectors currently registered
with ZenML, it may take a while to complete.

Examples:

- show a list of all S3 buckets that can be accessed by service connectors:

    $ zenml service-connector list-resources --resource-type s3-bucket

- show a list of all resources that the AWS connectors currently registered
with ZenML can access:

    $ zenml service-connector list-resources --connector-type aws

""",
)
@click.option(
    "--connector-type",
    "-c",
    "connector_type",
    help="The type of service connector to filter by.",
    required=False,
    type=str,
)
@click.option(
    "--resource-type",
    "-r",
    "resource_type",
    help="The type of resource to filter by.",
    required=False,
    type=str,
)
@click.option(
    "--resource-id",
    "-ri",
    "resource_id",
    help="The name of a resource to filter by.",
    required=False,
    type=str,
)
@click.option(
    "--exclude-errors",
    "-e",
    "exclude_errors",
    help="Exclude resources that cannot be accessed due to errors.",
    required=False,
    is_flag=True,
)
def list_service_connector_resources(
    connector_type: Optional[str] = None,
    resource_type: Optional[str] = None,
    resource_id: Optional[str] = None,
    exclude_errors: bool = False,
) -> None:
    """List resources that can be accessed by service connectors.

    Args:
        connector_type: The type of service connector to filter by.
        resource_type: The type of resource to filter by.
        resource_id: The name of a resource to filter by.
        exclude_errors: Exclude resources that cannot be accessed due to
            errors.
    """
    client = Client()

    if not resource_type and not resource_id:
        cli_utils.warning(
            "Fetching all service connector resources can take a long time, "
            "depending on the number of connectors currently registered with "
            "ZenML. Consider using the '--connector-type', '--resource-type' "
            "and '--resource-id' options to narrow down the list of resources "
            "to fetch."
        )

    with console.status(
        "Fetching all service connector resources (this could take a while)...\n"
    ):
        try:
            resource_list = client.list_service_connector_resources(
                connector_type=connector_type,
                resource_type=resource_type,
                resource_id=resource_id,
            )
        except (
            KeyError,
            ValueError,
            IllegalOperationError,
            NotImplementedError,
            AuthorizationException,
        ) as e:
            cli_utils.error(
                f"Could not fetch service connector resources: {e}"
            )

        if exclude_errors:
            resource_list = [r for r in resource_list if r.error is None]

        if not resource_list:
            cli_utils.declare(
                "No service connector resources match the given filters."
            )
            return

    resource_str = ""
    if resource_type:
        resource_str = f" '{resource_type}'"
    connector_str = ""
    if connector_type:
        connector_str = f" '{connector_type}'"
    if resource_id:
        resource_str = f"{resource_str} resource with name '{resource_id}'"
    else:
        resource_str = f"following{resource_str} resources"

    click.echo(
        f"The {resource_str} can be accessed by"
        f"{connector_str} service connectors:"
    )

    cli_utils.print_service_connector_resource_table(
        resources=resource_list,
    )

list_service_connector_types(type: Optional[str] = None, resource_type: Optional[str] = None, auth_method: Optional[str] = None, detailed: bool = False) -> None

List service connector types.

Parameters:

Name Type Description Default
type Optional[str]

Filter by service connector type.

None
resource_type Optional[str]

Filter by the type of resource to connect to.

None
auth_method Optional[str]

Filter by the supported authentication method.

None
detailed bool

Show detailed information about the service connectors.

False
Source code in src/zenml/cli/service_connectors.py
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
@service_connector.command(
    "list-types",
    help="""List available service connector types.
""",
)
@click.option(
    "--type",
    "-t",
    "type",
    help="Filter by service connector type.",
    required=False,
    type=str,
)
@click.option(
    "--resource-type",
    "-r",
    "resource_type",
    help="Filter by the type of resource to connect to.",
    required=False,
    type=str,
)
@click.option(
    "--auth-method",
    "-a",
    "auth_method",
    help="Filter by the supported authentication method.",
    required=False,
    type=str,
)
@click.option(
    "--detailed",
    "-d",
    "detailed",
    help="Show detailed information about the service connector types.",
    required=False,
    is_flag=True,
)
def list_service_connector_types(
    type: Optional[str] = None,
    resource_type: Optional[str] = None,
    auth_method: Optional[str] = None,
    detailed: bool = False,
) -> None:
    """List service connector types.

    Args:
        type: Filter by service connector type.
        resource_type: Filter by the type of resource to connect to.
        auth_method: Filter by the supported authentication method.
        detailed: Show detailed information about the service connectors.
    """
    client = Client()

    service_connector_types = client.list_service_connector_types(
        connector_type=type,
        resource_type=resource_type,
        auth_method=auth_method,
    )

    if not service_connector_types:
        cli_utils.error(
            "No service connector types found matching the criteria."
        )

    if detailed:
        for connector_type in service_connector_types:
            cli_utils.print_service_connector_type(connector_type)
    else:
        cli_utils.print_service_connector_types_table(
            connector_types=service_connector_types
        )

list_service_connectors(ctx: click.Context, /, labels: Optional[List[str]] = None, **kwargs: Any) -> None

List all service connectors.

Parameters:

Name Type Description Default
ctx Context

The click context object

required
labels Optional[List[str]]

Labels to filter by.

None
kwargs Any

Keyword arguments to filter the components.

{}
Source code in src/zenml/cli/service_connectors.py
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
@service_connector.command(
    "list",
    help="""List available service connectors.
""",
)
@list_options(ServiceConnectorFilter)
@click.option(
    "--label",
    "-l",
    "labels",
    help="Label to filter by. Takes the form `-l key1=value1` or `-l key` and "
    "can be used multiple times.",
    multiple=True,
)
@click.pass_context
def list_service_connectors(
    ctx: click.Context, /, labels: Optional[List[str]] = None, **kwargs: Any
) -> None:
    """List all service connectors.

    Args:
        ctx: The click context object
        labels: Labels to filter by.
        kwargs: Keyword arguments to filter the components.
    """
    client = Client()

    if labels:
        kwargs["labels"] = cli_utils.get_parsed_labels(
            labels, allow_label_only=True
        )

    connectors = client.list_service_connectors(**kwargs)
    if not connectors:
        cli_utils.declare("No service connectors found for the given filters.")
        return

    cli_utils.print_service_connectors_table(
        client=client,
        connectors=connectors.items,
        show_active=not is_sorted_or_filtered(ctx),
    )
    print_page_info(connectors)

list_stacks(ctx: click.Context, /, **kwargs: Any) -> None

List all stacks that fulfill the filter requirements.

Parameters:

Name Type Description Default
ctx Context

the Click context

required
kwargs Any

Keyword arguments to filter the stacks.

{}
Source code in src/zenml/cli/stack.py
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
@stack.command("list")
@list_options(StackFilter)
@click.pass_context
def list_stacks(ctx: click.Context, /, **kwargs: Any) -> None:
    """List all stacks that fulfill the filter requirements.

    Args:
        ctx: the Click context
        kwargs: Keyword arguments to filter the stacks.
    """
    client = Client()
    with console.status("Listing stacks...\n"):
        stacks = client.list_stacks(**kwargs)
        if not stacks:
            cli_utils.declare("No stacks found for the given filters.")
            return
        print_stacks_table(
            client=client,
            stacks=stacks.items,
            show_active=not is_sorted_or_filtered(ctx),
        )
        print_page_info(stacks)

list_tags(**kwargs: Any) -> None

List tags with filter.

Parameters:

Name Type Description Default
**kwargs Any

Keyword arguments to filter models.

{}
Source code in src/zenml/cli/tag.py
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
@cli_utils.list_options(TagFilter)
@tag.command("list", help="List tags with filter.")
def list_tags(**kwargs: Any) -> None:
    """List tags with filter.

    Args:
        **kwargs: Keyword arguments to filter models.
    """
    tags = Client().list_tags(**kwargs)

    if not tags:
        cli_utils.declare("No tags found.")
        return

    cli_utils.print_pydantic_models(
        tags,
        exclude_columns=["created"],
    )

list_users(ctx: click.Context, /, **kwargs: Any) -> None

List all users.

Parameters:

Name Type Description Default
ctx Context

The click context object

required
kwargs Any

Keyword arguments to filter the list of users.

{}
Source code in src/zenml/cli/user_management.py
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
@user.command("list")
@list_options(UserFilter)
@click.pass_context
def list_users(ctx: click.Context, /, **kwargs: Any) -> None:
    """List all users.

    Args:
        ctx: The click context object
        kwargs: Keyword arguments to filter the list of users.
    """
    client = Client()
    with console.status("Listing stacks...\n"):
        users = client.list_users(**kwargs)
        if not users:
            cli_utils.declare("No users found for the given filters.")
            return

        cli_utils.print_pydantic_models(
            users,
            exclude_columns=[
                "created",
                "updated",
                "email",
                "email_opted_in",
                "activation_token",
            ],
            active_models=[Client().active_user],
            show_active=not is_sorted_or_filtered(ctx),
        )

lock_authorized_device(id: str) -> None

Lock an authorized device.

Parameters:

Name Type Description Default
id str

The ID of the authorized device to lock.

required
Source code in src/zenml/cli/authorized_device.py
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
@authorized_device.command("lock")
@click.argument("id", type=str, required=True)
def lock_authorized_device(id: str) -> None:
    """Lock an authorized device.

    Args:
        id: The ID of the authorized device to lock.
    """
    try:
        Client().update_authorized_device(
            id_or_prefix=id,
            locked=True,
        )
    except KeyError as e:
        cli_utils.error(str(e))
    else:
        cli_utils.declare(f"Locked authorized device `{id}`.")

logging() -> None

Configuration of logging for ZenML pipelines.

Source code in src/zenml/cli/config.py
62
63
64
@cli.group(cls=TagGroup, tag=CliCategories.MANAGEMENT_TOOLS)
def logging() -> None:
    """Configuration of logging for ZenML pipelines."""

login_service_connector(name_id_or_prefix: str, resource_type: Optional[str] = None, resource_id: Optional[str] = None) -> None

Authenticate the local client/SDK with connector credentials.

Parameters:

Name Type Description Default
name_id_or_prefix str

The name or id of the service connector to use.

required
resource_type Optional[str]

The type of resource to connect to.

None
resource_id Optional[str]

Explicit resource ID to connect to.

None
Source code in src/zenml/cli/service_connectors.py
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
@service_connector.command(
    "login",
    help="""Configure the local client/SDK with credentials.

Some service connectors have the ability to configure clients or SDKs installed
on your local machine with credentials extracted from or generated by the
service connector. This command can be used to do that.

For connectors that are configured to access multiple types of resources or 
multiple resource instances, the resource type and resource ID must be
specified to indicate which resource is targeted by this command.

Examples:

- configure the local Kubernetes (kubectl) CLI with credentials generated from
a generic, multi-type, multi-instance AWS service connector:

    $ zenml service-connector login my-generic-aws-connector \\             
--resource-type kubernetes-cluster --resource-id my-eks-cluster

- configure the local Docker CLI with credentials configured in a Docker
service connector:

    $ zenml service-connector login my-docker-connector
""",
)
@click.option(
    "--resource-type",
    "-r",
    "resource_type",
    help="The type of resource to connect to.",
    required=False,
    type=str,
)
@click.option(
    "--resource-id",
    "-ri",
    "resource_id",
    help="Explicit resource ID to connect to.",
    required=False,
    type=str,
)
@click.argument("name_id_or_prefix", type=str, required=True)
def login_service_connector(
    name_id_or_prefix: str,
    resource_type: Optional[str] = None,
    resource_id: Optional[str] = None,
) -> None:
    """Authenticate the local client/SDK with connector credentials.

    Args:
        name_id_or_prefix: The name or id of the service connector to use.
        resource_type: The type of resource to connect to.
        resource_id: Explicit resource ID to connect to.
    """
    client = Client()

    with console.status(
        "Attempting to configure local client using service connector "
        f"'{name_id_or_prefix}'...\n"
    ):
        try:
            connector = client.login_service_connector(
                name_id_or_prefix=name_id_or_prefix,
                resource_type=resource_type,
                resource_id=resource_id,
            )
        except (
            KeyError,
            ValueError,
            IllegalOperationError,
            NotImplementedError,
            AuthorizationException,
        ) as e:
            cli_utils.error(
                f"Service connector '{name_id_or_prefix}' could not configure "
                f"the local client/SDK: {e}"
            )

        spec = connector.get_type()
        resource_type = resource_type or connector.resource_type
        assert resource_type is not None
        resource_name = spec.resource_type_dict[resource_type].name
        cli_utils.declare(
            f"The '{name_id_or_prefix}' {spec.name} connector was used to "
            f"successfully configure the local {resource_name} client/SDK."
        )

logs(follow: bool = False, raw: bool = False, tail: Optional[int] = None) -> None

Display the logs for a ZenML server.

Parameters:

Name Type Description Default
follow bool

Continue to output new log data as it becomes available.

False
tail Optional[int]

Only show the last NUM lines of log output.

None
raw bool

Show raw log contents (don't pretty-print logs).

False
Source code in src/zenml/cli/server.py
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
@cli.command("logs", help="Show the logs for the local ZenML server.")
@click.option(
    "--follow",
    "-f",
    is_flag=True,
    help="Continue to output new log data as it becomes available.",
)
@click.option(
    "--tail",
    "-t",
    type=click.INT,
    default=None,
    help="Only show the last NUM lines of log output.",
)
@click.option(
    "--raw",
    "-r",
    is_flag=True,
    help="Show raw log contents (don't pretty-print logs).",
)
def logs(
    follow: bool = False,
    raw: bool = False,
    tail: Optional[int] = None,
) -> None:
    """Display the logs for a ZenML server.

    Args:
        follow: Continue to output new log data as it becomes available.
        tail: Only show the last NUM lines of log output.
        raw: Show raw log contents (don't pretty-print logs).
    """
    server = get_local_server()
    if server is None:
        cli_utils.error(
            "The local ZenML dashboard is not running. Please call `zenml "
            "login --local` first to start the ZenML dashboard locally."
        )

    from zenml.zen_server.deploy.deployer import LocalServerDeployer

    deployer = LocalServerDeployer()

    cli_utils.declare(
        f"Showing logs for the local {server.config.provider} server"
    )

    from zenml.zen_server.deploy.exceptions import (
        ServerDeploymentNotFoundError,
    )

    try:
        logs = deployer.get_server_logs(follow=follow, tail=tail)
    except ServerDeploymentNotFoundError as e:
        cli_utils.error(f"Server not found: {e}")

    for line in logs:
        # don't pretty-print log lines that are already pretty-printed
        if raw or line.startswith("\x1b["):
            console.print(line, markup=False)
        else:
            try:
                console.print(line)
            except MarkupError:
                console.print(line, markup=False)

migrate_database(skip_default_registrations: bool = False) -> None

Migrate the ZenML database.

Parameters:

Name Type Description Default
skip_default_registrations bool

If True, registration of default components will be skipped.

False
Source code in src/zenml/cli/base.py
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
@cli.command(
    "migrate-database", help="Migrate the ZenML database.", hidden=True
)
@click.option(
    "--skip_default_registrations",
    is_flag=True,
    default=False,
    help="Skip registering default project, user and stack.",
    type=bool,
)
def migrate_database(skip_default_registrations: bool = False) -> None:
    """Migrate the ZenML database.

    Args:
        skip_default_registrations: If `True`, registration of default
            components will be skipped.
    """
    from zenml.zen_stores.base_zen_store import BaseZenStore

    store_config = GlobalConfiguration().store_configuration
    if store_config.type == StoreType.SQL:
        BaseZenStore.create_store(
            store_config, skip_default_registrations=skip_default_registrations
        )
        cli_utils.declare("Database migration finished.")
    else:
        cli_utils.warning(
            "Unable to migrate database while connected to a ZenML server."
        )

model() -> None

Interact with models and model versions in the Model Control Plane.

Source code in src/zenml/cli/model.py
81
82
83
@cli.group(cls=TagGroup, tag=CliCategories.MODEL_CONTROL_PLANE)
def model() -> None:
    """Interact with models and model versions in the Model Control Plane."""

opt_in() -> None

Opt-in to analytics.

Source code in src/zenml/cli/config.py
39
40
41
42
43
44
45
46
47
@analytics.command(
    "opt-in", context_settings=dict(ignore_unknown_options=True)
)
@track_decorator(AnalyticsEvent.OPT_IN_ANALYTICS)
def opt_in() -> None:
    """Opt-in to analytics."""
    gc = GlobalConfiguration()
    gc.analytics_opt_in = True
    cli_utils.declare("Opted in to analytics.")

opt_out() -> None

Opt-out of analytics.

Source code in src/zenml/cli/config.py
50
51
52
53
54
55
56
57
58
@analytics.command(
    "opt-out", context_settings=dict(ignore_unknown_options=True)
)
@track_decorator(AnalyticsEvent.OPT_OUT_ANALYTICS)
def opt_out() -> None:
    """Opt-out of analytics."""
    gc = GlobalConfiguration()
    gc.analytics_opt_in = False
    cli_utils.declare("Opted out of analytics.")

parse_name_and_extra_arguments(args: List[str], expand_args: bool = False, name_mandatory: bool = True) -> Tuple[Optional[str], Dict[str, str]]

Parse a name and extra arguments from the CLI.

This is a utility function used to parse a variable list of optional CLI arguments of the form --key=value that must also include one mandatory free-form name argument. There is no restriction as to the order of the arguments.

Examples:

>>> parse_name_and_extra_arguments(['foo']])
('foo', {})
>>> parse_name_and_extra_arguments(['foo', '--bar=1'])
('foo', {'bar': '1'})
>>> parse_name_and_extra_arguments(['--bar=1', 'foo', '--baz=2'])
('foo', {'bar': '1', 'baz': '2'})
>>> parse_name_and_extra_arguments(['--bar=1'])
Traceback (most recent call last):
    ...
    ValueError: Missing required argument: name

Parameters:

Name Type Description Default
args List[str]

A list of command line arguments from the CLI.

required
expand_args bool

Whether to expand argument values into the contents of the files they may be pointing at using the special @ character.

False
name_mandatory bool

Whether the name argument is mandatory.

True

Returns:

Type Description
Tuple[Optional[str], Dict[str, str]]

The name and a dict of parsed args.

Source code in src/zenml/cli/utils.py
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
def parse_name_and_extra_arguments(
    args: List[str],
    expand_args: bool = False,
    name_mandatory: bool = True,
) -> Tuple[Optional[str], Dict[str, str]]:
    """Parse a name and extra arguments from the CLI.

    This is a utility function used to parse a variable list of optional CLI
    arguments of the form `--key=value` that must also include one mandatory
    free-form name argument. There is no restriction as to the order of the
    arguments.

    Examples:
        >>> parse_name_and_extra_arguments(['foo']])
        ('foo', {})
        >>> parse_name_and_extra_arguments(['foo', '--bar=1'])
        ('foo', {'bar': '1'})
        >>> parse_name_and_extra_arguments(['--bar=1', 'foo', '--baz=2'])
        ('foo', {'bar': '1', 'baz': '2'})
        >>> parse_name_and_extra_arguments(['--bar=1'])
        Traceback (most recent call last):
            ...
            ValueError: Missing required argument: name

    Args:
        args: A list of command line arguments from the CLI.
        expand_args: Whether to expand argument values into the contents of the
            files they may be pointing at using the special `@` character.
        name_mandatory: Whether the name argument is mandatory.

    Returns:
        The name and a dict of parsed args.
    """
    name: Optional[str] = None
    # The name was not supplied as the first argument, we have to
    # search the other arguments for the name.
    for i, arg in enumerate(args):
        if not arg:
            # Skip empty arguments.
            continue
        if arg.startswith("--"):
            continue
        name = args.pop(i)
        break
    else:
        if name_mandatory:
            error(
                "A name must be supplied. Please see the command help for more "
                "information."
            )

    message = (
        "Please provide args with a proper "
        "identifier as the key and the following structure: "
        '--custom_argument="value"'
    )
    args_dict: Dict[str, str] = {}
    for a in args:
        if not a:
            # Skip empty arguments.
            continue
        if not a.startswith("--") or "=" not in a:
            error(f"Invalid argument: '{a}'. {message}")
        key, value = a[2:].split("=", maxsplit=1)
        if not key.isidentifier():
            error(f"Invalid argument: '{a}'. {message}")
        args_dict[key] = value

    if expand_args:
        args_dict = {
            k: expand_argument_value_from_file(k, v)
            for k, v in args_dict.items()
        }

    return name, args_dict

pipeline() -> None

Interact with pipelines, runs and schedules.

Source code in src/zenml/cli/pipeline.py
72
73
74
@cli.group(cls=TagGroup, tag=CliCategories.MANAGEMENT_TOOLS)
def pipeline() -> None:
    """Interact with pipelines, runs and schedules."""

pretty_print_model_deployer(model_services: List[BaseService], model_deployer: BaseModelDeployer) -> None

Given a list of served_models, print all associated key-value pairs.

Parameters:

Name Type Description Default
model_services List[BaseService]

list of model deployment services

required
model_deployer BaseModelDeployer

Active model deployer

required
Source code in src/zenml/cli/utils.py
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
def pretty_print_model_deployer(
    model_services: List["BaseService"], model_deployer: "BaseModelDeployer"
) -> None:
    """Given a list of served_models, print all associated key-value pairs.

    Args:
        model_services: list of model deployment services
        model_deployer: Active model deployer
    """
    model_service_dicts = []
    for model_service in model_services:
        dict_uuid = str(model_service.uuid)
        dict_pl_name = model_service.config.pipeline_name
        dict_pl_stp_name = model_service.config.pipeline_step_name
        dict_model_name = model_service.config.model_name
        type = model_service.SERVICE_TYPE.type
        flavor = model_service.SERVICE_TYPE.flavor
        model_service_dicts.append(
            {
                "STATUS": get_service_state_emoji(model_service.status.state),
                "UUID": dict_uuid,
                "TYPE": type,
                "FLAVOR": flavor,
                "PIPELINE_NAME": dict_pl_name,
                "PIPELINE_STEP_NAME": dict_pl_stp_name,
                "MODEL_NAME": dict_model_name,
            }
        )
    print_table(
        model_service_dicts, UUID=table.Column(header="UUID", min_width=36)
    )

pretty_print_secret(secret: Dict[str, str], hide_secret: bool = True) -> None

Print all key-value pairs associated with a secret.

Parameters:

Name Type Description Default
secret Dict[str, str]

Secret values to print.

required
hide_secret bool

boolean that configures if the secret values are shown on the CLI

True
Source code in src/zenml/cli/utils.py
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
def pretty_print_secret(
    secret: Dict[str, str],
    hide_secret: bool = True,
) -> None:
    """Print all key-value pairs associated with a secret.

    Args:
        secret: Secret values to print.
        hide_secret: boolean that configures if the secret values are shown
            on the CLI
    """
    title: Optional[str] = None

    def get_secret_value(value: Any) -> str:
        if value is None:
            return ""
        return "***" if hide_secret else str(value)

    stack_dicts = [
        {
            "SECRET_KEY": key,
            "SECRET_VALUE": get_secret_value(value),
        }
        for key, value in secret.items()
    ]

    print_table(stack_dicts, title=title)

print_model_url(url: Optional[str]) -> None

Pretty prints a given URL on the CLI.

Parameters:

Name Type Description Default
url Optional[str]

optional str, the URL to display.

required
Source code in src/zenml/cli/utils.py
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
def print_model_url(url: Optional[str]) -> None:
    """Pretty prints a given URL on the CLI.

    Args:
        url: optional str, the URL to display.
    """
    if url:
        declare(f"Dashboard URL: {url}")
    else:
        warning(
            "You can display various ZenML entities including pipelines, "
            "runs, stacks and much more on the ZenML Dashboard. "
            "You can try it locally, by running `zenml login --local`, or "
            "remotely, by deploying ZenML on the infrastructure of your choice."
        )

print_page_info(page: Page[T]) -> None

Print all page information showing the number of items and pages.

Parameters:

Name Type Description Default
page Page[T]

The page to print the information for.

required
Source code in src/zenml/cli/utils.py
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
def print_page_info(page: Page[T]) -> None:
    """Print all page information showing the number of items and pages.

    Args:
        page: The page to print the information for.
    """
    declare(
        f"Page `({page.index}/{page.total_pages})`, `{page.total}` items "
        f"found for the applied filters."
    )

print_served_model_configuration(model_service: BaseService, model_deployer: BaseModelDeployer) -> None

Prints the configuration of a model_service.

Parameters:

Name Type Description Default
model_service BaseService

Specific service instance to

required
model_deployer BaseModelDeployer

Active model deployer

required
Source code in src/zenml/cli/utils.py
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
def print_served_model_configuration(
    model_service: "BaseService", model_deployer: "BaseModelDeployer"
) -> None:
    """Prints the configuration of a model_service.

    Args:
        model_service: Specific service instance to
        model_deployer: Active model deployer
    """
    title_ = f"Properties of Served Model {model_service.uuid}"

    rich_table = table.Table(
        box=box.HEAVY_EDGE,
        title=title_,
        show_lines=True,
    )
    rich_table.add_column("MODEL SERVICE PROPERTY", overflow="fold")
    rich_table.add_column("VALUE", overflow="fold")

    # Get implementation specific info
    served_model_info = model_deployer.get_model_server_info(model_service)

    served_model_info = {
        **served_model_info,
        "UUID": str(model_service.uuid),
        "STATUS": get_service_state_emoji(model_service.status.state),
        "TYPE": model_service.SERVICE_TYPE.type,
        "FLAVOR": model_service.SERVICE_TYPE.flavor,
        "STATUS_MESSAGE": model_service.status.last_error,
        "PIPELINE_NAME": model_service.config.pipeline_name,
        "PIPELINE_STEP_NAME": model_service.config.pipeline_step_name,
    }

    # Sort fields alphabetically
    sorted_items = {k: v for k, v in sorted(served_model_info.items())}

    for item in sorted_items.items():
        rich_table.add_row(*[str(elem) for elem in item])

    # capitalize entries in first column
    rich_table.columns[0]._cells = [
        component.upper()  # type: ignore[union-attr]
        for component in rich_table.columns[0]._cells
    ]
    console.print(rich_table)

print_stacks_table(client: Client, stacks: Sequence[StackResponse], show_active: bool = False) -> None

Print a prettified list of all stacks supplied to this method.

Parameters:

Name Type Description Default
client Client

Repository instance

required
stacks Sequence[StackResponse]

List of stacks

required
show_active bool

Flag to decide whether to append the active stack on the top of the list.

False
Source code in src/zenml/cli/utils.py
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
def print_stacks_table(
    client: "Client",
    stacks: Sequence["StackResponse"],
    show_active: bool = False,
) -> None:
    """Print a prettified list of all stacks supplied to this method.

    Args:
        client: Repository instance
        stacks: List of stacks
        show_active: Flag to decide whether to append the active stack on the
            top of the list.
    """
    stack_dicts = []

    stacks = list(stacks)
    active_stack = client.active_stack_model
    if show_active:
        if active_stack.id not in [s.id for s in stacks]:
            stacks.append(active_stack)

        stacks = [s for s in stacks if s.id == active_stack.id] + [
            s for s in stacks if s.id != active_stack.id
        ]

    active_stack_model_id = client.active_stack_model.id
    for stack in stacks:
        is_active = stack.id == active_stack_model_id

        if stack.user:
            user_name = stack.user.name
        else:
            user_name = "-"

        stack_config = {
            "ACTIVE": ":point_right:" if is_active else "",
            "STACK NAME": stack.name,
            "STACK ID": stack.id,
            "OWNER": user_name,
            **{
                component_type.upper(): components[0].name
                for component_type, components in stack.components.items()
            },
        }
        stack_dicts.append(stack_config)

    print_table(stack_dicts)

print_table(obj: List[Dict[str, Any]], title: Optional[str] = None, caption: Optional[str] = None, **columns: table.Column) -> None

Prints the list of dicts in a table format.

The input object should be a List of Dicts. Each item in that list represent a line in the Table. Each dict should have the same keys. The keys of the dict will be used as headers of the resulting table.

Parameters:

Name Type Description Default
obj List[Dict[str, Any]]

A List containing dictionaries.

required
title Optional[str]

Title of the table.

None
caption Optional[str]

Caption of the table.

None
columns Column

Optional column configurations to be used in the table.

{}
Source code in src/zenml/cli/utils.py
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
def print_table(
    obj: List[Dict[str, Any]],
    title: Optional[str] = None,
    caption: Optional[str] = None,
    **columns: table.Column,
) -> None:
    """Prints the list of dicts in a table format.

    The input object should be a List of Dicts. Each item in that list represent
    a line in the Table. Each dict should have the same keys. The keys of the
    dict will be used as headers of the resulting table.

    Args:
        obj: A List containing dictionaries.
        title: Title of the table.
        caption: Caption of the table.
        columns: Optional column configurations to be used in the table.
    """
    from rich.text import Text

    column_keys = {key: None for dict_ in obj for key in dict_}
    column_names = [columns.get(key, key.upper()) for key in column_keys]
    rich_table = table.Table(
        box=box.HEAVY_EDGE, show_lines=True, title=title, caption=caption
    )
    for col_name in column_names:
        if isinstance(col_name, str):
            rich_table.add_column(str(col_name), overflow="fold")
        else:
            rich_table.add_column(
                str(col_name.header).upper(), overflow="fold"
            )
    for dict_ in obj:
        values = []
        for key in column_keys:
            if key is None:
                values.append(None)
            else:
                v = dict_.get(key) or " "
                if isinstance(v, str) and (
                    v.startswith("http://") or v.startswith("https://")
                ):
                    # Display the URL as a hyperlink in a way that doesn't break
                    # the URL when it needs to be wrapped over multiple lines
                    value: Union[str, Text] = Text(v, style=f"link {v}")
                else:
                    value = str(v)
                    # Escape text when square brackets are used, but allow
                    # links to be decorated as rich style links
                    if "[" in value and "[link=" not in value:
                        value = escape(value)
                values.append(value)
        rich_table.add_row(*values)
    if len(rich_table.columns) > 1:
        rich_table.columns[0].justify = "center"
    console.print(rich_table)

project() -> None

Commands for project management.

Source code in src/zenml/cli/project.py
33
34
35
@cli.group(cls=TagGroup, tag=CliCategories.MANAGEMENT_TOOLS)
def project() -> None:
    """Commands for project management."""

prompt_connector_name(default_name: Optional[str] = None, connector: Optional[UUID] = None) -> str

Prompt the user for a service connector name.

Parameters:

Name Type Description Default
default_name Optional[str]

The default name to use if the user doesn't provide one.

None
connector Optional[UUID]

The UUID of a service connector being renamed.

None

Returns:

Type Description
str

The name provided by the user.

Source code in src/zenml/cli/service_connectors.py
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
def prompt_connector_name(
    default_name: Optional[str] = None, connector: Optional[UUID] = None
) -> str:
    """Prompt the user for a service connector name.

    Args:
        default_name: The default name to use if the user doesn't provide one.
        connector: The UUID of a service connector being renamed.

    Returns:
        The name provided by the user.
    """
    client = Client()

    while True:
        # Ask for a name
        title = "Please enter a name for the service connector"
        if connector:
            title += " or press Enter to keep the current name"

        name = click.prompt(
            title,
            type=str,
            default=default_name,
        )
        if not name:
            cli_utils.warning("The name cannot be empty")
            continue
        assert isinstance(name, str)

        # Check if the name is taken
        try:
            existing_connector = client.get_service_connector(
                name_id_or_prefix=name, allow_name_prefix_match=False
            )
        except KeyError:
            break
        else:
            if existing_connector.id == connector:
                break
            cli_utils.warning(
                f"A service connector with the name '{name}' already "
                "exists. Please choose a different name."
            )

    return name

prompt_expiration_time(min: Optional[int] = None, max: Optional[int] = None, default: Optional[int] = None) -> int

Prompt the user for an expiration time.

Parameters:

Name Type Description Default
min Optional[int]

The minimum allowed expiration time.

None
max Optional[int]

The maximum allowed expiration time.

None
default Optional[int]

The default expiration time.

None

Returns:

Type Description
int

The expiration time provided by the user.

Source code in src/zenml/cli/service_connectors.py
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
def prompt_expiration_time(
    min: Optional[int] = None,
    max: Optional[int] = None,
    default: Optional[int] = None,
) -> int:
    """Prompt the user for an expiration time.

    Args:
        min: The minimum allowed expiration time.
        max: The maximum allowed expiration time.
        default: The default expiration time.

    Returns:
        The expiration time provided by the user.
    """
    if min is None:
        min = 0
    min_str = f"min: {min} = {seconds_to_human_readable(min)}; "
    if max is not None:
        max_str = str(max)
        max_str = f"max: {max} = {seconds_to_human_readable(max)}"
    else:
        max = -1
        max_str = "max: unlimited"
    if default:
        default_str = (
            f"; default: {default} = {seconds_to_human_readable(default)}"
        )
    else:
        default_str = ""

    while True:
        expiration_seconds = click.prompt(
            "The authentication method involves generating "
            "temporary credentials. Please enter the time that "
            "the credentials should be valid for, in seconds "
            f"({min_str}{max_str}{default_str})",
            type=int,
            default=default,
        )

        assert expiration_seconds is not None
        assert isinstance(expiration_seconds, int)
        if expiration_seconds < min:
            cli_utils.warning(
                f"The expiration time must be at least "
                f"{min} seconds. Please enter a larger value."
            )
            continue
        if max > 0 and expiration_seconds > max:
            cli_utils.warning(
                f"The expiration time must not exceed "
                f"{max} seconds. Please enter a smaller value."
            )
            continue

        confirm = click.confirm(
            f"Credentials will be valid for "
            f"{seconds_to_human_readable(expiration_seconds)}. Keep this "
            "value?",
            default=True,
        )
        if confirm:
            break

    return expiration_seconds

prompt_expires_at(default: Optional[datetime] = None) -> Optional[datetime]

Prompt the user for an expiration timestamp.

Parameters:

Name Type Description Default
default Optional[datetime]

The default expiration time.

None

Returns:

Type Description
Optional[datetime]

The expiration time provided by the user.

Source code in src/zenml/cli/service_connectors.py
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
def prompt_expires_at(
    default: Optional[datetime] = None,
) -> Optional[datetime]:
    """Prompt the user for an expiration timestamp.

    Args:
        default: The default expiration time.

    Returns:
        The expiration time provided by the user.
    """
    if default is None:
        confirm = click.confirm(
            "Are the credentials you configured temporary? If so, you'll be asked "
            "to provide an expiration time in the next step.",
            default=False,
        )
        if not confirm:
            return None

    while True:
        default_str = ""
        if default is not None:
            seconds = int(
                (default - utc_now(tz_aware=default)).total_seconds()
            )
            default_str = (
                f" [{str(default)} i.e. in "
                f"{seconds_to_human_readable(seconds)}]"
            )

        expires_at = click.prompt(
            "Please enter the exact UTC date and time when the credentials "
            f"will expire e.g. '2023-12-31 23:59:59'{default_str}",
            type=click.DateTime(),
            default=default,
            show_default=False,
        )

        assert expires_at is not None
        assert isinstance(expires_at, datetime)
        if expires_at < utc_now(tz_aware=expires_at):
            cli_utils.warning(
                "The expiration time must be in the future. Please enter a "
                "later date and time."
            )
            continue

        seconds = int(
            (expires_at - utc_now(tz_aware=expires_at)).total_seconds()
        )

        confirm = click.confirm(
            f"Credentials will be valid until {str(expires_at)} UTC (i.e. "
            f"in {seconds_to_human_readable(seconds)}. Keep this value?",
            default=True,
        )
        if confirm:
            break

    return expires_at

prompt_resource_id(resource_name: str, resource_ids: List[str]) -> Optional[str]

Prompt the user for a resource ID.

Parameters:

Name Type Description Default
resource_name str

The name of the resource.

required
resource_ids List[str]

The list of available resource IDs.

required

Returns:

Type Description
Optional[str]

The resource ID provided by the user.

Source code in src/zenml/cli/service_connectors.py
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
def prompt_resource_id(
    resource_name: str, resource_ids: List[str]
) -> Optional[str]:
    """Prompt the user for a resource ID.

    Args:
        resource_name: The name of the resource.
        resource_ids: The list of available resource IDs.

    Returns:
        The resource ID provided by the user.
    """
    resource_id: Optional[str] = None
    if resource_ids:
        resource_ids_list = "\n - " + "\n - ".join(resource_ids)
        prompt = (
            f"The following {resource_name} instances "
            "are reachable through this connector:"
            f"{resource_ids_list}\n"
            "Please select one or leave it empty to create a "
            "connector that can be used to access any of them"
        )
        while True:
            # Ask the user to enter an optional resource ID
            resource_id = click.prompt(
                prompt,
                default="",
                type=str,
            )
            if (
                not resource_ids
                or not resource_id
                or resource_id in resource_ids
            ):
                break

            cli_utils.warning(
                f"The selected '{resource_id}' value is not one of "
                "the listed values. Please try again."
            )
    else:
        prompt = (
            "The connector configuration can be used to access "
            f"multiple {resource_name} instances. If you "
            "would like to limit the scope of the connector to one "
            "instance, please enter the name of a particular "
            f"{resource_name} instance. Or leave it "
            "empty to create a multi-instance connector that can "
            f"be used to access any {resource_name}"
        )
        resource_id = click.prompt(
            prompt,
            default="",
            type=str,
        )

    if resource_id == "":
        resource_id = None

    return resource_id

prompt_resource_type(available_resource_types: List[str]) -> Optional[str]

Prompt the user for a resource type.

Parameters:

Name Type Description Default
available_resource_types List[str]

The list of available resource types.

required

Returns:

Type Description
Optional[str]

The resource type provided by the user.

Source code in src/zenml/cli/service_connectors.py
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
def prompt_resource_type(available_resource_types: List[str]) -> Optional[str]:
    """Prompt the user for a resource type.

    Args:
        available_resource_types: The list of available resource types.

    Returns:
        The resource type provided by the user.
    """
    resource_type = None
    if len(available_resource_types) == 1:
        # Default to the first resource type if only one type is available
        click.echo(
            "Only one resource type is available for this connector"
            f" ({available_resource_types[0]})."
        )
        resource_type = available_resource_types[0]
    else:
        # Ask the user to select a resource type
        while True:
            resource_type = click.prompt(
                "Please select a resource type or leave it empty to create "
                "a connector that can be used to access any of the "
                "supported resource types "
                f"({', '.join(available_resource_types)}).",
                type=str,
                default="",
            )
            if resource_type and resource_type not in available_resource_types:
                cli_utils.warning(
                    f"The entered resource type '{resource_type}' is not "
                    "one of the listed values. Please try again."
                )
                continue
            break

        if resource_type == "":
            resource_type = None

    return resource_type

prompt_select_resource(resource_list: List[ServiceConnectorResourcesModel]) -> Tuple[UUID, str]

Prompts the user to select a resource ID from a list of resources.

Parameters:

Name Type Description Default
resource_list List[ServiceConnectorResourcesModel]

List of resources to select from.

required

Returns:

Type Description
UUID

The ID of a selected connector and the ID of the selected resource

str

instance.

Source code in src/zenml/cli/stack_components.py
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
def prompt_select_resource(
    resource_list: List[ServiceConnectorResourcesModel],
) -> Tuple[UUID, str]:
    """Prompts the user to select a resource ID from a list of resources.

    Args:
        resource_list: List of resources to select from.

    Returns:
        The ID of a selected connector and the ID of the selected resource
        instance.
    """
    if len(resource_list) == 1:
        click.echo("Only one connector has compatible resources:")
    else:
        click.echo("The following connectors have compatible resources:")

    cli_utils.print_service_connector_resource_table(resource_list)

    if len(resource_list) == 1:
        connect = click.confirm(
            "Would you like to use this connector?",
            default=True,
        )
        if not connect:
            cli_utils.error("Aborting.")
        resources = resource_list[0]
    else:
        # Prompt the user to select a connector by its name or ID
        while True:
            connector_id = click.prompt(
                "Please enter the name or ID of the connector you want to use",
                type=click.Choice(
                    [
                        str(connector.id)
                        for connector in resource_list
                        if connector.id is not None
                    ]
                    + [
                        connector.name
                        for connector in resource_list
                        if connector.name is not None
                    ]
                ),
                show_choices=False,
            )
            matches = [
                c
                for c in resource_list
                if str(c.id) == connector_id or c.name == connector_id
            ]
            if len(matches) > 1:
                cli_utils.declare(
                    f"Multiple connectors with name '{connector_id}' "
                    "were found. Please try again."
                )
            else:
                resources = matches[0]
                break

    connector_uuid = resources.id
    assert connector_uuid is not None

    assert len(resources.resources) == 1
    resource_name = resources.resources[0].resource_type
    if not isinstance(resources.connector_type, str):
        resource_type_spec = resources.connector_type.resource_type_dict[
            resource_name
        ]
        resource_name = resource_type_spec.name

    resource_id = prompt_select_resource_id(
        resources.resources[0].resource_ids or [], resource_name=resource_name
    )

    return connector_uuid, resource_id

prompt_select_resource_id(resource_ids: List[str], resource_name: str, interactive: bool = True) -> str

Prompts the user to select a resource ID from a list of available IDs.

Parameters:

Name Type Description Default
resource_ids List[str]

A list of available resource IDs.

required
resource_name str

The name of the resource type to select.

required
interactive bool

Whether to prompt the user for input or error out if user input is required.

True

Returns:

Type Description
str

The selected resource ID.

Source code in src/zenml/cli/stack_components.py
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
def prompt_select_resource_id(
    resource_ids: List[str],
    resource_name: str,
    interactive: bool = True,
) -> str:
    """Prompts the user to select a resource ID from a list of available IDs.

    Args:
        resource_ids: A list of available resource IDs.
        resource_name: The name of the resource type to select.
        interactive: Whether to prompt the user for input or error out if
            user input is required.

    Returns:
        The selected resource ID.
    """
    if len(resource_ids) == 1:
        # Only one resource ID is available, so we can select it
        # without prompting the user
        return resource_ids[0]

    if len(resource_ids) > 1:
        resource_ids_list = "\n - " + "\n - ".join(resource_ids)
        msg = (
            f"Multiple {resource_name} resources are available for the "
            f"selected connector:\n{resource_ids_list}\n"
        )
        # User needs to select a resource ID from the list
        if not interactive:
            cli_utils.error(
                f"{msg}Please use the `--resource-id` command line "  # nosec
                f"argument to select a {resource_name} resource from the "
                "list."
            )
        resource_id = click.prompt(
            f"{msg}Please select the {resource_name} that you want to use",
            type=click.Choice(resource_ids),
            show_choices=False,
        )

        return cast(str, resource_id)

    # We should never get here, but just in case...
    cli_utils.error(
        "Could not determine which resource to use. Please select a "
        "different connector."
    )

prune_artifacts(only_artifact: bool = False, only_metadata: bool = False, yes: bool = False, ignore_errors: bool = False) -> None

Delete all unused artifacts and artifact versions.

Unused artifact versions are those that are no longer referenced by any pipeline runs. Similarly, unused artifacts are those that no longer have any used artifact versions.

Parameters:

Name Type Description Default
only_artifact bool

If set, only delete the actual artifact object from the artifact store but keep the metadata.

False
only_metadata bool

If set, only delete metadata and not the actual artifact objects stored in the artifact store.

False
yes bool

If set, don't ask for confirmation.

False
ignore_errors bool

If set, ignore errors and continue with the next artifact version.

False
Source code in src/zenml/cli/artifact.py
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
@artifact.command(
    "prune",
    help=(
        "Delete all unused artifacts and artifact versions that are no longer "
        "referenced by any pipeline runs."
    ),
)
@click.option(
    "--only-artifact",
    "-a",
    is_flag=True,
    help=(
        "Only delete the actual artifact object from the artifact store but "
        "keep the metadata."
    ),
)
@click.option(
    "--only-metadata",
    "-m",
    is_flag=True,
    help=(
        "Only delete metadata and not the actual artifact object stored in "
        "the artifact store."
    ),
)
@click.option(
    "--yes",
    "-y",
    is_flag=True,
    help="Don't ask for confirmation.",
)
@click.option(
    "--ignore-errors",
    "-i",
    is_flag=True,
    help="Ignore errors and continue with the next artifact version.",
)
def prune_artifacts(
    only_artifact: bool = False,
    only_metadata: bool = False,
    yes: bool = False,
    ignore_errors: bool = False,
) -> None:
    """Delete all unused artifacts and artifact versions.

    Unused artifact versions are those that are no longer referenced by any
    pipeline runs. Similarly, unused artifacts are those that no longer have
    any used artifact versions.

    Args:
        only_artifact: If set, only delete the actual artifact object from the
            artifact store but keep the metadata.
        only_metadata: If set, only delete metadata and not the actual artifact
            objects stored in the artifact store.
        yes: If set, don't ask for confirmation.
        ignore_errors: If set, ignore errors and continue with the next
            artifact version.
    """
    client = Client()
    unused_artifact_versions = depaginate(
        client.list_artifact_versions, only_unused=True
    )

    if not unused_artifact_versions:
        cli_utils.declare("No unused artifact versions found.")
        return

    if not yes:
        confirmation = cli_utils.confirmation(
            f"Found {len(unused_artifact_versions)} unused artifact versions. "
            f"Do you want to delete them?"
        )
        if not confirmation:
            cli_utils.declare("Artifact deletion canceled.")
            return

    for unused_artifact_version in unused_artifact_versions:
        try:
            Client().delete_artifact_version(
                name_id_or_prefix=unused_artifact_version.id,
                delete_metadata=not only_artifact,
                delete_from_artifact_store=not only_metadata,
            )
            unused_artifact = unused_artifact_version.artifact
            if not unused_artifact.versions and not only_artifact:
                Client().delete_artifact(unused_artifact.id)

        except Exception as e:
            if ignore_errors:
                cli_utils.warning(
                    f"Failed to delete artifact version {unused_artifact_version.id}: {str(e)}"
                )
            else:
                cli_utils.error(
                    f"Failed to delete artifact version {unused_artifact_version.id}: {str(e)}"
                )
    cli_utils.declare("All unused artifacts and artifact versions deleted.")

read_yaml(file_path: str) -> Any

Read YAML on file path and returns contents as dict.

Parameters:

Name Type Description Default
file_path str

Path to YAML file.

required

Returns:

Type Description
Any

Contents of the file in a dict.

Raises:

Type Description
FileNotFoundError

if file does not exist.

Source code in src/zenml/utils/yaml_utils.py
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
def read_yaml(file_path: str) -> Any:
    """Read YAML on file path and returns contents as dict.

    Args:
        file_path: Path to YAML file.

    Returns:
        Contents of the file in a dict.

    Raises:
        FileNotFoundError: if file does not exist.
    """
    if fileio.exists(file_path):
        contents = io_utils.read_file_contents_as_string(file_path)
        # TODO: [LOW] consider adding a default empty dict to be returned
        #   instead of None
        return yaml.safe_load(contents)
    else:
        raise FileNotFoundError(f"{file_path} does not exist.")

refresh_pipeline_run(run_name_or_id: str) -> None

Refresh the status of a pipeline run.

Parameters:

Name Type Description Default
run_name_or_id str

The name or ID of the pipeline run to refresh.

required
Source code in src/zenml/cli/pipeline.py
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
@runs.command("refresh")
@click.argument("run_name_or_id", type=str, required=True)
def refresh_pipeline_run(run_name_or_id: str) -> None:
    """Refresh the status of a pipeline run.

    Args:
        run_name_or_id: The name or ID of the pipeline run to refresh.
    """
    try:
        # Fetch and update the run
        run = Client().get_pipeline_run(name_id_or_prefix=run_name_or_id)
        run.refresh_run_status()

    except KeyError as e:
        cli_utils.error(str(e))
    else:
        cli_utils.declare(
            f"Refreshed the status of pipeline run '{run.name}'."
        )

register_all_stack_component_cli_commands() -> None

Registers CLI commands for all stack components.

Source code in src/zenml/cli/stack_components.py
1314
1315
1316
1317
1318
1319
def register_all_stack_component_cli_commands() -> None:
    """Registers CLI commands for all stack components."""
    for component_type in StackComponentType:
        register_single_stack_component_cli_commands(
            component_type, parent_group=cli
        )

register_annotator_subcommands() -> None

Registers CLI subcommands for the annotator.

Source code in src/zenml/cli/annotator.py
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
def register_annotator_subcommands() -> None:
    """Registers CLI subcommands for the annotator."""
    annotator_group = cast(TagGroup, cli.commands.get("annotator"))
    if not annotator_group:
        return

    @annotator_group.group(
        cls=TagGroup,
        help="Commands for interacting with annotation datasets.",
    )
    @click.pass_context
    def dataset(ctx: click.Context) -> None:
        """Interact with ZenML annotator datasets.

        Args:
            ctx: The click Context object.
        """
        from zenml.client import Client

        annotator_models = Client().active_stack_model.components.get(
            StackComponentType.ANNOTATOR
        )
        if annotator_models is None:
            cli_utils.error(
                "No active annotator found. Please register an annotator "
                "first and add it to your stack."
            )
            return

        from zenml.stack.stack_component import StackComponent

        ctx.obj = StackComponent.from_model(annotator_models[0])

    @dataset.command(
        "list",
        help="List the available datasets.",
    )
    @click.pass_obj
    def dataset_list(annotator: "BaseAnnotator") -> None:
        """List the available datasets.

        Args:
            annotator: The annotator stack component.
        """
        dataset_names = annotator.get_dataset_names()
        if not dataset_names:
            cli_utils.warning("No datasets found.")
            return
        cli_utils.print_list_items(
            list_items=dataset_names,
            column_title="DATASETS",
        )

    @dataset.command("stats")
    @click.argument("dataset_name", type=click.STRING)
    @click.pass_obj
    def dataset_stats(annotator: "BaseAnnotator", dataset_name: str) -> None:
        """Display statistics about a dataset.

        Args:
            annotator: The annotator stack component.
            dataset_name: The name of the dataset.
        """
        try:
            stats = annotator.get_dataset_stats(dataset_name)
            labeled_task_count, unlabeled_task_count = stats
        except IndexError:
            cli_utils.error(
                f"Dataset {dataset_name} does not exist. Please use `zenml "
                f"annotator dataset list` to list the available datasets."
            )
            return

        total_task_count = unlabeled_task_count + labeled_task_count
        cli_utils.declare(
            f"Annotation stats for '{dataset_name}' dataset:", bold=True
        )
        cli_utils.declare(f"Total annotation tasks: {total_task_count}")
        cli_utils.declare(f"Labeled annotation tasks: {labeled_task_count}")
        if annotator.flavor != "prodigy":
            # Prodigy doesn't allow you to get the unlabeled task count
            cli_utils.declare(
                f"Unlabeled annotation tasks: {unlabeled_task_count}"
            )

    @dataset.command("delete")
    @click.argument("dataset_name", type=click.STRING)
    @click.option(
        "--all",
        "-a",
        "all_",
        is_flag=True,
        help="Use this flag to delete all datasets.",
        type=click.BOOL,
    )
    @click.pass_obj
    def dataset_delete(
        annotator: "BaseAnnotator", dataset_name: str, all_: bool
    ) -> None:
        """Delete a dataset.

        If the --all flag is used, all datasets will be deleted.

        Args:
            annotator: The annotator stack component.
            dataset_name: Name of the dataset to delete.
            all_: Whether to delete all datasets.
        """
        if not cli_utils.confirmation(
            f"Are you sure you want to delete dataset '{dataset_name}'?"
        ):
            return
        cli_utils.declare(f"Deleting your dataset '{dataset_name}'")
        dataset_names = (
            annotator.get_dataset_names() if all_ else [dataset_name]
        )
        for dataset_name in dataset_names:
            try:
                annotator.delete_dataset(dataset_name=dataset_name)
                cli_utils.declare(
                    f"Dataset '{dataset_name}' has now been deleted."
                )
            except ValueError as e:
                cli_utils.error(
                    f"Failed to delete dataset '{dataset_name}': {e}"
                )

    @dataset.command(
        "annotate", context_settings={"ignore_unknown_options": True}
    )
    @click.argument("dataset_name", type=click.STRING)
    @click.argument("kwargs", nargs=-1, type=click.UNPROCESSED)
    @click.pass_obj
    def dataset_annotate(
        annotator: "BaseAnnotator",
        dataset_name: str,
        kwargs: Tuple[str, ...],
    ) -> None:
        """Command to launch the annotation interface for a dataset.

        Args:
            annotator: The annotator stack component.
            dataset_name: Name of the dataset
            kwargs: Additional keyword arguments to pass to the
                annotation client.

        Raises:
            ValueError: If the dataset does not exist.
        """
        cli_utils.declare(
            f"Launching the annotation interface for dataset '{dataset_name}'."
        )

        # Process the arbitrary keyword arguments
        kwargs_dict = {}
        for arg in kwargs:
            if arg.startswith("--"):
                key, value = arg.removeprefix("--").split("=", 1)
                kwargs_dict[key] = value

        if annotator.flavor == "prodigy":
            command = kwargs_dict.get("command")
            if not command:
                raise ValueError(
                    "The 'command' keyword argument is required for launching the Prodigy interface."
                )
            annotator.launch(**kwargs_dict)
        else:
            try:
                annotator.get_dataset(dataset_name=dataset_name)
                annotator.launch(
                    url=annotator.get_url_for_dataset(dataset_name)
                )
            except ValueError as e:
                raise ValueError("Dataset does not exist.") from e

register_code_repository(name: str, type_: str, source_path: Optional[str], description: Optional[str], logo_url: Optional[str], args: List[str]) -> None

Register a code repository.

Register a code repository with ZenML. This will allow ZenML to pull code from a remote repository and use it when running pipelines remotely. The configuration of the code repository can be different depending on the type of code repository. For more information, please refer to the documentation.

Parameters:

Name Type Description Default
name str

Name of the code repository

required
type_ str

Type of the code repository

required
source_path Optional[str]

Path to the source module if type is custom

required
description Optional[str]

The code repository description.

required
logo_url Optional[str]

URL of a logo (png, jpg or svg) for the code repository.

required
args List[str]

Additional arguments to be passed to the code repository

required
Source code in src/zenml/cli/code_repository.py
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
@code_repository.command(
    "register",
    context_settings={"ignore_unknown_options": True},
    help="Register a code repository.",
)
@click.argument("name", type=str)
@click.option(
    "--type",
    "-t",
    "type_",
    type=click.Choice(["github", "gitlab", "custom"]),
    required=True,
    help="Type of the code repository.",
)
@click.option(
    "--source",
    "-s",
    "source_path",
    type=str,
    required=False,
    help="Module containing the code repository implementation if type is custom.",
)
@click.option(
    "--description",
    "-d",
    type=str,
    required=False,
    help="The code repository description.",
)
@click.option(
    "--logo-url",
    "-l",
    type=str,
    required=False,
    help="URL of a logo (png, jpg or svg) for the code repository.",
)
@click.argument(
    "args",
    nargs=-1,
    type=click.UNPROCESSED,
)
def register_code_repository(
    name: str,
    type_: str,
    source_path: Optional[str],
    description: Optional[str],
    logo_url: Optional[str],
    args: List[str],
) -> None:
    """Register a code repository.

    Register a code repository with ZenML. This will allow ZenML to pull
    code from a remote repository and use it when running pipelines remotely.
    The configuration of the code repository can be different depending on the
    type of code repository. For more information, please refer to the
    documentation.

    Args:
        name: Name of the code repository
        type_: Type of the code repository
        source_path: Path to the source module if type is custom
        description: The code repository description.
        logo_url: URL of a logo (png, jpg or svg) for the code repository.
        args: Additional arguments to be passed to the code repository
    """
    parsed_name, parsed_args = cli_utils.parse_name_and_extra_arguments(
        list(args) + [name], expand_args=True
    )
    assert parsed_name
    name = parsed_name

    if type_ == "github":
        try:
            from zenml.integrations.github.code_repositories import (
                GitHubCodeRepository,
            )
        except ImportError:
            cli_utils.error(
                "You need to install the GitHub integration to use a GitHub "
                "code repository. Please run `zenml integration install "
                "github` and try again."
            )
        source = source_utils.resolve(GitHubCodeRepository)
    elif type_ == "gitlab":
        try:
            from zenml.integrations.gitlab.code_repositories import (
                GitLabCodeRepository,
            )
        except ImportError:
            cli_utils.error(
                "You need to install the GitLab integration to use a GitLab "
                "code repository. Please run `zenml integration install "
                "gitlab` and try again."
            )
        source = source_utils.resolve(GitLabCodeRepository)
    elif type_ == "custom":
        if not source_path:
            cli_utils.error(
                "When using a custom code repository type, you need to provide "
                "a path to the implementation class using the --source option: "
                "`zenml code-repository register --type=custom --source=<...>"
            )
        if not source_utils.validate_source_class(
            source_path, expected_class=BaseCodeRepository
        ):
            cli_utils.error(
                f"Your source {source_path} does not point to a "
                f"`{BaseCodeRepository.__name__}` subclass and can't be used "
                "to register a code repository."
            )

        source = Source.from_import_path(source_path)

    with console.status(f"Registering code repository '{name}'...\n"):
        Client().create_code_repository(
            name=name,
            config=parsed_args,
            source=source,
            description=description,
            logo_url=logo_url,
        )

        cli_utils.declare(f"Successfully registered code repository `{name}`.")

register_feature_store_subcommands() -> None

Registers CLI subcommands for the Feature Store.

Source code in src/zenml/cli/feature.py
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
def register_feature_store_subcommands() -> None:
    """Registers CLI subcommands for the Feature Store."""
    feature_store_group = cast(TagGroup, cli.commands.get("feature-store"))
    if not feature_store_group:
        return

    @feature_store_group.group(
        cls=TagGroup,
        help="Commands for interacting with your features.",
    )
    @click.pass_context
    def feature(ctx: click.Context) -> None:
        """Features as obtained from a feature store.

        Args:
            ctx: The click context.
        """
        from zenml.client import Client
        from zenml.stack.stack_component import StackComponent

        client = Client()
        feature_store_models = client.active_stack_model.components[
            StackComponentType.FEATURE_STORE
        ]
        if feature_store_models is None:
            error(
                "No active feature store found. Please create a feature store "
                "first and add it to your stack."
            )
            return
        ctx.obj = StackComponent.from_model(feature_store_models[0])

    @feature.command("get-data-sources")
    @click.pass_obj
    def get_data_sources(feature_store: "BaseFeatureStore") -> None:
        """Get all data sources from the feature store.

        Args:
            feature_store: The feature store.
        """
        data_sources = feature_store.get_data_sources()  # type: ignore[attr-defined]
        declare(f"Data sources: {data_sources}")

    @feature.command("get-entities")
    @click.pass_obj
    def get_entities(feature_store: "BaseFeatureStore") -> None:
        """Get all entities from the feature store.

        Args:
            feature_store: The feature store.
        """
        entities = feature_store.get_entities()  # type: ignore[attr-defined]
        declare(f"Entities: {entities}")

    @feature.command("get-feature-services")
    @click.pass_obj
    def get_feature_services(feature_store: "BaseFeatureStore") -> None:
        """Get all feature services from the feature store.

        Args:
            feature_store: The feature store.
        """
        feature_services = feature_store.get_feature_services()  # type: ignore[attr-defined]
        declare(f"Feature services: {feature_services}")

    @feature.command("get-feature-views")
    @click.pass_obj
    def get_feature_views(feature_store: "BaseFeatureStore") -> None:
        """Get all feature views from the feature store.

        Args:
            feature_store: The feature store.
        """
        feature_views = feature_store.get_feature_views()  # type: ignore[attr-defined]
        declare(f"Feature views: {feature_views}")

    @feature.command("get-project")
    @click.pass_obj
    def get_project(feature_store: "BaseFeatureStore") -> None:
        """Get the current project name from the feature store.

        Args:
            feature_store: The feature store.
        """
        project = feature_store.get_project()  # type: ignore[attr-defined]
        declare(f"Project name: {project}")

    @feature.command("get-feast-version")
    @click.pass_obj
    def get_feast_version(feature_store: "BaseFeatureStore") -> None:
        """Get the current Feast version being used.

        Args:
            feature_store: The feature store.
        """
        version = feature_store.get_feast_version()  # type: ignore[attr-defined]
        declare(f"Feast version: {version}")

register_model(name: str, license: Optional[str], description: Optional[str], audience: Optional[str], use_cases: Optional[str], tradeoffs: Optional[str], ethical: Optional[str], limitations: Optional[str], tag: Optional[List[str]], save_models_to_registry: Optional[bool]) -> None

Register a new model in the Model Control Plane.

Parameters:

Name Type Description Default
name str

The name of the model.

required
license Optional[str]

The license model created under.

required
description Optional[str]

The description of the model.

required
audience Optional[str]

The target audience of the model.

required
use_cases Optional[str]

The use cases of the model.

required
tradeoffs Optional[str]

The tradeoffs of the model.

required
ethical Optional[str]

The ethical implications of the model.

required
limitations Optional[str]

The know limitations of the model.

required
tag Optional[List[str]]

Tags associated with the model.

required
save_models_to_registry Optional[bool]

Whether to save the model to the registry.

required
Source code in src/zenml/cli/model.py
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
@model.command("register", help="Register a new model.")
@click.option(
    "--name",
    "-n",
    help="The name of the model.",
    type=str,
    required=True,
)
@click.option(
    "--license",
    "-l",
    help="The license under which the model is created.",
    type=str,
    required=False,
)
@click.option(
    "--description",
    "-d",
    help="The description of the model.",
    type=str,
    required=False,
)
@click.option(
    "--audience",
    "-a",
    help="The target audience for the model.",
    type=str,
    required=False,
)
@click.option(
    "--use-cases",
    "-u",
    help="The use cases of the model.",
    type=str,
    required=False,
)
@click.option(
    "--tradeoffs",
    help="The tradeoffs of the model.",
    type=str,
    required=False,
)
@click.option(
    "--ethical",
    "-e",
    help="The ethical implications of the model.",
    type=str,
    required=False,
)
@click.option(
    "--limitations",
    help="The known limitations of the model.",
    type=str,
    required=False,
)
@click.option(
    "--tag",
    "-t",
    help="Tags associated with the model.",
    type=str,
    required=False,
    multiple=True,
)
@click.option(
    "--save-models-to-registry",
    "-s",
    help="Whether to automatically save model artifacts to the model registry.",
    type=click.BOOL,
    required=False,
    default=True,
)
def register_model(
    name: str,
    license: Optional[str],
    description: Optional[str],
    audience: Optional[str],
    use_cases: Optional[str],
    tradeoffs: Optional[str],
    ethical: Optional[str],
    limitations: Optional[str],
    tag: Optional[List[str]],
    save_models_to_registry: Optional[bool],
) -> None:
    """Register a new model in the Model Control Plane.

    Args:
        name: The name of the model.
        license: The license model created under.
        description: The description of the model.
        audience: The target audience of the model.
        use_cases: The use cases of the model.
        tradeoffs: The tradeoffs of the model.
        ethical: The ethical implications of the model.
        limitations: The know limitations of the model.
        tag: Tags associated with the model.
        save_models_to_registry: Whether to save the model to the
            registry.
    """
    try:
        model = Client().create_model(
            **remove_none_values(
                dict(
                    name=name,
                    license=license,
                    description=description,
                    audience=audience,
                    use_cases=use_cases,
                    trade_offs=tradeoffs,
                    ethics=ethical,
                    limitations=limitations,
                    tags=tag,
                    save_models_to_registry=save_models_to_registry,
                )
            )
        )
    except (EntityExistsError, ValueError) as e:
        cli_utils.error(str(e))

    cli_utils.print_table([_model_to_print(model)])

register_model_deployer_subcommands() -> None

Registers CLI subcommands for the Model Deployer.

Source code in src/zenml/cli/served_model.py
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
def register_model_deployer_subcommands() -> None:  # noqa: C901
    """Registers CLI subcommands for the Model Deployer."""
    model_deployer_group = cast(TagGroup, cli.commands.get("model-deployer"))
    if not model_deployer_group:
        return

    @model_deployer_group.group(
        cls=TagGroup,
        help="Commands for interacting with served models.",
    )
    @click.pass_context
    def models(ctx: click.Context) -> None:
        """List and manage served models with the active model deployer.

        Args:
            ctx: The click context.
        """
        from zenml.client import Client
        from zenml.stack.stack_component import StackComponent

        client = Client()
        model_deployer_models = client.active_stack_model.components.get(
            StackComponentType.MODEL_DEPLOYER
        )
        if model_deployer_models is None:
            error(
                "No active model deployer found. Please add a model_deployer "
                "to your stack."
            )
            return
        ctx.obj = StackComponent.from_model(model_deployer_models[0])

    @models.command(
        "list",
        help="Get a list of all served models within the model-deployer stack "
        "component.",
    )
    @click.option(
        "--step",
        "-s",
        type=click.STRING,
        default=None,
        help="Show only served models that were deployed by the indicated "
        "pipeline step.",
    )
    @click.option(
        "--pipeline-run-id",
        "-r",
        type=click.STRING,
        default=None,
        help="Show only served models that were deployed by the indicated "
        "pipeline run.",
    )
    @click.option(
        "--pipeline-name",
        "-p",
        type=click.STRING,
        default=None,
        help="Show only served models that were deployed by the indicated "
        "pipeline.",
    )
    @click.option(
        "--model",
        "-m",
        type=click.STRING,
        default=None,
        help="Show only served model versions for the given model name.",
    )
    @click.option(
        "--model-version",
        "-v",
        type=click.STRING,
        default=None,
        help="Show only served model versions for the given model version.",
    )
    @click.option(
        "--flavor",
        "-f",
        type=click.STRING,
        default=None,
        help="Show only served model versions for the given model flavor.",
    )
    @click.option(
        "--running",
        is_flag=True,
        help="Show only model servers that are currently running.",
    )
    @click.pass_obj
    def list_models(
        model_deployer: "BaseModelDeployer",
        step: Optional[str],
        pipeline_name: Optional[str],
        pipeline_run_id: Optional[str],
        model: Optional[str],
        model_version: Optional[str],
        flavor: Optional[str],
        running: bool,
    ) -> None:
        """List of all served models within the model-deployer stack component.

        Args:
            model_deployer: The model-deployer stack component.
            step: Show only served models that were deployed by the indicated
                pipeline step.
            pipeline_run_id: Show only served models that were deployed by the
                indicated pipeline run.
            pipeline_name: Show only served models that were deployed by the
                indicated pipeline.
            model: Show only served model versions for the given model name.
            running: Show only model servers that are currently running.
            model_version: Show only served model versions for the given model
                version.
            flavor: Show only served model versions for the given model flavor.
        """
        services = model_deployer.find_model_server(
            running=running,
            pipeline_name=pipeline_name,
            pipeline_run_id=pipeline_run_id if pipeline_run_id else None,
            pipeline_step_name=step,
            model_name=model,
            model_version=model_version,
            flavor=flavor,
        )
        if services:
            pretty_print_model_deployer(
                services,
                model_deployer,
            )
        else:
            warning("No served models found.")

    @models.command("describe", help="Describe a specified served model.")
    @click.argument("served_model_uuid", type=click.STRING)
    @click.pass_obj
    def describe_model(
        model_deployer: "BaseModelDeployer", served_model_uuid: str
    ) -> None:
        """Describe a specified served model.

        Args:
            model_deployer: The model-deployer stack component.
            served_model_uuid: The UUID of the served model.
        """
        served_models = model_deployer.find_model_server(
            service_uuid=uuid.UUID(served_model_uuid)
        )
        if served_models:
            print_served_model_configuration(served_models[0], model_deployer)
            return
        warning(f"No model with uuid: '{served_model_uuid}' could be found.")
        return

    @models.command(
        "get-url",
        help="Return the prediction URL to a specified model server.",
    )
    @click.argument("served_model_uuid", type=click.STRING)
    @click.pass_obj
    def get_url(
        model_deployer: "BaseModelDeployer", served_model_uuid: str
    ) -> None:
        """Return the prediction URL to a specified model server.

        Args:
            model_deployer: The model-deployer stack component.
            served_model_uuid: The UUID of the served model.
        """
        served_models = model_deployer.find_model_server(
            service_uuid=uuid.UUID(served_model_uuid)
        )
        if served_models:
            try:
                prediction_url = model_deployer.get_model_server_info(
                    served_models[0]
                ).get("PREDICTION_URL")
                prediction_hostname = (
                    model_deployer.get_model_server_info(served_models[0]).get(
                        "PREDICTION_HOSTNAME"
                    )
                    or "No hostname specified for this service"
                )
                prediction_apis_urls = (
                    model_deployer.get_model_server_info(served_models[0]).get(
                        "PREDICTION_APIS_URLS"
                    )
                    or "No prediction APIs URLs specified for this service"
                )
                declare(
                    f"  Prediction URL of Served Model {served_model_uuid} "
                    f"is:\n"
                    f"  {prediction_url}\n"
                    f"  and the hostname is: {prediction_hostname}\n"
                    f"  and the prediction APIs URLs are: {prediction_apis_urls}\n"
                )
            except KeyError:
                warning("The deployed model instance has no 'prediction_url'.")
            return
        warning(f"No model with uuid: '{served_model_uuid}' could be found.")
        return

    @models.command("start", help="Start a specified model server.")
    @click.argument("served_model_uuid", type=click.STRING)
    @click.option(
        "--timeout",
        "-t",
        type=click.INT,
        default=300,
        help="Time in seconds to wait for the model to start. Set to 0 to "
        "return immediately after telling the server to start, without "
        "waiting for it to become fully active (default: 300s).",
    )
    @click.pass_obj
    def start_model_service(
        model_deployer: "BaseModelDeployer",
        served_model_uuid: str,
        timeout: int,
    ) -> None:
        """Start a specified model server.

        Args:
            model_deployer: The model-deployer stack component.
            served_model_uuid: The UUID of the served model.
            timeout: Time in seconds to wait for the model to start.
        """
        served_models = model_deployer.find_model_server(
            service_uuid=uuid.UUID(served_model_uuid)
        )
        if served_models:
            model_deployer.start_model_server(
                served_models[0].uuid, timeout=timeout
            )
            declare(f"Model server {served_models[0]} was started.")
            return

        warning(f"No model with uuid: '{served_model_uuid}' could be found.")
        return

    @models.command("stop", help="Stop a specified model server.")
    @click.argument("served_model_uuid", type=click.STRING)
    @click.option(
        "--timeout",
        "-t",
        type=click.INT,
        default=300,
        help="Time in seconds to wait for the model to start. Set to 0 to "
        "return immediately after telling the server to stop, without "
        "waiting for it to become inactive (default: 300s).",
    )
    @click.option(
        "--yes",
        "-y",
        "force",
        is_flag=True,
        help="Force the model server to stop. This will bypass any graceful "
        "shutdown processes and try to force the model server to stop "
        "immediately, if possible.",
    )
    @click.pass_obj
    def stop_model_service(
        model_deployer: "BaseModelDeployer",
        served_model_uuid: str,
        timeout: int,
        force: bool,
    ) -> None:
        """Stop a specified model server.

        Args:
            model_deployer: The model-deployer stack component.
            served_model_uuid: The UUID of the served model.
            timeout: Time in seconds to wait for the model to stop.
            force: Force the model server to stop.
        """
        served_models = model_deployer.find_model_server(
            service_uuid=uuid.UUID(served_model_uuid)
        )
        if served_models:
            model_deployer.stop_model_server(
                served_models[0].uuid, timeout=timeout, force=force
            )
            declare(f"Model server {served_models[0]} was stopped.")
            return

        warning(f"No model with uuid: '{served_model_uuid}' could be found.")
        return

    @models.command("delete", help="Delete a specified model server.")
    @click.argument("served_model_uuid", type=click.STRING)
    @click.option(
        "--timeout",
        "-t",
        type=click.INT,
        default=300,
        help="Time in seconds to wait for the model to be deleted. Set to 0 to "
        "return immediately after stopping and deleting the model server, "
        "without waiting for it to release all allocated resources.",
    )
    @click.option(
        "--yes",
        "-y",
        "force",
        is_flag=True,
        help="Force the model server to stop and delete. This will bypass any "
        "graceful shutdown processes and try to force the model server to "
        "stop and delete immediately, if possible.",
    )
    @click.pass_obj
    def delete_model_service(
        model_deployer: "BaseModelDeployer",
        served_model_uuid: str,
        timeout: int,
        force: bool,
    ) -> None:
        """Delete a specified model server.

        Args:
            model_deployer: The model-deployer stack component.
            served_model_uuid: The UUID of the served model.
            timeout: Time in seconds to wait for the model to be deleted.
            force: Force the model server to stop and delete.
        """
        served_models = model_deployer.find_model_server(
            service_uuid=uuid.UUID(served_model_uuid)
        )
        if served_models:
            model_deployer.delete_model_server(
                served_models[0].uuid, timeout=timeout, force=force
            )
            declare(f"Model server {served_models[0]} was deleted.")
            return

        warning(f"No model with uuid: '{served_model_uuid}' could be found.")
        return

    @models.command("logs", help="Show the logs for a model server.")
    @click.argument("served_model_uuid", type=click.STRING)
    @click.option(
        "--follow",
        "-f",
        is_flag=True,
        help="Continue to output new log data as it becomes available.",
    )
    @click.option(
        "--tail",
        "-t",
        type=click.INT,
        default=None,
        help="Only show the last NUM lines of log output.",
    )
    @click.option(
        "--raw",
        "-r",
        is_flag=True,
        help="Show raw log contents (don't pretty-print logs).",
    )
    @click.pass_obj
    def get_model_service_logs(
        model_deployer: "BaseModelDeployer",
        served_model_uuid: str,
        follow: bool,
        tail: Optional[int],
        raw: bool,
    ) -> None:
        """Display the logs for a model server.

        Args:
            model_deployer: The model-deployer stack component.
            served_model_uuid: The UUID of the served model.
            follow: Continue to output new log data as it becomes available.
            tail: Only show the last NUM lines of log output.
            raw: Show raw log contents (don't pretty-print logs).
        """
        served_models = model_deployer.find_model_server(
            service_uuid=uuid.UUID(served_model_uuid)
        )
        if not served_models:
            warning(
                f"No model with uuid: '{served_model_uuid}' could be found."
            )
            return

        model_logs = model_deployer.get_model_server_logs(
            served_models[0].uuid, follow=follow, tail=tail
        )
        if model_logs:
            for line in model_logs:
                # don't pretty-print log lines that are already pretty-printed
                if raw or line.startswith("\x1b["):
                    console.print(line, markup=False)
                else:
                    try:
                        console.print(line)
                    except MarkupError:
                        console.print(line, markup=False)

register_model_registry_subcommands() -> None

Registers CLI subcommands for the Model Registry.

Source code in src/zenml/cli/model_registry.py
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
def register_model_registry_subcommands() -> None:  # noqa: C901
    """Registers CLI subcommands for the Model Registry."""
    model_registry_group = cast(TagGroup, cli.commands.get("model-registry"))
    if not model_registry_group:
        return

    @model_registry_group.group(
        cls=TagGroup,
        help="Commands for interacting with registered models group of commands.",
    )
    @click.pass_context
    def models(ctx: click.Context) -> None:
        """List and manage models with the active model registry.

        Args:
            ctx: The click context.
        """
        from zenml.client import Client
        from zenml.stack.stack_component import StackComponent

        client = Client()
        model_registry_models = client.active_stack_model.components.get(
            StackComponentType.MODEL_REGISTRY
        )
        if model_registry_models is None:
            cli_utils.error(
                "No active model registry found. Please add a model_registry "
                "to your stack."
            )
            return
        ctx.obj = StackComponent.from_model(model_registry_models[0])

    @models.command(
        "list",
        help="Get a list of all registered models within the model registry.",
    )
    @click.option(
        "--metadata",
        "-m",
        type=(str, str),
        default=None,
        help="Filter models by metadata. can be used like: -m key1 value1 -m key2 value",
        multiple=True,
    )
    @click.pass_obj
    def list_registered_models(
        model_registry: "BaseModelRegistry",
        metadata: Optional[Dict[str, str]],
    ) -> None:
        """List of all registered models within the model registry.

        The list can be filtered by metadata (tags) using the --metadata flag.
        Example: zenml model-registry models list-versions -m key1 value1 -m key2 value2

        Args:
            model_registry: The model registry stack component.
            metadata: Filter models by Metadata (Tags).
        """
        metadata = dict(metadata) if metadata else None
        registered_models = model_registry.list_models(metadata=metadata)
        # Print registered models if any
        if registered_models:
            cli_utils.pretty_print_registered_model_table(registered_models)
        else:
            cli_utils.declare("No models found.")

    @models.command(
        "register",
        help="Register a model with the active model registry.",
    )
    @click.argument(
        "name",
        type=click.STRING,
        required=True,
    )
    @click.option(
        "--description",
        "-d",
        type=str,
        default=None,
        help="Description of the model to register.",
    )
    @click.option(
        "--metadata",
        "-t",
        type=(str, str),
        default=None,
        help="Metadata or Tags to add to the model. can be used like: -m key1 value1 -m key2 value",
        multiple=True,
    )
    @click.pass_obj
    def register_model(
        model_registry: "BaseModelRegistry",
        name: str,
        description: Optional[str],
        metadata: Optional[Dict[str, str]],
    ) -> None:
        """Register a model with the active model registry.

        Args:
            model_registry: The model registry stack component.
            name: Name of the model to register.
            description: Description of the model to register.
            metadata: Metadata or Tags to add to the registered model.
        """
        try:
            model_registry.get_model(name)
            cli_utils.error(f"Model with name {name} already exists.")
        except KeyError:
            pass
        metadata = dict(metadata) if metadata else None
        model_registry.register_model(
            name=name,
            description=description,
            metadata=metadata,
        )
        cli_utils.declare(f"Model {name} registered successfully.")

    @models.command(
        "delete",
        help="Delete a model from the active model registry.",
    )
    @click.argument(
        "name",
        type=click.STRING,
        required=True,
    )
    @click.option(
        "--yes",
        "-y",
        is_flag=True,
        help="Don't ask for confirmation.",
    )
    @click.pass_obj
    def delete_model(
        model_registry: "BaseModelRegistry",
        name: str,
        yes: bool = False,
    ) -> None:
        """Delete a model from the active model registry.

        Args:
            model_registry: The model registry stack component.
            name: Name of the model to delete.
            yes: If set, don't ask for confirmation.
        """
        try:
            model_registry.get_model(name)
        except KeyError:
            cli_utils.error(f"Model with name {name} does not exist.")
            return
        if not yes:
            confirmation = cli_utils.confirmation(
                f"Found Model with name {name}. Do you want to delete them?"
            )
            if not confirmation:
                cli_utils.declare("Model deletion canceled.")
                return
        model_registry.delete_model(name)
        cli_utils.declare(f"Model {name} deleted successfully.")

    @models.command(
        "update",
        help="Update a model in the active model registry.",
    )
    @click.argument(
        "name",
        type=click.STRING,
        required=True,
    )
    @click.option(
        "--description",
        "-d",
        type=str,
        default=None,
        help="Description of the model to update.",
    )
    @click.option(
        "--metadata",
        "-t",
        type=(str, str),
        default=None,
        help="Metadata or Tags to add to the model. Can be used like: -m key1 value1 -m key2 value",
        multiple=True,
    )
    @click.pass_obj
    def update_model(
        model_registry: "BaseModelRegistry",
        name: str,
        description: Optional[str],
        metadata: Optional[Dict[str, str]],
    ) -> None:
        """Update a model in the active model registry.

        Args:
            model_registry: The model registry stack component.
            name: Name of the model to update.
            description: Description of the model to update.
            metadata: Metadata or Tags to add to the model.
        """
        try:
            model_registry.get_model(name)
        except KeyError:
            cli_utils.error(f"Model with name {name} does not exist.")
            return
        metadata = dict(metadata) if metadata else None
        model_registry.update_model(
            name=name,
            description=description,
            metadata=metadata,
        )
        cli_utils.declare(f"Model {name} updated successfully.")

    @models.command(
        "get",
        help="Get a model from the active model registry.",
    )
    @click.argument(
        "name",
        type=click.STRING,
        required=True,
    )
    @click.pass_obj
    def get_model(
        model_registry: "BaseModelRegistry",
        name: str,
    ) -> None:
        """Get a model from the active model registry.

        Args:
            model_registry: The model registry stack component.
            name: Name of the model to get.
        """
        try:
            model = model_registry.get_model(name)
        except KeyError:
            cli_utils.error(f"Model with name {name} does not exist.")
            return
        cli_utils.pretty_print_registered_model_table([model])

    @models.command(
        "get-version",
        help="Get a model version from the active model registry.",
    )
    @click.argument(
        "name",
        type=click.STRING,
        required=True,
    )
    @click.option(
        "--version",
        "-v",
        type=str,
        default=None,
        help="Version of the model to get.",
        required=True,
    )
    @click.pass_obj
    def get_model_version(
        model_registry: "BaseModelRegistry",
        name: str,
        version: str,
    ) -> None:
        """Get a model version from the active model registry.

        Args:
            model_registry: The model registry stack component.
            name: Name of the model to get.
            version: Version of the model to get.
        """
        try:
            model_version = model_registry.get_model_version(name, version)
        except KeyError:
            cli_utils.error(
                f"Model with name {name} and version {version} does not exist."
            )
            return
        cli_utils.pretty_print_model_version_details(model_version)

    @models.command(
        "delete-version",
        help="Delete a model version from the active model registry.",
    )
    @click.argument(
        "name",
        type=click.STRING,
        required=True,
    )
    @click.option(
        "--version",
        "-v",
        type=str,
        default=None,
        help="Version of the model to delete.",
        required=True,
    )
    @click.option(
        "--yes",
        "-y",
        is_flag=True,
        help="Don't ask for confirmation.",
    )
    @click.pass_obj
    def delete_model_version(
        model_registry: "BaseModelRegistry",
        name: str,
        version: str,
        yes: bool = False,
    ) -> None:
        """Delete a model version from the active model registry.

        Args:
            model_registry: The model registry stack component.
            name: Name of the model to delete.
            version: Version of the model to delete.
            yes: If set, don't ask for confirmation.
        """
        try:
            model_registry.get_model_version(name, version)
        except KeyError:
            cli_utils.error(
                f"Model with name {name} and version {version} does not exist."
            )
            return
        if not yes:
            confirmation = cli_utils.confirmation(
                f"Found Model with the name `{name}` and the version `{version}`."
                f"Do you want to delete it?"
            )
            if not confirmation:
                cli_utils.declare("Model version deletion canceled.")
                return
        model_registry.delete_model_version(name, version)
        cli_utils.declare(
            f"Model {name} version {version} deleted successfully."
        )

    @models.command(
        "update-version",
        help="Update a model version in the active model registry.",
    )
    @click.argument(
        "name",
        type=click.STRING,
        required=True,
    )
    @click.option(
        "--version",
        "-v",
        type=str,
        default=None,
        help="Version of the model to update.",
        required=True,
    )
    @click.option(
        "--description",
        "-d",
        type=str,
        default=None,
        help="Description of the model to update.",
    )
    @click.option(
        "--metadata",
        "-m",
        type=(str, str),
        default=None,
        help="Metadata or Tags to add to the model. can be used like: --m key1 value1 -m key2 value",
        multiple=True,
    )
    @click.option(
        "--stage",
        "-s",
        type=click.Choice(["None", "Staging", "Production", "Archived"]),
        default=None,
        help="Stage of the model to update.",
    )
    @click.option(
        "--remove_metadata",
        "-rm",
        default=None,
        help="Metadata or Tags to remove from the model. Can be used like: -rm key1 -rm key2",
        multiple=True,
    )
    @click.pass_obj
    def update_model_version(
        model_registry: "BaseModelRegistry",
        name: str,
        version: str,
        description: Optional[str],
        metadata: Optional[Dict[str, str]],
        stage: Optional[str],
        remove_metadata: Optional[List[str]],
    ) -> None:
        """Update a model version in the active model registry.

        Args:
            model_registry: The model registry stack component.
            name: Name of the model to update.
            version: Version of the model to update.
            description: Description of the model to update.
            metadata: Metadata to add to the model version.
            stage: Stage of the model to update.
            remove_metadata: Metadata to remove from the model version.
        """
        try:
            model_registry.get_model_version(name, version)
        except KeyError:
            cli_utils.error(
                f"Model with name {name} and version {version} does not exist."
            )
            return
        metadata = dict(metadata) if metadata else {}
        remove_metadata = list(remove_metadata) if remove_metadata else []
        updated_version = model_registry.update_model_version(
            name=name,
            version=version,
            description=description,
            metadata=ModelRegistryModelMetadata(**metadata),
            stage=ModelVersionStage(stage) if stage else None,
            remove_metadata=remove_metadata,
        )
        cli_utils.declare(
            f"Model {name} version {version} updated successfully."
        )
        cli_utils.pretty_print_model_version_details(updated_version)

    @models.command(
        "list-versions",
        help="List all model versions in the active model registry.",
    )
    @click.argument(
        "name",
        type=click.STRING,
        required=True,
    )
    @click.option(
        "--model-uri",
        "-m",
        type=str,
        default=None,
        help="Model URI of the model to list versions for.",
    )
    @click.option(
        "--metadata",
        "-m",
        type=(str, str),
        default=None,
        help="Metadata or Tags to filter the model versions by. Can be used like: -m key1 value1 -m key2 value",
        multiple=True,
    )
    @click.option(
        "--count",
        "-c",
        type=int,
        help="Number of model versions to list.",
    )
    @click.option(
        "--order-by-date",
        type=click.Choice(["asc", "desc"]),
        default="desc",
        help="Order by date.",
    )
    @click.option(
        "--created-after",
        type=click.DateTime(formats=["%Y-%m-%d"]),
        default=None,
        help="List model versions created after this date.",
    )
    @click.option(
        "--created-before",
        type=click.DateTime(formats=["%Y-%m-%d"]),
        default=None,
        help="List model versions created before this date.",
    )
    @click.pass_obj
    def list_model_versions(
        model_registry: "BaseModelRegistry",
        name: str,
        model_uri: Optional[str],
        count: Optional[int],
        metadata: Optional[Dict[str, str]],
        order_by_date: str,
        created_after: Optional[datetime],
        created_before: Optional[datetime],
    ) -> None:
        """List all model versions in the active model registry.

        Args:
            model_registry: The model registry stack component.
            name: Name of the model to list versions for.
            model_uri: Model URI of the model to list versions for.
            metadata: Metadata or Tags to filter the model versions by.
            count: Number of model versions to list.
            order_by_date: Order by date.
            created_after: List model versions created after this date.
            created_before: List model versions created before this date.
        """
        metadata = dict(metadata) if metadata else {}
        model_versions = model_registry.list_model_versions(
            name=name,
            model_source_uri=model_uri,
            metadata=ModelRegistryModelMetadata(**metadata),
            count=count,
            order_by_date=order_by_date,
            created_after=created_after,
            created_before=created_before,
        )
        if not model_versions:
            cli_utils.declare("No model versions found.")
            return
        cli_utils.pretty_print_model_version_table(model_versions)

    @models.command(
        "register-version",
        help="Register a model version in the active model registry.",
    )
    @click.argument(
        "name",
        type=click.STRING,
        required=True,
    )
    @click.option(
        "--description",
        "-d",
        type=str,
        default=None,
        help="Description of the model version.",
    )
    @click.option(
        "--metadata",
        "-m",
        type=(str, str),
        default=None,
        help="Metadata or Tags to add to the model version. Can be used like: -m key1 value1 -m key2 value",
        multiple=True,
    )
    @click.option(
        "--version",
        "-v",
        type=str,
        required=True,
        default=None,
        help="Version of the model to register.",
    )
    @click.option(
        "--model-uri",
        "-u",
        type=str,
        default=None,
        help="Model URI of the model to register.",
        required=True,
    )
    @click.option(
        "--zenml-version",
        type=str,
        default=None,
        help="ZenML version of the model to register.",
    )
    @click.option(
        "--zenml-run-name",
        type=str,
        default=None,
        help="ZenML run name of the model to register.",
    )
    @click.option(
        "--zenml-pipeline-run-id",
        type=str,
        default=None,
        help="ZenML pipeline run ID of the model to register.",
    )
    @click.option(
        "--zenml-pipeline-name",
        type=str,
        default=None,
        help="ZenML pipeline name of the model to register.",
    )
    @click.option(
        "--zenml-step-name",
        type=str,
        default=None,
        help="ZenML step name of the model to register.",
    )
    @click.pass_obj
    def register_model_version(
        model_registry: "BaseModelRegistry",
        name: str,
        version: str,
        model_uri: str,
        description: Optional[str],
        metadata: Optional[Dict[str, str]],
        zenml_version: Optional[str],
        zenml_run_name: Optional[str],
        zenml_pipeline_name: Optional[str],
        zenml_step_name: Optional[str],
    ) -> None:
        """Register a model version in the active model registry.

        Args:
            model_registry: The model registry stack component.
            name: Name of the model to register.
            version: Version of the model to register.
            model_uri: Model URI of the model to register.
            description: Description of the model to register.
            metadata: Model version metadata.
            zenml_version: ZenML version of the model to register.
            zenml_run_name: ZenML pipeline run name of the model to register.
            zenml_pipeline_name: ZenML pipeline name of the model to register.
            zenml_step_name: ZenML step name of the model to register.
        """
        # Parse metadata
        metadata = dict(metadata) if metadata else {}
        registered_metadata = ModelRegistryModelMetadata(**dict(metadata))
        registered_metadata.zenml_version = zenml_version
        registered_metadata.zenml_run_name = zenml_run_name
        registered_metadata.zenml_pipeline_name = zenml_pipeline_name
        registered_metadata.zenml_step_name = zenml_step_name
        model_version = model_registry.register_model_version(
            name=name,
            version=version,
            model_source_uri=model_uri,
            description=description,
            metadata=registered_metadata,
        )
        cli_utils.declare(
            f"Model {name} version {version} registered successfully."
        )
        cli_utils.pretty_print_model_version_details(model_version)

register_pipeline(source: str, parameters_path: Optional[str] = None) -> None

Register a pipeline.

Parameters:

Name Type Description Default
source str

Importable source resolving to a pipeline instance.

required
parameters_path Optional[str]

Path to pipeline parameters file.

None
Source code in src/zenml/cli/pipeline.py
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
@pipeline.command(
    "register",
    help="Register a pipeline instance. The SOURCE argument needs to be an "
    "importable source path resolving to a ZenML pipeline instance, e.g. "
    "`my_module.my_pipeline_instance`.",
)
@click.argument("source")
@click.option(
    "--parameters",
    "-p",
    "parameters_path",
    type=click.Path(exists=True, dir_okay=False),
    required=False,
    help="Path to JSON file containing parameters for the pipeline function.",
)
def register_pipeline(
    source: str, parameters_path: Optional[str] = None
) -> None:
    """Register a pipeline.

    Args:
        source: Importable source resolving to a pipeline instance.
        parameters_path: Path to pipeline parameters file.
    """
    if "." not in source:
        cli_utils.error(
            f"The given source path `{source}` is invalid. Make sure it looks "
            "like `some.module.name_of_pipeline_instance_variable` and "
            "resolves to a pipeline object."
        )

    if not Client().root:
        cli_utils.warning(
            "You're running the `zenml pipeline register` command without a "
            "ZenML repository. Your current working directory will be used "
            "as the source root relative to which the `source` argument is "
            "expected. To silence this warning, run `zenml init` at your "
            "source code root."
        )

    pipeline_instance = _import_pipeline(source=source)

    parameters: Dict[str, Any] = {}
    if parameters_path:
        with open(parameters_path, "r") as f:
            parameters = json.load(f)

    try:
        pipeline_instance.prepare(**parameters)
    except ValueError:
        cli_utils.error(
            "Pipeline preparation failed. This is most likely due to your "
            "pipeline entrypoint function requiring arguments that were not "
            "provided. Please provide a JSON file with the parameters for "
            f"your pipeline like this: `zenml pipeline register {source} "
            "--parameters=<PATH_TO_JSON>`."
        )

    pipeline_instance.register()

register_project(project_name: str, set_project: bool = False, display_name: Optional[str] = None, set_default: bool = False) -> None

Register a new project.

Parameters:

Name Type Description Default
project_name str

The name of the project to register.

required
set_project bool

Whether to set the project as active.

False
display_name Optional[str]

The display name of the project.

None
set_default bool

Whether to set the project as the default project.

False
Source code in src/zenml/cli/project.py
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
@project.command("register")
@click.option(
    "--set",
    "set_project",
    is_flag=True,
    help="Immediately set this project as active.",
    type=click.BOOL,
)
@click.option(
    "--display-name",
    "display_name",
    type=str,
    required=False,
    help="The display name of the project.",
)
@click.option(
    "--set-default",
    "set_default",
    is_flag=True,
    help="Set this project as the default project.",
)
@click.argument("project_name", type=str, required=True)
def register_project(
    project_name: str,
    set_project: bool = False,
    display_name: Optional[str] = None,
    set_default: bool = False,
) -> None:
    """Register a new project.

    Args:
        project_name: The name of the project to register.
        set_project: Whether to set the project as active.
        display_name: The display name of the project.
        set_default: Whether to set the project as the default project.
    """
    check_zenml_pro_project_availability()
    client = Client()
    with console.status("Creating project...\n"):
        try:
            project = client.create_project(
                project_name,
                description="",
                display_name=display_name,
            )
            cli_utils.declare("Project created successfully.")
        except Exception as e:
            cli_utils.error(str(e))

    if set_project:
        client.set_active_project(project_name)
        cli_utils.declare(f"The active project has been set to {project_name}")

    if set_default:
        client.update_user(
            name_id_or_prefix=client.active_user.id,
            updated_default_project_id=project.id,
        )
        cli_utils.declare(
            f"The default project has been set to {project.name}"
        )

register_secrets(skip_existing: bool, stack_name_or_id: Optional[str] = None) -> None

Interactively registers all required secrets for a stack.

Parameters:

Name Type Description Default
skip_existing bool

If True, skip asking for secret values that already exist.

required
stack_name_or_id Optional[str]

Name of the stack for which to register secrets. If empty, the active stack will be used.

None
Source code in src/zenml/cli/stack.py
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
@stack.command(
    "register-secrets",
    help="Interactively register all required secrets for a stack.",
)
@click.argument("stack_name_or_id", type=str, required=False)
@click.option(
    "--skip-existing",
    "skip_existing",
    is_flag=True,
    default=False,
    help="Skip secrets with existing values.",
    type=bool,
)
def register_secrets(
    skip_existing: bool,
    stack_name_or_id: Optional[str] = None,
) -> None:
    """Interactively registers all required secrets for a stack.

    Args:
        skip_existing: If `True`, skip asking for secret values that already
            exist.
        stack_name_or_id: Name of the stack for which to register secrets.
                          If empty, the active stack will be used.
    """
    from zenml.stack.stack import Stack

    client = Client()

    stack_model = client.get_stack(name_id_or_prefix=stack_name_or_id)

    stack_ = Stack.from_model(stack_model)
    required_secrets = stack_.required_secrets

    if not required_secrets:
        cli_utils.declare("No secrets required for this stack.")
        return

    secret_names = {s.name for s in required_secrets}

    secrets_to_register = []
    secrets_to_update = []
    for name in secret_names:
        try:
            secret_content = client.get_secret(name).secret_values.copy()
            secret_exists = True
        except KeyError:
            secret_content = {}
            secret_exists = False

        required_keys = {s.key for s in required_secrets if s.name == name}
        needs_update = False

        for key in required_keys:
            existing_value = secret_content.get(key, None)

            if existing_value:
                if skip_existing:
                    continue

                value = getpass.getpass(
                    f"Value for secret `{name}.{key}` "
                    "(Leave empty to use existing value):"
                )
                if value:
                    value = cli_utils.expand_argument_value_from_file(
                        name=key, value=value
                    )
                else:
                    value = existing_value

                # only need to update if the value changed
                needs_update = needs_update or value != existing_value
            else:
                value = None
                while not value:
                    value = getpass.getpass(
                        f"Value for secret `{name}.{key}`:"
                    )
                value = cli_utils.expand_argument_value_from_file(
                    name=key, value=value
                )
                needs_update = True

            secret_content[key] = value

        if not secret_exists:
            secrets_to_register.append(
                (
                    name,
                    secret_content,
                )
            )
        elif needs_update:
            secrets_to_update.append(
                (
                    name,
                    secret_content,
                )
            )

    for secret_name, secret_values in secrets_to_register:
        cli_utils.declare(f"Registering secret `{secret_name}`:")
        cli_utils.pretty_print_secret(secret_values, hide_secret=True)
        client.create_secret(secret_name, values=secret_values)
    for secret_name, secret_values in secrets_to_update:
        cli_utils.declare(f"Updating secret `{secret_name}`:")
        cli_utils.pretty_print_secret(secret_values, hide_secret=True)
        client.update_secret(secret_name, add_or_update_values=secret_values)

register_service_connector(name: Optional[str], args: List[str], description: Optional[str] = None, connector_type: Optional[str] = None, resource_type: Optional[str] = None, resource_id: Optional[str] = None, auth_method: Optional[str] = None, expires_at: Optional[datetime] = None, expires_skew_tolerance: Optional[int] = None, expiration_seconds: Optional[int] = None, no_verify: bool = False, labels: Optional[List[str]] = None, interactive: bool = False, no_docs: bool = False, show_secrets: bool = False, auto_configure: bool = False) -> None

Registers a service connector.

Parameters:

Name Type Description Default
name Optional[str]

The name to use for the service connector.

required
args List[str]

Configuration arguments for the service connector.

required
description Optional[str]

Short description for the service connector.

None
connector_type Optional[str]

The service connector type.

None
resource_type Optional[str]

The type of resource to connect to.

None
resource_id Optional[str]

The ID of the resource to connect to.

None
auth_method Optional[str]

The authentication method to use.

None
expires_at Optional[datetime]

The exact UTC date and time when the credentials configured for this connector will expire.

None
expires_skew_tolerance Optional[int]

The tolerance, in seconds, allowed when determining when the credentials configured for or generated by this connector will expire.

None
expiration_seconds Optional[int]

The duration, in seconds, that the temporary credentials generated by this connector should remain valid.

None
no_verify bool

Do not verify the service connector before registering.

False
labels Optional[List[str]]

Labels to be associated with the service connector.

None
interactive bool

Register a new service connector interactively.

False
no_docs bool

Don't show documentation details during the interactive configuration.

False
show_secrets bool

Show security sensitive configuration attributes in the terminal.

False
auto_configure bool

Auto configure the service connector.

False

Raises:

Type Description
TypeError

If the connector_model does not have the correct type.

Source code in src/zenml/cli/service_connectors.py
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
@service_connector.command(
    "register",
    context_settings={"ignore_unknown_options": True},
    help="""Configure, validate and register a service connector.

This command can be used to configure and register a ZenML service connector and
to optionally verify that the service connector configuration and credentials
are valid and can be used to access the specified resource(s).

If the `-i|--interactive` flag is set, it will prompt the user for all the
information required to configure a service connector in a wizard-like fashion:

    $ zenml service-connector register -i

To trim down the amount of information displayed in interactive mode, pass the
`-n|--no-docs` flag:

    $ zenml service-connector register -ni

Secret configuration attributes are not shown by default. Use the
`-x|--show-secrets` flag to show them:

    $ zenml service-connector register -ix

Non-interactive examples:

- register a multi-purpose AWS service connector capable of accessing
any of the resource types that it supports (e.g. S3 buckets, EKS Kubernetes
clusters) using auto-configured credentials (i.e. extracted from the environment
variables or AWS CLI configuration files):

    $ zenml service-connector register aws-auto-multi --description \\
"Multi-purpose AWS connector" --type aws --auto-configure \\
--label auto=true --label purpose=multi

- register a Docker service connector providing access to a single DockerHub
repository named `dockerhub-hyppo` using explicit credentials:

    $ zenml service-connector register dockerhub-hyppo --description \\
"Hyppo's DockerHub repo" --type docker --resource-id dockerhub-hyppo \\
--username=hyppo --password=mypassword

- register an AWS service connector providing access to all the S3 buckets
that it's authorized to access using IAM role credentials:

    $ zenml service-connector register aws-s3-multi --description \\   
"Multi-bucket S3 connector" --type aws --resource-type s3-bucket \\    
--auth_method iam-role --role_arn=arn:aws:iam::<account>:role/<role> \\
--aws_region=us-east-1 --aws-access-key-id=<aws-key-id> \\            
--aws_secret_access_key=<aws-secret-key> --expiration-seconds 3600

All registered service connectors are validated before being registered. To
skip validation, pass the `--no-verify` flag.
""",
)
@click.argument(
    "name",
    type=str,
    required=False,
)
@click.option(
    "--description",
    "description",
    help="Short description for the connector instance.",
    required=False,
    type=str,
)
@click.option(
    "--type",
    "-t",
    "connector_type",
    help="The service connector type.",
    required=False,
    type=str,
)
@click.option(
    "--resource-type",
    "-r",
    "resource_type",
    help="The type of resource to connect to.",
    required=False,
    type=str,
)
@click.option(
    "--resource-id",
    "-ri",
    "resource_id",
    help="The ID of the resource to connect to.",
    required=False,
    type=str,
)
@click.option(
    "--auth-method",
    "-a",
    "auth_method",
    help="The authentication method to use.",
    required=False,
    type=str,
)
@click.option(
    "--expires-at",
    "expires_at",
    help="The exact UTC date and time when the credentials configured for this "
    "connector will expire. Takes the form 'YYYY-MM-DD HH:MM:SS'. This is only "
    "required if you are configuring a service connector with expiring "
    "credentials.",
    required=False,
    type=click.DateTime(),
)
@click.option(
    "--expires-skew-tolerance",
    "expires_skew_tolerance",
    help="The tolerance, in seconds, allowed when determining when the "
    "credentials configured for or generated by this connector will expire.",
    required=False,
    type=int,
)
@click.option(
    "--expiration-seconds",
    "expiration_seconds",
    help="The duration, in seconds, that the temporary credentials "
    "generated by this connector should remain valid.",
    required=False,
    type=int,
)
@click.option(
    "--label",
    "-l",
    "labels",
    help="Labels to be associated with the service connector. Takes the form "
    "-l key1=value1 and can be used multiple times.",
    multiple=True,
)
@click.option(
    "--no-verify",
    "no_verify",
    is_flag=True,
    default=False,
    help="Do not verify the service connector before registering.",
    type=click.BOOL,
)
@click.option(
    "--interactive",
    "-i",
    "interactive",
    is_flag=True,
    default=False,
    help="Register a new service connector interactively.",
    type=click.BOOL,
)
@click.option(
    "--no-docs",
    "-n",
    "no_docs",
    is_flag=True,
    default=False,
    help="Don't show documentation details during the interactive "
    "configuration.",
    type=click.BOOL,
)
@click.option(
    "--show-secrets",
    "-x",
    "show_secrets",
    is_flag=True,
    default=False,
    help="Show security sensitive configuration attributes in the terminal.",
    type=click.BOOL,
)
@click.option(
    "--auto-configure",
    "auto_configure",
    is_flag=True,
    default=False,
    help="Auto configure the service connector.",
    type=click.BOOL,
)
@click.argument("args", nargs=-1, type=click.UNPROCESSED)
def register_service_connector(
    name: Optional[str],
    args: List[str],
    description: Optional[str] = None,
    connector_type: Optional[str] = None,
    resource_type: Optional[str] = None,
    resource_id: Optional[str] = None,
    auth_method: Optional[str] = None,
    expires_at: Optional[datetime] = None,
    expires_skew_tolerance: Optional[int] = None,
    expiration_seconds: Optional[int] = None,
    no_verify: bool = False,
    labels: Optional[List[str]] = None,
    interactive: bool = False,
    no_docs: bool = False,
    show_secrets: bool = False,
    auto_configure: bool = False,
) -> None:
    """Registers a service connector.

    Args:
        name: The name to use for the service connector.
        args: Configuration arguments for the service connector.
        description: Short description for the service connector.
        connector_type: The service connector type.
        resource_type: The type of resource to connect to.
        resource_id: The ID of the resource to connect to.
        auth_method: The authentication method to use.
        expires_at: The exact UTC date and time when the credentials configured
            for this connector will expire.
        expires_skew_tolerance: The tolerance, in seconds, allowed when
            determining when the credentials configured for or generated by
            this connector will expire.
        expiration_seconds: The duration, in seconds, that the temporary
            credentials generated by this connector should remain valid.
        no_verify: Do not verify the service connector before
            registering.
        labels: Labels to be associated with the service connector.
        interactive: Register a new service connector interactively.
        no_docs: Don't show documentation details during the interactive
            configuration.
        show_secrets: Show security sensitive configuration attributes in
            the terminal.
        auto_configure: Auto configure the service connector.

    Raises:
        TypeError: If the connector_model does not have the correct type.
    """
    from rich.markdown import Markdown

    client = Client()

    # Parse the given args
    name, parsed_args = cli_utils.parse_name_and_extra_arguments(
        list(args) + [name or ""],
        expand_args=True,
        name_mandatory=not interactive,
    )

    # Parse the given labels
    parsed_labels = cast(Dict[str, str], cli_utils.get_parsed_labels(labels))

    if interactive:
        # Get the list of available service connector types
        connector_types = client.list_service_connector_types(
            connector_type=connector_type,
            resource_type=resource_type,
            auth_method=auth_method,
        )
        if not connector_types:
            cli_utils.error(
                "No service connectors found with the given parameters: "
                + f"type={connector_type} "
                if connector_type
                else "" + f"resource_type={resource_type} "
                if resource_type
                else "" + f"auth_method={auth_method} "
                if auth_method
                else "",
            )

        # Ask for a connector name
        name = prompt_connector_name(name)

        # Ask for a description
        description = click.prompt(
            "Please enter a description for the service connector",
            type=str,
            default="",
        )

        available_types = {c.connector_type: c for c in connector_types}
        if len(available_types) == 1:
            # Default to the first connector type if not supplied and if
            # only one type is available
            connector_type = connector_type or list(available_types.keys())[0]

        # Print the name, type and description of all available service
        # connectors
        if not no_docs:
            message = "# Available service connector types\n"
            for spec in connector_types:
                message += cli_utils.print_service_connector_type(
                    connector_type=spec,
                    heading="##",
                    footer="",
                    include_auth_methods=False,
                    include_resource_types=False,
                    print=False,
                )
            console.print(Markdown(f"{message}---"), justify="left", width=80)

        # Ask the user to select a service connector type
        connector_type = click.prompt(
            "Please select a service connector type",
            type=click.Choice(list(available_types.keys())),
            default=connector_type,
        )

        assert connector_type is not None
        connector_type_spec = available_types[connector_type]

        available_resource_types = [
            t.resource_type for t in connector_type_spec.resource_types
        ]

        if not no_docs:
            # Print the name, resource type identifiers and description of all
            # available resource types
            message = "# Available resource types\n"
            for r in connector_type_spec.resource_types:
                message += cli_utils.print_service_connector_resource_type(
                    resource_type=r,
                    heading="##",
                    footer="",
                    print=False,
                )
            console.print(Markdown(f"{message}---"), justify="left", width=80)

        # Ask the user to select a resource type
        resource_type = prompt_resource_type(
            available_resource_types=available_resource_types
        )

        # Ask the user whether to use autoconfiguration, if the connector
        # implementation is locally available and if autoconfiguration is
        # supported
        if (
            connector_type_spec.supports_auto_configuration
            and connector_type_spec.local
        ):
            auto_configure = click.confirm(
                "Would you like to attempt auto-configuration to extract the "
                "authentication configuration from your local environment ?",
                default=False,
            )
        else:
            auto_configure = False

        connector_model: Optional[
            Union[ServiceConnectorRequest, ServiceConnectorResponse]
        ] = None
        connector_resources: Optional[ServiceConnectorResourcesModel] = None
        if auto_configure:
            # Try to autoconfigure the service connector
            try:
                with console.status("Auto-configuring service connector...\n"):
                    (
                        connector_model,
                        connector_resources,
                    ) = client.create_service_connector(
                        name=name,
                        description=description or "",
                        connector_type=connector_type,
                        resource_type=resource_type,
                        auth_method=auth_method,
                        expires_skew_tolerance=expires_skew_tolerance,
                        auto_configure=True,
                        verify=True,
                        register=False,
                    )

                assert connector_model is not None
                assert connector_resources is not None
            except (
                KeyError,
                ValueError,
                IllegalOperationError,
                NotImplementedError,
                AuthorizationException,
            ) as e:
                cli_utils.warning(
                    f"Auto-configuration was not successful: {e} "
                )
                # Ask the user whether to continue with manual configuration
                manual = click.confirm(
                    "Would you like to continue with manual configuration ?",
                    default=True,
                )
                if not manual:
                    return
            else:
                auth_method = connector_model.auth_method
                expiration_seconds = connector_model.expiration_seconds
                expires_at = connector_model.expires_at
                cli_utils.declare(
                    "Service connector auto-configured successfully with the "
                    "following configuration:"
                )

                # Print the configuration detected by the autoconfiguration
                # process
                # TODO: Normally, this could have been handled with setter
                #   functions over the connector type property in the response
                #   model. However, pydantic breaks property setter functions.
                #   We can find a more elegant solution here.
                if isinstance(connector_model, ServiceConnectorResponse):
                    connector_model.set_connector_type(connector_type_spec)
                elif isinstance(connector_model, ServiceConnectorRequest):
                    connector_model.connector_type = connector_type_spec
                else:
                    raise TypeError(
                        "The service connector must be an instance of either"
                        "`ServiceConnectorResponse` or "
                        "`ServiceConnectorRequest`."
                    )

                cli_utils.print_service_connector_configuration(
                    connector_model,
                    active_status=False,
                    show_secrets=show_secrets,
                )
                cli_utils.declare(
                    "The service connector configuration has access to the "
                    "following resources:"
                )
                cli_utils.print_service_connector_resource_table(
                    [connector_resources],
                    show_resources_only=True,
                )

                # Ask the user whether to continue with the autoconfiguration
                choice = click.prompt(
                    "Would you like to continue with the auto-discovered "
                    "configuration or switch to manual ?",
                    type=click.Choice(["auto", "manual"]),
                    default="auto",
                )
                if choice == "manual":
                    # Reset the connector configuration to default to let the
                    # manual configuration kick in the next step
                    connector_model = None
                    connector_resources = None
                    expires_at = None

        if connector_model is not None and connector_resources is not None:
            assert auth_method is not None
            auth_method_spec = connector_type_spec.auth_method_dict[
                auth_method
            ]
        else:
            # In this branch, we are either not using autoconfiguration or the
            # autoconfiguration failed or was dismissed. In all cases, we need
            # to ask the user for the authentication method to use and then
            # prompt for the configuration

            auth_methods = list(connector_type_spec.auth_method_dict.keys())

            if not no_docs:
                # Print the name, identifier and description of all available
                # auth methods
                message = "# Available authentication methods\n"
                for a in auth_methods:
                    message += cli_utils.print_service_connector_auth_method(
                        auth_method=connector_type_spec.auth_method_dict[a],
                        heading="##",
                        footer="",
                        print=False,
                    )
                console.print(
                    Markdown(f"{message}---"), justify="left", width=80
                )

            if len(auth_methods) == 1:
                # Default to the first auth method if only one method is
                # available
                confirm = click.confirm(
                    "Only one authentication method is available for this "
                    f"connector ({auth_methods[0]}). Would you like to use it?",
                    default=True,
                )
                if not confirm:
                    return

                auth_method = auth_methods[0]
            else:
                # Ask the user to select an authentication method
                auth_method = click.prompt(
                    "Please select an authentication method",
                    type=click.Choice(auth_methods),
                    default=auth_method,
                )

            assert auth_method is not None
            auth_method_spec = connector_type_spec.auth_method_dict[
                auth_method
            ]

            cli_utils.declare(
                f"Please enter the configuration for the {auth_method_spec.name} "
                "authentication method."
            )

            # Prompt for the configuration of the selected authentication method
            # field by field
            config_schema = auth_method_spec.config_schema or {}
            config_dict = cli_utils.prompt_configuration(
                config_schema=config_schema,
                show_secrets=show_secrets,
            )

            # Prompt for an expiration time if the auth method supports it
            if auth_method_spec.supports_temporary_credentials():
                expiration_seconds = prompt_expiration_time(
                    min=auth_method_spec.min_expiration_seconds,
                    max=auth_method_spec.max_expiration_seconds,
                    default=auth_method_spec.default_expiration_seconds,
                )

            # Prompt for the time when the credentials will expire
            expires_at = prompt_expires_at(expires_at)

            try:
                # Validate the connector configuration and fetch all available
                # resources that are accessible with the provided configuration
                # in the process
                with console.status(
                    "Validating service connector configuration...\n"
                ):
                    (
                        connector_model,
                        connector_resources,
                    ) = client.create_service_connector(
                        name=name,
                        description=description or "",
                        connector_type=connector_type,
                        auth_method=auth_method,
                        resource_type=resource_type,
                        configuration=config_dict,
                        expires_at=expires_at,
                        expires_skew_tolerance=expires_skew_tolerance,
                        expiration_seconds=expiration_seconds,
                        auto_configure=False,
                        verify=True,
                        register=False,
                    )
                assert connector_model is not None
                assert connector_resources is not None
            except (
                KeyError,
                ValueError,
                IllegalOperationError,
                NotImplementedError,
                AuthorizationException,
            ) as e:
                cli_utils.error(f"Failed to configure service connector: {e}")

        if resource_type:
            # Finally, for connectors that are configured with a particular
            # resource type, prompt the user to select one of the available
            # resources that can be accessed with the connector. We don't do
            # need to do this for resource types that don't support instances.
            resource_type_spec = connector_type_spec.resource_type_dict[
                resource_type
            ]
            if resource_type_spec.supports_instances:
                assert len(connector_resources.resources) == 1
                resource_ids = connector_resources.resources[0].resource_ids
                assert resource_ids is not None
                resource_id = prompt_resource_id(
                    resource_name=resource_type_spec.name,
                    resource_ids=resource_ids,
                )
            else:
                resource_id = None
        else:
            resource_id = None

        # Prepare the rest of the variables to fall through to the
        # non-interactive configuration case
        parsed_args = connector_model.configuration
        parsed_args.update(
            {
                k: s.get_secret_value()
                for k, s in connector_model.secrets.items()
                if s is not None
            }
        )
        auto_configure = False
        no_verify = False
        expiration_seconds = connector_model.expiration_seconds

    if not connector_type:
        cli_utils.error(
            "The connector type must be specified when using non-interactive "
            "configuration."
        )

    with console.status(f"Registering service connector '{name}'...\n"):
        try:
            # Create a new service connector
            assert name is not None
            (
                connector_model,
                connector_resources,
            ) = client.create_service_connector(
                name=name,
                connector_type=connector_type,
                auth_method=auth_method,
                resource_type=resource_type,
                configuration=parsed_args,
                resource_id=resource_id,
                description=description or "",
                expires_skew_tolerance=expires_skew_tolerance,
                expiration_seconds=expiration_seconds,
                expires_at=expires_at,
                labels=parsed_labels,
                verify=not no_verify,
                auto_configure=auto_configure,
                register=True,
            )
        except (
            KeyError,
            ValueError,
            IllegalOperationError,
            NotImplementedError,
            AuthorizationException,
        ) as e:
            cli_utils.error(f"Failed to register service connector: {e}")

    if connector_resources is not None:
        cli_utils.declare(
            f"Successfully registered service connector `{name}` with access "
            "to the following resources:"
        )

        cli_utils.print_service_connector_resource_table(
            [connector_resources],
            show_resources_only=True,
        )

    else:
        cli_utils.declare(
            f"Successfully registered service connector `{name}`."
        )

register_single_stack_component_cli_commands(component_type: StackComponentType, parent_group: click.Group) -> None

Registers all basic stack component CLI commands.

Parameters:

Name Type Description Default
component_type StackComponentType

Type of the component to generate the command for.

required
parent_group Group

The parent group to register the commands to.

required
Source code in src/zenml/cli/stack_components.py
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
def register_single_stack_component_cli_commands(
    component_type: StackComponentType, parent_group: click.Group
) -> None:
    """Registers all basic stack component CLI commands.

    Args:
        component_type: Type of the component to generate the command for.
        parent_group: The parent group to register the commands to.
    """
    command_name = component_type.value.replace("_", "-")
    singular_display_name = _component_display_name(component_type)
    plural_display_name = _component_display_name(component_type, plural=True)

    @parent_group.group(
        command_name,
        cls=TagGroup,
        help=f"Commands to interact with {plural_display_name}.",
        tag=CliCategories.STACK_COMPONENTS,
    )
    def command_group() -> None:
        """Group commands for a single stack component type."""

    # zenml stack-component get
    get_command = generate_stack_component_get_command(component_type)
    command_group.command(
        "get", help=f"Get the name of the active {singular_display_name}."
    )(get_command)

    # zenml stack-component describe
    describe_command = generate_stack_component_describe_command(
        component_type
    )
    command_group.command(
        "describe",
        help=f"Show details about the (active) {singular_display_name}.",
    )(describe_command)

    # zenml stack-component list
    list_command = generate_stack_component_list_command(component_type)
    command_group.command(
        "list", help=f"List all registered {plural_display_name}."
    )(list_command)

    # zenml stack-component register
    register_command = generate_stack_component_register_command(
        component_type
    )
    context_settings = {"ignore_unknown_options": True}
    command_group.command(
        "register",
        context_settings=context_settings,
        help=f"Register a new {singular_display_name}.",
    )(register_command)

    # zenml stack-component update
    update_command = generate_stack_component_update_command(component_type)
    context_settings = {"ignore_unknown_options": True}
    command_group.command(
        "update",
        context_settings=context_settings,
        help=f"Update a registered {singular_display_name}.",
    )(update_command)

    # zenml stack-component remove-attribute
    remove_attribute_command = (
        generate_stack_component_remove_attribute_command(component_type)
    )
    context_settings = {"ignore_unknown_options": True}
    command_group.command(
        "remove-attribute",
        context_settings=context_settings,
        help=f"Remove attributes from a registered {singular_display_name}.",
    )(remove_attribute_command)

    # zenml stack-component rename
    rename_command = generate_stack_component_rename_command(component_type)
    command_group.command(
        "rename", help=f"Rename a registered {singular_display_name}."
    )(rename_command)

    # zenml stack-component delete
    delete_command = generate_stack_component_delete_command(component_type)
    command_group.command(
        "delete", help=f"Delete a registered {singular_display_name}."
    )(delete_command)

    # zenml stack-component copy
    copy_command = generate_stack_component_copy_command(component_type)
    command_group.command(
        "copy", help=f"Copy a registered {singular_display_name}."
    )(copy_command)

    # zenml stack-component logs
    logs_command = generate_stack_component_logs_command(component_type)
    command_group.command(
        "logs", help=f"Display {singular_display_name} logs."
    )(logs_command)

    # zenml stack-component connect
    connect_command = generate_stack_component_connect_command(component_type)
    command_group.command(
        "connect",
        help=f"Connect {singular_display_name} to a service connector.",
    )(connect_command)

    # zenml stack-component connect
    disconnect_command = generate_stack_component_disconnect_command(
        component_type
    )
    command_group.command(
        "disconnect",
        help=f"Disconnect {singular_display_name} from a service connector.",
    )(disconnect_command)

    # zenml stack-component explain
    explain_command = generate_stack_component_explain_command(component_type)
    command_group.command(
        "explain", help=f"Explaining the {plural_display_name}."
    )(explain_command)

    # zenml stack-component flavor
    @command_group.group(
        "flavor", help=f"Commands to interact with {plural_display_name}."
    )
    def flavor_group() -> None:
        """Group commands to handle flavors for a stack component type."""

    # zenml stack-component flavor register
    register_flavor_command = generate_stack_component_flavor_register_command(
        component_type=component_type
    )
    flavor_group.command(
        "register",
        help=f"Register a new {singular_display_name} flavor.",
    )(register_flavor_command)

    # zenml stack-component flavor list
    list_flavor_command = generate_stack_component_flavor_list_command(
        component_type=component_type
    )
    flavor_group.command(
        "list",
        help=f"List all registered flavors for {plural_display_name}.",
    )(list_flavor_command)

    # zenml stack-component flavor describe
    describe_flavor_command = generate_stack_component_flavor_describe_command(
        component_type=component_type
    )
    flavor_group.command(
        "describe",
        help=f"Describe a {singular_display_name} flavor.",
    )(describe_flavor_command)

    # zenml stack-component flavor delete
    delete_flavor_command = generate_stack_component_flavor_delete_command(
        component_type=component_type
    )
    flavor_group.command(
        "delete",
        help=f"Delete a {plural_display_name} flavor.",
    )(delete_flavor_command)

register_stack(stack_name: str, artifact_store: Optional[str] = None, orchestrator: Optional[str] = None, container_registry: Optional[str] = None, model_registry: Optional[str] = None, step_operator: Optional[str] = None, feature_store: Optional[str] = None, model_deployer: Optional[str] = None, experiment_tracker: Optional[str] = None, alerter: Optional[str] = None, annotator: Optional[str] = None, data_validator: Optional[str] = None, image_builder: Optional[str] = None, set_stack: bool = False, provider: Optional[str] = None, connector: Optional[str] = None) -> None

Register a stack.

Parameters:

Name Type Description Default
stack_name str

Unique name of the stack

required
artifact_store Optional[str]

Name of the artifact store for this stack.

None
orchestrator Optional[str]

Name of the orchestrator for this stack.

None
container_registry Optional[str]

Name of the container registry for this stack.

None
model_registry Optional[str]

Name of the model registry for this stack.

None
step_operator Optional[str]

Name of the step operator for this stack.

None
feature_store Optional[str]

Name of the feature store for this stack.

None
model_deployer Optional[str]

Name of the model deployer for this stack.

None
experiment_tracker Optional[str]

Name of the experiment tracker for this stack.

None
alerter Optional[str]

Name of the alerter for this stack.

None
annotator Optional[str]

Name of the annotator for this stack.

None
data_validator Optional[str]

Name of the data validator for this stack.

None
image_builder Optional[str]

Name of the new image builder for this stack.

None
set_stack bool

Immediately set this stack as active.

False
provider Optional[str]

Name of the cloud provider for this stack.

None
connector Optional[str]

Name of the service connector for this stack.

None
Source code in src/zenml/cli/stack.py
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
@stack.command(
    "register",
    context_settings=dict(ignore_unknown_options=True),
    help="Register a stack with components.",
)
@click.argument("stack_name", type=str, required=True)
@click.option(
    "-a",
    "--artifact-store",
    "artifact_store",
    help="Name of the artifact store for this stack.",
    type=str,
    required=False,
)
@click.option(
    "-o",
    "--orchestrator",
    "orchestrator",
    help="Name of the orchestrator for this stack.",
    type=str,
    required=False,
)
@click.option(
    "-c",
    "--container_registry",
    "container_registry",
    help="Name of the container registry for this stack.",
    type=str,
    required=False,
)
@click.option(
    "-r",
    "--model_registry",
    "model_registry",
    help="Name of the model registry for this stack.",
    type=str,
    required=False,
)
@click.option(
    "-s",
    "--step_operator",
    "step_operator",
    help="Name of the step operator for this stack.",
    type=str,
    required=False,
)
@click.option(
    "-f",
    "--feature_store",
    "feature_store",
    help="Name of the feature store for this stack.",
    type=str,
    required=False,
)
@click.option(
    "-d",
    "--model_deployer",
    "model_deployer",
    help="Name of the model deployer for this stack.",
    type=str,
    required=False,
)
@click.option(
    "-e",
    "--experiment_tracker",
    "experiment_tracker",
    help="Name of the experiment tracker for this stack.",
    type=str,
    required=False,
)
@click.option(
    "-al",
    "--alerter",
    "alerter",
    help="Name of the alerter for this stack.",
    type=str,
    required=False,
)
@click.option(
    "-an",
    "--annotator",
    "annotator",
    help="Name of the annotator for this stack.",
    type=str,
    required=False,
)
@click.option(
    "-dv",
    "--data_validator",
    "data_validator",
    help="Name of the data validator for this stack.",
    type=str,
    required=False,
)
@click.option(
    "-i",
    "--image_builder",
    "image_builder",
    help="Name of the image builder for this stack.",
    type=str,
    required=False,
)
@click.option(
    "--set",
    "set_stack",
    is_flag=True,
    help="Immediately set this stack as active.",
    type=click.BOOL,
)
@click.option(
    "-p",
    "--provider",
    help="Name of the cloud provider for this stack.",
    type=click.Choice(["aws", "azure", "gcp"]),
    required=False,
)
@click.option(
    "-sc",
    "--connector",
    help="Name of the service connector for this stack.",
    type=str,
    required=False,
)
def register_stack(
    stack_name: str,
    artifact_store: Optional[str] = None,
    orchestrator: Optional[str] = None,
    container_registry: Optional[str] = None,
    model_registry: Optional[str] = None,
    step_operator: Optional[str] = None,
    feature_store: Optional[str] = None,
    model_deployer: Optional[str] = None,
    experiment_tracker: Optional[str] = None,
    alerter: Optional[str] = None,
    annotator: Optional[str] = None,
    data_validator: Optional[str] = None,
    image_builder: Optional[str] = None,
    set_stack: bool = False,
    provider: Optional[str] = None,
    connector: Optional[str] = None,
) -> None:
    """Register a stack.

    Args:
        stack_name: Unique name of the stack
        artifact_store: Name of the artifact store for this stack.
        orchestrator: Name of the orchestrator for this stack.
        container_registry: Name of the container registry for this stack.
        model_registry: Name of the model registry for this stack.
        step_operator: Name of the step operator for this stack.
        feature_store: Name of the feature store for this stack.
        model_deployer: Name of the model deployer for this stack.
        experiment_tracker: Name of the experiment tracker for this stack.
        alerter: Name of the alerter for this stack.
        annotator: Name of the annotator for this stack.
        data_validator: Name of the data validator for this stack.
        image_builder: Name of the new image builder for this stack.
        set_stack: Immediately set this stack as active.
        provider: Name of the cloud provider for this stack.
        connector: Name of the service connector for this stack.
    """
    if (provider is None and connector is None) and (
        artifact_store is None or orchestrator is None
    ):
        cli_utils.error(
            "The only way to register a stack without specifying an "
            "orchestrator and an artifact store is by using either a provider"
            "(-p/--provider) or an existing service connector "
            "(-sc/--connector). Please specify the artifact store and "
            "the orchestrator or the service connector or cloud type settings."
        )

    client = Client()

    if provider is not None or connector is not None:
        if client.zen_store.is_local_store():
            cli_utils.error(
                "You are registering a stack using a service connector, but "
                "this feature cannot be used with a local ZenML deployment. "
                "ZenML needs to be accessible from the cloud provider to allow "
                "the stack and its components to be registered automatically. "
                "Please deploy ZenML in a remote environment as described in "
                "the documentation: https://docs.zenml.io/getting-started/deploying-zenml "
                "or use a managed ZenML Pro server instance for quick access "
                "to this feature and more: https://www.zenml.io/pro"
            )

    try:
        client.get_stack(
            name_id_or_prefix=stack_name,
            allow_name_prefix_match=False,
        )
        cli_utils.error(
            f"A stack with name `{stack_name}` already exists, "
            "please use a different name."
        )
    except KeyError:
        pass

    labels: Dict[str, str] = {}
    components: Dict[StackComponentType, List[Union[UUID, ComponentInfo]]] = {}

    # Cloud Flow
    created_objects: Set[str] = set()
    service_connector: Optional[Union[UUID, ServiceConnectorInfo]] = None
    if provider is not None and connector is None:
        service_connector_response = None
        use_auto_configure = False
        try:
            service_connector_response, _ = client.create_service_connector(
                name=stack_name,
                connector_type=provider,
                register=False,
                auto_configure=True,
                verify=False,
            )
        except NotImplementedError:
            cli_utils.warning(
                f"The {provider.upper()} service connector libraries are not "
                "installed properly. Please run `zenml integration install "
                f"{provider}` and try again to enable auto-discovery of the "
                "connection configuration."
            )
        except Exception:
            pass

        if service_connector_response:
            use_auto_configure = Confirm.ask(
                f"[bold]{provider.upper()} cloud service connector[/bold] "
                "has detected connection credentials in your environment.\n"
                "Would you like to use these credentials or create a new "
                "configuration by providing connection details?",
                default=True,
                show_choices=True,
                show_default=True,
            )

        connector_selected: Optional[int] = None
        if not use_auto_configure:
            service_connector_response = None
            existing_connectors = client.list_service_connectors(
                connector_type=provider, size=100
            )
            if existing_connectors.total:
                connector_selected = cli_utils.multi_choice_prompt(
                    object_type=f"{provider.upper()} service connectors",
                    choices=[
                        [connector.name]
                        for connector in existing_connectors.items
                    ],
                    headers=["Name"],
                    prompt_text=f"We found these {provider.upper()} service "
                    "connectors. Do you want to create a new one or use one "
                    "of the existing ones?",
                    default_choice="0",
                    allow_zero_be_a_new_object=True,
                )
        if use_auto_configure or connector_selected is None:
            service_connector = _get_service_connector_info(
                cloud_provider=provider,
                connector_details=service_connector_response,
            )
            created_objects.add("service_connector")
        else:
            selected_connector = existing_connectors.items[connector_selected]
            service_connector = selected_connector.id
            connector = selected_connector.name
            if isinstance(selected_connector.connector_type, str):
                provider = selected_connector.connector_type
            else:
                provider = selected_connector.connector_type.connector_type
    elif connector is not None:
        service_connector_response = client.get_service_connector(connector)
        service_connector = service_connector_response.id
        if provider:
            if service_connector_response.type != provider:
                cli_utils.warning(
                    f"The service connector `{connector}` is not of type `{provider}`."
                )
        else:
            provider = service_connector_response.type

    if service_connector:
        labels["zenml:wizard"] = "true"
        if provider:
            labels["zenml:provider"] = provider
        resources_info = None
        # explore the service connector
        with console.status(
            "Exploring resources available to the service connector...\n"
        ):
            resources_info = (
                get_resources_options_from_resource_model_for_full_stack(
                    connector_details=service_connector
                )
            )
        if resources_info is None:
            cli_utils.error(
                f"Failed to fetch service connector resources information for {service_connector}..."
            )

        # create components
        needed_components = (
            (StackComponentType.ARTIFACT_STORE, artifact_store),
            (StackComponentType.ORCHESTRATOR, orchestrator),
            (StackComponentType.CONTAINER_REGISTRY, container_registry),
        )
        for component_type, preset_name in needed_components:
            component_info: Optional[Union[UUID, ComponentInfo]] = None
            if preset_name is not None:
                component_response = client.get_stack_component(
                    component_type, preset_name
                )
                component_info = component_response.id
                component_name = component_response.name
            else:
                if isinstance(service_connector, UUID):
                    # find existing components under same connector
                    if (
                        component_type
                        in resources_info.components_resources_info
                    ):
                        existing_components = [
                            existing_response
                            for res_info in resources_info.components_resources_info[
                                component_type
                            ]
                            for existing_response in res_info.connected_through_service_connector
                        ]

                        # if some existing components are found - prompt user what to do
                        component_selected: Optional[int] = None
                        component_selected = cli_utils.multi_choice_prompt(
                            object_type=component_type.value.replace("_", " "),
                            choices=[
                                [
                                    component.flavor_name,
                                    component.name,
                                    component.configuration or "",
                                    component.connector_resource_id,
                                ]
                                for component in existing_components
                            ],
                            headers=[
                                "Type",
                                "Name",
                                "Configuration",
                                "Connected as",
                            ],
                            prompt_text=f"We found these {component_type.value.replace('_', ' ')} "
                            "connected using the current service connector. Do you "
                            "want to create a new one or use existing one?",
                            default_choice="0",
                            allow_zero_be_a_new_object=True,
                        )
                else:
                    component_selected = None

                if component_selected is None:
                    component_info = _get_stack_component_info(
                        component_type=component_type.value,
                        cloud_provider=provider
                        or resources_info.connector_type,
                        resources_info=resources_info,
                        service_connector_index=0,
                    )
                    component_name = stack_name
                    created_objects.add(component_type.value)
                else:
                    selected_component = existing_components[
                        component_selected
                    ]
                    component_info = selected_component.id
                    component_name = selected_component.name

            components[component_type] = [component_info]
            if component_type == StackComponentType.ARTIFACT_STORE:
                artifact_store = component_name
            if component_type == StackComponentType.ORCHESTRATOR:
                orchestrator = component_name
            if component_type == StackComponentType.CONTAINER_REGISTRY:
                container_registry = component_name

    # normal flow once all components are defined
    with console.status(f"Registering stack '{stack_name}'...\n"):
        for component_type_, component_name_ in [
            (StackComponentType.ARTIFACT_STORE, artifact_store),
            (StackComponentType.ORCHESTRATOR, orchestrator),
            (StackComponentType.ALERTER, alerter),
            (StackComponentType.ANNOTATOR, annotator),
            (StackComponentType.DATA_VALIDATOR, data_validator),
            (StackComponentType.FEATURE_STORE, feature_store),
            (StackComponentType.IMAGE_BUILDER, image_builder),
            (StackComponentType.MODEL_DEPLOYER, model_deployer),
            (StackComponentType.MODEL_REGISTRY, model_registry),
            (StackComponentType.STEP_OPERATOR, step_operator),
            (StackComponentType.EXPERIMENT_TRACKER, experiment_tracker),
            (StackComponentType.CONTAINER_REGISTRY, container_registry),
        ]:
            if component_name_ and component_type_ not in components:
                components[component_type_] = [
                    client.get_stack_component(
                        component_type_, component_name_
                    ).id
                ]

        try:
            created_stack = client.zen_store.create_stack(
                stack=StackRequest(
                    name=stack_name,
                    components=components,
                    service_connectors=[service_connector]
                    if service_connector
                    else [],
                    labels=labels,
                )
            )
        except (KeyError, IllegalOperationError) as err:
            cli_utils.error(str(err))

        cli_utils.declare(
            f"Stack '{created_stack.name}' successfully registered!"
        )
        cli_utils.print_stack_configuration(
            stack=created_stack,
            active=created_stack.id == client.active_stack_model.id,
        )

    if set_stack:
        client.activate_stack(created_stack.id)

        scope = "repository" if client.uses_local_configuration else "global"
        cli_utils.declare(
            f"Active {scope} stack set to:'{created_stack.name}'"
        )

    delete_commands = []
    if "service_connector" in created_objects:
        created_objects.remove("service_connector")
        connectors = set()
        for each in created_objects:
            if comps_ := created_stack.components[StackComponentType(each)]:
                if conn_ := comps_[0].connector:
                    connectors.add(conn_.name)
        for connector in connectors:
            delete_commands.append(
                "zenml service-connector delete " + connector
            )
    for each in created_objects:
        if comps_ := created_stack.components[StackComponentType(each)]:
            delete_commands.append(
                f"zenml {each.replace('_', '-')} delete {comps_[0].name}"
            )
    delete_commands.append("zenml stack delete -y " + created_stack.name)

    Console().print(
        "To delete the objects created by this command run, please run in a sequence:\n"
    )
    Console().print(Syntax("\n".join(delete_commands[::-1]), "bash"))

    print_model_url(get_stack_url(created_stack))

register_tag(name: str, color: Optional[ColorVariants]) -> None

Register a new model in the Model Control Plane.

Parameters:

Name Type Description Default
name str

The name of the tag.

required
color Optional[ColorVariants]

The color variant for UI.

required
Source code in src/zenml/cli/tag.py
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
@tag.command("register", help="Register a new tag.")
@click.option(
    "--name",
    "-n",
    help="The name of the tag.",
    type=str,
    required=True,
)
@click.option(
    "--color",
    "-c",
    help="The color variant for UI.",
    type=click.Choice(choices=ColorVariants.values()),
    required=False,
)
def register_tag(name: str, color: Optional[ColorVariants]) -> None:
    """Register a new model in the Model Control Plane.

    Args:
        name: The name of the tag.
        color: The color variant for UI.
    """
    request_dict = remove_none_values(dict(name=name, color=color))
    try:
        tag = Client().create_tag(**request_dict)
    except (EntityExistsError, ValueError) as e:
        cli_utils.error(str(e))

    cli_utils.print_pydantic_models(
        [tag],
        exclude_columns=["created"],
    )

remove_none_values(dict_: Dict[str, Any], recursive: bool = False) -> Dict[str, Any]

Removes all key-value pairs with None value.

Parameters:

Name Type Description Default
dict_ Dict[str, Any]

The dict from which the key-value pairs should be removed.

required
recursive bool

If True, will recursively remove None values in all child dicts.

False

Returns:

Type Description
Dict[str, Any]

The updated dictionary.

Source code in src/zenml/utils/dict_utils.py
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
def remove_none_values(
    dict_: Dict[str, Any], recursive: bool = False
) -> Dict[str, Any]:
    """Removes all key-value pairs with `None` value.

    Args:
        dict_: The dict from which the key-value pairs should be removed.
        recursive: If `True`, will recursively remove `None` values in all
            child dicts.

    Returns:
        The updated dictionary.
    """

    def _maybe_recurse(value: Any) -> Any:
        """Calls `remove_none_values` recursively if required.

        Args:
            value: A dictionary value.

        Returns:
            The updated dictionary value.
        """
        if recursive and isinstance(value, Dict):
            return remove_none_values(value, recursive=True)
        else:
            return value

    return {k: _maybe_recurse(v) for k, v in dict_.items() if v is not None}

remove_stack_component(stack_name_or_id: Optional[str] = None, container_registry_flag: Optional[bool] = False, step_operator_flag: Optional[bool] = False, feature_store_flag: Optional[bool] = False, model_deployer_flag: Optional[bool] = False, experiment_tracker_flag: Optional[bool] = False, alerter_flag: Optional[bool] = False, annotator_flag: Optional[bool] = False, data_validator_flag: Optional[bool] = False, image_builder_flag: Optional[bool] = False, model_registry_flag: Optional[str] = None) -> None

Remove stack components from a stack.

Parameters:

Name Type Description Default
stack_name_or_id Optional[str]

Name of the stack to remove components from.

None
container_registry_flag Optional[bool]

To remove the container registry from this stack.

False
step_operator_flag Optional[bool]

To remove the step operator from this stack.

False
feature_store_flag Optional[bool]

To remove the feature store from this stack.

False
model_deployer_flag Optional[bool]

To remove the model deployer from this stack.

False
experiment_tracker_flag Optional[bool]

To remove the experiment tracker from this stack.

False
alerter_flag Optional[bool]

To remove the alerter from this stack.

False
annotator_flag Optional[bool]

To remove the annotator from this stack.

False
data_validator_flag Optional[bool]

To remove the data validator from this stack.

False
image_builder_flag Optional[bool]

To remove the image builder from this stack.

False
model_registry_flag Optional[str]

To remove the model registry from this stack.

None
Source code in src/zenml/cli/stack.py
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
@stack.command(
    "remove-component",
    context_settings=dict(ignore_unknown_options=True),
    help="Remove stack components from a stack.",
)
@click.argument("stack_name_or_id", type=str, required=False)
@click.option(
    "-c",
    "--container_registry",
    "container_registry_flag",
    help="Include this to remove the container registry from this stack.",
    is_flag=True,
    required=False,
)
@click.option(
    "-s",
    "--step_operator",
    "step_operator_flag",
    help="Include this to remove the step operator from this stack.",
    is_flag=True,
    required=False,
)
@click.option(
    "-r",
    "--model_registry",
    "model_registry_flag",
    help="Include this to remove the model registry from this stack.",
    is_flag=True,
    required=False,
)
@click.option(
    "-f",
    "--feature_store",
    "feature_store_flag",
    help="Include this to remove the feature store from this stack.",
    is_flag=True,
    required=False,
)
@click.option(
    "-d",
    "--model_deployer",
    "model_deployer_flag",
    help="Include this to remove the model deployer from this stack.",
    is_flag=True,
    required=False,
)
@click.option(
    "-e",
    "--experiment_tracker",
    "experiment_tracker_flag",
    help="Include this to remove the experiment tracker from this stack.",
    is_flag=True,
    required=False,
)
@click.option(
    "-al",
    "--alerter",
    "alerter_flag",
    help="Include this to remove the alerter from this stack.",
    is_flag=True,
    required=False,
)
@click.option(
    "-an",
    "--annotator",
    "annotator_flag",
    help="Include this to remove the annotator from this stack.",
    is_flag=True,
    required=False,
)
@click.option(
    "-dv",
    "--data_validator",
    "data_validator_flag",
    help="Include this to remove the data validator from this stack.",
    is_flag=True,
    required=False,
)
@click.option(
    "-i",
    "--image_builder",
    "image_builder_flag",
    help="Include this to remove the image builder from this stack.",
    is_flag=True,
    required=False,
)
def remove_stack_component(
    stack_name_or_id: Optional[str] = None,
    container_registry_flag: Optional[bool] = False,
    step_operator_flag: Optional[bool] = False,
    feature_store_flag: Optional[bool] = False,
    model_deployer_flag: Optional[bool] = False,
    experiment_tracker_flag: Optional[bool] = False,
    alerter_flag: Optional[bool] = False,
    annotator_flag: Optional[bool] = False,
    data_validator_flag: Optional[bool] = False,
    image_builder_flag: Optional[bool] = False,
    model_registry_flag: Optional[str] = None,
) -> None:
    """Remove stack components from a stack.

    Args:
        stack_name_or_id: Name of the stack to remove components from.
        container_registry_flag: To remove the container registry from this
            stack.
        step_operator_flag: To remove the step operator from this stack.
        feature_store_flag: To remove the feature store from this stack.
        model_deployer_flag: To remove the model deployer from this stack.
        experiment_tracker_flag: To remove the experiment tracker from this
            stack.
        alerter_flag: To remove the alerter from this stack.
        annotator_flag: To remove the annotator from this stack.
        data_validator_flag: To remove the data validator from this stack.
        image_builder_flag: To remove the image builder from this stack.
        model_registry_flag: To remove the model registry from this stack.
    """
    client = Client()

    with console.status("Updating the stack...\n"):
        stack_component_update: Dict[StackComponentType, List[Any]] = dict()

        if container_registry_flag:
            stack_component_update[StackComponentType.CONTAINER_REGISTRY] = []

        if step_operator_flag:
            stack_component_update[StackComponentType.STEP_OPERATOR] = []

        if feature_store_flag:
            stack_component_update[StackComponentType.FEATURE_STORE] = []

        if model_deployer_flag:
            stack_component_update[StackComponentType.MODEL_DEPLOYER] = []

        if experiment_tracker_flag:
            stack_component_update[StackComponentType.EXPERIMENT_TRACKER] = []

        if alerter_flag:
            stack_component_update[StackComponentType.ALERTER] = []

        if model_registry_flag:
            stack_component_update[StackComponentType.MODEL_REGISTRY] = []

        if annotator_flag:
            stack_component_update[StackComponentType.ANNOTATOR] = []

        if data_validator_flag:
            stack_component_update[StackComponentType.DATA_VALIDATOR] = []

        if image_builder_flag:
            stack_component_update[StackComponentType.IMAGE_BUILDER] = []

        try:
            updated_stack = client.update_stack(
                name_id_or_prefix=stack_name_or_id,
                component_updates=stack_component_update,
            )
        except (KeyError, IllegalOperationError) as err:
            cli_utils.error(str(err))
        cli_utils.declare(
            f"Stack `{updated_stack.name}` successfully updated!"
        )

rename_secret(name_or_id: str, new_name: str) -> None

Update a secret for a given name or id.

Parameters:

Name Type Description Default
name_or_id str

The name or id of the secret to update.

required
new_name str

The new name of the secret.

required
Source code in src/zenml/cli/secret.py
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
@secret.command(
    "rename",
    context_settings={"ignore_unknown_options": True},
    help="Rename a secret with a given name or id.",
)
@click.argument(
    "name_or_id",
    type=click.STRING,
)
@click.option(
    "--new-name",
    "-n",
    type=click.STRING,
)
def rename_secret(
    name_or_id: str,
    new_name: str,
) -> None:
    """Update a secret for a given name or id.

    Args:
        name_or_id: The name or id of the secret to update.
        new_name: The new name of the secret.
    """
    if new_name == "name":
        error("Your secret cannot be called 'name'.")

    client = Client()

    with console.status(f"Checking secret `{name_or_id}`..."):
        try:
            client.get_secret(name_id_or_prefix=name_or_id)
        except KeyError as e:
            error(
                f"Secret with name `{name_or_id}` does not exist or could not "
                f"be loaded: {str(e)}."
            )
        except NotImplementedError as e:
            error(f"Centralized secrets management is disabled: {str(e)}")

    client.update_secret(
        name_id_or_prefix=name_or_id,
        new_name=new_name,
    )
    declare(f"Secret '{name_or_id}' successfully renamed to '{new_name}'.")

rename_stack(stack_name_or_id: str, new_stack_name: str) -> None

Rename a stack.

Parameters:

Name Type Description Default
stack_name_or_id str

Name of the stack to rename.

required
new_stack_name str

New name of the stack.

required
Source code in src/zenml/cli/stack.py
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
@stack.command("rename", help="Rename a stack.")
@click.argument("stack_name_or_id", type=str, required=True)
@click.argument("new_stack_name", type=str, required=True)
def rename_stack(
    stack_name_or_id: str,
    new_stack_name: str,
) -> None:
    """Rename a stack.

    Args:
        stack_name_or_id: Name of the stack to rename.
        new_stack_name: New name of the stack.
    """
    client = Client()

    with console.status("Renaming stack...\n"):
        try:
            stack_ = client.update_stack(
                name_id_or_prefix=stack_name_or_id,
                name=new_stack_name,
            )
        except (KeyError, IllegalOperationError) as err:
            cli_utils.error(str(err))
        cli_utils.declare(
            f"Stack `{stack_name_or_id}` successfully renamed to `"
            f"{new_stack_name}`!"
        )

    print_model_url(get_stack_url(stack_))

restore_database(strategy: Optional[str] = None, location: Optional[str] = None, cleanup: bool = False) -> None

Restore the ZenML database.

Parameters:

Name Type Description Default
strategy Optional[str]

Custom backup strategy to use. Defaults to whatever is configured in the store config.

None
location Optional[str]

Custom location where the backup is stored. Defaults to whatever is configured in the store config. Depending on the strategy, this can be a local path or a database name.

None
cleanup bool

Whether to cleanup the backup after restoring.

False
Source code in src/zenml/cli/base.py
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
@cli.command(
    "restore-database", help="Restore the database from a backup.", hidden=True
)
@click.option(
    "--strategy",
    "-s",
    help="Custom backup strategy to use. Defaults to whatever is configured "
    "in the store config.",
    type=click.Choice(choices=DatabaseBackupStrategy.values()),
    required=False,
    default=None,
)
@click.option(
    "--location",
    default=None,
    help="Custom location where the backup is stored. Defaults to whatever is "
    "configured in the store config. Depending on the strategy, this can be "
    "a local path or a database name.",
    type=str,
)
@click.option(
    "--cleanup",
    "-c",
    is_flag=True,
    default=False,
    help="Cleanup the backup after restoring.",
    type=bool,
)
def restore_database(
    strategy: Optional[str] = None,
    location: Optional[str] = None,
    cleanup: bool = False,
) -> None:
    """Restore the ZenML database.

    Args:
        strategy: Custom backup strategy to use. Defaults to whatever is
            configured in the store config.
        location: Custom location where the backup is stored. Defaults to
            whatever is configured in the store config. Depending on the
            strategy, this can be a local path or a database name.
        cleanup: Whether to cleanup the backup after restoring.
    """
    from zenml.zen_stores.base_zen_store import BaseZenStore
    from zenml.zen_stores.sql_zen_store import SqlZenStore

    store_config = GlobalConfiguration().store_configuration
    if store_config.type == StoreType.SQL:
        store = BaseZenStore.create_store(
            store_config, skip_default_registrations=True, skip_migrations=True
        )
        assert isinstance(store, SqlZenStore)
        store.restore_database(
            strategy=DatabaseBackupStrategy(strategy) if strategy else None,
            location=location,
            cleanup=cleanup,
        )
        cli_utils.declare("Database restore finished.")
    else:
        cli_utils.warning(
            "Cannot restore database while connected to a ZenML server."
        )

restore_secrets(ignore_errors: bool = False, delete_secrets: bool = False) -> None

Backup all secrets to the backup secrets store.

Parameters:

Name Type Description Default
ignore_errors bool

Whether to ignore individual errors when backing up secrets and continue with the backup operation until all secrets have been backed up.

False
delete_secrets bool

Whether to delete the secrets that have been successfully restored from the backup secrets store. Setting this flag effectively moves all secrets from the backup secrets store to the primary secrets store.

False
Source code in src/zenml/cli/secret.py
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
@secret.command(
    "restore", help="Restore all secrets from the backup secrets store."
)
@click.option(
    "--ignore-errors",
    "-i",
    type=click.BOOL,
    default=False,
    help="Whether to ignore individual errors when backing up secrets and "
    "continue with the backup operation until all secrets have been backed up.",
)
@click.option(
    "--delete-secrets",
    "-d",
    is_flag=True,
    default=False,
    help="Whether to delete the secrets that have been successfully restored "
    "from the backup secrets store. Setting this flag effectively moves all "
    "secrets from the backup secrets store to the primary secrets store.",
)
def restore_secrets(
    ignore_errors: bool = False, delete_secrets: bool = False
) -> None:
    """Backup all secrets to the backup secrets store.

    Args:
        ignore_errors: Whether to ignore individual errors when backing up
            secrets and continue with the backup operation until all secrets
            have been backed up.
        delete_secrets: Whether to delete the secrets that have been
            successfully restored from the backup secrets store. Setting
            this flag effectively moves all secrets from the backup secrets
            store to the primary secrets store.
    """
    client = Client()

    with console.status("Restoring secrets from backup..."):
        try:
            client.restore_secrets(
                ignore_errors=ignore_errors, delete_secrets=delete_secrets
            )
            declare("Secrets successfully restored.")
        except NotImplementedError as e:
            error(f"Could not restore secrets: {str(e)}")

rotate_api_key(service_account_name_or_id: str, name_or_id: str, retain: int = 0, set_key: bool = False, output_file: Optional[str] = None) -> None

Rotate an API key.

Parameters:

Name Type Description Default
service_account_name_or_id str

The name or ID of the service account to which the API key belongs.

required
name_or_id str

The name or ID of the API key to rotate.

required
retain int

Number of minutes for which the previous key is still valid after it has been rotated.

0
set_key bool

Configure the local client with the newly generated key.

False
output_file Optional[str]

Output file to write the API key to.

None
Source code in src/zenml/cli/service_accounts.py
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
@api_key.command("rotate", help="Rotate an API key.")
@click.argument("name_or_id", type=str, required=True)
@click.option(
    "--retain",
    type=int,
    required=False,
    default=0,
    help="Number of minutes for which the previous key is still valid after it "
    "has been rotated.",
)
@click.option(
    "--set-key",
    is_flag=True,
    help="Configure the local client with the generated key.",
)
@click.option(
    "--output-file",
    type=str,
    required=False,
    help="File to write the API key to.",
)
@click.pass_obj
def rotate_api_key(
    service_account_name_or_id: str,
    name_or_id: str,
    retain: int = 0,
    set_key: bool = False,
    output_file: Optional[str] = None,
) -> None:
    """Rotate an API key.

    Args:
        service_account_name_or_id: The name or ID of the service account to
            which the API key belongs.
        name_or_id: The name or ID of the API key to rotate.
        retain: Number of minutes for which the previous key is still valid
            after it has been rotated.
        set_key: Configure the local client with the newly generated key.
        output_file: Output file to write the API key to.
    """
    client = Client()
    zen_store = client.zen_store

    try:
        api_key = client.rotate_api_key(
            service_account_name_id_or_prefix=service_account_name_or_id,
            name_id_or_prefix=name_or_id,
            retain_period_minutes=retain,
        )
    except KeyError as e:
        cli_utils.error(str(e))

    cli_utils.declare(f"Successfully rotated API key `{name_or_id}`.")
    if retain:
        cli_utils.declare(
            f"The previous API key will remain valid for {retain} minutes."
        )

    if set_key and api_key.key:
        if zen_store.TYPE != StoreType.REST:
            cli_utils.warning(
                "Could not configure the local ZenML client with the generated "
                "API key. This type of authentication is only supported if "
                "connected to a ZenML server."
            )
        else:
            client.set_api_key(api_key.key)
            cli_utils.declare(
                "The local client has been configured with the new API key."
            )
            return

    if output_file and api_key.key:
        with open(output_file, "w") as f:
            f.write(api_key.key)

        cli_utils.declare(f"Wrote API key value to {output_file}")
    else:
        cli_utils.declare(
            f"The new API key value is: '{api_key.key}'\nPlease store it "
            "safely as it will not be shown again.\nTo configure a ZenML "
            "client to use this API key, run:\n\n"
            f"zenml login {zen_store.config.url} --api-key \n\n"
            f"and enter the following API key when prompted: {api_key.key}\n"
        )

run_pipeline(source: str, config_path: Optional[str] = None, stack_name_or_id: Optional[str] = None, build_path_or_id: Optional[str] = None, prevent_build_reuse: bool = False) -> None

Run a pipeline.

Parameters:

Name Type Description Default
source str

Importable source resolving to a pipeline instance.

required
config_path Optional[str]

Path to pipeline configuration file.

None
stack_name_or_id Optional[str]

Name or ID of the stack on which the pipeline should run.

None
build_path_or_id Optional[str]

ID of file path of the build to use for the pipeline run.

None
prevent_build_reuse bool

If True, prevents automatic reusing of previous builds.

False
Source code in src/zenml/cli/pipeline.py
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
@pipeline.command(
    "run",
    help="Run a pipeline. The SOURCE argument needs to be an "
    "importable source path resolving to a ZenML pipeline instance, e.g. "
    "`my_module.my_pipeline_instance`.",
)
@click.argument("source")
@click.option(
    "--config",
    "-c",
    "config_path",
    type=click.Path(exists=True, dir_okay=False),
    required=False,
    help="Path to configuration file for the run.",
)
@click.option(
    "--stack",
    "-s",
    "stack_name_or_id",
    type=str,
    required=False,
    help="Name or ID of the stack to run on.",
)
@click.option(
    "--build",
    "-b",
    "build_path_or_id",
    type=str,
    required=False,
    help="ID or path of the build to use.",
)
@click.option(
    "--prevent-build-reuse",
    is_flag=True,
    default=False,
    required=False,
    help="Prevent automatic build reusing.",
)
def run_pipeline(
    source: str,
    config_path: Optional[str] = None,
    stack_name_or_id: Optional[str] = None,
    build_path_or_id: Optional[str] = None,
    prevent_build_reuse: bool = False,
) -> None:
    """Run a pipeline.

    Args:
        source: Importable source resolving to a pipeline instance.
        config_path: Path to pipeline configuration file.
        stack_name_or_id: Name or ID of the stack on which the pipeline should
            run.
        build_path_or_id: ID of file path of the build to use for the pipeline
            run.
        prevent_build_reuse: If True, prevents automatic reusing of previous
            builds.
    """
    if not Client().root:
        cli_utils.warning(
            "You're running the `zenml pipeline run` command without a "
            "ZenML repository. Your current working directory will be used "
            "as the source root relative to which the registered step classes "
            "will be resolved. To silence this warning, run `zenml init` at "
            "your source code root."
        )

    with cli_utils.temporary_active_stack(stack_name_or_id=stack_name_or_id):
        pipeline_instance = _import_pipeline(source=source)

        build: Union[str, PipelineBuildBase, None] = None
        if build_path_or_id:
            if uuid_utils.is_valid_uuid(build_path_or_id):
                build = build_path_or_id
            elif os.path.exists(build_path_or_id):
                build = PipelineBuildBase.from_yaml(build_path_or_id)
            else:
                cli_utils.error(
                    f"The specified build {build_path_or_id} is not a valid UUID "
                    "or file path."
                )

        pipeline_instance = pipeline_instance.with_options(
            config_path=config_path,
            build=build,
            prevent_build_reuse=prevent_build_reuse,
        )
        pipeline_instance()

runs() -> None

Commands for pipeline runs.

Source code in src/zenml/cli/pipeline.py
486
487
488
@pipeline.group()
def runs() -> None:
    """Commands for pipeline runs."""

schedule() -> None

Commands for pipeline run schedules.

Source code in src/zenml/cli/pipeline.py
427
428
429
@pipeline.group()
def schedule() -> None:
    """Commands for pipeline run schedules."""

seconds_to_human_readable(time_seconds: int) -> str

Converts seconds to human-readable format.

Parameters:

Name Type Description Default
time_seconds int

Seconds to convert.

required

Returns:

Type Description
str

Human readable string.

Source code in src/zenml/utils/time_utils.py
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
def seconds_to_human_readable(time_seconds: int) -> str:
    """Converts seconds to human-readable format.

    Args:
        time_seconds: Seconds to convert.

    Returns:
        Human readable string.
    """
    seconds = time_seconds % 60
    minutes = (time_seconds // 60) % 60
    hours = (time_seconds // 3600) % 24
    days = time_seconds // 86400
    tokens = []
    if days:
        tokens.append(f"{days}d")
    if hours:
        tokens.append(f"{hours}h")
    if minutes:
        tokens.append(f"{minutes}m")
    if seconds:
        tokens.append(f"{seconds}s")

    return "".join(tokens)

secret() -> None

Create, list, update, or delete secrets.

Source code in src/zenml/cli/secret.py
49
50
51
@cli.group(cls=TagGroup, tag=CliCategories.IDENTITY_AND_SECURITY)
def secret() -> None:
    """Create, list, update, or delete secrets."""

server() -> None

Commands for managing ZenML servers.

Source code in src/zenml/cli/server.py
511
512
513
@cli.group(cls=TagGroup, tag=CliCategories.MANAGEMENT_TOOLS)
def server() -> None:
    """Commands for managing ZenML servers."""

server_list(verbose: bool = False, all: bool = False, pro_api_url: Optional[str] = None) -> None

List all ZenML servers that this client is authorized to access.

Parameters:

Name Type Description Default
verbose bool

Whether to show verbose output.

False
all bool

Whether to show all ZenML servers.

False
pro_api_url Optional[str]

Custom URL for the ZenML Pro API.

None
Source code in src/zenml/cli/server.py
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
@server.command(
    "list",
    help="""List all ZenML servers that this client is authenticated to.

    The CLI can be authenticated to multiple ZenML servers at the same time,
    even though it can only be connected to one server at a time. You can list
    all the ZenML servers that the client is currently authenticated to by
    using this command.

    When logged in to ZenML Pro, this list will also include all ZenML Pro
    servers that the authenticated user can access or could potentially access,
    including details such as their current state and the organization they
    belong to.

    The complete list of servers displayed by this command includes the
    following:

      * ZenML Pro servers that the authenticated ZenML Pro user can or could
        access. The client needs to be logged to ZenML Pro via
        `zenml login --pro` to access these servers.

      * ZenML servers that the client has logged in to via
        `zenml login --url` in the past.

      * the local ZenML server started with `zenml login --local`, if one is
        running.

    By default, this command does not display ZenML servers that are not
    accessible: servers that are not running, are no longer accessible due to
    an expired authentication and ZenML Pro servers where the user is not a
    member. To include these servers in the list, use the `--all` flag.
    """,
)
@click.option(
    "--verbose",
    "-v",
    is_flag=True,
    help="Show verbose output.",
)
@click.option(
    "--all",
    "-a",
    is_flag=True,
    help="Show all ZenML servers, including those that are not running "
    "and those with an expired authentication.",
)
@click.option(
    "--pro-api-url",
    type=str,
    default=None,
    help="Custom URL for the ZenML Pro API. Useful when disconnecting "
    "from a self-hosted ZenML Pro deployment.",
)
def server_list(
    verbose: bool = False,
    all: bool = False,
    pro_api_url: Optional[str] = None,
) -> None:
    """List all ZenML servers that this client is authorized to access.

    Args:
        verbose: Whether to show verbose output.
        all: Whether to show all ZenML servers.
        pro_api_url: Custom URL for the ZenML Pro API.
    """
    from zenml.login.credentials_store import get_credentials_store
    from zenml.login.pro.client import ZenMLProClient
    from zenml.login.pro.constants import ZENML_PRO_API_URL
    from zenml.login.pro.workspace.models import WorkspaceRead, WorkspaceStatus

    pro_api_url = pro_api_url or ZENML_PRO_API_URL
    pro_api_url = pro_api_url.rstrip("/")

    credentials_store = get_credentials_store()
    pro_token = credentials_store.get_pro_token(
        allow_expired=True, pro_api_url=pro_api_url
    )
    current_store_config = GlobalConfiguration().store_configuration

    # The list of ZenML Pro servers kept in the credentials store
    pro_servers = credentials_store.list_credentials(type=ServerType.PRO)
    # The list of regular remote ZenML servers kept in the credentials store
    servers = list(credentials_store.list_credentials(type=ServerType.REMOTE))
    # The list of local ZenML servers kept in the credentials store
    local_servers = list(
        credentials_store.list_credentials(type=ServerType.LOCAL)
    )

    if pro_token and not pro_token.expired:
        # If the ZenML Pro authentication is still valid, we include all ZenML
        # Pro servers that the current ZenML Pro user can access, even those
        # that the user has never connected to (and are therefore not stored in
        # the credentials store).

        accessible_pro_servers: List[WorkspaceRead] = []
        try:
            client = ZenMLProClient(pro_api_url)
            accessible_pro_servers = client.workspace.list(member_only=not all)
        except AuthorizationException as e:
            cli_utils.warning(f"ZenML Pro authorization error: {e}")

        # We update the list of stored ZenML Pro servers with the ones that the
        # client is a member of
        for accessible_server in accessible_pro_servers:
            for idx, stored_server in enumerate(pro_servers):
                if stored_server.server_id == accessible_server.id:
                    # All ZenML Pro servers accessible by the current ZenML Pro
                    # user have an authentication that is valid at least until
                    # the current ZenML Pro authentication token expires.
                    stored_server.update_server_info(
                        accessible_server,
                    )
                    updated_server = stored_server.model_copy()
                    # Replace the current server API token with the current
                    # ZenML Pro API token to reflect the current authentication
                    # status.
                    updated_server.api_token = pro_token
                    pro_servers[idx] = updated_server
                    break
            else:
                stored_server = ServerCredentials(
                    url=accessible_server.url or "",
                    api_token=pro_token,
                )
                stored_server.update_server_info(accessible_server)
                pro_servers.append(stored_server)

        if not all:
            accessible_pro_servers = [
                s
                for s in accessible_pro_servers
                if s.status == WorkspaceStatus.AVAILABLE
            ]

        if not accessible_pro_servers:
            cli_utils.declare(
                "No ZenML Pro servers that are accessible to the current "
                "user could be found."
            )
            if not all:
                cli_utils.declare(
                    "Hint: use the `--all` flag to show all ZenML servers, "
                    "including those that the client is not currently "
                    "authorized to access or are not running."
                )

    elif pro_servers:
        cli_utils.warning(
            "The ZenML Pro authentication has expired. Please re-login "
            "to ZenML Pro using `zenml login` to include all ZenML Pro servers "
            "that you are a member of in the list."
        )

    # We add the local server to the list of servers, if it is running
    local_server = get_local_server()
    if local_server:
        url = (
            local_server.status.url if local_server.status else None
        ) or local_server.config.url
        status = local_server.status.status if local_server.status else ""
        local_servers.append(
            ServerCredentials(
                url=url or "",
                status=status,
                version=zenml.__version__,
                server_id=GlobalConfiguration().user_id,
                server_name=f"local {local_server.config.provider} server",
            )
        )

    all_servers = pro_servers + local_servers + servers

    if not all:
        # Filter out servers that are expired or not running
        all_servers = [s for s in all_servers if s.is_available]

    if verbose:
        columns = [
            "type",
            "server_id_hyperlink",
            "server_name_hyperlink",
            "organization_hyperlink" if pro_servers else "",
            "version",
            "status",
            "dashboard_url",
            "api_hyperlink",
            "auth_status",
        ]
    elif all:
        columns = [
            "type",
            "server_id_hyperlink",
            "server_name_hyperlink",
            "organization_hyperlink" if pro_servers else "",
            "version",
            "status",
            "api_hyperlink",
        ]
    else:
        columns = [
            "type",
            "server_id_hyperlink" if pro_servers else "",
            "server_name_hyperlink",
            "organization_hyperlink" if pro_servers else "",
            "version",
            "api_hyperlink" if servers else "",
        ]

    # Remove empty columns
    columns = [c for c in columns if c]

    # Figure out if the client is already connected to one of the
    # servers in the list
    current_server: List[ServerCredentials] = []
    if current_store_config.type == StoreType.REST:
        current_server = [
            s for s in all_servers if s.url == current_store_config.url
        ]

    cli_utils.print_pydantic_models(  # type: ignore[type-var]
        all_servers,
        columns=columns,
        rename_columns={
            "server_name_hyperlink": "name",
            "server_id_hyperlink": "ID",
            "organization_hyperlink": "organization",
            "dashboard_url": "dashboard URL",
            "api_hyperlink": "API URL",
            "auth_status": "auth status",
        },
        active_models=current_server,
        show_active=True,
    )

service_account() -> None

Commands for service account management.

Source code in src/zenml/cli/service_accounts.py
94
95
96
@cli.group(cls=TagGroup, tag=CliCategories.IDENTITY_AND_SECURITY)
def service_account() -> None:
    """Commands for service account management."""

service_connector() -> None

Configure and manage service connectors.

Source code in src/zenml/cli/service_connectors.py
43
44
45
46
47
48
@cli.group(
    cls=TagGroup,
    tag=CliCategories.IDENTITY_AND_SECURITY,
)
def service_connector() -> None:
    """Configure and manage service connectors."""

set_active_stack_command(stack_name_or_id: str) -> None

Sets a stack as active.

Parameters:

Name Type Description Default
stack_name_or_id str

Name of the stack to set as active.

required
Source code in src/zenml/cli/stack.py
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
@stack.command("set", help="Sets a stack as active.")
@click.argument("stack_name_or_id", type=str)
def set_active_stack_command(stack_name_or_id: str) -> None:
    """Sets a stack as active.

    Args:
        stack_name_or_id: Name of the stack to set as active.
    """
    client = Client()
    scope = "repository" if client.uses_local_configuration else "global"

    with console.status(
        f"Setting the {scope} active stack to '{stack_name_or_id}'..."
    ):
        try:
            client.activate_stack(stack_name_id_or_prefix=stack_name_or_id)
        except KeyError as err:
            cli_utils.error(str(err))

        cli_utils.declare(
            f"Active {scope} stack set to: '{client.active_stack_model.name}'"
        )

set_logging_verbosity(verbosity: str) -> None

Set logging level.

Parameters:

Name Type Description Default
verbosity str

The logging level.

required

Raises:

Type Description
KeyError

If the logging level is not supported.

Source code in src/zenml/cli/config.py
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
@logging.command("set-verbosity")
@click.argument(
    "verbosity",
    type=click.Choice(
        list(map(lambda x: x.name, LoggingLevels)), case_sensitive=False
    ),
)
def set_logging_verbosity(verbosity: str) -> None:
    """Set logging level.

    Args:
        verbosity: The logging level.

    Raises:
        KeyError: If the logging level is not supported.
    """
    verbosity = verbosity.upper()
    if verbosity not in LoggingLevels.__members__:
        raise KeyError(
            f"Verbosity must be one of {list(LoggingLevels.__members__.keys())}"
        )
    cli_utils.declare(f"Set verbosity to: {verbosity}")

set_project(project_name_or_id: str, default: bool = False) -> None

Set the active project.

Parameters:

Name Type Description Default
project_name_or_id str

The name or ID of the project to set as active.

required
default bool

Whether to set the project as the default project.

False
Source code in src/zenml/cli/project.py
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
@project.command("set")
@click.argument("project_name_or_id", type=str, required=True)
@click.option(
    "--default",
    "default",
    is_flag=True,
    help="Set this project as the default project.",
)
def set_project(project_name_or_id: str, default: bool = False) -> None:
    """Set the active project.

    Args:
        project_name_or_id: The name or ID of the project to set as active.
        default: Whether to set the project as the default project.
    """
    check_zenml_pro_project_availability()
    client = Client()
    with console.status("Setting project...\n"):
        try:
            project = client.set_active_project(project_name_or_id)
            cli_utils.declare(
                f"The active project has been set to {project_name_or_id}"
            )
        except Exception as e:
            cli_utils.error(str(e))

    if default:
        client.update_user(
            name_id_or_prefix=client.active_user.id,
            updated_default_project_id=project.id,
        )
        cli_utils.declare(
            f"The default project has been set to {project.name}"
        )

show(local: bool = False, ngrok_token: Optional[str] = None) -> None

Show the ZenML dashboard.

Parameters:

Name Type Description Default
local bool

Whether to show the ZenML dashboard for the local server.

False
ngrok_token Optional[str]

An ngrok auth token to use for exposing the ZenML dashboard on a public domain. Primarily used for accessing the local dashboard in Colab.

None
Source code in src/zenml/cli/server.py
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
@server.command(
    "show",
    help="Show the ZenML dashboard for the server that the client is connected to.",
)
@click.option(
    "--local",
    is_flag=True,
    help="Show the ZenML dashboard for the local server.",
    default=False,
    type=click.BOOL,
)
@click.option(
    "--ngrok-token",
    type=str,
    default=None,
    help="Specify an ngrok auth token to use for exposing the local ZenML "
    "server. Only used when `--local` is set. Primarily used for accessing the "
    "local dashboard in Colab.",
)
def show(local: bool = False, ngrok_token: Optional[str] = None) -> None:
    """Show the ZenML dashboard.

    Args:
        local: Whether to show the ZenML dashboard for the local server.
        ngrok_token: An ngrok auth token to use for exposing the ZenML dashboard
            on a public domain. Primarily used for accessing the local dashboard
            in Colab.
    """
    try:
        zenml.show(ngrok_token=ngrok_token)
    except RuntimeError as e:
        cli_utils.error(str(e))

show_dashboard(local: bool = False, ngrok_token: Optional[str] = None) -> None

Show the ZenML dashboard.

Parameters:

Name Type Description Default
local bool

Whether to show the dashboard for the local server or the one for the active server.

False
ngrok_token Optional[str]

An ngrok auth token to use for exposing the ZenML dashboard on a public domain. Primarily used for accessing the dashboard in Colab.

None

Raises:

Type Description
RuntimeError

If no server is connected.

Source code in src/zenml/utils/dashboard_utils.py
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
def show_dashboard(
    local: bool = False,
    ngrok_token: Optional[str] = None,
) -> None:
    """Show the ZenML dashboard.

    Args:
        local: Whether to show the dashboard for the local server or the
            one for the active server.
        ngrok_token: An ngrok auth token to use for exposing the ZenML
            dashboard on a public domain. Primarily used for accessing the
            dashboard in Colab.

    Raises:
        RuntimeError: If no server is connected.
    """
    from zenml.utils.networking_utils import get_or_create_ngrok_tunnel

    url: Optional[str] = None
    if not local:
        gc = GlobalConfiguration()
        if gc.store_configuration.type == StoreType.REST:
            url = gc.store_configuration.url

    if not url:
        # Else, check for local servers
        server = get_local_server()
        if server and server.status and server.status.url:
            url = server.status.url

    if not url:
        raise RuntimeError(
            "ZenML is not connected to any server right now. Please use "
            "`zenml login` to connect to a server or spin up a new local server "
            "via `zenml login --local`."
        )

    if ngrok_token:
        parsed_url = urlparse(url)

        ngrok_url = get_or_create_ngrok_tunnel(
            ngrok_token=ngrok_token, port=parsed_url.port or 80
        )
        logger.debug(f"Tunneling dashboard from {url} to {ngrok_url}.")
        url = ngrok_url

    show_dashboard_with_url(url)

stack() -> None

Stacks to define various environments.

Source code in src/zenml/cli/stack.py
89
90
91
92
93
94
@cli.group(
    cls=TagGroup,
    tag=CliCategories.MANAGEMENT_TOOLS,
)
def stack() -> None:
    """Stacks to define various environments."""

start_local_server(docker: bool = False, ip_address: Union[ipaddress.IPv4Address, ipaddress.IPv6Address, None] = None, port: Optional[int] = None, blocking: bool = False, image: Optional[str] = None, ngrok_token: Optional[str] = None, restart: bool = False) -> None

Start the ZenML dashboard locally and connect the client to it.

Parameters:

Name Type Description Default
docker bool

Use a docker deployment instead of the local process.

False
ip_address Union[IPv4Address, IPv6Address, None]

The IP address to bind the server to.

None
port Optional[int]

The port to bind the server to.

None
blocking bool

Block the CLI while the server is running.

False
image Optional[str]

A custom Docker image to use for the server, when the --docker flag is set.

None
ngrok_token Optional[str]

An ngrok auth token to use for exposing the ZenML dashboard on a public domain. Primarily used for accessing the dashboard in Colab.

None
restart bool

Restart the local ZenML server if it is already running.

False
Source code in src/zenml/cli/login.py
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
def start_local_server(
    docker: bool = False,
    ip_address: Union[
        ipaddress.IPv4Address, ipaddress.IPv6Address, None
    ] = None,
    port: Optional[int] = None,
    blocking: bool = False,
    image: Optional[str] = None,
    ngrok_token: Optional[str] = None,
    restart: bool = False,
) -> None:
    """Start the ZenML dashboard locally and connect the client to it.

    Args:
        docker: Use a docker deployment instead of the local process.
        ip_address: The IP address to bind the server to.
        port: The port to bind the server to.
        blocking: Block the CLI while the server is running.
        image: A custom Docker image to use for the server, when the
            `--docker` flag is set.
        ngrok_token: An ngrok auth token to use for exposing the ZenML dashboard
            on a public domain. Primarily used for accessing the dashboard in
            Colab.
        restart: Restart the local ZenML server if it is already running.
    """
    from zenml.zen_server.deploy.deployer import LocalServerDeployer

    if docker:
        from zenml.utils.docker_utils import check_docker

        if not check_docker():
            cli_utils.error(
                "Docker does not seem to be installed on your system. Please "
                "install Docker to use the Docker ZenML server local "
                "deployment or use one of the other deployment options."
            )
        provider = ServerProviderType.DOCKER
    else:
        if sys.platform == "win32" and not blocking:
            cli_utils.error(
                "Running the ZenML server locally as a background process is "
                "not supported on Windows. Please use the `--blocking` flag "
                "to run the server in blocking mode, or run the server in "
                "a Docker container by setting `--docker` instead."
            )
        else:
            pass
        provider = ServerProviderType.DAEMON
    if cli_utils.requires_mac_env_var_warning():
        cli_utils.error(
            "The `OBJC_DISABLE_INITIALIZE_FORK_SAFETY` environment variable "
            "is recommended to run the ZenML server locally on a Mac. "
            "Please set it to `YES` and try again."
        )

    deployer = LocalServerDeployer()

    config_attrs: Dict[str, Any] = dict(
        provider=provider,
    )
    if not docker:
        config_attrs["blocking"] = blocking
    elif image:
        config_attrs["image"] = image
    if port is not None:
        config_attrs["port"] = port
    if ip_address is not None:
        config_attrs["ip_address"] = ip_address

    from zenml.zen_server.deploy.deployment import LocalServerDeploymentConfig

    server_config = LocalServerDeploymentConfig(**config_attrs)
    if blocking:
        deployer.remove_server()
        cli_utils.declare(
            "The local ZenML dashboard is about to deploy in a "
            "blocking process."
        )

    server = deployer.deploy_server(server_config, restart=restart)

    if not blocking:
        deployer.connect_to_server()

        if server.status and server.status.url:
            cli_utils.declare(
                f"The local ZenML dashboard is available at "
                f"'{server.status.url}'."
            )
            show_dashboard(
                local=True,
                ngrok_token=ngrok_token,
            )

status() -> None

Show details about the current configuration.

Source code in src/zenml/cli/server.py
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
@cli.command(
    "status", help="Show information about the current configuration."
)
def status() -> None:
    """Show details about the current configuration."""
    from zenml.login.credentials_store import get_credentials_store
    from zenml.login.pro.client import ZenMLProClient
    from zenml.login.pro.constants import ZENML_PRO_API_URL

    gc = GlobalConfiguration()
    client = Client()
    _ = client.zen_store

    store_cfg = gc.store_configuration

    # Write about the current ZenML client
    cli_utils.declare("-----ZenML Client Status-----")
    if gc.uses_default_store():
        cli_utils.declare(
            f"Connected to the local ZenML database: '{store_cfg.url}'"
        )
    elif connected_to_local_server():
        cli_utils.declare(
            f"Connected to the local ZenML server: {store_cfg.url}"
        )
    elif re.match(r"^mysql://", store_cfg.url):
        cli_utils.declare(
            f"Connected directly to a SQL database: '{store_cfg.url}'"
        )
    else:
        credentials_store = get_credentials_store()
        server = credentials_store.get_credentials(store_cfg.url)
        if server:
            if server.type == ServerType.PRO:
                # If connected to a ZenML Pro server, refresh the server info
                pro_credentials = credentials_store.get_pro_credentials(
                    pro_api_url=server.pro_api_url or ZENML_PRO_API_URL,
                    allow_expired=False,
                )
                if pro_credentials:
                    pro_client = ZenMLProClient(pro_credentials.url)
                    pro_servers = pro_client.workspace.list(
                        url=store_cfg.url, member_only=True
                    )
                    if pro_servers:
                        credentials_store.update_server_info(
                            server_url=store_cfg.url,
                            server_info=pro_servers[0],
                        )

                cli_utils.declare(
                    f"Connected to a ZenML Pro server: `{server.server_name_hyperlink}`"
                    f" [{server.server_id_hyperlink}]"
                )

                cli_utils.declare(
                    f"  ZenML Pro Organization: {server.organization_hyperlink}"
                )
                if pro_credentials:
                    cli_utils.declare(
                        f"  ZenML Pro authentication: {pro_credentials.auth_status}"
                    )
            else:
                cli_utils.declare(
                    f"Connected to a remote ZenML server: `{server.dashboard_hyperlink}`"
                )

            cli_utils.declare(f"  Dashboard: {server.dashboard_hyperlink}")
            cli_utils.declare(f"  API: {server.api_hyperlink}")
            cli_utils.declare(f"  Server status: '{server.status}'")
            cli_utils.declare(f"  Server authentication: {server.auth_status}")

        else:
            cli_utils.declare(
                f"Connected to a remote ZenML server: [link={store_cfg.url}]"
                f"{store_cfg.url}[/link]"
            )

    try:
        client.zen_store.get_store_info()
    except Exception as e:
        cli_utils.warning(f"Error while initializing client: {e}")
    else:
        # Write about the active entities
        scope = "repository" if client.uses_local_configuration else "global"
        cli_utils.declare(f"  The active user is: '{client.active_user.name}'")
        cli_utils.declare(
            f"  The active project is: '{client.active_project.name}'"
        )
        cli_utils.declare(
            f"  The active stack is: '{client.active_stack_model.name}' ({scope})"
        )

    if client.root:
        cli_utils.declare(f"Active repository root: {client.root}")

    # Write about the configuration files
    cli_utils.declare(f"Using configuration from: '{gc.config_directory}'")
    cli_utils.declare(
        f"Local store files are located at: '{gc.local_stores_path}'"
    )

    cli_utils.declare("\n-----Local ZenML Server Status-----")
    local_server = get_local_server()
    if local_server:
        if local_server.status:
            if local_server.status.status == ServiceState.ACTIVE:
                cli_utils.declare(
                    f"The local {local_server.config.provider} server is "
                    f"running at: {local_server.status.url}"
                )
            else:
                cli_utils.declare(
                    f"The local {local_server.config.provider} server is not "
                    "available."
                )
                cli_utils.declare(
                    f"  Server state: {local_server.status.status}"
                )
                if local_server.status.status_message:
                    cli_utils.declare(
                        f"  Status message: {local_server.status.status_message}"
                    )
        else:
            cli_utils.declare(
                f"The local {local_server.config.provider} server is not "
                "running."
            )
    else:
        cli_utils.declare("The local server has not been started.")

tag() -> None

Interact with tags.

Source code in src/zenml/cli/tag.py
35
36
37
@cli.group(cls=TagGroup, tag=CliCategories.MANAGEMENT_TOOLS)
def tag() -> None:
    """Interact with tags."""

title(text: str) -> None

Echo a title formatted string on the CLI.

Parameters:

Name Type Description Default
text str

Input text string.

required
Source code in src/zenml/cli/utils.py
116
117
118
119
120
121
122
def title(text: str) -> None:
    """Echo a title formatted string on the CLI.

    Args:
        text: Input text string.
    """
    console.print(text.upper(), style=zenml_style_defaults["title"])

track_decorator(event: AnalyticsEvent) -> Callable[[F], F]

Decorator to track event.

If the decorated function takes in a AnalyticsTrackedModelMixin object as an argument or returns one, it will be called to track the event. The return value takes precedence over the argument when determining which object is called to track the event.

If the decorated function is a method of a class that inherits from AnalyticsTrackerMixin, the parent object will be used to intermediate tracking analytics.

Parameters:

Name Type Description Default
event AnalyticsEvent

Event string to stamp with.

required

Returns:

Type Description
Callable[[F], F]

A decorator that applies the analytics tracking to a function.

Source code in src/zenml/analytics/utils.py
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
def track_decorator(event: AnalyticsEvent) -> Callable[[F], F]:
    """Decorator to track event.

    If the decorated function takes in a `AnalyticsTrackedModelMixin` object as
    an argument or returns one, it will be called to track the event. The return
    value takes precedence over the argument when determining which object is
    called to track the event.

    If the decorated function is a method of a class that inherits from
    `AnalyticsTrackerMixin`, the parent object will be used to intermediate
    tracking analytics.

    Args:
        event: Event string to stamp with.

    Returns:
        A decorator that applies the analytics tracking to a function.
    """

    def inner_decorator(func: F) -> F:
        """Inner decorator function.

        Args:
            func: Function to decorate.

        Returns:
            Decorated function.
        """

        @wraps(func)
        def inner_func(*args: Any, **kwargs: Any) -> Any:
            """Inner function.

            Args:
                *args: Arguments to be passed to the function.
                **kwargs: Keyword arguments to be passed to the function.

            Returns:
                Result of the function.
            """
            with track_handler(event=event) as handler:
                try:
                    for obj in list(args) + list(kwargs.values()):
                        if isinstance(obj, AnalyticsTrackedModelMixin):
                            handler.metadata = obj.get_analytics_metadata()
                            break
                except Exception as e:
                    logger.debug(f"Analytics tracking failure for {func}: {e}")

                result = func(*args, **kwargs)

                try:
                    if isinstance(result, AnalyticsTrackedModelMixin):
                        handler.metadata = result.get_analytics_metadata()
                except Exception as e:
                    logger.debug(f"Analytics tracking failure for {func}: {e}")

                return result

        return cast(F, inner_func)

    return inner_decorator

uninstall(integrations: Tuple[str], force: bool = False, uv: bool = False) -> None

Uninstalls the required packages for a given integration.

If no integration is specified all required packages for all integrations are uninstalled using pip or uv.

Parameters:

Name Type Description Default
integrations Tuple[str]

The name of the integration to uninstall the requirements for.

required
force bool

Force the uninstallation of the required packages.

False
uv bool

Use uv for package uninstallation (experimental).

False
Source code in src/zenml/cli/integration.py
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
@integration.command(
    help="Uninstall the required packages for the integration of choice."
)
@click.argument("integrations", nargs=-1, required=False)
@click.option(
    "--yes",
    "-y",
    "force",
    is_flag=True,
    help="Force the uninstallation of the required packages. This will skip "
    "the confirmation step",
)
@click.option(
    "--uv",
    "uv",
    is_flag=True,
    help="Experimental: Use uv for package uninstallation.",
    default=False,
)
def uninstall(
    integrations: Tuple[str], force: bool = False, uv: bool = False
) -> None:
    """Uninstalls the required packages for a given integration.

    If no integration is specified all required packages for all integrations
    are uninstalled using pip or uv.

    Args:
        integrations: The name of the integration to uninstall the requirements
            for.
        force: Force the uninstallation of the required packages.
        uv: Use uv for package uninstallation (experimental).
    """
    from zenml.cli.utils import is_pip_installed, is_uv_installed
    from zenml.integrations.registry import integration_registry

    if uv and not is_uv_installed():
        error("Package `uv` is not installed. Please install it and retry.")

    if not uv and not is_pip_installed():
        error(
            "Pip is not installed. Please install pip or use the uv flag "
            "(--uv) for package installation."
        )

    if not integrations:
        # no integrations specified, use all registered integrations
        integrations = tuple(integration_registry.integrations.keys())

    requirements = []
    for integration_name in integrations:
        try:
            if integration_registry.is_installed(integration_name):
                requirements += (
                    integration_registry.select_uninstall_requirements(
                        integration_name
                    )
                )
            else:
                warning(
                    f"Requirements for integration '{integration_name}' "
                    f"already not installed."
                )
        except KeyError:
            warning(f"Unable to find integration '{integration_name}'.")

    if requirements and (
        force
        or confirmation(
            "Are you sure you want to uninstall the following "
            "packages from the current environment?\n"
            f"{requirements}"
        )
    ):
        for n in track(
            range(len(requirements)),
            description="Uninstalling integrations...",
        ):
            uninstall_package(requirements[n], use_uv=uv)

uninstall_package(package: str, use_uv: bool = False) -> None

Uninstalls pypi package from the current environment with pip or uv.

Parameters:

Name Type Description Default
package str

The package to uninstall.

required
use_uv bool

Whether to use uv for package uninstallation.

False
Source code in src/zenml/cli/utils.py
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
def uninstall_package(package: str, use_uv: bool = False) -> None:
    """Uninstalls pypi package from the current environment with pip or uv.

    Args:
        package: The package to uninstall.
        use_uv: Whether to use uv for package uninstallation.
    """
    if use_uv and not is_installed_in_python_environment("uv"):
        # If uv is installed globally, don't run as a python module
        command = []
    else:
        command = [sys.executable, "-m"]

    command += (
        ["uv", "pip", "uninstall", "-q"]
        if use_uv
        else ["pip", "uninstall", "-y", "-qqq"]
    )
    command += [package]

    subprocess.check_call(command)

unlock_authorized_device(id: str) -> None

Unlock an authorized device.

Parameters:

Name Type Description Default
id str

The ID of the authorized device to unlock.

required
Source code in src/zenml/cli/authorized_device.py
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
@authorized_device.command("unlock")
@click.argument("id", type=str, required=True)
def unlock_authorized_device(id: str) -> None:
    """Unlock an authorized device.

    Args:
        id: The ID of the authorized device to unlock.
    """
    try:
        Client().update_authorized_device(
            id_or_prefix=id,
            locked=False,
        )
    except KeyError as e:
        cli_utils.error(str(e))
    else:
        cli_utils.declare(f"Locked authorized device `{id}`.")

up(docker: bool = False, ip_address: Union[ipaddress.IPv4Address, ipaddress.IPv6Address, None] = None, port: Optional[int] = None, blocking: bool = False, image: Optional[str] = None, ngrok_token: Optional[str] = None) -> None

Start the ZenML dashboard locally and connect the client to it.

Parameters:

Name Type Description Default
docker bool

Use a docker deployment instead of the local process.

False
ip_address Union[IPv4Address, IPv6Address, None]

The IP address to bind the server to.

None
port Optional[int]

The port to bind the server to.

None
blocking bool

Block the CLI while the server is running.

False
image Optional[str]

A custom Docker image to use for the server, when the --docker flag is set.

None
ngrok_token Optional[str]

An ngrok auth token to use for exposing the ZenML dashboard on a public domain. Primarily used for accessing the dashboard in Colab.

None
Source code in src/zenml/cli/server.py
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
@cli.command(
    "up",
    help="""Start the ZenML dashboard locally.

DEPRECATED: Please use `zenml login --local` instead.             
""",
)
@click.option(
    "--docker",
    is_flag=True,
    help="Start the ZenML dashboard as a Docker container instead of a local "
    "process.",
    default=False,
    type=click.BOOL,
)
@click.option(
    "--port",
    type=int,
    default=None,
    help="Use a custom TCP port value for the ZenML dashboard.",
)
@click.option(
    "--ip-address",
    type=ipaddress.ip_address,
    default=None,
    help="Have the ZenML dashboard listen on an IP address different than the "
    "localhost.",
)
@click.option(
    "--blocking",
    is_flag=True,
    help="Run the ZenML dashboard in blocking mode. The CLI will not return "
    "until the dashboard is stopped.",
    default=False,
    type=click.BOOL,
)
@click.option(
    "--image",
    type=str,
    default=None,
    help="Use a custom Docker image for the ZenML server. Only used when "
    "`--docker` is set.",
)
@click.option(
    "--ngrok-token",
    type=str,
    default=None,
    help="Specify an ngrok auth token to use for exposing the ZenML server.",
)
def up(
    docker: bool = False,
    ip_address: Union[
        ipaddress.IPv4Address, ipaddress.IPv6Address, None
    ] = None,
    port: Optional[int] = None,
    blocking: bool = False,
    image: Optional[str] = None,
    ngrok_token: Optional[str] = None,
) -> None:
    """Start the ZenML dashboard locally and connect the client to it.

    Args:
        docker: Use a docker deployment instead of the local process.
        ip_address: The IP address to bind the server to.
        port: The port to bind the server to.
        blocking: Block the CLI while the server is running.
        image: A custom Docker image to use for the server, when the
            `--docker` flag is set.
        ngrok_token: An ngrok auth token to use for exposing the ZenML dashboard
            on a public domain. Primarily used for accessing the dashboard in
            Colab.
    """
    cli_utils.warning(
        "The `zenml up` command is deprecated and will be removed in a "
        "future release. Please use the `zenml login --local` command instead."
    )

    # Calling the `zenml login` command
    cli_utils.declare("Calling `zenml login --local`...")
    login.callback(  # type: ignore[misc]
        local=True,
        docker=docker,
        ip_address=ip_address,
        port=port,
        blocking=blocking,
        image=image,
        ngrok_token=ngrok_token,
    )

update_api_key(service_account_name_or_id: str, name_or_id: str, name: Optional[str] = None, description: Optional[str] = None, active: Optional[bool] = None) -> None

Update an API key.

Parameters:

Name Type Description Default
service_account_name_or_id str

The name or ID of the service account to which the API key belongs.

required
name_or_id str

The name or ID of the API key to update.

required
name Optional[str]

The new name of the API key.

None
description Optional[str]

The new description of the API key.

None
active Optional[bool]

Set an API key to active/inactive.

None
Source code in src/zenml/cli/service_accounts.py
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
@api_key.command("update", help="Update an API key.")
@click.argument("name_or_id", type=str, required=True)
@click.option("--name", type=str, required=False, help="The new name.")
@click.option(
    "--description", type=str, required=False, help="The new description."
)
@click.option(
    "--active",
    type=bool,
    required=False,
    help="Activate or deactivate an API key.",
)
@click.pass_obj
def update_api_key(
    service_account_name_or_id: str,
    name_or_id: str,
    name: Optional[str] = None,
    description: Optional[str] = None,
    active: Optional[bool] = None,
) -> None:
    """Update an API key.

    Args:
        service_account_name_or_id: The name or ID of the service account to
            which the API key belongs.
        name_or_id: The name or ID of the API key to update.
        name: The new name of the API key.
        description: The new description of the API key.
        active: Set an API key to active/inactive.
    """
    try:
        Client().update_api_key(
            service_account_name_id_or_prefix=service_account_name_or_id,
            name_id_or_prefix=name_or_id,
            name=name,
            description=description,
            active=active,
        )
    except (KeyError, EntityExistsError) as e:
        cli_utils.error(str(e))

    cli_utils.declare(f"Successfully updated API key `{name_or_id}`.")

update_artifact(artifact_name_or_id: str, name: Optional[str] = None, tag: Optional[List[str]] = None, remove_tag: Optional[List[str]] = None) -> None

Update an artifact by ID or name.

Usage example:

zenml artifact update <NAME> -n <NEW_NAME> -t <TAG1> -t <TAG2> -r <TAG_TO_REMOVE>

Parameters:

Name Type Description Default
artifact_name_or_id str

Name or ID of the artifact to update.

required
name Optional[str]

New name of the artifact.

None
tag Optional[List[str]]

New tags of the artifact.

None
remove_tag Optional[List[str]]

Tags to remove from the artifact.

None
Source code in src/zenml/cli/artifact.py
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
@artifact.command("update", help="Update an artifact.")
@click.argument("artifact_name_or_id")
@click.option(
    "--name",
    "-n",
    type=str,
    help="New name of the artifact.",
)
@click.option(
    "--tag",
    "-t",
    type=str,
    multiple=True,
    help="Tags to add to the artifact.",
)
@click.option(
    "--remove-tag",
    "-r",
    type=str,
    multiple=True,
    help="Tags to remove from the artifact.",
)
def update_artifact(
    artifact_name_or_id: str,
    name: Optional[str] = None,
    tag: Optional[List[str]] = None,
    remove_tag: Optional[List[str]] = None,
) -> None:
    """Update an artifact by ID or name.

    Usage example:
    ```
    zenml artifact update <NAME> -n <NEW_NAME> -t <TAG1> -t <TAG2> -r <TAG_TO_REMOVE>
    ```

    Args:
        artifact_name_or_id: Name or ID of the artifact to update.
        name: New name of the artifact.
        tag: New tags of the artifact.
        remove_tag: Tags to remove from the artifact.
    """
    try:
        artifact = Client().update_artifact(
            name_id_or_prefix=artifact_name_or_id,
            new_name=name,
            add_tags=tag,
            remove_tags=remove_tag,
        )
    except (KeyError, ValueError) as e:
        cli_utils.error(str(e))
    else:
        cli_utils.declare(f"Artifact '{artifact.id}' updated.")

update_artifact_version(name_id_or_prefix: str, version: Optional[str] = None, tag: Optional[List[str]] = None, remove_tag: Optional[List[str]] = None) -> None

Update an artifact version by ID or artifact name.

Usage example:

zenml artifact version update <NAME> -v <VERSION> -t <TAG1> -t <TAG2> -r <TAG_TO_REMOVE>

Parameters:

Name Type Description Default
name_id_or_prefix str

Either the ID of the artifact version or the name of the artifact.

required
version Optional[str]

The version of the artifact to get. Only used if name_id_or_prefix is the name of the artifact. If not specified, the latest version is returned.

None
tag Optional[List[str]]

Tags to add to the artifact version.

None
remove_tag Optional[List[str]]

Tags to remove from the artifact version.

None
Source code in src/zenml/cli/artifact.py
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
@version.command("update", help="Update an artifact version.")
@click.argument("name_id_or_prefix")
@click.option(
    "--version",
    "-v",
    type=str,
    help=(
        "The version of the artifact to get. Only used if "
        "`name_id_or_prefix` is the name of the artifact. If not specified, "
        "the latest version is returned."
    ),
)
@click.option(
    "--tag",
    "-t",
    type=str,
    multiple=True,
    help="Tags to add to the artifact version.",
)
@click.option(
    "--remove-tag",
    "-r",
    type=str,
    multiple=True,
    help="Tags to remove from the artifact version.",
)
def update_artifact_version(
    name_id_or_prefix: str,
    version: Optional[str] = None,
    tag: Optional[List[str]] = None,
    remove_tag: Optional[List[str]] = None,
) -> None:
    """Update an artifact version by ID or artifact name.

    Usage example:
    ```
    zenml artifact version update <NAME> -v <VERSION> -t <TAG1> -t <TAG2> -r <TAG_TO_REMOVE>
    ```

    Args:
        name_id_or_prefix: Either the ID of the artifact version or the name of
            the artifact.
        version: The version of the artifact to get. Only used if
            `name_id_or_prefix` is the name of the artifact. If not specified,
            the latest version is returned.
        tag: Tags to add to the artifact version.
        remove_tag: Tags to remove from the artifact version.
    """
    try:
        artifact_version = Client().update_artifact_version(
            name_id_or_prefix=name_id_or_prefix,
            version=version,
            add_tags=tag,
            remove_tags=remove_tag,
        )
    except (KeyError, ValueError) as e:
        cli_utils.error(str(e))
    else:
        cli_utils.declare(f"Artifact version '{artifact_version.id}' updated.")

update_code_repository(name_or_id: str, name: Optional[str], description: Optional[str], logo_url: Optional[str], args: List[str]) -> None

Update a code repository.

Parameters:

Name Type Description Default
name_or_id str

Name or ID of the code repository to update.

required
name Optional[str]

New name of the code repository.

required
description Optional[str]

New description of the code repository.

required
logo_url Optional[str]

New logo URL of the code repository.

required
args List[str]

Code repository configurations.

required
Source code in src/zenml/cli/code_repository.py
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
@code_repository.command(
    "update",
    help="Update a code repository.",
    context_settings={"ignore_unknown_options": True},
)
@click.argument("name_or_id", type=str, required=True)
@click.option(
    "--name",
    "-n",
    type=str,
    required=False,
    help="The new code repository name.",
)
@click.option(
    "--description",
    "-d",
    type=str,
    required=False,
    help="The new code repository description.",
)
@click.option(
    "--logo-url",
    "-l",
    type=str,
    required=False,
    help="New URL of a logo (png, jpg or svg) for the code repository.",
)
@click.argument(
    "args",
    nargs=-1,
    type=click.UNPROCESSED,
)
def update_code_repository(
    name_or_id: str,
    name: Optional[str],
    description: Optional[str],
    logo_url: Optional[str],
    args: List[str],
) -> None:
    """Update a code repository.

    Args:
        name_or_id: Name or ID of the code repository to update.
        name: New name of the code repository.
        description: New description of the code repository.
        logo_url: New logo URL of the code repository.
        args: Code repository configurations.
    """
    parsed_name_or_id, parsed_args = cli_utils.parse_name_and_extra_arguments(
        list(args) + [name_or_id], expand_args=True, name_mandatory=True
    )
    assert parsed_name_or_id

    with console.status(
        f"Updating code repository '{parsed_name_or_id}'...\n"
    ):
        Client().update_code_repository(
            name_id_or_prefix=parsed_name_or_id,
            name=name,
            description=description,
            logo_url=logo_url,
            config=parsed_args,
        )
        cli_utils.declare(
            f"Successfully updated code repository `{parsed_name_or_id}`."
        )

update_model(model_name_or_id: str, name: Optional[str], license: Optional[str], description: Optional[str], audience: Optional[str], use_cases: Optional[str], tradeoffs: Optional[str], ethical: Optional[str], limitations: Optional[str], tag: Optional[List[str]], remove_tag: Optional[List[str]], save_models_to_registry: Optional[bool]) -> None

Register a new model in the Model Control Plane.

Parameters:

Name Type Description Default
model_name_or_id str

The name of the model.

required
name Optional[str]

The name of the model.

required
license Optional[str]

The license model created under.

required
description Optional[str]

The description of the model.

required
audience Optional[str]

The target audience of the model.

required
use_cases Optional[str]

The use cases of the model.

required
tradeoffs Optional[str]

The tradeoffs of the model.

required
ethical Optional[str]

The ethical implications of the model.

required
limitations Optional[str]

The know limitations of the model.

required
tag Optional[List[str]]

Tags to be added to the model.

required
remove_tag Optional[List[str]]

Tags to be removed from the model.

required
save_models_to_registry Optional[bool]

Whether to save the model to the registry.

required
Source code in src/zenml/cli/model.py
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
@model.command("update", help="Update an existing model.")
@click.argument("model_name_or_id")
@click.option(
    "--name",
    "-n",
    help="The name of the model.",
    type=str,
    required=False,
)
@click.option(
    "--license",
    "-l",
    help="The license under which the model is created.",
    type=str,
    required=False,
)
@click.option(
    "--description",
    "-d",
    help="The description of the model.",
    type=str,
    required=False,
)
@click.option(
    "--audience",
    "-a",
    help="The target audience for the model.",
    type=str,
    required=False,
)
@click.option(
    "--use-cases",
    "-u",
    help="The use cases of the model.",
    type=str,
    required=False,
)
@click.option(
    "--tradeoffs",
    help="The tradeoffs of the model.",
    type=str,
    required=False,
)
@click.option(
    "--ethical",
    "-e",
    help="The ethical implications of the model.",
    type=str,
    required=False,
)
@click.option(
    "--limitations",
    help="The known limitations of the model.",
    type=str,
    required=False,
)
@click.option(
    "--tag",
    "-t",
    help="Tags to be added to the model.",
    type=str,
    required=False,
    multiple=True,
)
@click.option(
    "--remove-tag",
    "-r",
    help="Tags to be removed from the model.",
    type=str,
    required=False,
    multiple=True,
)
@click.option(
    "--save-models-to-registry",
    "-s",
    help="Whether to automatically save model artifacts to the model registry.",
    type=click.BOOL,
    required=False,
    default=True,
)
def update_model(
    model_name_or_id: str,
    name: Optional[str],
    license: Optional[str],
    description: Optional[str],
    audience: Optional[str],
    use_cases: Optional[str],
    tradeoffs: Optional[str],
    ethical: Optional[str],
    limitations: Optional[str],
    tag: Optional[List[str]],
    remove_tag: Optional[List[str]],
    save_models_to_registry: Optional[bool],
) -> None:
    """Register a new model in the Model Control Plane.

    Args:
        model_name_or_id: The name of the model.
        name: The name of the model.
        license: The license model created under.
        description: The description of the model.
        audience: The target audience of the model.
        use_cases: The use cases of the model.
        tradeoffs: The tradeoffs of the model.
        ethical: The ethical implications of the model.
        limitations: The know limitations of the model.
        tag: Tags to be added to the model.
        remove_tag: Tags to be removed from the model.
        save_models_to_registry: Whether to save the model to the
            registry.
    """
    model_id = Client().get_model(model_name_or_id=model_name_or_id).id
    update_dict = remove_none_values(
        dict(
            name=name,
            license=license,
            description=description,
            audience=audience,
            use_cases=use_cases,
            trade_offs=tradeoffs,
            ethics=ethical,
            limitations=limitations,
            add_tags=tag,
            remove_tags=remove_tag,
            save_models_to_registry=save_models_to_registry,
        )
    )
    model = Client().update_model(model_name_or_id=model_id, **update_dict)

    cli_utils.print_table([_model_to_print(model)])

update_model_version(model_name_or_id: str, model_version_name_or_number_or_id: str, stage: Optional[str], name: Optional[str], description: Optional[str], tag: Optional[List[str]], remove_tag: Optional[List[str]], force: bool = False) -> None

Update an existing model version stage in the Model Control Plane.

Parameters:

Name Type Description Default
model_name_or_id str

The ID or name of the model containing version.

required
model_version_name_or_number_or_id str

The ID, number or name of the model version.

required
stage Optional[str]

The stage of the model version to be set.

required
name Optional[str]

The name of the model version.

required
description Optional[str]

The description of the model version.

required
tag Optional[List[str]]

Tags to be added to the model version.

required
remove_tag Optional[List[str]]

Tags to be removed from the model version.

required
force bool

Whether existing model version in target stage should be silently archived.

False
Source code in src/zenml/cli/model.py
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
@version.command("update", help="Update an existing model version stage.")
@click.argument("model_name_or_id")
@click.argument("model_version_name_or_number_or_id")
@click.option(
    "--stage",
    "-s",
    type=click.Choice(choices=ModelStages.values()),
    required=False,
    help="The stage of the model version.",
)
@click.option(
    "--name",
    "-n",
    type=str,
    required=False,
    help="The name of the model version.",
)
@click.option(
    "--description",
    "-d",
    type=str,
    required=False,
    help="The description of the model version.",
)
@click.option(
    "--tag",
    "-t",
    help="Tags to be added to the model.",
    type=str,
    required=False,
    multiple=True,
)
@click.option(
    "--remove-tag",
    "-r",
    help="Tags to be removed from the model.",
    type=str,
    required=False,
    multiple=True,
)
@click.option(
    "--force",
    "-f",
    is_flag=True,
    help="Don't ask for confirmation, if stage already occupied.",
)
def update_model_version(
    model_name_or_id: str,
    model_version_name_or_number_or_id: str,
    stage: Optional[str],
    name: Optional[str],
    description: Optional[str],
    tag: Optional[List[str]],
    remove_tag: Optional[List[str]],
    force: bool = False,
) -> None:
    """Update an existing model version stage in the Model Control Plane.

    Args:
        model_name_or_id: The ID or name of the model containing version.
        model_version_name_or_number_or_id: The ID, number or name of the model version.
        stage: The stage of the model version to be set.
        name: The name of the model version.
        description: The description of the model version.
        tag: Tags to be added to the model version.
        remove_tag: Tags to be removed from the model version.
        force: Whether existing model version in target stage should be silently archived.
    """
    model_version = Client().get_model_version(
        model_name_or_id=model_name_or_id,
        model_version_name_or_number_or_id=model_version_name_or_number_or_id,
    )
    try:
        model_version = Client().update_model_version(
            model_name_or_id=model_name_or_id,
            version_name_or_id=model_version.id,
            stage=stage,
            add_tags=tag,
            remove_tags=remove_tag,
            force=force,
            name=name,
            description=description,
        )
    except RuntimeError:
        if not force:
            cli_utils.print_table([_model_version_to_print(model_version)])

            confirmation = cli_utils.confirmation(
                "Are you sure you want to change the status of model "
                f"version '{model_version_name_or_number_or_id}' to "
                f"'{stage}'?\nThis stage is already taken by "
                "model version shown above and if you will proceed this "
                "model version will get into archived stage."
            )
            if not confirmation:
                cli_utils.declare("Model version stage update canceled.")
                return
            model_version = Client().update_model_version(
                model_name_or_id=model_version.model.id,
                version_name_or_id=model_version.id,
                stage=stage,
                add_tags=tag,
                remove_tags=remove_tag,
                force=True,
                description=description,
            )
    cli_utils.print_table([_model_version_to_print(model_version)])

update_secret(name_or_id: str, extra_args: List[str], private: Optional[bool] = None, remove_keys: List[str] = [], interactive: bool = False, values: str = '') -> None

Update a secret for a given name or id.

Parameters:

Name Type Description Default
name_or_id str

The name or id of the secret to update.

required
private Optional[bool]

Private status of the secret to update.

None
extra_args List[str]

The arguments to pass to the secret.

required
interactive bool

Whether to use interactive mode to update the secret.

False
remove_keys List[str]

The keys to remove from the secret.

[]
values str

Secret key-value pairs to be passed as JSON or YAML.

''
Source code in src/zenml/cli/secret.py
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
@secret.command(
    "update",
    context_settings={"ignore_unknown_options": True},
    help="Update a secret with a given name or id.",
)
@click.argument(
    "name_or_id",
    type=click.STRING,
)
@click.option(
    "--private",
    "-p",
    "private",
    type=click.BOOL,
    required=False,
    help="Update the private status of the secret.",
)
@click.option(
    "--interactive",
    "-i",
    "interactive",
    is_flag=True,
    help="Use interactive mode to update the secret values.",
    type=click.BOOL,
)
@click.option(
    "--values",
    "-v",
    "values",
    help="Pass one or more values using JSON or YAML format or reference a file by prefixing the filename with the @ "
    "special character.",
    required=False,
    type=str,
)
@click.option("--remove-keys", "-r", type=click.STRING, multiple=True)
@click.argument("extra_args", nargs=-1, type=click.UNPROCESSED)
def update_secret(
    name_or_id: str,
    extra_args: List[str],
    private: Optional[bool] = None,
    remove_keys: List[str] = [],
    interactive: bool = False,
    values: str = "",
) -> None:
    """Update a secret for a given name or id.

    Args:
        name_or_id: The name or id of the secret to update.
        private: Private status of the secret to update.
        extra_args: The arguments to pass to the secret.
        interactive: Whether to use interactive mode to update the secret.
        remove_keys: The keys to remove from the secret.
        values: Secret key-value pairs to be passed as JSON or YAML.
    """
    name, parsed_args = parse_name_and_extra_arguments(
        list(extra_args) + [name_or_id], expand_args=True
    )
    if values:
        inline_values = expand_argument_value_from_file(SECRET_VALUES, values)
        inline_values_dict = convert_structured_str_to_dict(inline_values)
        parsed_args.update(inline_values_dict)

    client = Client()

    with console.status(f"Checking secret `{name}`..."):
        try:
            secret = client.get_secret(
                name_id_or_prefix=name_or_id, allow_partial_name_match=False
            )
        except KeyError as e:
            error(
                f"Secret with name `{name}` does not exist or could not be "
                f"loaded: {str(e)}."
            )
        except NotImplementedError as e:
            error(f"Centralized secrets management is disabled: {str(e)}")

    declare(f"Updating secret with name '{secret.name}' and ID '{secret.id}'")

    if "name" in parsed_args:
        error("The word 'name' cannot be used as a key for a secret.")

    if interactive:
        if parsed_args:
            error(
                "Cannot pass secret fields as arguments when using "
                "interactive mode."
            )

        declare(
            "You will now have a chance to update each secret pair one by one."
        )
        secret_args_add_update = {}
        for k, _ in secret.secret_values.items():
            item_choice = (
                click.prompt(
                    text=f"Do you want to update key '{k}'? (enter to skip)",
                    type=click.Choice(["y", "n"]),
                    default="n",
                ),
            )
            if "n" in item_choice:
                continue
            elif "y" in item_choice:
                new_value = getpass.getpass(
                    f"Please enter the new secret value for the key '{k}'"
                )
                if new_value:
                    secret_args_add_update[k] = new_value

        # check if any additions to be made
        while True:
            addition_check = confirmation(
                "Do you want to add a new key:value pair?"
            )
            if not addition_check:
                break

            new_key = click.prompt(
                text="Please enter the new key name",
                type=click.STRING,
            )
            new_value = getpass.getpass(
                f"Please enter the new secret value for the key '{new_key}'"
            )
            secret_args_add_update[new_key] = new_value
    else:
        secret_args_add_update = parsed_args

    client.update_secret(
        name_id_or_prefix=secret.id,
        update_private=private,
        add_or_update_values=secret_args_add_update,
        remove_values=remove_keys,
    )
    declare(f"Secret '{secret.name}' successfully updated.")

update_service_account(service_account_name_or_id: str, updated_name: Optional[str] = None, description: Optional[str] = None, active: Optional[bool] = None) -> None

Update an existing service account.

Parameters:

Name Type Description Default
service_account_name_or_id str

The name or ID of the service account to update.

required
updated_name Optional[str]

The new name of the service account.

None
description Optional[str]

The new API key description.

None
active Optional[bool]

Activate or deactivate a service account.

None
Source code in src/zenml/cli/service_accounts.py
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
@service_account.command(
    "update",
    help="Update a service account.",
)
@click.argument("service_account_name_or_id", type=str, required=True)
@click.option(
    "--name",
    "-n",
    "updated_name",
    type=str,
    required=False,
    help="New service account name.",
)
@click.option(
    "--description",
    "-d",
    type=str,
    required=False,
    help="The API key description.",
)
@click.option(
    "--active",
    type=bool,
    required=False,
    help="Activate or deactivate a service account.",
)
def update_service_account(
    service_account_name_or_id: str,
    updated_name: Optional[str] = None,
    description: Optional[str] = None,
    active: Optional[bool] = None,
) -> None:
    """Update an existing service account.

    Args:
        service_account_name_or_id: The name or ID of the service account to
            update.
        updated_name: The new name of the service account.
        description: The new API key description.
        active: Activate or deactivate a service account.
    """
    try:
        Client().update_service_account(
            name_id_or_prefix=service_account_name_or_id,
            updated_name=updated_name,
            description=description,
            active=active,
        )
    except (KeyError, EntityExistsError) as err:
        cli_utils.error(str(err))

update_service_connector(args: List[str], name_id_or_prefix: Optional[str] = None, name: Optional[str] = None, description: Optional[str] = None, connector_type: Optional[str] = None, resource_type: Optional[str] = None, resource_id: Optional[str] = None, auth_method: Optional[str] = None, expires_at: Optional[datetime] = None, expires_skew_tolerance: Optional[int] = None, expiration_seconds: Optional[int] = None, no_verify: bool = False, labels: Optional[List[str]] = None, interactive: bool = False, show_secrets: bool = False, remove_attrs: Optional[List[str]] = None) -> None

Updates a service connector.

Parameters:

Name Type Description Default
args List[str]

Configuration arguments for the service connector.

required
name_id_or_prefix Optional[str]

The name or ID of the service connector to update.

None
name Optional[str]

New connector name.

None
description Optional[str]

Short description for the service connector.

None
connector_type Optional[str]

The service connector type.

None
resource_type Optional[str]

The type of resource to connect to.

None
resource_id Optional[str]

The ID of the resource to connect to.

None
auth_method Optional[str]

The authentication method to use.

None
expires_at Optional[datetime]

The time at which the credentials configured for this connector will expire.

None
expires_skew_tolerance Optional[int]

The tolerance, in seconds, allowed when determining when the credentials configured for or generated by this connector will expire.

None
expiration_seconds Optional[int]

The duration, in seconds, that the temporary credentials generated by this connector should remain valid.

None
no_verify bool

Do not verify the service connector before updating.

False
labels Optional[List[str]]

Labels to be associated with the service connector.

None
interactive bool

Register a new service connector interactively.

False
show_secrets bool

Show security sensitive configuration attributes in the terminal.

False
remove_attrs Optional[List[str]]

Configuration attributes to be removed from the configuration.

None
Source code in src/zenml/cli/service_connectors.py
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
@service_connector.command(
    "update",
    context_settings={"ignore_unknown_options": True},
    help="""Update and verify an existing service connector.

This command can be used to update an existing ZenML service connector and
to optionally verify that the updated service connector configuration and
credentials are still valid and can be used to access the specified resource(s).

If the `-i|--interactive` flag is set, it will prompt the user for all the
information required to update the service connector configuration:

    $ zenml service-connector update -i <connector-name-or-id>

For consistency reasons, the connector type cannot be changed. If you need to
change the connector type, you need to create a new service connector.
You also cannot change the authentication method, resource type and resource ID
of a service connector that is already actively being used by one or more stack
components.

Secret configuration attributes are not shown by default. Use the
`-x|--show-secrets` flag to show them:

    $ zenml service-connector update -ix <connector-name-or-id>

Non-interactive examples:

- update the DockerHub repository that a Docker service connector is configured
to provide access to:

    $ zenml service-connector update dockerhub-hyppo --resource-id lylemcnew

- update the AWS credentials that an AWS service connector is configured to
use from an STS token to an AWS secret key. This involves updating some config
values and deleting others:

    $ zenml service-connector update aws-auto-multi \\
--aws_access_key_id=<aws-key-id> \\
--aws_secret_access_key=<aws-secret-key>  \\
--remove-attr aws-sts-token

- update the foo label to a new value and delete the baz label from a connector:

    $ zenml service-connector update gcp-eu-multi \\                          
--label foo=bar --label baz

All service connectors updates are validated before being applied. To skip
validation, pass the `--no-verify` flag.
""",
)
@click.argument(
    "name_id_or_prefix",
    type=str,
    required=True,
)
@click.option(
    "--name",
    "name",
    help="New connector name.",
    required=False,
    type=str,
)
@click.option(
    "--description",
    "description",
    help="Short description for the connector instance.",
    required=False,
    type=str,
)
@click.option(
    "--resource-type",
    "-r",
    "resource_type",
    help="The type of resource to connect to.",
    required=False,
    type=str,
)
@click.option(
    "--resource-id",
    "-ri",
    "resource_id",
    help="The ID of the resource to connect to.",
    required=False,
    type=str,
)
@click.option(
    "--auth-method",
    "-a",
    "auth_method",
    help="The authentication method to use.",
    required=False,
    type=str,
)
@click.option(
    "--expires-at",
    "expires_at",
    help="The time at which the credentials configured for this connector "
    "will expire.",
    required=False,
    type=click.DateTime(),
)
@click.option(
    "--expires-skew-tolerance",
    "expires_skew_tolerance",
    help="The tolerance, in seconds, allowed when determining when the "
    "credentials configured for or generated by this connector will expire.",
    required=False,
    type=int,
)
@click.option(
    "--expiration-seconds",
    "expiration_seconds",
    help="The duration, in seconds, that the temporary credentials "
    "generated by this connector should remain valid.",
    required=False,
    type=int,
)
@click.option(
    "--label",
    "-l",
    "labels",
    help="Labels to be associated with the service connector. Takes the form "
    "`-l key1=value1` or `-l key1` and can be used multiple times.",
    multiple=True,
)
@click.option(
    "--no-verify",
    "no_verify",
    is_flag=True,
    default=False,
    help="Do not verify the service connector before registering.",
    type=click.BOOL,
)
@click.option(
    "--interactive",
    "-i",
    "interactive",
    is_flag=True,
    default=False,
    help="Register a new service connector interactively.",
    type=click.BOOL,
)
@click.option(
    "--show-secrets",
    "-x",
    "show_secrets",
    is_flag=True,
    default=False,
    help="Show security sensitive configuration attributes in the terminal.",
    type=click.BOOL,
)
@click.option(
    "--remove-attr",
    "-r",
    "remove_attrs",
    help="Configuration attributes to be removed from the configuration. Takes "
    "the form `-r attr-name` and can be used multiple times.",
    multiple=True,
)
@click.argument("args", nargs=-1, type=click.UNPROCESSED)
def update_service_connector(
    args: List[str],
    name_id_or_prefix: Optional[str] = None,
    name: Optional[str] = None,
    description: Optional[str] = None,
    connector_type: Optional[str] = None,
    resource_type: Optional[str] = None,
    resource_id: Optional[str] = None,
    auth_method: Optional[str] = None,
    expires_at: Optional[datetime] = None,
    expires_skew_tolerance: Optional[int] = None,
    expiration_seconds: Optional[int] = None,
    no_verify: bool = False,
    labels: Optional[List[str]] = None,
    interactive: bool = False,
    show_secrets: bool = False,
    remove_attrs: Optional[List[str]] = None,
) -> None:
    """Updates a service connector.

    Args:
        args: Configuration arguments for the service connector.
        name_id_or_prefix: The name or ID of the service connector to
            update.
        name: New connector name.
        description: Short description for the service connector.
        connector_type: The service connector type.
        resource_type: The type of resource to connect to.
        resource_id: The ID of the resource to connect to.
        auth_method: The authentication method to use.
        expires_at: The time at which the credentials configured for this
            connector will expire.
        expires_skew_tolerance: The tolerance, in seconds, allowed when
            determining when the credentials configured for or generated by
            this connector will expire.
        expiration_seconds: The duration, in seconds, that the temporary
            credentials generated by this connector should remain valid.
        no_verify: Do not verify the service connector before
            updating.
        labels: Labels to be associated with the service connector.
        interactive: Register a new service connector interactively.
        show_secrets: Show security sensitive configuration attributes in
            the terminal.
        remove_attrs: Configuration attributes to be removed from the
            configuration.
    """
    client = Client()

    # Parse the given args
    name_id_or_prefix, parsed_args = cli_utils.parse_name_and_extra_arguments(
        list(args) + [name_id_or_prefix or ""],
        expand_args=True,
        name_mandatory=True,
    )
    assert name_id_or_prefix is not None

    # Parse the given labels
    parsed_labels = cli_utils.get_parsed_labels(labels, allow_label_only=True)

    # Start by fetching the existing connector configuration
    try:
        connector = client.get_service_connector(
            name_id_or_prefix,
            allow_name_prefix_match=False,
            load_secrets=True,
        )
    except KeyError as e:
        cli_utils.error(str(e))

    if interactive:
        # Fetch the connector type specification if not already embedded
        # into the connector model
        if isinstance(connector.connector_type, str):
            try:
                connector_type_spec = client.get_service_connector_type(
                    connector.connector_type
                )
            except KeyError as e:
                cli_utils.error(
                    "Could not find the connector type "
                    f"'{connector.connector_type}' associated with the "
                    f"'{connector.name}' connector: {e}."
                )
        else:
            connector_type_spec = connector.connector_type

        # Ask for a new name, if needed
        name = prompt_connector_name(connector.name, connector=connector.id)

        # Ask for a new description, if needed
        description = click.prompt(
            "Updated service connector description",
            type=str,
            default=connector.description,
        )

        # Ask for a new authentication method
        auth_method = click.prompt(
            "If you would like to update the authentication method, please "
            "select a new one from the following options, otherwise press "
            "enter to keep the existing one. Please note that changing "
            "the authentication method may invalidate the existing "
            "configuration and credentials and may require you to reconfigure "
            "the connector from scratch",
            type=click.Choice(
                list(connector_type_spec.auth_method_dict.keys()),
            ),
            default=connector.auth_method,
        )

        assert auth_method is not None
        auth_method_spec = connector_type_spec.auth_method_dict[auth_method]

        # If the authentication method has changed, we need to reconfigure
        # the connector from scratch; otherwise, we ask the user if they
        # want to update the existing configuration
        if auth_method != connector.auth_method:
            confirm = True
        else:
            confirm = click.confirm(
                "Would you like to update the authentication configuration?",
                default=False,
            )

        existing_config = connector.full_configuration

        if confirm:
            # Here we reconfigure the connector or update the existing
            # configuration. The existing configuration is used as much
            # as possible to avoid the user having to re-enter the same
            # values from scratch.

            cli_utils.declare(
                f"Please update or verify the existing configuration for the "
                f"'{auth_method_spec.name}' authentication method."
            )

            # Prompt for the configuration of the selected authentication method
            # field by field
            config_schema = auth_method_spec.config_schema or {}
            config_dict = cli_utils.prompt_configuration(
                config_schema=config_schema,
                show_secrets=show_secrets,
                existing_config=existing_config,
            )

        else:
            config_dict = existing_config

        # Next, we address resource type updates. If the connector is
        # configured to access a single resource type, we don't need to
        # ask the user for a new resource type. We only look at the
        # resource types that support the selected authentication method.
        available_resource_types = [
            r.resource_type
            for r in connector_type_spec.resource_types
            if auth_method in r.auth_methods
        ]
        if len(available_resource_types) == 1:
            resource_type = available_resource_types[0]
        else:
            if connector.is_multi_type:
                resource_type = None
                title = (
                    "The connector is configured to access any of the supported "
                    f"resource types ({', '.join(available_resource_types)}). "
                    "Would you like to restrict it to a single resource type?"
                )
            else:
                resource_type = connector.resource_types[0]
                title = (
                    "The connector is configured to access the "
                    f"{resource_type} resource type. "
                    "Would you like to change that?"
                )
            confirm = click.confirm(title, default=False)

            if confirm:
                # Prompt for a new resource type, if needed
                resource_type = prompt_resource_type(
                    available_resource_types=available_resource_types
                )

        # Prompt for a new expiration time if the auth method supports it
        expiration_seconds = None
        if auth_method_spec.supports_temporary_credentials():
            expiration_seconds = prompt_expiration_time(
                min=auth_method_spec.min_expiration_seconds,
                max=auth_method_spec.max_expiration_seconds,
                default=connector.expiration_seconds
                or auth_method_spec.default_expiration_seconds,
            )

        # Prompt for the time when the credentials will expire
        expires_at = prompt_expires_at(expires_at or connector.expires_at)

        try:
            # Validate the connector configuration and fetch all available
            # resources that are accessible with the provided configuration
            # in the process
            with console.status("Validating service connector update...\n"):
                (
                    connector_model,
                    connector_resources,
                ) = client.update_service_connector(
                    name_id_or_prefix=connector.id,
                    name=name,
                    description=description,
                    auth_method=auth_method,
                    # Use empty string to indicate that the resource type
                    # should be removed in the update if not set here
                    resource_type=resource_type or "",
                    configuration=config_dict,
                    expires_at=expires_at,
                    # Use zero value to indicate that the expiration time
                    # should be removed in the update if not set here
                    expiration_seconds=expiration_seconds or 0,
                    expires_skew_tolerance=expires_skew_tolerance,
                    verify=True,
                    update=False,
                )
            assert connector_model is not None
            assert connector_resources is not None
        except (
            KeyError,
            ValueError,
            IllegalOperationError,
            NotImplementedError,
            AuthorizationException,
        ) as e:
            cli_utils.error(f"Failed to verify service connector update: {e}")

        if resource_type:
            # Finally, for connectors that are configured with a particular
            # resource type, prompt the user to select one of the available
            # resources that can be accessed with the connector. We don't need
            # to do this for resource types that don't support instances.
            resource_type_spec = connector_type_spec.resource_type_dict[
                resource_type
            ]
            if resource_type_spec.supports_instances:
                assert len(connector_resources.resources) == 1
                resource_ids = connector_resources.resources[0].resource_ids
                assert resource_ids is not None
                resource_id = prompt_resource_id(
                    resource_name=resource_type_spec.name,
                    resource_ids=resource_ids,
                )
            else:
                resource_id = None
        else:
            resource_id = None

        # Prepare the rest of the variables to fall through to the
        # non-interactive configuration case
        no_verify = False

    else:
        # Non-interactive configuration

        # Apply the configuration from the command line arguments
        config_dict = connector.full_configuration
        config_dict.update(parsed_args)

        if not resource_type and not connector.is_multi_type:
            resource_type = connector.resource_types[0]

        resource_id = resource_id or connector.resource_id
        expiration_seconds = expiration_seconds or connector.expiration_seconds

        # Remove attributes that the user has indicated should be removed
        if remove_attrs:
            for remove_attr in remove_attrs:
                config_dict.pop(remove_attr, None)
            if "resource_id" in remove_attrs or "resource-id" in remove_attrs:
                resource_id = None
            if (
                "resource_type" in remove_attrs
                or "resource-type" in remove_attrs
            ):
                resource_type = None
            if (
                "expiration_seconds" in remove_attrs
                or "expiration-seconds" in remove_attrs
            ):
                expiration_seconds = None

    with console.status(
        f"Updating service connector {name_id_or_prefix}...\n"
    ):
        try:
            (
                connector_model,
                connector_resources,
            ) = client.update_service_connector(
                name_id_or_prefix=connector.id,
                name=name,
                auth_method=auth_method,
                # Use empty string to indicate that the resource type
                # should be removed in the update if not set here
                resource_type=resource_type or "",
                configuration=config_dict,
                # Use empty string to indicate that the resource ID
                # should be removed in the update if not set here
                resource_id=resource_id or "",
                description=description,
                expires_at=expires_at,
                # Use empty string to indicate that the expiration time
                # should be removed in the update if not set here
                expiration_seconds=expiration_seconds or 0,
                expires_skew_tolerance=expires_skew_tolerance,
                labels=parsed_labels,
                verify=not no_verify,
                update=True,
            )
        except (
            KeyError,
            ValueError,
            IllegalOperationError,
            NotImplementedError,
            AuthorizationException,
        ) as e:
            cli_utils.error(f"Failed to update service connector: {e}")

    if connector_resources is not None:
        cli_utils.declare(
            f"Successfully updated service connector `{connector.name}`. It "
            "can now be used to access the following resources:"
        )

        cli_utils.print_service_connector_resource_table(
            [connector_resources],
            show_resources_only=True,
        )

    else:
        cli_utils.declare(
            f"Successfully updated service connector `{connector.name}` "
        )

update_stack(stack_name_or_id: Optional[str] = None, artifact_store: Optional[str] = None, orchestrator: Optional[str] = None, container_registry: Optional[str] = None, step_operator: Optional[str] = None, feature_store: Optional[str] = None, model_deployer: Optional[str] = None, experiment_tracker: Optional[str] = None, alerter: Optional[str] = None, annotator: Optional[str] = None, data_validator: Optional[str] = None, image_builder: Optional[str] = None, model_registry: Optional[str] = None) -> None

Update a stack.

Parameters:

Name Type Description Default
stack_name_or_id Optional[str]

Name or id of the stack to update.

None
artifact_store Optional[str]

Name of the new artifact store for this stack.

None
orchestrator Optional[str]

Name of the new orchestrator for this stack.

None
container_registry Optional[str]

Name of the new container registry for this stack.

None
step_operator Optional[str]

Name of the new step operator for this stack.

None
feature_store Optional[str]

Name of the new feature store for this stack.

None
model_deployer Optional[str]

Name of the new model deployer for this stack.

None
experiment_tracker Optional[str]

Name of the new experiment tracker for this stack.

None
alerter Optional[str]

Name of the new alerter for this stack.

None
annotator Optional[str]

Name of the new annotator for this stack.

None
data_validator Optional[str]

Name of the new data validator for this stack.

None
image_builder Optional[str]

Name of the new image builder for this stack.

None
model_registry Optional[str]

Name of the new model registry for this stack.

None
Source code in src/zenml/cli/stack.py
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
@stack.command(
    "update",
    context_settings=dict(ignore_unknown_options=True),
    help="Update a stack with new components.",
)
@click.argument("stack_name_or_id", type=str, required=False)
@click.option(
    "-a",
    "--artifact-store",
    "artifact_store",
    help="Name of the new artifact store for this stack.",
    type=str,
    required=False,
)
@click.option(
    "-o",
    "--orchestrator",
    "orchestrator",
    help="Name of the new orchestrator for this stack.",
    type=str,
    required=False,
)
@click.option(
    "-c",
    "--container_registry",
    "container_registry",
    help="Name of the new container registry for this stack.",
    type=str,
    required=False,
)
@click.option(
    "-r",
    "--model_registry",
    "model_registry",
    help="Name of the model registry for this stack.",
    type=str,
    required=False,
)
@click.option(
    "-s",
    "--step_operator",
    "step_operator",
    help="Name of the new step operator for this stack.",
    type=str,
    required=False,
)
@click.option(
    "-f",
    "--feature_store",
    "feature_store",
    help="Name of the new feature store for this stack.",
    type=str,
    required=False,
)
@click.option(
    "-d",
    "--model_deployer",
    "model_deployer",
    help="Name of the new model deployer for this stack.",
    type=str,
    required=False,
)
@click.option(
    "-e",
    "--experiment_tracker",
    "experiment_tracker",
    help="Name of the new experiment tracker for this stack.",
    type=str,
    required=False,
)
@click.option(
    "-al",
    "--alerter",
    "alerter",
    help="Name of the new alerter for this stack.",
    type=str,
    required=False,
)
@click.option(
    "-an",
    "--annotator",
    "annotator",
    help="Name of the new annotator for this stack.",
    type=str,
    required=False,
)
@click.option(
    "-dv",
    "--data_validator",
    "data_validator",
    help="Name of the data validator for this stack.",
    type=str,
    required=False,
)
@click.option(
    "-i",
    "--image_builder",
    "image_builder",
    help="Name of the image builder for this stack.",
    type=str,
    required=False,
)
def update_stack(
    stack_name_or_id: Optional[str] = None,
    artifact_store: Optional[str] = None,
    orchestrator: Optional[str] = None,
    container_registry: Optional[str] = None,
    step_operator: Optional[str] = None,
    feature_store: Optional[str] = None,
    model_deployer: Optional[str] = None,
    experiment_tracker: Optional[str] = None,
    alerter: Optional[str] = None,
    annotator: Optional[str] = None,
    data_validator: Optional[str] = None,
    image_builder: Optional[str] = None,
    model_registry: Optional[str] = None,
) -> None:
    """Update a stack.

    Args:
        stack_name_or_id: Name or id of the stack to update.
        artifact_store: Name of the new artifact store for this stack.
        orchestrator: Name of the new orchestrator for this stack.
        container_registry: Name of the new container registry for this stack.
        step_operator: Name of the new step operator for this stack.
        feature_store: Name of the new feature store for this stack.
        model_deployer: Name of the new model deployer for this stack.
        experiment_tracker: Name of the new experiment tracker for this
            stack.
        alerter: Name of the new alerter for this stack.
        annotator: Name of the new annotator for this stack.
        data_validator: Name of the new data validator for this stack.
        image_builder: Name of the new image builder for this stack.
        model_registry: Name of the new model registry for this stack.
    """
    client = Client()

    with console.status("Updating stack...\n"):
        updates: Dict[StackComponentType, List[Union[str, UUID]]] = dict()
        if artifact_store:
            updates[StackComponentType.ARTIFACT_STORE] = [artifact_store]
        if alerter:
            updates[StackComponentType.ALERTER] = [alerter]
        if annotator:
            updates[StackComponentType.ANNOTATOR] = [annotator]
        if container_registry:
            updates[StackComponentType.CONTAINER_REGISTRY] = [
                container_registry
            ]
        if data_validator:
            updates[StackComponentType.DATA_VALIDATOR] = [data_validator]
        if experiment_tracker:
            updates[StackComponentType.EXPERIMENT_TRACKER] = [
                experiment_tracker
            ]
        if feature_store:
            updates[StackComponentType.FEATURE_STORE] = [feature_store]
        if model_registry:
            updates[StackComponentType.MODEL_REGISTRY] = [model_registry]
        if image_builder:
            updates[StackComponentType.IMAGE_BUILDER] = [image_builder]
        if model_deployer:
            updates[StackComponentType.MODEL_DEPLOYER] = [model_deployer]
        if orchestrator:
            updates[StackComponentType.ORCHESTRATOR] = [orchestrator]
        if step_operator:
            updates[StackComponentType.STEP_OPERATOR] = [step_operator]

        try:
            updated_stack = client.update_stack(
                name_id_or_prefix=stack_name_or_id,
                component_updates=updates,
            )

        except (KeyError, IllegalOperationError) as err:
            cli_utils.error(str(err))

        cli_utils.declare(
            f"Stack `{updated_stack.name}` successfully updated!"
        )
    print_model_url(get_stack_url(updated_stack))

update_tag(tag_name_or_id: Union[str, UUID], name: Optional[str], color: Optional[str]) -> None

Register a new model in the Model Control Plane.

Parameters:

Name Type Description Default
tag_name_or_id Union[str, UUID]

The name or ID of the tag.

required
name Optional[str]

The name of the tag.

required
color Optional[str]

The color variant for UI.

required
Source code in src/zenml/cli/tag.py
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
@tag.command("update", help="Update an existing tag.")
@click.argument("tag_name_or_id")
@click.option(
    "--name",
    "-n",
    help="The name of the tag.",
    type=str,
    required=False,
)
@click.option(
    "--color",
    "-c",
    help="The color variant for UI.",
    type=click.Choice(choices=ColorVariants.values()),
    required=False,
)
def update_tag(
    tag_name_or_id: Union[str, UUID], name: Optional[str], color: Optional[str]
) -> None:
    """Register a new model in the Model Control Plane.

    Args:
        tag_name_or_id: The name or ID of the tag.
        name: The name of the tag.
        color: The color variant for UI.
    """
    update_dict = remove_none_values(dict(name=name, color=color))
    if not update_dict:
        cli_utils.declare("You need to specify --name or --color for update.")
        return

    tag = Client().update_tag(
        tag_name_or_id=tag_name_or_id,
        **update_dict,
    )

    cli_utils.print_pydantic_models(
        [tag],
        exclude_columns=["created"],
    )

update_user(user_name_or_id: str, updated_name: Optional[str] = None, updated_full_name: Optional[str] = None, updated_email: Optional[str] = None, make_admin: Optional[bool] = None, make_user: Optional[bool] = None, active: Optional[bool] = None) -> None

Update an existing user.

Parameters:

Name Type Description Default
user_name_or_id str

The name of the user to create.

required
updated_name Optional[str]

The name of the user to create.

None
updated_full_name Optional[str]

The name of the user to create.

None
updated_email Optional[str]

The name of the user to create.

None
make_admin Optional[bool]

Whether the user should be an admin.

None
make_user Optional[bool]

Whether the user should be a regular user.

None
active Optional[bool]

Use to activate or deactivate a user account.

None
Source code in src/zenml/cli/user_management.py
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
@user.command(
    "update",
    help="Update user information through the cli.",
)
@click.argument("user_name_or_id", type=str, required=True)
@click.option(
    "--name",
    "-n",
    "updated_name",
    type=str,
    required=False,
    help="New user name.",
)
@click.option(
    "--full_name",
    "-f",
    "updated_full_name",
    type=str,
    required=False,
    help="New full name. If this contains an empty space make sure to surround "
    "the name with quotes '<Full Name>'.",
)
@click.option(
    "--email",
    "-e",
    "updated_email",
    type=str,
    required=False,
    help="New user email.",
)
@click.option(
    "--admin",
    "-a",
    "make_admin",
    is_flag=True,
    required=False,
    default=None,
    help="Whether the user should be an admin.",
)
@click.option(
    "--user",
    "-u",
    "make_user",
    is_flag=True,
    required=False,
    default=None,
    help="Whether the user should be a regular user.",
)
@click.option(
    "--active",
    "active",
    type=bool,
    required=False,
    default=None,
    help="Use to activate or deactivate a user account.",
)
def update_user(
    user_name_or_id: str,
    updated_name: Optional[str] = None,
    updated_full_name: Optional[str] = None,
    updated_email: Optional[str] = None,
    make_admin: Optional[bool] = None,
    make_user: Optional[bool] = None,
    active: Optional[bool] = None,
) -> None:
    """Update an existing user.

    Args:
        user_name_or_id: The name of the user to create.
        updated_name: The name of the user to create.
        updated_full_name: The name of the user to create.
        updated_email: The name of the user to create.
        make_admin: Whether the user should be an admin.
        make_user: Whether the user should be a regular user.
        active: Use to activate or deactivate a user account.
    """
    if make_admin is not None and make_user is not None:
        cli_utils.error(
            "Cannot set both --admin and --user flags as these are mutually exclusive."
        )
    try:
        current_user = Client().get_user(
            user_name_or_id, allow_name_prefix_match=False
        )
        if current_user.is_admin and make_user:
            confirmation = cli_utils.confirmation(
                f"Currently user `{current_user.name}` is an admin. Are you "
                "sure you want to make them a regular user?"
            )
            if not confirmation:
                cli_utils.declare("User update canceled.")
                return

        updated_is_admin = None
        if make_admin is True:
            updated_is_admin = True
        elif make_user is True:
            updated_is_admin = False
        Client().update_user(
            name_id_or_prefix=user_name_or_id,
            updated_name=updated_name,
            updated_full_name=updated_full_name,
            updated_email=updated_email,
            updated_is_admin=updated_is_admin,
            active=active,
        )
    except (KeyError, IllegalOperationError) as err:
        cli_utils.error(str(err))

upgrade(integrations: Tuple[str], force: bool = False, uv: bool = False) -> None

Upgrade the required packages for a given integration.

If no integration is specified all required packages for all integrations are installed using pip or uv.

Parameters:

Name Type Description Default
integrations Tuple[str]

The name of the integration to install the requirements for.

required
force bool

Force the installation of the required packages.

False
uv bool

Use uv for package installation (experimental).

False
Source code in src/zenml/cli/integration.py
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
@integration.command(
    help="Upgrade the required packages for the integration of choice."
)
@click.argument("integrations", nargs=-1, required=False)
@click.option(
    "--yes",
    "-y",
    "force",
    is_flag=True,
    help="Force the upgrade of the required packages. This will skip the "
    "confirmation step and re-upgrade existing packages as well",
)
@click.option(
    "--uv",
    "uv",
    is_flag=True,
    help="Experimental: Use uv for package upgrade.",
    default=False,
)
def upgrade(
    integrations: Tuple[str],
    force: bool = False,
    uv: bool = False,
) -> None:
    """Upgrade the required packages for a given integration.

    If no integration is specified all required packages for all integrations
    are installed using pip or uv.

    Args:
        integrations: The name of the integration to install the requirements
            for.
        force: Force the installation of the required packages.
        uv: Use uv for package installation (experimental).
    """
    from zenml.cli.utils import is_pip_installed, is_uv_installed
    from zenml.integrations.registry import integration_registry

    if uv and not is_uv_installed():
        error("Package `uv` is not installed. Please install it and retry.")

    if not uv and not is_pip_installed():
        error(
            "Pip is not installed. Please install pip or use the uv flag "
            "(--uv) for package installation."
        )

    if not integrations:
        # no integrations specified, use all registered integrations
        integrations = set(integration_registry.integrations.keys())

    requirements = []
    integrations_to_install = []
    for integration_name in integrations:
        try:
            if integration_registry.is_installed(integration_name):
                requirements += (
                    integration_registry.select_integration_requirements(
                        integration_name
                    )
                )
                integrations_to_install.append(integration_name)
            else:
                declare(
                    f"None of the required packages for integration "
                    f"'{integration_name}' are installed."
                )
        except KeyError:
            warning(f"Unable to find integration '{integration_name}'.")

    if requirements and (
        force
        or confirmation(
            f"Are you sure you want to upgrade the following "
            "packages to the current environment?\n"
            f"{requirements}"
        )
    ):
        with console.status("Upgrading integrations..."):
            install_packages(requirements, upgrade=True, use_uv=uv)

user() -> None

Commands for user management.

Source code in src/zenml/cli/user_management.py
35
36
37
@cli.group(cls=TagGroup, tag=CliCategories.IDENTITY_AND_SECURITY)
def user() -> None:
    """Commands for user management."""

utc_now(tz_aware: Union[bool, datetime] = False) -> datetime

Get the current time in the UTC timezone.

Parameters:

Name Type Description Default
tz_aware Union[bool, datetime]

Use this flag to control whether the returned datetime is timezone-aware or timezone-naive. If a datetime is provided, the returned datetime will be timezone-aware if and only if the input datetime is also timezone-aware.

False

Returns:

Type Description
datetime

The current UTC time. If tz_aware is a datetime, the returned datetime

datetime

will be timezone-aware only if the input datetime is also timezone-aware.

datetime

If tz_aware is a boolean, the returned datetime will be timezone-aware

datetime

if True, and timezone-naive if False.

Source code in src/zenml/utils/time_utils.py
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
def utc_now(tz_aware: Union[bool, datetime] = False) -> datetime:
    """Get the current time in the UTC timezone.

    Args:
        tz_aware: Use this flag to control whether the returned datetime is
            timezone-aware or timezone-naive. If a datetime is provided, the
            returned datetime will be timezone-aware if and only if the input
            datetime is also timezone-aware.

    Returns:
        The current UTC time. If tz_aware is a datetime, the returned datetime
        will be timezone-aware only if the input datetime is also timezone-aware.
        If tz_aware is a boolean, the returned datetime will be timezone-aware
        if True, and timezone-naive if False.
    """
    now = datetime.now(timezone.utc)
    if (
        isinstance(tz_aware, bool)
        and tz_aware is False
        or isinstance(tz_aware, datetime)
        and tz_aware.tzinfo is None
    ):
        return now.replace(tzinfo=None)

    return now

utc_now_tz_aware() -> datetime

Get the current timezone-aware UTC time.

Returns:

Type Description
datetime

The current UTC time.

Source code in src/zenml/utils/time_utils.py
47
48
49
50
51
52
53
def utc_now_tz_aware() -> datetime:
    """Get the current timezone-aware UTC time.

    Returns:
        The current UTC time.
    """
    return utc_now(tz_aware=True)

validate_keys(key: str) -> None

Validates key if it is a valid python string.

Parameters:

Name Type Description Default
key str

key to validate

required
Source code in src/zenml/cli/utils.py
880
881
882
883
884
885
886
887
def validate_keys(key: str) -> None:
    """Validates key if it is a valid python string.

    Args:
        key: key to validate
    """
    if not key.isidentifier():
        error("Please provide args with a proper identifier as the key.")

validate_name(ctx: click.Context, param: str, value: str) -> str

Validate the name of the stack.

Parameters:

Name Type Description Default
ctx Context

The click context.

required
param str

The parameter name.

required
value str

The value of the parameter.

required

Returns:

Type Description
str

The validated value.

Raises:

Type Description
BadParameter

If the name is invalid.

Source code in src/zenml/cli/stack.py
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
def validate_name(ctx: click.Context, param: str, value: str) -> str:
    """Validate the name of the stack.

    Args:
        ctx: The click context.
        param: The parameter name.
        value: The value of the parameter.

    Returns:
        The validated value.

    Raises:
        BadParameter: If the name is invalid.
    """
    if not value:
        return value

    if not re.match(r"^[a-zA-Z0-9-]*$", value):
        raise click.BadParameter(
            "Stack name must contain only alphanumeric characters and hyphens."
        )

    if len(value) > 16:
        raise click.BadParameter(
            "Stack name must have a maximum length of 16 characters."
        )

    return value

verify_service_connector(name_id_or_prefix: str, resource_type: Optional[str] = None, resource_id: Optional[str] = None, verify_only: bool = False) -> None

Verifies if a service connector has access to one or more resources.

Parameters:

Name Type Description Default
name_id_or_prefix str

The name or id of the service connector to verify.

required
resource_type Optional[str]

The type of resource for which to verify access.

None
resource_id Optional[str]

The ID of the resource for which to verify access.

None
verify_only bool

Only verify the service connector, do not list resources.

False
Source code in src/zenml/cli/service_connectors.py
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
@service_connector.command(
    "verify",
    help="""Verify and list resources for a service connector.

Use this command to check if a registered ZenML service connector is correctly
configured with valid credentials and is able to actively access one or more
resources.

This command has a double purpose:

1. first, it can be used to check if a service connector is correctly configured
and has valid credentials, by actively exercising its credentials and trying to
gain access to the remote service or resource it is configured for.

2. second, it is used to fetch the list of resources that a service connector
has access to. This is useful when the service connector is configured to access
multiple resources, and you want to know which ones it has access to, or even
as a confirmation that it has access to the single resource that it is
configured for. 

You can use this command to answer questions like:

- is this connector valid and correctly configured?
- have I configured this connector to access the correct resource?
- which resources can this connector give me access to?

For connectors that are configured to access multiple types of resources, a
list of resources is not fetched, because it would be too expensive to list
all resources of all types that the connector has access to. In this case,
you can use the `--resource-type` argument to scope down the verification to
a particular resource type.

Examples:

- check if a Kubernetes service connector has access to the cluster it is
configured for:

    $ zenml service-connector verify my-k8s-connector

- check if a generic, multi-type, multi-instance AWS service connector has
access to a particular S3 bucket:

    $ zenml service-connector verify my-generic-aws-connector \\               
--resource-type s3-bucket --resource-id my-bucket

""",
)
@click.option(
    "--resource-type",
    "-r",
    "resource_type",
    help="The type of the resource for which to verify access.",
    required=False,
    type=str,
)
@click.option(
    "--resource-id",
    "-ri",
    "resource_id",
    help="The ID of the resource for which to verify access.",
    required=False,
    type=str,
)
@click.option(
    "--verify-only",
    "-v",
    "verify_only",
    help="Only verify the service connector, do not list resources.",
    required=False,
    is_flag=True,
)
@click.argument("name_id_or_prefix", type=str, required=True)
def verify_service_connector(
    name_id_or_prefix: str,
    resource_type: Optional[str] = None,
    resource_id: Optional[str] = None,
    verify_only: bool = False,
) -> None:
    """Verifies if a service connector has access to one or more resources.

    Args:
        name_id_or_prefix: The name or id of the service connector to verify.
        resource_type: The type of resource for which to verify access.
        resource_id: The ID of the resource for which to verify access.
        verify_only: Only verify the service connector, do not list resources.
    """
    client = Client()

    with console.status(
        f"Verifying service connector '{name_id_or_prefix}'...\n"
    ):
        try:
            resources = client.verify_service_connector(
                name_id_or_prefix=name_id_or_prefix,
                resource_type=resource_type,
                resource_id=resource_id,
                list_resources=not verify_only,
            )
        except (
            KeyError,
            ValueError,
            IllegalOperationError,
            NotImplementedError,
            AuthorizationException,
        ) as e:
            cli_utils.error(
                f"Service connector '{name_id_or_prefix}' verification failed: "
                f"{e}"
            )

    click.echo(
        f"Service connector '{name_id_or_prefix}' is correctly configured "
        f"with valid credentials and has access to the following resources:"
    )

    cli_utils.print_service_connector_resource_table(
        resources=[resources],
        show_resources_only=True,
    )

version() -> None

Interact with model versions in the Model Control Plane.

Source code in src/zenml/cli/model.py
394
395
396
@model.group()
def version() -> None:
    """Interact with model versions in the Model Control Plane."""

warning(text: str, bold: Optional[bool] = None, italic: Optional[bool] = None, **kwargs: Any) -> None

Echo a warning string on the CLI.

Parameters:

Name Type Description Default
text str

Input text string.

required
bold Optional[bool]

Optional boolean to bold the text.

None
italic Optional[bool]

Optional boolean to italicize the text.

None
**kwargs Any

Optional kwargs to be passed to console.print().

{}
Source code in src/zenml/cli/utils.py
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
def warning(
    text: str,
    bold: Optional[bool] = None,
    italic: Optional[bool] = None,
    **kwargs: Any,
) -> None:
    """Echo a warning string on the CLI.

    Args:
        text: Input text string.
        bold: Optional boolean to bold the text.
        italic: Optional boolean to italicize the text.
        **kwargs: Optional kwargs to be passed to console.print().
    """
    base_style = zenml_style_defaults["warning"]
    style = Style.chain(base_style, Style(bold=bold, italic=italic))
    console.print(text, style=style, **kwargs)

web_login(url: Optional[str] = None, verify_ssl: Optional[Union[str, bool]] = None, pro_api_url: Optional[str] = None) -> APIToken

Implements the OAuth2 Device Authorization Grant flow.

This function implements the client side of the OAuth2 Device Authorization Grant flow as defined in https://tools.ietf.org/html/rfc8628, with the following customizations:

  • the unique ZenML client ID (user_id in the global config) is used as the OAuth2 client ID value
  • additional information is added to the user agent header to be used by users to identify the ZenML client

Upon completion of the flow, the access token is saved in the credentials store.

Parameters:

Name Type Description Default
url Optional[str]

The URL of the OAuth2 server. If not provided, the ZenML Pro API server is used by default.

None
verify_ssl Optional[Union[str, bool]]

Whether to verify the SSL certificate of the OAuth2 server. If a string is passed, it is interpreted as the path to a CA bundle file.

None
pro_api_url Optional[str]

The URL of the ZenML Pro API server. If not provided, the default ZenML Pro API server URL is used.

None

Returns:

Type Description
APIToken

The response returned by the OAuth2 server.

Raises:

Type Description
AuthorizationException

If an error occurred during the authorization process.

Source code in src/zenml/login/web_login.py
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
def web_login(
    url: Optional[str] = None,
    verify_ssl: Optional[Union[str, bool]] = None,
    pro_api_url: Optional[str] = None,
) -> APIToken:
    """Implements the OAuth2 Device Authorization Grant flow.

    This function implements the client side of the OAuth2 Device Authorization
    Grant flow as defined in https://tools.ietf.org/html/rfc8628, with the
    following customizations:

    * the unique ZenML client ID (`user_id` in the global config) is used
    as the OAuth2 client ID value
    * additional information is added to the user agent header to be used by
    users to identify the ZenML client

    Upon completion of the flow, the access token is saved in the credentials store.

    Args:
        url: The URL of the OAuth2 server. If not provided, the ZenML Pro API
            server is used by default.
        verify_ssl: Whether to verify the SSL certificate of the OAuth2 server.
            If a string is passed, it is interpreted as the path to a CA bundle
            file.
        pro_api_url: The URL of the ZenML Pro API server. If not provided, the
            default ZenML Pro API server URL is used.

    Returns:
        The response returned by the OAuth2 server.

    Raises:
        AuthorizationException: If an error occurred during the authorization
            process.
    """
    from zenml.login.credentials_store import get_credentials_store
    from zenml.models import (
        OAuthDeviceAuthorizationRequest,
        OAuthDeviceAuthorizationResponse,
        OAuthDeviceTokenRequest,
        OAuthDeviceUserAgentHeader,
        OAuthTokenResponse,
    )

    credentials_store = get_credentials_store()

    # Make a request to the OAuth2 server to get the device code and user code.
    # The client ID used for the request is the unique ID of the ZenML client.
    response: Optional[requests.Response] = None

    # Add the following information in the user agent header to be used by users
    # to identify the ZenML client:
    #
    # * the ZenML version
    # * the python version
    # * the OS type
    # * the hostname
    #
    user_agent_header = OAuthDeviceUserAgentHeader(
        hostname=platform.node(),
        zenml_version=__version__,
        python_version=platform.python_version(),
        os=platform.system(),
    )

    zenml_pro = False
    if not url:
        # If no URL is provided, we use the ZenML Pro API server by default
        zenml_pro = True
        url = base_url = pro_api_url or ZENML_PRO_API_URL
    else:
        # Get rid of any trailing slashes to prevent issues when having double
        # slashes in the URL
        url = url.rstrip("/")
        if pro_api_url:
            # This is a ZenML Pro server. The device authentication is done
            # through the ZenML Pro API.
            zenml_pro = True
            base_url = pro_api_url
        else:
            base_url = url

    auth_request = OAuthDeviceAuthorizationRequest(
        client_id=GlobalConfiguration().user_id
    )

    # If an existing token is found in the credentials store, we reuse its
    # device ID to avoid creating a new device ID for the same device.
    existing_token = credentials_store.get_token(url)
    if existing_token and existing_token.device_id:
        auth_request.device_id = existing_token.device_id

    if zenml_pro:
        auth_url = base_url + AUTH + DEVICE_AUTHORIZATION
        login_url = base_url + AUTH + LOGIN
    else:
        auth_url = base_url + API + VERSION_1 + DEVICE_AUTHORIZATION
        login_url = base_url + API + VERSION_1 + LOGIN

    try:
        response = requests.post(
            auth_url,
            headers={
                "Content-Type": "application/x-www-form-urlencoded",
                "User-Agent": user_agent_header.encode(),
            },
            data=auth_request.model_dump(exclude_none=True),
            verify=verify_ssl,
            timeout=DEFAULT_HTTP_TIMEOUT,
        )
        if response.status_code == 200:
            auth_response = OAuthDeviceAuthorizationResponse(**response.json())
        else:
            logger.info(f"Error: {response.status_code} {response.text}")
            raise AuthorizationException(
                f"Could not connect to {base_url}. Please check the URL."
            )
    except (requests.exceptions.JSONDecodeError, ValueError, TypeError):
        logger.exception("Bad response received from API server.")
        raise AuthorizationException(
            "Bad response received from API server. Please check the URL."
        )
    except requests.exceptions.RequestException:
        logger.exception("Could not connect to API server.")
        raise AuthorizationException(
            f"Could not connect to {base_url}. Please check the URL."
        )

    # Open the verification URL in the user's browser
    verification_uri = (
        auth_response.verification_uri_complete
        or auth_response.verification_uri
    )
    if verification_uri.startswith("/"):
        # If the verification URI is a relative path, we need to add the base
        # URL to it
        verification_uri = base_url + verification_uri
    webbrowser.open(verification_uri)
    logger.info(
        f"If your browser did not open automatically, please open the "
        f"following URL into your browser to proceed with the authentication:"
        f"\n\n{verification_uri}\n"
    )

    # Poll the OAuth2 server until the user has authorized the device
    token_request = OAuthDeviceTokenRequest(
        device_code=auth_response.device_code,
        client_id=auth_request.client_id,
    )
    expires_in = auth_response.expires_in
    interval = auth_response.interval
    token_response: OAuthTokenResponse
    while True:
        response = requests.post(
            login_url,
            headers={"Content-Type": "application/x-www-form-urlencoded"},
            data=token_request.model_dump(),
            verify=verify_ssl,
            timeout=DEFAULT_HTTP_TIMEOUT,
        )
        if response.status_code == 200:
            # The user has authorized the device, so we can extract the access token
            token_response = OAuthTokenResponse(**response.json())
            if zenml_pro:
                logger.info("Successfully logged in to ZenML Pro.")
            else:
                logger.info(f"Successfully logged in to {url}.")
            break
        elif response.status_code == 400:
            try:
                error_response = OAuthError(**response.json())
            except (
                requests.exceptions.JSONDecodeError,
                ValueError,
                TypeError,
            ):
                raise AuthorizationException(
                    f"Error received from {base_url}: {response.text}"
                )

            if error_response.error == "authorization_pending":
                # The user hasn't authorized the device yet, so we wait for the
                # interval and try again
                pass
            elif error_response.error == "slow_down":
                # The OAuth2 server is asking us to slow down our polling
                interval += 5
            else:
                # There was another error with the request
                raise AuthorizationException(
                    f"Error: {error_response.error} {error_response.error_description}"
                )

            expires_in -= interval
            if expires_in <= 0:
                raise AuthorizationException(
                    "User did not authorize the device in time."
                )
            time.sleep(interval)
        else:
            # There was another error with the request
            raise AuthorizationException(
                f"Error: {response.status_code} {response.json()['error']}"
            )

    # Save the token in the credentials store
    return credentials_store.set_token(
        url, token_response, is_zenml_pro=zenml_pro
    )

write_yaml(file_path: str, contents: Union[Dict[Any, Any], List[Any]], sort_keys: bool = True) -> None

Write contents as YAML format to file_path.

Parameters:

Name Type Description Default
file_path str

Path to YAML file.

required
contents Union[Dict[Any, Any], List[Any]]

Contents of YAML file as dict or list.

required
sort_keys bool

If True, keys are sorted alphabetically. If False, the order in which the keys were inserted into the dict will be preserved.

True

Raises:

Type Description
FileNotFoundError

if directory does not exist.

Source code in src/zenml/utils/yaml_utils.py
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
def write_yaml(
    file_path: str,
    contents: Union[Dict[Any, Any], List[Any]],
    sort_keys: bool = True,
) -> None:
    """Write contents as YAML format to file_path.

    Args:
        file_path: Path to YAML file.
        contents: Contents of YAML file as dict or list.
        sort_keys: If `True`, keys are sorted alphabetically. If `False`,
            the order in which the keys were inserted into the dict will
            be preserved.

    Raises:
        FileNotFoundError: if directory does not exist.
    """
    if not io_utils.is_remote(file_path):
        dir_ = str(Path(file_path).parent)
        if not fileio.isdir(dir_):
            raise FileNotFoundError(f"Directory {dir_} does not exist.")
    io_utils.write_file_contents_as_string(
        file_path, yaml.dump(contents, sort_keys=sort_keys)
    )

Modules

annotator

Functionality for annotator CLI subcommands.

Classes
Functions
register_annotator_subcommands() -> None

Registers CLI subcommands for the annotator.

Source code in src/zenml/cli/annotator.py
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
def register_annotator_subcommands() -> None:
    """Registers CLI subcommands for the annotator."""
    annotator_group = cast(TagGroup, cli.commands.get("annotator"))
    if not annotator_group:
        return

    @annotator_group.group(
        cls=TagGroup,
        help="Commands for interacting with annotation datasets.",
    )
    @click.pass_context
    def dataset(ctx: click.Context) -> None:
        """Interact with ZenML annotator datasets.

        Args:
            ctx: The click Context object.
        """
        from zenml.client import Client

        annotator_models = Client().active_stack_model.components.get(
            StackComponentType.ANNOTATOR
        )
        if annotator_models is None:
            cli_utils.error(
                "No active annotator found. Please register an annotator "
                "first and add it to your stack."
            )
            return

        from zenml.stack.stack_component import StackComponent

        ctx.obj = StackComponent.from_model(annotator_models[0])

    @dataset.command(
        "list",
        help="List the available datasets.",
    )
    @click.pass_obj
    def dataset_list(annotator: "BaseAnnotator") -> None:
        """List the available datasets.

        Args:
            annotator: The annotator stack component.
        """
        dataset_names = annotator.get_dataset_names()
        if not dataset_names:
            cli_utils.warning("No datasets found.")
            return
        cli_utils.print_list_items(
            list_items=dataset_names,
            column_title="DATASETS",
        )

    @dataset.command("stats")
    @click.argument("dataset_name", type=click.STRING)
    @click.pass_obj
    def dataset_stats(annotator: "BaseAnnotator", dataset_name: str) -> None:
        """Display statistics about a dataset.

        Args:
            annotator: The annotator stack component.
            dataset_name: The name of the dataset.
        """
        try:
            stats = annotator.get_dataset_stats(dataset_name)
            labeled_task_count, unlabeled_task_count = stats
        except IndexError:
            cli_utils.error(
                f"Dataset {dataset_name} does not exist. Please use `zenml "
                f"annotator dataset list` to list the available datasets."
            )
            return

        total_task_count = unlabeled_task_count + labeled_task_count
        cli_utils.declare(
            f"Annotation stats for '{dataset_name}' dataset:", bold=True
        )
        cli_utils.declare(f"Total annotation tasks: {total_task_count}")
        cli_utils.declare(f"Labeled annotation tasks: {labeled_task_count}")
        if annotator.flavor != "prodigy":
            # Prodigy doesn't allow you to get the unlabeled task count
            cli_utils.declare(
                f"Unlabeled annotation tasks: {unlabeled_task_count}"
            )

    @dataset.command("delete")
    @click.argument("dataset_name", type=click.STRING)
    @click.option(
        "--all",
        "-a",
        "all_",
        is_flag=True,
        help="Use this flag to delete all datasets.",
        type=click.BOOL,
    )
    @click.pass_obj
    def dataset_delete(
        annotator: "BaseAnnotator", dataset_name: str, all_: bool
    ) -> None:
        """Delete a dataset.

        If the --all flag is used, all datasets will be deleted.

        Args:
            annotator: The annotator stack component.
            dataset_name: Name of the dataset to delete.
            all_: Whether to delete all datasets.
        """
        if not cli_utils.confirmation(
            f"Are you sure you want to delete dataset '{dataset_name}'?"
        ):
            return
        cli_utils.declare(f"Deleting your dataset '{dataset_name}'")
        dataset_names = (
            annotator.get_dataset_names() if all_ else [dataset_name]
        )
        for dataset_name in dataset_names:
            try:
                annotator.delete_dataset(dataset_name=dataset_name)
                cli_utils.declare(
                    f"Dataset '{dataset_name}' has now been deleted."
                )
            except ValueError as e:
                cli_utils.error(
                    f"Failed to delete dataset '{dataset_name}': {e}"
                )

    @dataset.command(
        "annotate", context_settings={"ignore_unknown_options": True}
    )
    @click.argument("dataset_name", type=click.STRING)
    @click.argument("kwargs", nargs=-1, type=click.UNPROCESSED)
    @click.pass_obj
    def dataset_annotate(
        annotator: "BaseAnnotator",
        dataset_name: str,
        kwargs: Tuple[str, ...],
    ) -> None:
        """Command to launch the annotation interface for a dataset.

        Args:
            annotator: The annotator stack component.
            dataset_name: Name of the dataset
            kwargs: Additional keyword arguments to pass to the
                annotation client.

        Raises:
            ValueError: If the dataset does not exist.
        """
        cli_utils.declare(
            f"Launching the annotation interface for dataset '{dataset_name}'."
        )

        # Process the arbitrary keyword arguments
        kwargs_dict = {}
        for arg in kwargs:
            if arg.startswith("--"):
                key, value = arg.removeprefix("--").split("=", 1)
                kwargs_dict[key] = value

        if annotator.flavor == "prodigy":
            command = kwargs_dict.get("command")
            if not command:
                raise ValueError(
                    "The 'command' keyword argument is required for launching the Prodigy interface."
                )
            annotator.launch(**kwargs_dict)
        else:
            try:
                annotator.get_dataset(dataset_name=dataset_name)
                annotator.launch(
                    url=annotator.get_url_for_dataset(dataset_name)
                )
            except ValueError as e:
                raise ValueError("Dataset does not exist.") from e
Modules

base

Base functionality for the CLI.

Classes
ZenMLProjectTemplateLocation

Bases: BaseModel

A ZenML project template location.

Attributes
copier_github_url: str property

Get the GitHub URL for the copier.

Returns:

Type Description
str

A GitHub URL in copier format.

Functions
backup_database(strategy: Optional[str] = None, location: Optional[str] = None, overwrite: bool = False) -> None

Backup the ZenML database.

Parameters:

Name Type Description Default
strategy Optional[str]

Custom backup strategy to use. Defaults to whatever is configured in the store config.

None
location Optional[str]

Custom location to store the backup. Defaults to whatever is configured in the store config. Depending on the strategy, this can be a local path or a database name.

None
overwrite bool

Whether to overwrite the existing backup.

False
Source code in src/zenml/cli/base.py
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
@cli.command("backup-database", help="Create a database backup.", hidden=True)
@click.option(
    "--strategy",
    "-s",
    help="Custom backup strategy to use. Defaults to whatever is configured "
    "in the store config.",
    type=click.Choice(choices=DatabaseBackupStrategy.values()),
    required=False,
    default=None,
)
@click.option(
    "--location",
    default=None,
    help="Custom location to store the backup. Defaults to whatever is "
    "configured in the store config. Depending on the strategy, this can be "
    "a local path or a database name.",
    type=str,
)
@click.option(
    "--overwrite",
    "-o",
    is_flag=True,
    default=False,
    help="Overwrite the existing backup.",
    type=bool,
)
def backup_database(
    strategy: Optional[str] = None,
    location: Optional[str] = None,
    overwrite: bool = False,
) -> None:
    """Backup the ZenML database.

    Args:
        strategy: Custom backup strategy to use. Defaults to whatever is
            configured in the store config.
        location: Custom location to store the backup. Defaults to whatever is
            configured in the store config. Depending on the strategy, this can
            be a local path or a database name.
        overwrite: Whether to overwrite the existing backup.
    """
    from zenml.zen_stores.base_zen_store import BaseZenStore
    from zenml.zen_stores.sql_zen_store import SqlZenStore

    store_config = GlobalConfiguration().store_configuration
    if store_config.type == StoreType.SQL:
        store = BaseZenStore.create_store(
            store_config, skip_default_registrations=True, skip_migrations=True
        )
        assert isinstance(store, SqlZenStore)
        msg, location = store.backup_database(
            strategy=DatabaseBackupStrategy(strategy) if strategy else None,
            location=location,
            overwrite=overwrite,
        )
        cli_utils.declare(f"Database was backed up to {msg}.")
    else:
        cli_utils.warning(
            "Cannot backup database while connected to a ZenML server."
        )
clean(yes: bool = False, local: bool = False) -> None

Delete all ZenML metadata, artifacts and stacks.

This is a destructive operation, primarily intended for use in development.

Parameters:

Name Type Description Default
yes bool

If you don't want a confirmation prompt.

False
local bool

If you want to delete local files associated with the active stack.

False
Source code in src/zenml/cli/base.py
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
@cli.command(
    "clean",
    hidden=True,
    help="Delete all ZenML metadata, artifacts and stacks.",
)
@click.option(
    "--yes",
    "-y",
    is_flag=True,
    default=False,
    help="Don't ask for confirmation.",
)
@click.option(
    "--local",
    "-l",
    is_flag=True,
    default=False,
    help="Delete local files relating to the active stack.",
)
def clean(yes: bool = False, local: bool = False) -> None:
    """Delete all ZenML metadata, artifacts and stacks.

    This is a destructive operation, primarily intended for use in development.

    Args:
        yes: If you don't want a confirmation prompt.
        local: If you want to delete local files associated with the active
            stack.
    """
    if local:
        curr_version = version.parse(zenml_version)

        global_version = GlobalConfiguration().version
        if global_version is not None:
            config_version = version.parse(global_version)

            if config_version > curr_version:
                error(
                    "Due to this version mismatch, ZenML can not detect and "
                    "shut down any running dashboards or clean any resources "
                    "related to the active stack."
                )
        _delete_local_files(force_delete=yes)
        return

    confirm = None
    if not yes:
        confirm = confirmation(
            "DANGER: This will completely delete all artifacts, metadata and "
            "stacks \never created during the use of ZenML. Pipelines and "
            "stack components running non-\nlocally will still exist. Please "
            "delete those manually. \n\nAre you sure you want to proceed?"
        )

    if yes or confirm:
        server = get_local_server()

        if server:
            from zenml.zen_server.deploy.deployer import LocalServerDeployer

            deployer = LocalServerDeployer()
            deployer.remove_server()
            cli_utils.declare("The local ZenML dashboard has been shut down.")

        # delete the .zen folder
        local_zen_repo_config = Path.cwd() / REPOSITORY_DIRECTORY_NAME
        if fileio.exists(str(local_zen_repo_config)):
            fileio.rmtree(str(local_zen_repo_config))
            declare(
                f"Deleted local ZenML config from {local_zen_repo_config}."
            )

        # delete the zen store and all other files and directories used by ZenML
        # to persist information locally (e.g. artifacts)
        global_zen_config = Path(get_global_config_directory())
        if fileio.exists(str(global_zen_config)):
            gc = GlobalConfiguration()
            for dir_name in fileio.listdir(str(global_zen_config)):
                if fileio.isdir(str(global_zen_config / str(dir_name))):
                    warning(
                        f"Deleting '{str(dir_name)}' directory from global "
                        f"config."
                    )
            fileio.rmtree(str(global_zen_config))
            declare(f"Deleted global ZenML config from {global_zen_config}.")
            GlobalConfiguration._reset_instance()
            fresh_gc = GlobalConfiguration(
                user_id=gc.user_id,
                analytics_opt_in=gc.analytics_opt_in,
                version=zenml_version,
            )
            fresh_gc.set_default_store()
            declare(f"Reinitialized ZenML global config at {Path.cwd()}.")

    else:
        declare("Aborting clean.")
go() -> None

Quickly explore ZenML with this walk-through.

Raises:

Type Description
GitNotFoundError

If git is not installed.

e

when Jupyter Notebook fails to launch.

Source code in src/zenml/cli/base.py
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
@cli.command("go")
def go() -> None:
    """Quickly explore ZenML with this walk-through.

    Raises:
        GitNotFoundError: If git is not installed.
        e: when Jupyter Notebook fails to launch.
    """
    from zenml.cli.text_utils import (
        zenml_cli_privacy_message,
        zenml_cli_welcome_message,
        zenml_go_notebook_tutorial_message,
    )

    metadata = {}

    console.print(zenml_cli_welcome_message, width=80)

    client = Client()

    # Only ask them if they haven't been asked before and the email
    # hasn't been supplied by other means
    if (
        not GlobalConfiguration().user_email
        and client.active_user.email_opted_in is None
    ):
        gave_email = _prompt_email(AnalyticsEventSource.ZENML_GO)
        metadata = {"gave_email": gave_email}

    zenml_tutorial_path = os.path.join(os.getcwd(), "zenml_tutorial")

    if not is_jupyter_installed():
        cli_utils.error(
            "Jupyter Notebook or JupyterLab is not installed. "
            "Please install the 'notebook' package with `pip` "
            "first so you can run the tutorial notebooks."
        )

    with track_handler(event=AnalyticsEvent.RUN_ZENML_GO, metadata=metadata):
        console.print(zenml_cli_privacy_message, width=80)

        if not os.path.isdir(zenml_tutorial_path):
            try:
                from git.repo.base import Repo
            except ImportError as e:
                cli_utils.error(
                    "At this point we would want to clone our tutorial repo "
                    "onto your machine to let you dive right into our code. "
                    "However, this machine has no installation of Git. Feel "
                    "free to install git and rerun this command. Alternatively "
                    "you can also download the repo manually here: "
                    f"{TUTORIAL_REPO}. The tutorial is in the "
                    f"'examples/quickstart/notebooks' directory."
                )
                raise GitNotFoundError(e)

            with tempfile.TemporaryDirectory() as tmpdirname:
                tmp_cloned_dir = os.path.join(tmpdirname, "zenml_repo")
                with console.status(
                    "Cloning tutorial. This sometimes takes a minute..."
                ):
                    Repo.clone_from(
                        TUTORIAL_REPO,
                        tmp_cloned_dir,
                        branch=f"release/{zenml_version}",
                        depth=1,  # to prevent timeouts when downloading
                    )
                example_dir = os.path.join(
                    tmp_cloned_dir, "examples/quickstart"
                )
                copy_dir(example_dir, zenml_tutorial_path)
        else:
            cli_utils.warning(
                f"{zenml_tutorial_path} already exists! Continuing without "
                "cloning."
            )

        # get list of all .ipynb files in zenml_tutorial_path
        ipynb_files = []
        for dirpath, _, filenames in os.walk(zenml_tutorial_path):
            for filename in filenames:
                if filename.endswith(".ipynb"):
                    ipynb_files.append(os.path.join(dirpath, filename))

        ipynb_files.sort()
        console.print(
            zenml_go_notebook_tutorial_message(ipynb_files), width=80
        )
        input("Press ENTER to continue...")

    try:
        subprocess.check_call(
            ["jupyter", "notebook", "--ContentsManager.allow_hidden=True"],
            cwd=zenml_tutorial_path,
        )
    except subprocess.CalledProcessError as e:
        cli_utils.error(
            "An error occurred while launching Jupyter Notebook. "
            "Please make sure Jupyter is properly installed and try again."
        )
        raise e
info(packages: Tuple[str], all: bool = False, file: str = '', stack: bool = False) -> None

Show information about the current user setup.

Parameters:

Name Type Description Default
packages Tuple[str]

List of packages to show information about.

required
all bool

Flag to show information about all installed packages.

False
file str

Flag to output to a file.

''
stack bool

Flag to output information about active stack and components

False
Source code in src/zenml/cli/base.py
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
@cli.command(
    "info", help="Show information about the current user setup.", hidden=True
)
@click.option(
    "--all",
    "-a",
    is_flag=True,
    default=False,
    help="Output information about all installed packages.",
    type=bool,
)
@click.option(
    "--file",
    "-f",
    default="",
    help="Path to export to a .yaml file.",
    type=click.Path(exists=False, dir_okay=False),
)
@click.option(
    "--packages",
    "-p",
    multiple=True,
    help="Select specific installed packages.",
    type=str,
)
@click.option(
    "--stack",
    "-s",
    is_flag=True,
    default=False,
    help="Output information about active stack and components.",
    type=bool,
)
def info(
    packages: Tuple[str],
    all: bool = False,
    file: str = "",
    stack: bool = False,
) -> None:
    """Show information about the current user setup.

    Args:
        packages: List of packages to show information about.
        all: Flag to show information about all installed packages.
        file: Flag to output to a file.
        stack: Flag to output information about active stack and components
    """
    gc = GlobalConfiguration()
    environment = Environment()
    client = Client()
    store_info = client.zen_store.get_store_info()

    store_cfg = gc.store_configuration

    user_info = {
        "zenml_local_version": zenml_version,
        "zenml_server_version": store_info.version,
        "zenml_server_database": str(store_info.database_type),
        "zenml_server_deployment_type": str(store_info.deployment_type),
        "zenml_config_dir": gc.config_directory,
        "zenml_local_store_dir": gc.local_stores_path,
        "zenml_server_url": store_cfg.url,
        "zenml_active_repository_root": str(client.root),
        "python_version": environment.python_version(),
        "environment": get_environment(),
        "system_info": environment.get_system_info(),
        "active_project": client.active_project.name,
        "active_stack": client.active_stack_model.name,
        "active_user": client.active_user.name,
        "telemetry_status": "enabled" if gc.analytics_opt_in else "disabled",
        "analytics_client_id": str(gc.user_id),
        "analytics_user_id": str(client.active_user.id),
        "analytics_server_id": str(client.zen_store.get_store_info().id),
        "integrations": integration_registry.get_installed_integrations(),
        "packages": {},
        "query_packages": {},
    }

    if all:
        user_info["packages"] = cli_utils.get_package_information()
    if packages:
        if user_info.get("packages"):
            if isinstance(user_info["packages"], dict):
                user_info["query_packages"] = {
                    p: v
                    for p, v in user_info["packages"].items()
                    if p in packages
                }
        else:
            user_info["query_packages"] = cli_utils.get_package_information(
                list(packages)
            )
    if file:
        file_write_path = os.path.abspath(file)
        write_yaml(file, user_info)
        declare(f"Wrote user debug info to file at '{file_write_path}'.")
    else:
        cli_utils.print_user_info(user_info)

    if stack:
        try:
            cli_utils.print_debug_stack()
        except ModuleNotFoundError as e:
            cli_utils.warning(
                "Could not print debug stack information. Please make sure "
                "you have the necessary dependencies and integrations "
                "installed for all your stack components."
            )
            cli_utils.warning(f"The missing package is: '{e.name}'")
init(path: Optional[Path], template: Optional[str] = None, template_tag: Optional[str] = None, template_with_defaults: bool = False, test: bool = False) -> None

Initialize ZenML on given path.

Parameters:

Name Type Description Default
path Optional[Path]

Path to the repository.

required
template Optional[str]

Optional name or URL of the ZenML project template to use to initialize the repository. Can be a string like e2e_batch, nlp, starter or a copier URL like gh:owner/repo_name. If not specified, no template is used.

None
template_tag Optional[str]

Optional tag of the ZenML project template to use to initialize the repository. If template is a pre-defined template, then this is ignored.

None
template_with_defaults bool

Whether to use default parameters of the ZenML project template

False
test bool

Whether to skip interactivity when testing.

False
Source code in src/zenml/cli/base.py
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
@cli.command("init", help="Initialize a ZenML repository.")
@click.option(
    "--path",
    type=click.Path(
        exists=True, file_okay=False, dir_okay=True, path_type=Path
    ),
)
@click.option(
    "--template",
    type=str,
    required=False,
    help="Name or URL of the ZenML project template to use to initialize the "
    "repository, Can be a string like `e2e_batch`, `nlp`, `llm_finetuning`, "
    "`starter` etc. or a copier URL like gh:owner/repo_name. If not specified, "
    "no template is used.",
)
@click.option(
    "--template-tag",
    type=str,
    required=False,
    help="Optional tag of the ZenML project template to use to initialize the "
    "repository.",
)
@click.option(
    "--template-with-defaults",
    is_flag=True,
    default=False,
    required=False,
    help="Whether to use default parameters of the ZenML project template",
)
@click.option(
    "--test",
    is_flag=True,
    default=False,
    help="To skip interactivity when testing.",
    hidden=True,
)
def init(
    path: Optional[Path],
    template: Optional[str] = None,
    template_tag: Optional[str] = None,
    template_with_defaults: bool = False,
    test: bool = False,
) -> None:
    """Initialize ZenML on given path.

    Args:
        path: Path to the repository.
        template: Optional name or URL of the ZenML project template to use to
            initialize the repository. Can be a string like `e2e_batch`,
            `nlp`, `starter` or a copier URL like `gh:owner/repo_name`. If
            not specified, no template is used.
        template_tag: Optional tag of the ZenML project template to use to
            initialize the repository. If template is a pre-defined template,
            then this is ignored.
        template_with_defaults: Whether to use default parameters of
            the ZenML project template
        test: Whether to skip interactivity when testing.
    """
    if path is None:
        path = Path.cwd()

    os.environ[ENV_ZENML_ENABLE_REPO_INIT_WARNINGS] = "False"

    if template:
        try:
            from copier import Worker
        except ImportError:
            error(
                "You need to install the ZenML project template requirements "
                "to use templates. Please run `pip install zenml[templates]` "
                "and try again."
            )
            return

        from zenml.cli.text_utils import (
            zenml_cli_privacy_message,
            zenml_cli_welcome_message,
        )

        console.print(zenml_cli_welcome_message, width=80)

        client = Client()
        # Only ask them if they haven't been asked before and the email
        # hasn't been supplied by other means
        if (
            not GlobalConfiguration().user_email
            and client.active_user.email_opted_in is None
            and not test
        ):
            _prompt_email(AnalyticsEventSource.ZENML_INIT)

        email = GlobalConfiguration().user_email or ""
        metadata = {
            "email": email,
            "template": template,
            "prompt": not template_with_defaults,
        }

        with track_handler(
            event=AnalyticsEvent.GENERATE_TEMPLATE,
            metadata=metadata,
        ):
            console.print(zenml_cli_privacy_message, width=80)

            if not template_with_defaults:
                from rich.markdown import Markdown

                prompt_message = Markdown(
                    """
## 🧑‍🏫 Project template parameters
"""
                )

                console.print(prompt_message, width=80)

            # Check if template is a URL or a preset template name
            vcs_ref: Optional[str] = None
            if template in ZENML_PROJECT_TEMPLATES:
                declare(f"Using the {template} template...")
                zenml_project_template = ZENML_PROJECT_TEMPLATES[template]
                src_path = zenml_project_template.copier_github_url
                # template_tag is ignored in this case
                vcs_ref = zenml_project_template.github_tag
            else:
                declare(
                    f"List of known templates is: {', '.join(ZENML_PROJECT_TEMPLATES.keys())}"
                )
                declare(
                    f"No known templates specified. Using `{template}` as URL."
                    "If this is not a valid copier template URL, this will "
                    "fail."
                )

                src_path = template
                vcs_ref = template_tag

            with Worker(
                src_path=src_path,
                vcs_ref=vcs_ref,
                dst_path=path,
                data=dict(
                    email=email,
                    template=template,
                ),
                defaults=template_with_defaults,
                user_defaults=dict(
                    email=email,
                ),
                overwrite=template_with_defaults,
                unsafe=True,
            ) as worker:
                worker.run_copy()

    with console.status(f"Initializing ZenML repository at {path}.\n"):
        try:
            Client.initialize(root=path)
            declare(f"ZenML repository initialized at {path}.")
        except InitializationException as e:
            declare(f"{e}")
            return

    declare(
        f"The local active stack was initialized to "
        f"'{Client().active_stack_model.name}'. This local configuration "
        f"will only take effect when you're running ZenML from the initialized "
        f"repository root, or from a subdirectory. For more information on "
        f"repositories and configurations, please visit "
        f"https://docs.zenml.io/user-guides/production-guide/understand-stacks."
    )
migrate_database(skip_default_registrations: bool = False) -> None

Migrate the ZenML database.

Parameters:

Name Type Description Default
skip_default_registrations bool

If True, registration of default components will be skipped.

False
Source code in src/zenml/cli/base.py
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
@cli.command(
    "migrate-database", help="Migrate the ZenML database.", hidden=True
)
@click.option(
    "--skip_default_registrations",
    is_flag=True,
    default=False,
    help="Skip registering default project, user and stack.",
    type=bool,
)
def migrate_database(skip_default_registrations: bool = False) -> None:
    """Migrate the ZenML database.

    Args:
        skip_default_registrations: If `True`, registration of default
            components will be skipped.
    """
    from zenml.zen_stores.base_zen_store import BaseZenStore

    store_config = GlobalConfiguration().store_configuration
    if store_config.type == StoreType.SQL:
        BaseZenStore.create_store(
            store_config, skip_default_registrations=skip_default_registrations
        )
        cli_utils.declare("Database migration finished.")
    else:
        cli_utils.warning(
            "Unable to migrate database while connected to a ZenML server."
        )
restore_database(strategy: Optional[str] = None, location: Optional[str] = None, cleanup: bool = False) -> None

Restore the ZenML database.

Parameters:

Name Type Description Default
strategy Optional[str]

Custom backup strategy to use. Defaults to whatever is configured in the store config.

None
location Optional[str]

Custom location where the backup is stored. Defaults to whatever is configured in the store config. Depending on the strategy, this can be a local path or a database name.

None
cleanup bool

Whether to cleanup the backup after restoring.

False
Source code in src/zenml/cli/base.py
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
@cli.command(
    "restore-database", help="Restore the database from a backup.", hidden=True
)
@click.option(
    "--strategy",
    "-s",
    help="Custom backup strategy to use. Defaults to whatever is configured "
    "in the store config.",
    type=click.Choice(choices=DatabaseBackupStrategy.values()),
    required=False,
    default=None,
)
@click.option(
    "--location",
    default=None,
    help="Custom location where the backup is stored. Defaults to whatever is "
    "configured in the store config. Depending on the strategy, this can be "
    "a local path or a database name.",
    type=str,
)
@click.option(
    "--cleanup",
    "-c",
    is_flag=True,
    default=False,
    help="Cleanup the backup after restoring.",
    type=bool,
)
def restore_database(
    strategy: Optional[str] = None,
    location: Optional[str] = None,
    cleanup: bool = False,
) -> None:
    """Restore the ZenML database.

    Args:
        strategy: Custom backup strategy to use. Defaults to whatever is
            configured in the store config.
        location: Custom location where the backup is stored. Defaults to
            whatever is configured in the store config. Depending on the
            strategy, this can be a local path or a database name.
        cleanup: Whether to cleanup the backup after restoring.
    """
    from zenml.zen_stores.base_zen_store import BaseZenStore
    from zenml.zen_stores.sql_zen_store import SqlZenStore

    store_config = GlobalConfiguration().store_configuration
    if store_config.type == StoreType.SQL:
        store = BaseZenStore.create_store(
            store_config, skip_default_registrations=True, skip_migrations=True
        )
        assert isinstance(store, SqlZenStore)
        store.restore_database(
            strategy=DatabaseBackupStrategy(strategy) if strategy else None,
            location=location,
            cleanup=cleanup,
        )
        cli_utils.declare("Database restore finished.")
    else:
        cli_utils.warning(
            "Cannot restore database while connected to a ZenML server."
        )
Modules

cli_utils

Utility functions for the CLI.

Classes
Functions
check_zenml_pro_project_availability() -> None

Check if the ZenML Pro project feature is available.

Source code in src/zenml/cli/utils.py
2273
2274
2275
2276
2277
2278
2279
2280
def check_zenml_pro_project_availability() -> None:
    """Check if the ZenML Pro project feature is available."""
    client = Client()
    if not client.zen_store.get_store_info().is_pro_server():
        warning(
            "The ZenML projects feature is available only on ZenML Pro. "
            "Please visit https://zenml.io/pro to learn more."
        )
confirmation(text: str, *args: Any, **kwargs: Any) -> bool

Echo a confirmation string on the CLI.

Parameters:

Name Type Description Default
text str

Input text string.

required
*args Any

Args to be passed to click.confirm().

()
**kwargs Any

Kwargs to be passed to click.confirm().

{}

Returns:

Type Description
bool

Boolean based on user response.

Source code in src/zenml/cli/utils.py
125
126
127
128
129
130
131
132
133
134
135
136
def confirmation(text: str, *args: Any, **kwargs: Any) -> bool:
    """Echo a confirmation string on the CLI.

    Args:
        text: Input text string.
        *args: Args to be passed to click.confirm().
        **kwargs: Kwargs to be passed to click.confirm().

    Returns:
        Boolean based on user response.
    """
    return Confirm.ask(text, console=console)
convert_structured_str_to_dict(string: str) -> Dict[str, str]

Convert a structured string (JSON or YAML) into a dict.

Examples:

>>> convert_structured_str_to_dict('{"location": "Nevada", "aliens":"many"}')
{'location': 'Nevada', 'aliens': 'many'}
>>> convert_structured_str_to_dict('location: Nevada \naliens: many')
{'location': 'Nevada', 'aliens': 'many'}
>>> convert_structured_str_to_dict("{'location': 'Nevada', 'aliens': 'many'}")
{'location': 'Nevada', 'aliens': 'many'}

Parameters:

Name Type Description Default
string str

JSON or YAML string value

required

Returns:

Name Type Description
dict_ Dict[str, str]

dict from structured JSON or YAML str

Source code in src/zenml/cli/utils.py
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
def convert_structured_str_to_dict(string: str) -> Dict[str, str]:
    """Convert a structured string (JSON or YAML) into a dict.

    Examples:
        >>> convert_structured_str_to_dict('{"location": "Nevada", "aliens":"many"}')
        {'location': 'Nevada', 'aliens': 'many'}
        >>> convert_structured_str_to_dict('location: Nevada \\naliens: many')
        {'location': 'Nevada', 'aliens': 'many'}
        >>> convert_structured_str_to_dict("{'location': 'Nevada', 'aliens': 'many'}")
        {'location': 'Nevada', 'aliens': 'many'}

    Args:
        string: JSON or YAML string value

    Returns:
        dict_: dict from structured JSON or YAML str
    """
    try:
        dict_: Dict[str, str] = json.loads(string)
        return dict_
    except ValueError:
        pass

    try:
        # Here, Dict type in str is implicitly supported by yaml.safe_load()
        dict_ = yaml.safe_load(string)
        return dict_
    except yaml.YAMLError:
        pass

    error(
        f"Invalid argument: '{string}'. Please provide the value in JSON or YAML format."
    )
create_data_type_help_text(filter_model: Type[BaseFilter], field: str) -> str

Create a general help text for a fields datatype.

Parameters:

Name Type Description Default
filter_model Type[BaseFilter]

The filter model to use

required
field str

The field within that filter model

required

Returns:

Type Description
str

The help text.

Source code in src/zenml/cli/utils.py
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
def create_data_type_help_text(
    filter_model: Type[BaseFilter], field: str
) -> str:
    """Create a general help text for a fields datatype.

    Args:
        filter_model: The filter model to use
        field: The field within that filter model

    Returns:
        The help text.
    """
    filter_generator = FilterGenerator(filter_model)
    if filter_generator.is_datetime_field(field):
        return (
            f"[DATETIME] supported filter operators: "
            f"{[str(op) for op in NumericFilter.ALLOWED_OPS]}"
        )
    elif filter_generator.is_uuid_field(field):
        return (
            f"[UUID] supported filter operators: "
            f"{[str(op) for op in UUIDFilter.ALLOWED_OPS]}"
        )
    elif filter_generator.is_int_field(field):
        return (
            f"[INTEGER] supported filter operators: "
            f"{[str(op) for op in NumericFilter.ALLOWED_OPS]}"
        )
    elif filter_generator.is_bool_field(field):
        return (
            f"[BOOL] supported filter operators: "
            f"{[str(op) for op in BoolFilter.ALLOWED_OPS]}"
        )
    elif filter_generator.is_str_field(field):
        return (
            f"[STRING] supported filter operators: "
            f"{[str(op) for op in StrFilter.ALLOWED_OPS]}"
        )
    else:
        return f"{field}"
create_filter_help_text(filter_model: Type[BaseFilter], field: str) -> str

Create the help text used in the click option help text.

Parameters:

Name Type Description Default
filter_model Type[BaseFilter]

The filter model to use

required
field str

The field within that filter model

required

Returns:

Type Description
str

The help text.

Source code in src/zenml/cli/utils.py
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
def create_filter_help_text(filter_model: Type[BaseFilter], field: str) -> str:
    """Create the help text used in the click option help text.

    Args:
        filter_model: The filter model to use
        field: The field within that filter model

    Returns:
        The help text.
    """
    filter_generator = FilterGenerator(filter_model)
    if filter_generator.is_sort_by_field(field):
        return (
            "[STRING] Example: --sort_by='desc:name' to sort by name in "
            "descending order. "
        )
    if filter_generator.is_datetime_field(field):
        return (
            f"[DATETIME] The following datetime format is supported: "
            f"'{FILTERING_DATETIME_FORMAT}'. Make sure to keep it in "
            f"quotation marks. "
            f"Example: --{field}="
            f"'{GenericFilterOps.GTE}:{FILTERING_DATETIME_FORMAT}' to "
            f"filter for everything created on or after the given date."
        )
    elif filter_generator.is_uuid_field(field):
        return (
            f"[UUID] Example: --{field}='{GenericFilterOps.STARTSWITH}:ab53ca' "
            f"to filter for all UUIDs starting with that prefix."
        )
    elif filter_generator.is_int_field(field):
        return (
            f"[INTEGER] Example: --{field}='{GenericFilterOps.GTE}:25' to "
            f"filter for all entities where this field has a value greater than "
            f"or equal to the value."
        )
    elif filter_generator.is_bool_field(field):
        return (
            f"[BOOL] Example: --{field}='True' to "
            f"filter for all instances where this field is true."
        )
    elif filter_generator.is_str_field(field):
        return (
            f"[STRING] Example: --{field}='{GenericFilterOps.CONTAINS}:example' "
            f"to filter everything that contains the query string somewhere in "
            f"its {field}."
        )
    else:
        return ""
declare(text: Union[str, Text], bold: Optional[bool] = None, italic: Optional[bool] = None, **kwargs: Any) -> None

Echo a declaration on the CLI.

Parameters:

Name Type Description Default
text Union[str, Text]

Input text string.

required
bold Optional[bool]

Optional boolean to bold the text.

None
italic Optional[bool]

Optional boolean to italicize the text.

None
**kwargs Any

Optional kwargs to be passed to console.print().

{}
Source code in src/zenml/cli/utils.py
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
def declare(
    text: Union[str, "Text"],
    bold: Optional[bool] = None,
    italic: Optional[bool] = None,
    **kwargs: Any,
) -> None:
    """Echo a declaration on the CLI.

    Args:
        text: Input text string.
        bold: Optional boolean to bold the text.
        italic: Optional boolean to italicize the text.
        **kwargs: Optional kwargs to be passed to console.print().
    """
    base_style = zenml_style_defaults["info"]
    style = Style.chain(base_style, Style(bold=bold, italic=italic))
    console.print(text, style=style, **kwargs)
describe_pydantic_object(schema_json: Dict[str, Any]) -> None

Describes a Pydantic object based on the dict-representation of its schema.

Parameters:

Name Type Description Default
schema_json Dict[str, Any]

str, represents the schema of a Pydantic object, which can be obtained through BaseModelClass.schema_json()

required
Source code in src/zenml/cli/utils.py
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
def describe_pydantic_object(schema_json: Dict[str, Any]) -> None:
    """Describes a Pydantic object based on the dict-representation of its schema.

    Args:
        schema_json: str, represents the schema of a Pydantic object, which
            can be obtained through BaseModelClass.schema_json()
    """
    # Get the schema dict
    # Extract values with defaults
    schema_title = schema_json["title"]
    required = schema_json.get("required", [])
    description = schema_json.get("description", "")
    properties = schema_json.get("properties", {})

    # Pretty print the schema
    warning(f"Configuration class: {schema_title}\n", bold=True)

    if description:
        declare(f"{description}\n")

    if properties:
        warning("Properties", bold=True)
        for prop, prop_schema in properties.items():
            if "$ref" not in prop_schema.keys():
                if "type" in prop_schema.keys():
                    prop_type = prop_schema["type"]
                elif "anyOf" in prop_schema.keys():
                    prop_type = ", ".join(
                        [p.get("type", "object") for p in prop_schema["anyOf"]]
                    )
                    prop_type = f"one of: {prop_type}"
                else:
                    prop_type = "object"
                warning(
                    f"{prop}, {prop_type}"
                    f"{', REQUIRED' if prop in required else ''}"
                )

            if "description" in prop_schema:
                declare(f"  {prop_schema['description']}", width=80)
error(text: str) -> NoReturn

Echo an error string on the CLI.

Parameters:

Name Type Description Default
text str

Input text string.

required

Raises:

Type Description
ClickException

when called.

Source code in src/zenml/cli/utils.py
158
159
160
161
162
163
164
165
166
167
def error(text: str) -> NoReturn:
    """Echo an error string on the CLI.

    Args:
        text: Input text string.

    Raises:
        ClickException: when called.
    """
    raise click.ClickException(message=click.style(text, fg="red", bold=True))
expand_argument_value_from_file(name: str, value: str) -> str

Expands the value of an argument pointing to a file into the contents of that file.

Parameters:

Name Type Description Default
name str

Name of the argument. Used solely for logging purposes.

required
value str

The value of the argument. This is to be interpreted as a filename if it begins with a @ character.

required

Returns:

Type Description
str

The argument value expanded into the contents of the file, if the

str

argument value begins with a @ character. Otherwise, the argument

str

value is returned unchanged.

Raises:

Type Description
ValueError

If the argument value points to a file that doesn't exist, that cannot be read, or is too long(i.e. exceeds MAX_ARGUMENT_VALUE_SIZE bytes).

Source code in src/zenml/cli/utils.py
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
def expand_argument_value_from_file(name: str, value: str) -> str:
    """Expands the value of an argument pointing to a file into the contents of that file.

    Args:
        name: Name of the argument. Used solely for logging purposes.
        value: The value of the argument. This is to be interpreted as a
            filename if it begins with a `@` character.

    Returns:
        The argument value expanded into the contents of the file, if the
        argument value begins with a `@` character. Otherwise, the argument
        value is returned unchanged.

    Raises:
        ValueError: If the argument value points to a file that doesn't exist,
            that cannot be read, or is too long(i.e. exceeds
            `MAX_ARGUMENT_VALUE_SIZE` bytes).
    """
    if value.startswith("@@"):
        return value[1:]
    if not value.startswith("@"):
        return value
    filename = os.path.abspath(os.path.expanduser(value[1:]))
    logger.info(
        f"Expanding argument value `{name}` to contents of file `{filename}`."
    )
    if not os.path.isfile(filename):
        raise ValueError(
            f"Could not load argument '{name}' value: file "
            f"'{filename}' does not exist or is not readable."
        )
    try:
        if os.path.getsize(filename) > MAX_ARGUMENT_VALUE_SIZE:
            raise ValueError(
                f"Could not load argument '{name}' value: file "
                f"'{filename}' is too large (max size is "
                f"{MAX_ARGUMENT_VALUE_SIZE} bytes)."
            )

        with open(filename, "r") as f:
            return f.read()
    except OSError as e:
        raise ValueError(
            f"Could not load argument '{name}' value: file "
            f"'{filename}' could not be accessed: {str(e)}"
        )
format_integration_list(integrations: List[Tuple[str, Type[Integration]]]) -> List[Dict[str, str]]

Formats a list of integrations into a List of Dicts.

This list of dicts can then be printed in a table style using cli_utils.print_table.

Parameters:

Name Type Description Default
integrations List[Tuple[str, Type[Integration]]]

List of tuples containing the name of the integration and the integration metadata.

required

Returns:

Type Description
List[Dict[str, str]]

List of Dicts containing the name of the integration and the integration

Source code in src/zenml/cli/utils.py
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
def format_integration_list(
    integrations: List[Tuple[str, Type["Integration"]]],
) -> List[Dict[str, str]]:
    """Formats a list of integrations into a List of Dicts.

    This list of dicts can then be printed in a table style using
    cli_utils.print_table.

    Args:
        integrations: List of tuples containing the name of the integration and
            the integration metadata.

    Returns:
        List of Dicts containing the name of the integration and the integration
    """
    list_of_dicts = []
    for name, integration_impl in integrations:
        is_installed = integration_impl.check_installation()
        list_of_dicts.append(
            {
                "INSTALLED": ":white_check_mark:" if is_installed else ":x:",
                "INTEGRATION": name,
                "REQUIRED_PACKAGES": ", ".join(
                    integration_impl.get_requirements()
                ),
            }
        )
    return list_of_dicts
get_boolean_emoji(value: bool) -> str

Returns the emoji for displaying a boolean.

Parameters:

Name Type Description Default
value bool

The boolean value to display

required

Returns:

Type Description
str

The emoji for the boolean

Source code in src/zenml/cli/utils.py
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
def get_boolean_emoji(value: bool) -> str:
    """Returns the emoji for displaying a boolean.

    Args:
        value: The boolean value to display

    Returns:
        The emoji for the boolean
    """
    return ":white_heavy_check_mark:" if value else ":heavy_minus_sign:"
get_execution_status_emoji(status: ExecutionStatus) -> str

Returns an emoji representing the given execution status.

Parameters:

Name Type Description Default
status ExecutionStatus

The execution status to get the emoji for.

required

Returns:

Type Description
str

An emoji representing the given execution status.

Raises:

Type Description
RuntimeError

If the given execution status is not supported.

Source code in src/zenml/cli/utils.py
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
def get_execution_status_emoji(status: "ExecutionStatus") -> str:
    """Returns an emoji representing the given execution status.

    Args:
        status: The execution status to get the emoji for.

    Returns:
        An emoji representing the given execution status.

    Raises:
        RuntimeError: If the given execution status is not supported.
    """
    from zenml.enums import ExecutionStatus

    if status == ExecutionStatus.INITIALIZING:
        return ":hourglass_flowing_sand:"
    if status == ExecutionStatus.FAILED:
        return ":x:"
    if status == ExecutionStatus.RUNNING:
        return ":gear:"
    if status == ExecutionStatus.COMPLETED:
        return ":white_check_mark:"
    if status == ExecutionStatus.CACHED:
        return ":package:"
    raise RuntimeError(f"Unknown status: {status}")
get_package_information(package_names: Optional[List[str]] = None) -> Dict[str, str]

Get a dictionary of installed packages.

Parameters:

Name Type Description Default
package_names Optional[List[str]]

Specific package names to get the information for.

None

Returns:

Type Description
Dict[str, str]

A dictionary of the name:version for the package names passed in or all packages and their respective versions.

Source code in src/zenml/cli/utils.py
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
def get_package_information(
    package_names: Optional[List[str]] = None,
) -> Dict[str, str]:
    """Get a dictionary of installed packages.

    Args:
        package_names: Specific package names to get the information for.

    Returns:
        A dictionary of the name:version for the package names passed in or
            all packages and their respective versions.
    """
    import pkg_resources

    if package_names:
        return {
            pkg.key: pkg.version
            for pkg in pkg_resources.working_set
            if pkg.key in package_names
        }

    return {pkg.key: pkg.version for pkg in pkg_resources.working_set}
get_parsed_labels(labels: Optional[List[str]], allow_label_only: bool = False) -> Dict[str, Optional[str]]

Parse labels into a dictionary.

Parameters:

Name Type Description Default
labels Optional[List[str]]

The labels to parse.

required
allow_label_only bool

Whether to allow labels without values.

False

Returns:

Type Description
Dict[str, Optional[str]]

A dictionary of the metadata.

Raises:

Type Description
ValueError

If the labels are not in the correct format.

Source code in src/zenml/cli/utils.py
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
def get_parsed_labels(
    labels: Optional[List[str]], allow_label_only: bool = False
) -> Dict[str, Optional[str]]:
    """Parse labels into a dictionary.

    Args:
        labels: The labels to parse.
        allow_label_only: Whether to allow labels without values.

    Returns:
        A dictionary of the metadata.

    Raises:
        ValueError: If the labels are not in the correct format.
    """
    if not labels:
        return {}

    metadata_dict = {}
    for m in labels:
        try:
            key, value = m.split("=")
        except ValueError:
            if not allow_label_only:
                raise ValueError(
                    "Labels must be in the format key=value"
                ) from None
            key = m
            value = None
        metadata_dict[key] = value

    return metadata_dict
get_service_state_emoji(state: ServiceState) -> str

Get the rich emoji representing the operational state of a Service.

Parameters:

Name Type Description Default
state ServiceState

Service state to get emoji for.

required

Returns:

Type Description
str

String representing the emoji.

Source code in src/zenml/cli/utils.py
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
def get_service_state_emoji(state: "ServiceState") -> str:
    """Get the rich emoji representing the operational state of a Service.

    Args:
        state: Service state to get emoji for.

    Returns:
        String representing the emoji.
    """
    from zenml.enums import ServiceState

    if state == ServiceState.ACTIVE:
        return ":white_check_mark:"
    if state == ServiceState.INACTIVE:
        return ":pause_button:"
    if state == ServiceState.ERROR:
        return ":heavy_exclamation_mark:"
    if state == ServiceState.PENDING_STARTUP:
        return ":hourglass:"
    if state == ServiceState.SCALED_TO_ZERO:
        return ":chart_decreasing:"
    return ":hourglass_not_done:"
install_packages(packages: List[str], upgrade: bool = False, use_uv: bool = False) -> None

Installs pypi packages into the current environment with pip or uv.

When using with uv, a virtual environment is required.

Parameters:

Name Type Description Default
packages List[str]

List of packages to install.

required
upgrade bool

Whether to upgrade the packages if they are already installed.

False
use_uv bool

Whether to use uv for package installation.

False

Raises:

Type Description
e

If the package installation fails.

Source code in src/zenml/cli/utils.py
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
def install_packages(
    packages: List[str],
    upgrade: bool = False,
    use_uv: bool = False,
) -> None:
    """Installs pypi packages into the current environment with pip or uv.

    When using with `uv`, a virtual environment is required.

    Args:
        packages: List of packages to install.
        upgrade: Whether to upgrade the packages if they are already installed.
        use_uv: Whether to use uv for package installation.

    Raises:
        e: If the package installation fails.
    """
    if "neptune" in packages:
        declare(
            "Uninstalling legacy `neptune-client` package to avoid version "
            "conflicts with new `neptune` package..."
        )
        uninstall_package("neptune-client")

    if "prodigy" in packages:
        packages.remove("prodigy")
        declare(
            "The `prodigy` package should be installed manually using your "
            "license key. Please visit https://prodi.gy/docs/install for more "
            "information."
        )
    if not packages:
        # if user only tried to install prodigy, we can
        # just return without doing anything
        return

    if use_uv and not is_installed_in_python_environment("uv"):
        # If uv is installed globally, don't run as a python module
        command = []
    else:
        command = [sys.executable, "-m"]

    command += ["uv", "pip", "install"] if use_uv else ["pip", "install"]

    if upgrade:
        command += ["--upgrade"]

    command += packages

    if not IS_DEBUG_ENV:
        quiet_flag = "-q" if use_uv else "-qqq"
        command.append(quiet_flag)
        if not use_uv:
            command.append("--no-warn-conflicts")

    try:
        subprocess.check_call(command)
    except subprocess.CalledProcessError as e:
        if (
            use_uv
            and "Failed to locate a virtualenv or Conda environment" in str(e)
        ):
            error(
                "Failed to locate a virtualenv or Conda environment. "
                "When using uv, a virtual environment is required. "
                "Run `uv venv` to create a virtualenv and retry."
            )
        else:
            raise e
is_installed_in_python_environment(package: str) -> bool

Check if a package is installed in the current python environment.

Parameters:

Name Type Description Default
package str

The package to check.

required

Returns:

Type Description
bool

True if the package is installed, False otherwise.

Source code in src/zenml/cli/utils.py
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
def is_installed_in_python_environment(package: str) -> bool:
    """Check if a package is installed in the current python environment.

    Args:
        package: The package to check.

    Returns:
        True if the package is installed, False otherwise.
    """
    try:
        pkg_resources.get_distribution(package)
        return True
    except pkg_resources.DistributionNotFound:
        return False
is_jupyter_installed() -> bool

Checks if Jupyter notebook is installed.

Returns:

Name Type Description
bool bool

True if Jupyter notebook is installed, False otherwise.

Source code in src/zenml/cli/utils.py
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
def is_jupyter_installed() -> bool:
    """Checks if Jupyter notebook is installed.

    Returns:
        bool: True if Jupyter notebook is installed, False otherwise.
    """
    try:
        pkg_resources.get_distribution("notebook")
        return True
    except pkg_resources.DistributionNotFound:
        return False
is_pip_installed() -> bool

Check if pip is installed in the current environment.

Returns:

Type Description
bool

True if pip is installed, False otherwise.

Source code in src/zenml/cli/utils.py
1138
1139
1140
1141
1142
1143
1144
def is_pip_installed() -> bool:
    """Check if pip is installed in the current environment.

    Returns:
        True if pip is installed, False otherwise.
    """
    return is_installed_in_python_environment("pip")
is_sorted_or_filtered(ctx: click.Context) -> bool

Decides whether any filtering/sorting happens during a 'list' CLI call.

Parameters:

Name Type Description Default
ctx Context

the Click context of the CLI call.

required

Returns:

Type Description
bool

a boolean indicating whether any sorting or filtering parameters were

bool

used during the list CLI call.

Source code in src/zenml/cli/utils.py
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
def is_sorted_or_filtered(ctx: click.Context) -> bool:
    """Decides whether any filtering/sorting happens during a 'list' CLI call.

    Args:
        ctx: the Click context of the CLI call.

    Returns:
        a boolean indicating whether any sorting or filtering parameters were
        used during the list CLI call.
    """
    try:
        for _, source in ctx._parameter_source.items():
            if source != click.core.ParameterSource.DEFAULT:
                return True
        return False

    except Exception as e:
        logger.debug(
            f"There was a problem accessing the parameter source for "
            f'the "sort_by" option: {e}'
        )
        return False
is_uv_installed() -> bool

Check if uv is installed.

Returns:

Type Description
bool

True if uv is installed, False otherwise.

Source code in src/zenml/cli/utils.py
1129
1130
1131
1132
1133
1134
1135
def is_uv_installed() -> bool:
    """Check if uv is installed.

    Returns:
        True if uv is installed, False otherwise.
    """
    return shutil.which("uv") is not None
list_options(filter_model: Type[BaseFilter]) -> Callable[[F], F]

Create a decorator to generate the correct list of filter parameters.

The Outer decorator (list_options) is responsible for creating the inner decorator. This is necessary so that the type of FilterModel can be passed in as a parameter.

Based on the filter model, the inner decorator extracts all the click options that should be added to the decorated function (wrapper).

Parameters:

Name Type Description Default
filter_model Type[BaseFilter]

The filter model based on which to decorate the function.

required

Returns:

Type Description
Callable[[F], F]

The inner decorator.

Source code in src/zenml/cli/utils.py
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
def list_options(filter_model: Type[BaseFilter]) -> Callable[[F], F]:
    """Create a decorator to generate the correct list of filter parameters.

    The Outer decorator (`list_options`) is responsible for creating the inner
    decorator. This is necessary so that the type of `FilterModel` can be passed
    in as a parameter.

    Based on the filter model, the inner decorator extracts all the click
    options that should be added to the decorated function (wrapper).

    Args:
        filter_model: The filter model based on which to decorate the function.

    Returns:
        The inner decorator.
    """

    def inner_decorator(func: F) -> F:
        options = []
        data_type_descriptors = set()
        for k, v in filter_model.model_fields.items():
            if k not in filter_model.CLI_EXCLUDE_FIELDS:
                options.append(
                    click.option(
                        f"--{k}",
                        type=str,
                        default=v.default,
                        required=False,
                        multiple=_is_list_field(v),
                        help=create_filter_help_text(filter_model, k),
                    )
                )
            if k not in filter_model.FILTER_EXCLUDE_FIELDS:
                data_type_descriptors.add(
                    create_data_type_help_text(filter_model, k)
                )

        def wrapper(function: F) -> F:
            for option in reversed(options):
                function = option(function)
            return function

        func.__doc__ = (
            f"{func.__doc__} By default all filters are "
            f"interpreted as a check for equality. However advanced "
            f"filter operators can be used to tune the filtering by "
            f"writing the operator and separating it from the "
            f"query parameter with a colon `:`, e.g. "
            f"--field='operator:query'."
        )

        if data_type_descriptors:
            joined_data_type_descriptors = "\n\n".join(data_type_descriptors)

            func.__doc__ = (
                f"{func.__doc__} \n\n"
                f"\b Each datatype supports a specific "
                f"set of filter operations, here are the relevant "
                f"ones for the parameters of this command: \n\n"
                f"{joined_data_type_descriptors}"
            )

        return wrapper(func)

    return inner_decorator
multi_choice_prompt(object_type: str, choices: List[List[Any]], headers: List[str], prompt_text: str, allow_zero_be_a_new_object: bool = False, default_choice: Optional[str] = None) -> Optional[int]

Prompts the user to select a choice from a list of choices.

Parameters:

Name Type Description Default
object_type str

The type of the object

required
choices List[List[Any]]

The list of choices

required
prompt_text str

The prompt text

required
headers List[str]

The list of headers.

required
allow_zero_be_a_new_object bool

Whether to allow zero as a new object

False
default_choice Optional[str]

The default choice

None

Returns:

Type Description
Optional[int]

The selected choice index or None for new object

Raises:

Type Description
RuntimeError

If no choice is made.

Source code in src/zenml/cli/utils.py
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
def multi_choice_prompt(
    object_type: str,
    choices: List[List[Any]],
    headers: List[str],
    prompt_text: str,
    allow_zero_be_a_new_object: bool = False,
    default_choice: Optional[str] = None,
) -> Optional[int]:
    """Prompts the user to select a choice from a list of choices.

    Args:
        object_type: The type of the object
        choices: The list of choices
        prompt_text: The prompt text
        headers: The list of headers.
        allow_zero_be_a_new_object: Whether to allow zero as a new object
        default_choice: The default choice

    Returns:
        The selected choice index or None for new object

    Raises:
        RuntimeError: If no choice is made.
    """
    table = Table(
        title=f"Available {object_type}",
        show_header=True,
        border_style=None,
        expand=True,
        show_lines=True,
    )
    table.add_column("Choice", justify="left", width=1)
    for h in headers:
        table.add_column(
            h.replace("_", " ").capitalize(), justify="left", width=10
        )

    i_shift = 0
    if allow_zero_be_a_new_object:
        i_shift = 1
        table.add_row(
            "[0]",
            *([f"Create a new {object_type}"] * len(headers)),
        )
    for i, one_choice in enumerate(choices):
        table.add_row(f"[{i + i_shift}]", *[str(x) for x in one_choice])
    Console().print(table)

    selected = Prompt.ask(
        prompt_text,
        choices=[str(i) for i in range(0, len(choices) + 1)],
        default=default_choice,
        show_choices=False,
    )
    if selected is None:
        raise RuntimeError(f"No {object_type} was selected")

    if selected == "0" and allow_zero_be_a_new_object:
        return None
    else:
        return int(selected) - i_shift
parse_name_and_extra_arguments(args: List[str], expand_args: bool = False, name_mandatory: bool = True) -> Tuple[Optional[str], Dict[str, str]]

Parse a name and extra arguments from the CLI.

This is a utility function used to parse a variable list of optional CLI arguments of the form --key=value that must also include one mandatory free-form name argument. There is no restriction as to the order of the arguments.

Examples:

>>> parse_name_and_extra_arguments(['foo']])
('foo', {})
>>> parse_name_and_extra_arguments(['foo', '--bar=1'])
('foo', {'bar': '1'})
>>> parse_name_and_extra_arguments(['--bar=1', 'foo', '--baz=2'])
('foo', {'bar': '1', 'baz': '2'})
>>> parse_name_and_extra_arguments(['--bar=1'])
Traceback (most recent call last):
    ...
    ValueError: Missing required argument: name

Parameters:

Name Type Description Default
args List[str]

A list of command line arguments from the CLI.

required
expand_args bool

Whether to expand argument values into the contents of the files they may be pointing at using the special @ character.

False
name_mandatory bool

Whether the name argument is mandatory.

True

Returns:

Type Description
Tuple[Optional[str], Dict[str, str]]

The name and a dict of parsed args.

Source code in src/zenml/cli/utils.py
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
def parse_name_and_extra_arguments(
    args: List[str],
    expand_args: bool = False,
    name_mandatory: bool = True,
) -> Tuple[Optional[str], Dict[str, str]]:
    """Parse a name and extra arguments from the CLI.

    This is a utility function used to parse a variable list of optional CLI
    arguments of the form `--key=value` that must also include one mandatory
    free-form name argument. There is no restriction as to the order of the
    arguments.

    Examples:
        >>> parse_name_and_extra_arguments(['foo']])
        ('foo', {})
        >>> parse_name_and_extra_arguments(['foo', '--bar=1'])
        ('foo', {'bar': '1'})
        >>> parse_name_and_extra_arguments(['--bar=1', 'foo', '--baz=2'])
        ('foo', {'bar': '1', 'baz': '2'})
        >>> parse_name_and_extra_arguments(['--bar=1'])
        Traceback (most recent call last):
            ...
            ValueError: Missing required argument: name

    Args:
        args: A list of command line arguments from the CLI.
        expand_args: Whether to expand argument values into the contents of the
            files they may be pointing at using the special `@` character.
        name_mandatory: Whether the name argument is mandatory.

    Returns:
        The name and a dict of parsed args.
    """
    name: Optional[str] = None
    # The name was not supplied as the first argument, we have to
    # search the other arguments for the name.
    for i, arg in enumerate(args):
        if not arg:
            # Skip empty arguments.
            continue
        if arg.startswith("--"):
            continue
        name = args.pop(i)
        break
    else:
        if name_mandatory:
            error(
                "A name must be supplied. Please see the command help for more "
                "information."
            )

    message = (
        "Please provide args with a proper "
        "identifier as the key and the following structure: "
        '--custom_argument="value"'
    )
    args_dict: Dict[str, str] = {}
    for a in args:
        if not a:
            # Skip empty arguments.
            continue
        if not a.startswith("--") or "=" not in a:
            error(f"Invalid argument: '{a}'. {message}")
        key, value = a[2:].split("=", maxsplit=1)
        if not key.isidentifier():
            error(f"Invalid argument: '{a}'. {message}")
        args_dict[key] = value

    if expand_args:
        args_dict = {
            k: expand_argument_value_from_file(k, v)
            for k, v in args_dict.items()
        }

    return name, args_dict
parse_unknown_component_attributes(args: List[str]) -> List[str]

Parse unknown options from the CLI.

Parameters:

Name Type Description Default
args List[str]

A list of strings from the CLI.

required

Returns:

Type Description
List[str]

List of parsed args.

Source code in src/zenml/cli/utils.py
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
def parse_unknown_component_attributes(args: List[str]) -> List[str]:
    """Parse unknown options from the CLI.

    Args:
        args: A list of strings from the CLI.

    Returns:
        List of parsed args.
    """
    warning_message = (
        "Please provide args with a proper "
        "identifier as the key and the following structure: "
        "--custom_attribute"
    )

    assert all(a.startswith("--") for a in args), warning_message
    p_args = [a.lstrip("-") for a in args]
    assert all(v.isidentifier() for v in p_args), warning_message
    return p_args
pretty_print_model_deployer(model_services: List[BaseService], model_deployer: BaseModelDeployer) -> None

Given a list of served_models, print all associated key-value pairs.

Parameters:

Name Type Description Default
model_services List[BaseService]

list of model deployment services

required
model_deployer BaseModelDeployer

Active model deployer

required
Source code in src/zenml/cli/utils.py
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
def pretty_print_model_deployer(
    model_services: List["BaseService"], model_deployer: "BaseModelDeployer"
) -> None:
    """Given a list of served_models, print all associated key-value pairs.

    Args:
        model_services: list of model deployment services
        model_deployer: Active model deployer
    """
    model_service_dicts = []
    for model_service in model_services:
        dict_uuid = str(model_service.uuid)
        dict_pl_name = model_service.config.pipeline_name
        dict_pl_stp_name = model_service.config.pipeline_step_name
        dict_model_name = model_service.config.model_name
        type = model_service.SERVICE_TYPE.type
        flavor = model_service.SERVICE_TYPE.flavor
        model_service_dicts.append(
            {
                "STATUS": get_service_state_emoji(model_service.status.state),
                "UUID": dict_uuid,
                "TYPE": type,
                "FLAVOR": flavor,
                "PIPELINE_NAME": dict_pl_name,
                "PIPELINE_STEP_NAME": dict_pl_stp_name,
                "MODEL_NAME": dict_model_name,
            }
        )
    print_table(
        model_service_dicts, UUID=table.Column(header="UUID", min_width=36)
    )
pretty_print_model_version_details(model_version: RegistryModelVersion) -> None

Given a model_version, print all associated key-value pairs.

Parameters:

Name Type Description Default
model_version RegistryModelVersion

model version

required
Source code in src/zenml/cli/utils.py
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
def pretty_print_model_version_details(
    model_version: "RegistryModelVersion",
) -> None:
    """Given a model_version, print all associated key-value pairs.

    Args:
        model_version: model version
    """
    title_ = f"Properties of model `{model_version.registered_model.name}` version `{model_version.version}`"

    rich_table = table.Table(
        box=box.HEAVY_EDGE,
        title=title_,
        show_lines=True,
    )
    rich_table.add_column("MODEL VERSION PROPERTY", overflow="fold")
    rich_table.add_column("VALUE", overflow="fold")
    model_version_info = {
        "REGISTERED_MODEL_NAME": model_version.registered_model.name,
        "VERSION": model_version.version,
        "VERSION_DESCRIPTION": model_version.description,
        "CREATED_AT": (
            str(model_version.created_at)
            if model_version.created_at
            else "N/A"
        ),
        "UPDATED_AT": (
            str(model_version.last_updated_at)
            if model_version.last_updated_at
            else "N/A"
        ),
        "METADATA": (
            model_version.metadata.model_dump()
            if model_version.metadata
            else {}
        ),
        "MODEL_SOURCE_URI": model_version.model_source_uri,
        "STAGE": model_version.stage.value,
    }

    for item in model_version_info.items():
        rich_table.add_row(*[str(elem) for elem in item])

    # capitalize entries in first column
    rich_table.columns[0]._cells = [
        component.upper()  # type: ignore[union-attr]
        for component in rich_table.columns[0]._cells
    ]
    console.print(rich_table)
pretty_print_model_version_table(model_versions: List[RegistryModelVersion]) -> None

Given a list of model_versions, print all associated key-value pairs.

Parameters:

Name Type Description Default
model_versions List[RegistryModelVersion]

list of model versions

required
Source code in src/zenml/cli/utils.py
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
def pretty_print_model_version_table(
    model_versions: List["RegistryModelVersion"],
) -> None:
    """Given a list of model_versions, print all associated key-value pairs.

    Args:
        model_versions: list of model versions
    """
    model_version_dicts = [
        {
            "NAME": model_version.registered_model.name,
            "MODEL_VERSION": model_version.version,
            "VERSION_DESCRIPTION": model_version.description,
            "METADATA": (
                model_version.metadata.model_dump()
                if model_version.metadata
                else {}
            ),
        }
        for model_version in model_versions
    ]
    print_table(
        model_version_dicts, UUID=table.Column(header="UUID", min_width=36)
    )
pretty_print_registered_model_table(registered_models: List[RegisteredModel]) -> None

Given a list of registered_models, print all associated key-value pairs.

Parameters:

Name Type Description Default
registered_models List[RegisteredModel]

list of registered models

required
Source code in src/zenml/cli/utils.py
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
def pretty_print_registered_model_table(
    registered_models: List["RegisteredModel"],
) -> None:
    """Given a list of registered_models, print all associated key-value pairs.

    Args:
        registered_models: list of registered models
    """
    registered_model_dicts = [
        {
            "NAME": registered_model.name,
            "DESCRIPTION": registered_model.description,
            "METADATA": registered_model.metadata,
        }
        for registered_model in registered_models
    ]
    print_table(
        registered_model_dicts, UUID=table.Column(header="UUID", min_width=36)
    )
pretty_print_secret(secret: Dict[str, str], hide_secret: bool = True) -> None

Print all key-value pairs associated with a secret.

Parameters:

Name Type Description Default
secret Dict[str, str]

Secret values to print.

required
hide_secret bool

boolean that configures if the secret values are shown on the CLI

True
Source code in src/zenml/cli/utils.py
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
def pretty_print_secret(
    secret: Dict[str, str],
    hide_secret: bool = True,
) -> None:
    """Print all key-value pairs associated with a secret.

    Args:
        secret: Secret values to print.
        hide_secret: boolean that configures if the secret values are shown
            on the CLI
    """
    title: Optional[str] = None

    def get_secret_value(value: Any) -> str:
        if value is None:
            return ""
        return "***" if hide_secret else str(value)

    stack_dicts = [
        {
            "SECRET_KEY": key,
            "SECRET_VALUE": get_secret_value(value),
        }
        for key, value in secret.items()
    ]

    print_table(stack_dicts, title=title)
print_components_table(client: Client, component_type: StackComponentType, components: Sequence[ComponentResponse], show_active: bool = False) -> None

Prints a table with configuration options for a list of stack components.

If a component is active (its name matches the active_component_name), it will be highlighted in a separate table column.

Parameters:

Name Type Description Default
client Client

Instance of the Repository singleton

required
component_type StackComponentType

Type of stack component

required
components Sequence[ComponentResponse]

List of stack components to print.

required
show_active bool

Flag to decide whether to append the active stack component on the top of the list.

False
Source code in src/zenml/cli/utils.py
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
def print_components_table(
    client: "Client",
    component_type: StackComponentType,
    components: Sequence["ComponentResponse"],
    show_active: bool = False,
) -> None:
    """Prints a table with configuration options for a list of stack components.

    If a component is active (its name matches the `active_component_name`),
    it will be highlighted in a separate table column.

    Args:
        client: Instance of the Repository singleton
        component_type: Type of stack component
        components: List of stack components to print.
        show_active: Flag to decide whether to append the active stack component
            on the top of the list.
    """
    display_name = _component_display_name(component_type, plural=True)

    if len(components) == 0:
        warning(f"No {display_name} registered.")
        return

    active_stack = client.active_stack_model
    active_component = None
    if component_type in active_stack.components.keys():
        active_components = active_stack.components[component_type]
        active_component = active_components[0] if active_components else None

    components = list(components)
    if show_active and active_component is not None:
        if active_component.id not in [c.id for c in components]:
            components.append(active_component)

        components = [c for c in components if c.id == active_component.id] + [
            c for c in components if c.id != active_component.id
        ]

    configurations = []
    for component in components:
        is_active = False

        if active_component is not None:
            is_active = component.id == active_component.id

        component_config = {
            "ACTIVE": ":point_right:" if is_active else "",
            "NAME": component.name,
            "COMPONENT ID": component.id,
            "FLAVOR": component.flavor_name,
            "OWNER": f"{component.user.name if component.user else '-'}",
        }
        configurations.append(component_config)
    print_table(configurations)
print_debug_stack() -> None

Print active stack and components for debugging purposes.

Source code in src/zenml/cli/utils.py
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
def print_debug_stack() -> None:
    """Print active stack and components for debugging purposes."""
    from zenml.client import Client

    client = Client()
    stack = client.get_stack()

    declare("\nCURRENT STACK\n", bold=True)
    console.print(f"Name: {stack.name}")
    console.print(f"ID: {str(stack.id)}")
    if stack.user and stack.user.name and stack.user.id:  # mypy check
        console.print(f"User: {stack.user.name} / {str(stack.user.id)}")

    for component_type, components in stack.components.items():
        component = components[0]
        component_response = client.get_stack_component(
            name_id_or_prefix=component.id, component_type=component.type
        )
        declare(
            f"\n{component.type.value.upper()}: {component.name}\n", bold=True
        )
        console.print(f"Name: {component.name}")
        console.print(f"ID: {str(component.id)}")
        console.print(f"Type: {component.type.value}")
        console.print(f"Flavor: {component.flavor_name}")

        flavor = Flavor.from_model(component.flavor)
        config = flavor.config_class(**component.configuration)

        console.print(f"Configuration: {_scrub_secret(config)}")
        if (
            component_response.user
            and component_response.user.name
            and component_response.user.id
        ):  # mypy check
            console.print(
                f"User: {component_response.user.name} / {str(component_response.user.id)}"
            )
print_flavor_list(flavors: Page[FlavorResponse]) -> None

Prints the list of flavors.

Parameters:

Name Type Description Default
flavors Page[FlavorResponse]

List of flavors to print.

required
Source code in src/zenml/cli/utils.py
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
def print_flavor_list(flavors: Page["FlavorResponse"]) -> None:
    """Prints the list of flavors.

    Args:
        flavors: List of flavors to print.
    """
    flavor_table = []
    for f in flavors.items:
        flavor_table.append(
            {
                "FLAVOR": f.name,
                "INTEGRATION": f.integration,
                "SOURCE": f.source,
                "CONNECTOR TYPE": f.connector_type or "",
                "RESOURCE TYPE": f.connector_resource_type or "",
            }
        )

    print_table(flavor_table)
print_list_items(list_items: List[str], column_title: str) -> None

Prints the configuration options of a stack.

Parameters:

Name Type Description Default
list_items List[str]

List of items

required
column_title str

Title of the column

required
Source code in src/zenml/cli/utils.py
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
def print_list_items(list_items: List[str], column_title: str) -> None:
    """Prints the configuration options of a stack.

    Args:
        list_items: List of items
        column_title: Title of the column
    """
    rich_table = table.Table(
        box=box.HEAVY_EDGE,
        show_lines=True,
    )
    rich_table.add_column(column_title.upper(), overflow="fold")
    list_items.sort()
    for item in list_items:
        rich_table.add_row(item)

    console.print(rich_table)
print_markdown(text: str) -> None

Prints a string as markdown.

Parameters:

Name Type Description Default
text str

Markdown string to be printed.

required
Source code in src/zenml/cli/utils.py
189
190
191
192
193
194
195
196
def print_markdown(text: str) -> None:
    """Prints a string as markdown.

    Args:
        text: Markdown string to be printed.
    """
    markdown_text = Markdown(text)
    console.print(markdown_text)
print_markdown_with_pager(text: str) -> None

Prints a string as markdown with a pager.

Parameters:

Name Type Description Default
text str

Markdown string to be printed.

required
Source code in src/zenml/cli/utils.py
199
200
201
202
203
204
205
206
207
def print_markdown_with_pager(text: str) -> None:
    """Prints a string as markdown with a pager.

    Args:
        text: Markdown string to be printed.
    """
    markdown_text = Markdown(text)
    with console.pager():
        console.print(markdown_text)
print_model_url(url: Optional[str]) -> None

Pretty prints a given URL on the CLI.

Parameters:

Name Type Description Default
url Optional[str]

optional str, the URL to display.

required
Source code in src/zenml/cli/utils.py
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
def print_model_url(url: Optional[str]) -> None:
    """Pretty prints a given URL on the CLI.

    Args:
        url: optional str, the URL to display.
    """
    if url:
        declare(f"Dashboard URL: {url}")
    else:
        warning(
            "You can display various ZenML entities including pipelines, "
            "runs, stacks and much more on the ZenML Dashboard. "
            "You can try it locally, by running `zenml login --local`, or "
            "remotely, by deploying ZenML on the infrastructure of your choice."
        )
print_page_info(page: Page[T]) -> None

Print all page information showing the number of items and pages.

Parameters:

Name Type Description Default
page Page[T]

The page to print the information for.

required
Source code in src/zenml/cli/utils.py
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
def print_page_info(page: Page[T]) -> None:
    """Print all page information showing the number of items and pages.

    Args:
        page: The page to print the information for.
    """
    declare(
        f"Page `({page.index}/{page.total_pages})`, `{page.total}` items "
        f"found for the applied filters."
    )
print_pipeline_runs_table(pipeline_runs: Sequence[PipelineRunResponse]) -> None

Print a prettified list of all pipeline runs supplied to this method.

Parameters:

Name Type Description Default
pipeline_runs Sequence[PipelineRunResponse]

List of pipeline runs

required
Source code in src/zenml/cli/utils.py
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
def print_pipeline_runs_table(
    pipeline_runs: Sequence["PipelineRunResponse"],
) -> None:
    """Print a prettified list of all pipeline runs supplied to this method.

    Args:
        pipeline_runs: List of pipeline runs
    """
    runs_dicts = []
    for pipeline_run in pipeline_runs:
        if pipeline_run.user:
            user_name = pipeline_run.user.name
        else:
            user_name = "-"

        if pipeline_run.pipeline is None:
            pipeline_name = "unlisted"
        else:
            pipeline_name = pipeline_run.pipeline.name
        if pipeline_run.stack is None:
            stack_name = "[DELETED]"
        else:
            stack_name = pipeline_run.stack.name
        status = pipeline_run.status
        status_emoji = get_execution_status_emoji(status)
        run_dict = {
            "PIPELINE NAME": pipeline_name,
            "RUN NAME": pipeline_run.name,
            "RUN ID": pipeline_run.id,
            "STATUS": status_emoji,
            "STACK": stack_name,
            "OWNER": user_name,
        }
        runs_dicts.append(run_dict)
    print_table(runs_dicts)
print_pydantic_model(title: str, model: BaseModel, exclude_columns: Optional[AbstractSet[str]] = None, columns: Optional[AbstractSet[str]] = None) -> None

Prints a single Pydantic model in a table.

Parameters:

Name Type Description Default
title str

Title of the table.

required
model BaseModel

Pydantic model that will be represented as a row in the table.

required
exclude_columns Optional[AbstractSet[str]]

Optionally specify columns to exclude.

None
columns Optional[AbstractSet[str]]

Optionally specify subset and order of columns to display.

None
Source code in src/zenml/cli/utils.py
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
def print_pydantic_model(
    title: str,
    model: BaseModel,
    exclude_columns: Optional[AbstractSet[str]] = None,
    columns: Optional[AbstractSet[str]] = None,
) -> None:
    """Prints a single Pydantic model in a table.

    Args:
        title: Title of the table.
        model: Pydantic model that will be represented as a row in the table.
        exclude_columns: Optionally specify columns to exclude.
        columns: Optionally specify subset and order of columns to display.
    """
    rich_table = table.Table(
        box=box.HEAVY_EDGE,
        title=title,
        show_lines=True,
    )
    rich_table.add_column("PROPERTY", overflow="fold")
    rich_table.add_column("VALUE", overflow="fold")

    # TODO: This uses the same _dictify function up in the print_pydantic_models
    #   function. This 2 can be generalized.
    if exclude_columns is None:
        exclude_columns = set()

    if not columns:
        if isinstance(model, BaseIdentifiedResponse):
            include_columns = ["id"]

            if "name" in type(model).model_fields:
                include_columns.append("name")

            include_columns.extend(
                [
                    k
                    for k in type(model.get_body()).model_fields.keys()
                    if k not in exclude_columns
                ]
            )

            if model.metadata is not None:
                include_columns.extend(
                    [
                        k
                        for k in type(model.get_metadata()).model_fields.keys()
                        if k not in exclude_columns
                    ]
                )

        else:
            include_columns = [
                k
                for k in model.model_dump().keys()
                if k not in exclude_columns
            ]
    else:
        include_columns = list(columns)

    items: Dict[str, Any] = {}

    for k in include_columns:
        value = getattr(model, k)
        if isinstance(value, BaseIdentifiedResponse):
            if "name" in type(value).model_fields:
                items[k] = str(getattr(value, "name"))
            else:
                items[k] = str(value.id)

        # If it is a list of `BaseResponse`s access each Model within
        #  the list and extract either name or id
        elif isinstance(value, list):
            for v in value:
                if isinstance(v, BaseIdentifiedResponse):
                    if "name" in type(v).model_fields:
                        items.setdefault(k, []).append(str(getattr(v, "name")))
                    else:
                        items.setdefault(k, []).append(str(v.id))

                items[k] = str(items[k])
        elif isinstance(value, Set) or isinstance(value, List):
            items[k] = str([str(v) for v in value])
        else:
            items[k] = str(value)

    for k, v in items.items():
        rich_table.add_row(str(k).upper(), v)

    console.print(rich_table)
print_pydantic_models(models: Union[Page[T], List[T]], columns: Optional[List[str]] = None, exclude_columns: Optional[List[str]] = None, active_models: Optional[List[T]] = None, show_active: bool = False, rename_columns: Dict[str, str] = {}) -> None

Prints the list of Pydantic models in a table.

Parameters:

Name Type Description Default
models Union[Page[T], List[T]]

List of Pydantic models that will be represented as a row in the table.

required
columns Optional[List[str]]

Optionally specify subset and order of columns to display.

None
exclude_columns Optional[List[str]]

Optionally specify columns to exclude. (Note: columns takes precedence over exclude_columns.)

None
active_models Optional[List[T]]

Optional list of active models of the given type T.

None
show_active bool

Flag to decide whether to append the active model on the top of the list.

False
rename_columns Dict[str, str]

Optional dictionary to rename columns.

{}
Source code in src/zenml/cli/utils.py
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
def print_pydantic_models(
    models: Union[Page[T], List[T]],
    columns: Optional[List[str]] = None,
    exclude_columns: Optional[List[str]] = None,
    active_models: Optional[List[T]] = None,
    show_active: bool = False,
    rename_columns: Dict[str, str] = {},
) -> None:
    """Prints the list of Pydantic models in a table.

    Args:
        models: List of Pydantic models that will be represented as a row in
            the table.
        columns: Optionally specify subset and order of columns to display.
        exclude_columns: Optionally specify columns to exclude. (Note: `columns`
            takes precedence over `exclude_columns`.)
        active_models: Optional list of active models of the given type T.
        show_active: Flag to decide whether to append the active model on the
            top of the list.
        rename_columns: Optional dictionary to rename columns.
    """
    if exclude_columns is None:
        exclude_columns = list()

    show_active_column = True
    if active_models is None:
        show_active_column = False
        active_models = list()

    def __dictify(model: T) -> Dict[str, str]:
        """Helper function to map over the list to turn Models into dicts.

        Args:
            model: Pydantic model.

        Returns:
            Dict of model attributes.
        """
        # Explicitly defined columns take precedence over exclude columns
        if not columns:
            if isinstance(model, BaseIdentifiedResponse):
                include_columns = ["id"]

                if "name" in type(model).model_fields:
                    include_columns.append("name")

                include_columns.extend(
                    [
                        k
                        for k in type(model.get_body()).model_fields.keys()
                        if k not in exclude_columns
                    ]
                )

                if model.metadata is not None:
                    include_columns.extend(
                        [
                            k
                            for k in type(
                                model.get_metadata()
                            ).model_fields.keys()
                            if k not in exclude_columns
                        ]
                    )

            else:
                include_columns = [
                    k
                    for k in model.model_dump().keys()
                    if k not in exclude_columns
                ]
        else:
            include_columns = columns

        items: Dict[str, Any] = {}

        for k in include_columns:
            value = getattr(model, k)
            if k in rename_columns:
                k = rename_columns[k]
            # In case the response model contains nested `BaseResponse`s
            #  we want to attempt to represent them by name, if they contain
            #  such a field, else the id is used
            if isinstance(value, BaseIdentifiedResponse):
                if "name" in type(value).model_fields:
                    items[k] = str(getattr(value, "name"))
                else:
                    items[k] = str(value.id)

            # If it is a list of `BaseResponse`s access each Model within
            #  the list and extract either name or id
            elif isinstance(value, list):
                for v in value:
                    if isinstance(v, BaseIdentifiedResponse):
                        if "name" in type(v).model_fields:
                            items.setdefault(k, []).append(
                                str(getattr(v, "name"))
                            )
                        else:
                            items.setdefault(k, []).append(str(v.id))
            elif isinstance(value, Set) or isinstance(value, List):
                items[k] = [str(v) for v in value]
            else:
                items[k] = str(value)

        # prepend an active marker if a function to mark active was passed
        if not active_models and not show_active:
            return items

        marker = "active"
        if marker in items:
            marker = "current"
        if active_models is not None and show_active_column:
            return {
                marker: (
                    ":point_right:"
                    if any(model.id == a.id for a in active_models)
                    else ""
                ),
                **items,
            }

        return items

    active_ids = [a.id for a in active_models]
    if isinstance(models, Page):
        table_items = list(models.items)

        if show_active:
            for active_model in active_models:
                if active_model.id not in [i.id for i in table_items]:
                    table_items.append(active_model)

            table_items = [i for i in table_items if i.id in active_ids] + [
                i for i in table_items if i.id not in active_ids
            ]

        print_table([__dictify(model) for model in table_items])
        print_page_info(models)
    else:
        table_items = list(models)

        if show_active:
            for active_model in active_models:
                if active_model.id not in [i.id for i in table_items]:
                    table_items.append(active_model)

            table_items = [i for i in table_items if i.id in active_ids] + [
                i for i in table_items if i.id not in active_ids
            ]

        print_table([__dictify(model) for model in table_items])
print_served_model_configuration(model_service: BaseService, model_deployer: BaseModelDeployer) -> None

Prints the configuration of a model_service.

Parameters:

Name Type Description Default
model_service BaseService

Specific service instance to

required
model_deployer BaseModelDeployer

Active model deployer

required
Source code in src/zenml/cli/utils.py
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
def print_served_model_configuration(
    model_service: "BaseService", model_deployer: "BaseModelDeployer"
) -> None:
    """Prints the configuration of a model_service.

    Args:
        model_service: Specific service instance to
        model_deployer: Active model deployer
    """
    title_ = f"Properties of Served Model {model_service.uuid}"

    rich_table = table.Table(
        box=box.HEAVY_EDGE,
        title=title_,
        show_lines=True,
    )
    rich_table.add_column("MODEL SERVICE PROPERTY", overflow="fold")
    rich_table.add_column("VALUE", overflow="fold")

    # Get implementation specific info
    served_model_info = model_deployer.get_model_server_info(model_service)

    served_model_info = {
        **served_model_info,
        "UUID": str(model_service.uuid),
        "STATUS": get_service_state_emoji(model_service.status.state),
        "TYPE": model_service.SERVICE_TYPE.type,
        "FLAVOR": model_service.SERVICE_TYPE.flavor,
        "STATUS_MESSAGE": model_service.status.last_error,
        "PIPELINE_NAME": model_service.config.pipeline_name,
        "PIPELINE_STEP_NAME": model_service.config.pipeline_step_name,
    }

    # Sort fields alphabetically
    sorted_items = {k: v for k, v in sorted(served_model_info.items())}

    for item in sorted_items.items():
        rich_table.add_row(*[str(elem) for elem in item])

    # capitalize entries in first column
    rich_table.columns[0]._cells = [
        component.upper()  # type: ignore[union-attr]
        for component in rich_table.columns[0]._cells
    ]
    console.print(rich_table)
print_service_connector_auth_method(auth_method: AuthenticationMethodModel, title: str = '', heading: str = '#', footer: str = '---', print: bool = True) -> str

Prints details for a service connector authentication method.

Parameters:

Name Type Description Default
auth_method AuthenticationMethodModel

Service connector authentication method to print.

required
title str

Markdown title to use for the authentication method details.

''
heading str

Markdown heading to use for the authentication method title.

'#'
footer str

Markdown footer to use for the authentication method description.

'---'
print bool

Whether to print the authentication method details to the console or just return the message as a string.

True

Returns:

Type Description
str

The MarkDown authentication method details as a string.

Source code in src/zenml/cli/utils.py
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
def print_service_connector_auth_method(
    auth_method: "AuthenticationMethodModel",
    title: str = "",
    heading: str = "#",
    footer: str = "---",
    print: bool = True,
) -> str:
    """Prints details for a service connector authentication method.

    Args:
        auth_method: Service connector authentication method to print.
        title: Markdown title to use for the authentication method details.
        heading: Markdown heading to use for the authentication method title.
        footer: Markdown footer to use for the authentication method description.
        print: Whether to print the authentication method details to the console
            or just return the message as a string.

    Returns:
        The MarkDown authentication method details as a string.
    """
    message = f"{title}\n" if title else ""
    emoji = Emoji("lock")
    message += (
        f"{heading} {emoji} {auth_method.name} "
        f"(auth method: {auth_method.auth_method})\n"
    )
    message += (
        f"**Supports issuing temporary credentials**: "
        f"{auth_method.supports_temporary_credentials()}\n\n"
    )
    message += f"{auth_method.description}\n"

    attributes: List[str] = []
    for attr_name, attr_schema in auth_method.config_schema.get(
        "properties", {}
    ).items():
        title = attr_schema.get("title", "<no description>")
        attr_type = attr_schema.get("type", "string")
        required = attr_name in auth_method.config_schema.get("required", [])
        hidden = attr_schema.get("format", "") == "password"
        subtitles: List[str] = []
        subtitles.append(attr_type)
        if hidden:
            subtitles.append("secret")
        if required:
            subtitles.append("required")
        else:
            subtitles.append("optional")

        description = f"- `{attr_name}`"
        if subtitles:
            description = f"{description} {{{', '.join(subtitles)}}}"
        description = f"{description}: _{title}_"
        attributes.append(description)
    if attributes:
        message += "\n**Attributes**:\n"
        message += "\n".join(attributes) + "\n"

    message += footer

    if print:
        console.print(Markdown(message), justify="left", width=80)

    return message
print_service_connector_configuration(connector: Union[ServiceConnectorResponse, ServiceConnectorRequest], active_status: bool, show_secrets: bool) -> None

Prints the configuration options of a service connector.

Parameters:

Name Type Description Default
connector Union[ServiceConnectorResponse, ServiceConnectorRequest]

The service connector to print.

required
active_status bool

Whether the connector is active.

required
show_secrets bool

Whether to show secrets.

required
Source code in src/zenml/cli/utils.py
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
def print_service_connector_configuration(
    connector: Union["ServiceConnectorResponse", "ServiceConnectorRequest"],
    active_status: bool,
    show_secrets: bool,
) -> None:
    """Prints the configuration options of a service connector.

    Args:
        connector: The service connector to print.
        active_status: Whether the connector is active.
        show_secrets: Whether to show secrets.
    """
    from uuid import UUID

    from zenml.models import ServiceConnectorResponse

    if connector.user:
        if isinstance(connector.user, UUID):
            user_name = str(connector.user)
        else:
            user_name = connector.user.name
    else:
        user_name = "-"

    if isinstance(connector, ServiceConnectorResponse):
        declare(
            f"Service connector '{connector.name}' of type "
            f"'{connector.type}' with id '{connector.id}' is owned by "
            f"user '{user_name}'."
        )
    else:
        declare(
            f"Service connector '{connector.name}' of type '{connector.type}'."
        )

    title_ = f"'{connector.name}' {connector.type} Service Connector Details"

    if active_status:
        title_ += " (ACTIVE)"
    rich_table = table.Table(
        box=box.HEAVY_EDGE,
        title=title_,
        show_lines=True,
    )
    rich_table.add_column("PROPERTY")
    rich_table.add_column("VALUE", overflow="fold")

    if connector.expiration_seconds is None:
        expiration = "N/A"
    else:
        expiration = str(connector.expiration_seconds) + "s"

    if isinstance(connector, ServiceConnectorResponse):
        properties = {
            "ID": connector.id,
            "NAME": connector.name,
            "TYPE": connector.emojified_connector_type,
            "AUTH METHOD": connector.auth_method,
            "RESOURCE TYPES": ", ".join(connector.emojified_resource_types),
            "RESOURCE NAME": connector.resource_id or "<multiple>",
            "SESSION DURATION": expiration,
            "EXPIRES IN": (
                expires_in(
                    connector.expires_at,
                    ":name_badge: Expired!",
                    connector.expires_skew_tolerance,
                )
                if connector.expires_at
                else "N/A"
            ),
            "EXPIRES_SKEW_TOLERANCE": (
                connector.expires_skew_tolerance
                if connector.expires_skew_tolerance
                else "N/A"
            ),
            "OWNER": user_name,
            "CREATED_AT": connector.created,
            "UPDATED_AT": connector.updated,
        }
    else:
        properties = {
            "NAME": connector.name,
            "TYPE": connector.emojified_connector_type,
            "AUTH METHOD": connector.auth_method,
            "RESOURCE TYPES": ", ".join(connector.emojified_resource_types),
            "RESOURCE NAME": connector.resource_id or "<multiple>",
            "SESSION DURATION": expiration,
            "EXPIRES IN": (
                expires_in(
                    connector.expires_at,
                    ":name_badge: Expired!",
                    connector.expires_skew_tolerance,
                )
                if connector.expires_at
                else "N/A"
            ),
            "EXPIRES_SKEW_TOLERANCE": (
                connector.expires_skew_tolerance
                if connector.expires_skew_tolerance
                else "N/A"
            ),
        }

    for item in properties.items():
        elements = [str(elem) for elem in item]
        rich_table.add_row(*elements)

    console.print(rich_table)

    if len(connector.configuration) == 0 and len(connector.secrets) == 0:
        declare("No configuration options are set for this connector.")

    else:
        rich_table = table.Table(
            box=box.HEAVY_EDGE,
            title="Configuration",
            show_lines=True,
        )
        rich_table.add_column("PROPERTY")
        rich_table.add_column("VALUE", overflow="fold")

        config = connector.configuration.copy()
        secrets = connector.secrets.copy()
        for key, value in secrets.items():
            if not show_secrets:
                config[key] = "[HIDDEN]"
            elif value is None:
                config[key] = "[UNAVAILABLE]"
            else:
                config[key] = value.get_secret_value()

        for item in config.items():
            elements = [str(elem) for elem in item]
            rich_table.add_row(*elements)

        console.print(rich_table)

    if not connector.labels:
        declare("No labels are set for this service connector.")
        return

    rich_table = table.Table(
        box=box.HEAVY_EDGE,
        title="Labels",
        show_lines=True,
    )
    rich_table.add_column("LABEL")
    rich_table.add_column("VALUE", overflow="fold")

    items = connector.labels.items()
    for item in items:
        elements = [str(elem) for elem in item]
        rich_table.add_row(*elements)

    console.print(rich_table)
print_service_connector_resource_table(resources: List[ServiceConnectorResourcesModel], show_resources_only: bool = False) -> None

Prints a table with details for a list of service connector resources.

Parameters:

Name Type Description Default
resources List[ServiceConnectorResourcesModel]

List of service connector resources to print.

required
show_resources_only bool

If True, only the resources will be printed.

False
Source code in src/zenml/cli/utils.py
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
def print_service_connector_resource_table(
    resources: List["ServiceConnectorResourcesModel"],
    show_resources_only: bool = False,
) -> None:
    """Prints a table with details for a list of service connector resources.

    Args:
        resources: List of service connector resources to print.
        show_resources_only: If True, only the resources will be printed.
    """
    resource_table = []
    for resource_model in resources:
        printed_connector = False
        resource_row: Dict[str, Any] = {}

        if resource_model.error:
            # Global error
            if not show_resources_only:
                resource_row = {
                    "CONNECTOR ID": str(resource_model.id),
                    "CONNECTOR NAME": resource_model.name,
                    "CONNECTOR TYPE": resource_model.emojified_connector_type,
                }
            resource_row.update(
                {
                    "RESOURCE TYPE": "\n".join(
                        resource_model.get_emojified_resource_types()
                    ),
                    "RESOURCE NAMES": f":collision: error: {resource_model.error}",
                }
            )
            resource_table.append(resource_row)
            continue

        for resource in resource_model.resources:
            resource_type = resource_model.get_emojified_resource_types(
                resource.resource_type
            )[0]
            if resource.error:
                # Error fetching resources
                resource_ids = [f":collision: error: {resource.error}"]
            elif resource.resource_ids:
                resource_ids = resource.resource_ids
            else:
                resource_ids = [":person_shrugging: none listed"]

            resource_row = {}
            if not show_resources_only:
                resource_row = {
                    "CONNECTOR ID": (
                        str(resource_model.id) if not printed_connector else ""
                    ),
                    "CONNECTOR NAME": (
                        resource_model.name if not printed_connector else ""
                    ),
                    "CONNECTOR TYPE": (
                        resource_model.emojified_connector_type
                        if not printed_connector
                        else ""
                    ),
                }
            resource_row.update(
                {
                    "RESOURCE TYPE": resource_type,
                    "RESOURCE NAMES": "\n".join(resource_ids),
                }
            )
            resource_table.append(resource_row)
            printed_connector = True
    print_table(resource_table)
print_service_connector_resource_type(resource_type: ResourceTypeModel, title: str = '', heading: str = '#', footer: str = '---', print: bool = True) -> str

Prints details for a service connector resource type.

Parameters:

Name Type Description Default
resource_type ResourceTypeModel

Service connector resource type to print.

required
title str

Markdown title to use for the resource type details.

''
heading str

Markdown heading to use for the resource type title.

'#'
footer str

Markdown footer to use for the resource type description.

'---'
print bool

Whether to print the resource type details to the console or just return the message as a string.

True

Returns:

Type Description
str

The MarkDown resource type details as a string.

Source code in src/zenml/cli/utils.py
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
def print_service_connector_resource_type(
    resource_type: "ResourceTypeModel",
    title: str = "",
    heading: str = "#",
    footer: str = "---",
    print: bool = True,
) -> str:
    """Prints details for a service connector resource type.

    Args:
        resource_type: Service connector resource type to print.
        title: Markdown title to use for the resource type details.
        heading: Markdown heading to use for the resource type title.
        footer: Markdown footer to use for the resource type description.
        print: Whether to print the resource type details to the console or
            just return the message as a string.

    Returns:
        The MarkDown resource type details as a string.
    """
    message = f"{title}\n" if title else ""
    emoji = replace_emojis(resource_type.emoji) if resource_type.emoji else ""
    supported_auth_methods = [
        f"{Emoji('lock')} {a}" for a in resource_type.auth_methods
    ]
    message += (
        f"{heading} {emoji} {resource_type.name} "
        f"(resource type: {resource_type.resource_type})\n"
    )
    message += (
        f"**Authentication methods**: "
        f"{', '.join(resource_type.auth_methods)}\n\n"
    )
    message += (
        f"**Supports resource instances**: "
        f"{resource_type.supports_instances}\n\n"
    )
    message += (
        "**Authentication methods**:\n\n- "
        + "\n- ".join(supported_auth_methods)
        + "\n\n"
    )
    message += f"{resource_type.description}\n"

    message += footer

    if print:
        console.print(Markdown(message), justify="left", width=80)

    return message
print_service_connector_type(connector_type: ServiceConnectorTypeModel, title: str = '', heading: str = '#', footer: str = '---', include_resource_types: bool = True, include_auth_methods: bool = True, print: bool = True) -> str

Prints details for a service connector type.

Parameters:

Name Type Description Default
connector_type ServiceConnectorTypeModel

Service connector type to print.

required
title str

Markdown title to use for the service connector type details.

''
heading str

Markdown heading to use for the service connector type title.

'#'
footer str

Markdown footer to use for the service connector type description.

'---'
include_resource_types bool

Whether to include the resource types for the service connector type.

True
include_auth_methods bool

Whether to include the authentication methods for the service connector type.

True
print bool

Whether to print the service connector type details to the console or just return the message as a string.

True

Returns:

Type Description
str

The MarkDown service connector type details as a string.

Source code in src/zenml/cli/utils.py
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
def print_service_connector_type(
    connector_type: "ServiceConnectorTypeModel",
    title: str = "",
    heading: str = "#",
    footer: str = "---",
    include_resource_types: bool = True,
    include_auth_methods: bool = True,
    print: bool = True,
) -> str:
    """Prints details for a service connector type.

    Args:
        connector_type: Service connector type to print.
        title: Markdown title to use for the service connector type details.
        heading: Markdown heading to use for the service connector type title.
        footer: Markdown footer to use for the service connector type
            description.
        include_resource_types: Whether to include the resource types for the
            service connector type.
        include_auth_methods: Whether to include the authentication methods for
            the service connector type.
        print: Whether to print the service connector type details to the
            console or just return the message as a string.

    Returns:
        The MarkDown service connector type details as a string.
    """
    message = f"{title}\n" if title else ""
    supported_auth_methods = [
        f"{Emoji('lock')} {a.auth_method}" for a in connector_type.auth_methods
    ]
    supported_resource_types = [
        f"{replace_emojis(r.emoji)} {r.resource_type}"
        if r.emoji
        else r.resource_type
        for r in connector_type.resource_types
    ]

    emoji = (
        replace_emojis(connector_type.emoji) if connector_type.emoji else ""
    )

    message += (
        f"{heading} {emoji} {connector_type.name} "
        f"(connector type: {connector_type.connector_type})\n"
    )
    message += (
        "**Authentication methods**:\n\n- "
        + "\n- ".join(supported_auth_methods)
        + "\n\n"
    )
    message += (
        "**Resource types**:\n\n- "
        + "\n- ".join(supported_resource_types)
        + "\n\n"
    )
    message += (
        f"**Supports auto-configuration**: "
        f"{connector_type.supports_auto_configuration}\n\n"
    )
    message += f"**Available locally**: {connector_type.local}\n\n"
    message += f"**Available remotely**: {connector_type.remote}\n\n"
    message += f"{connector_type.description}\n"

    if include_resource_types:
        for r in connector_type.resource_types:
            message += print_service_connector_resource_type(
                r,
                heading=heading + "#",
                footer="",
                print=False,
            )

    if include_auth_methods:
        for a in connector_type.auth_methods:
            message += print_service_connector_auth_method(
                a,
                heading=heading + "#",
                footer="",
                print=False,
            )

    message += footer

    if print:
        console.print(Markdown(message), justify="left", width=80)

    return message
print_service_connector_types_table(connector_types: Sequence[ServiceConnectorTypeModel]) -> None

Prints a table with details for a list of service connectors types.

Parameters:

Name Type Description Default
connector_types Sequence[ServiceConnectorTypeModel]

List of service connector types to print.

required
Source code in src/zenml/cli/utils.py
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
def print_service_connector_types_table(
    connector_types: Sequence["ServiceConnectorTypeModel"],
) -> None:
    """Prints a table with details for a list of service connectors types.

    Args:
        connector_types: List of service connector types to print.
    """
    if len(connector_types) == 0:
        warning("No service connector types found.")
        return

    configurations = []
    for connector_type in connector_types:
        supported_auth_methods = list(connector_type.auth_method_dict.keys())

        connector_type_config = {
            "NAME": connector_type.name,
            "TYPE": connector_type.emojified_connector_type,
            "RESOURCE TYPES": "\n".join(
                connector_type.emojified_resource_types
            ),
            "AUTH METHODS": "\n".join(supported_auth_methods),
            "LOCAL": get_boolean_emoji(connector_type.local),
            "REMOTE": get_boolean_emoji(connector_type.remote),
        }
        configurations.append(connector_type_config)
    print_table(configurations)
print_service_connectors_table(client: Client, connectors: Sequence[ServiceConnectorResponse], show_active: bool = False) -> None

Prints a table with details for a list of service connectors.

Parameters:

Name Type Description Default
client Client

Instance of the Repository singleton

required
connectors Sequence[ServiceConnectorResponse]

List of service connectors to print.

required
show_active bool

lag to decide whether to append the active connectors on the top of the list.

False
Source code in src/zenml/cli/utils.py
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
def print_service_connectors_table(
    client: "Client",
    connectors: Sequence["ServiceConnectorResponse"],
    show_active: bool = False,
) -> None:
    """Prints a table with details for a list of service connectors.

    Args:
        client: Instance of the Repository singleton
        connectors: List of service connectors to print.
        show_active: lag to decide whether to append the active connectors
            on the top of the list.
    """
    if len(connectors) == 0:
        return

    active_connectors: List["ServiceConnectorResponse"] = []
    for components in client.active_stack_model.components.values():
        for component in components:
            if component.connector:
                connector = component.connector
                if connector.id not in [c.id for c in active_connectors]:
                    if isinstance(connector.connector_type, str):
                        # The connector embedded within the stack component
                        # does not include a hydrated connector type. We need
                        # that to print its emojis.
                        connector.set_connector_type(
                            client.get_service_connector_type(
                                connector.connector_type
                            )
                        )
                    active_connectors.append(connector)

    connectors = list(connectors)
    if show_active:
        active_ids = [c.id for c in connectors]
        for active_connector in active_connectors:
            if active_connector.id not in active_ids:
                connectors.append(active_connector)

            connectors = [c for c in connectors if c.id in active_ids] + [
                c for c in connectors if c.id not in active_ids
            ]

    configurations = []
    for connector in connectors:
        is_active = connector.id in [c.id for c in active_connectors]
        labels = [
            f"{label}:{value}" for label, value in connector.labels.items()
        ]
        resource_name = connector.resource_id or "<multiple>"

        connector_config = {
            "ACTIVE": ":point_right:" if is_active else "",
            "NAME": connector.name,
            "ID": connector.id,
            "TYPE": connector.emojified_connector_type,
            "RESOURCE TYPES": "\n".join(connector.emojified_resource_types),
            "RESOURCE NAME": resource_name,
            "OWNER": f"{connector.user.name if connector.user else '-'}",
            "EXPIRES IN": (
                expires_in(
                    connector.expires_at,
                    ":name_badge: Expired!",
                    connector.expires_skew_tolerance,
                )
                if connector.expires_at
                else ""
            ),
            "LABELS": "\n".join(labels),
        }
        configurations.append(connector_config)
    print_table(configurations)
print_stack_component_configuration(component: ComponentResponse, active_status: bool, connector_requirements: Optional[ServiceConnectorRequirements] = None) -> None

Prints the configuration options of a stack component.

Parameters:

Name Type Description Default
component ComponentResponse

The stack component to print.

required
active_status bool

Whether the stack component is active.

required
connector_requirements Optional[ServiceConnectorRequirements]

Connector requirements for the component, taken from the component flavor. Only needed if the component has a connector.

None
Source code in src/zenml/cli/utils.py
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
def print_stack_component_configuration(
    component: "ComponentResponse",
    active_status: bool,
    connector_requirements: Optional[ServiceConnectorRequirements] = None,
) -> None:
    """Prints the configuration options of a stack component.

    Args:
        component: The stack component to print.
        active_status: Whether the stack component is active.
        connector_requirements: Connector requirements for the component, taken
            from the component flavor. Only needed if the component has a
            connector.
    """
    if component.user:
        user_name = component.user.name
    else:
        user_name = "-"

    declare(
        f"{component.type.value.title()} '{component.name}' of flavor "
        f"'{component.flavor_name}' with id '{component.id}' is owned by "
        f"user '{user_name}'."
    )

    if len(component.configuration) == 0:
        declare("No configuration options are set for this component.")

    else:
        title_ = (
            f"'{component.name}' {component.type.value.upper()} "
            f"Component Configuration"
        )

        if active_status:
            title_ += " (ACTIVE)"
        rich_table = table.Table(
            box=box.HEAVY_EDGE,
            title=title_,
            show_lines=True,
        )
        rich_table.add_column("COMPONENT_PROPERTY")
        rich_table.add_column("VALUE", overflow="fold")

        items = component.configuration.items()
        for item in items:
            elements = []
            for idx, elem in enumerate(item):
                if idx == 0:
                    elements.append(f"{elem.upper()}")
                else:
                    elements.append(str(elem))
            rich_table.add_row(*elements)

        console.print(rich_table)

    if not component.labels:
        declare("No labels are set for this component.")
    else:
        rich_table = table.Table(
            box=box.HEAVY_EDGE,
            title="Labels",
            show_lines=True,
        )
        rich_table.add_column("LABEL")
        rich_table.add_column("VALUE", overflow="fold")

        for label, value in component.labels.items():
            rich_table.add_row(label, str(value))

        console.print(rich_table)

    if not component.connector:
        declare("No connector is set for this component.")
    else:
        rich_table = table.Table(
            box=box.HEAVY_EDGE,
            title="Service Connector",
            show_lines=True,
        )
        rich_table.add_column("PROPERTY")
        rich_table.add_column("VALUE", overflow="fold")

        resource_type = (
            connector_requirements.resource_type
            if connector_requirements
            else component.connector.resource_types[0]
        )

        connector_dict = {
            "ID": str(component.connector.id),
            "NAME": component.connector.name,
            "TYPE": component.connector.type,
            "RESOURCE TYPE": resource_type,
            "RESOURCE NAME": component.connector_resource_id
            or component.connector.resource_id
            or "N/A",
        }

        for label, value in connector_dict.items():
            rich_table.add_row(label, value)

        console.print(rich_table)
print_stack_configuration(stack: StackResponse, active: bool) -> None

Prints the configuration options of a stack.

Parameters:

Name Type Description Default
stack StackResponse

Instance of a stack model.

required
active bool

Whether the stack is active.

required
Source code in src/zenml/cli/utils.py
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
def print_stack_configuration(stack: "StackResponse", active: bool) -> None:
    """Prints the configuration options of a stack.

    Args:
        stack: Instance of a stack model.
        active: Whether the stack is active.
    """
    stack_caption = f"'{stack.name}' stack"
    if active:
        stack_caption += " (ACTIVE)"
    rich_table = table.Table(
        box=box.HEAVY_EDGE,
        title="Stack Configuration",
        caption=stack_caption,
        show_lines=True,
    )
    rich_table.add_column("COMPONENT_TYPE", overflow="fold")
    rich_table.add_column("COMPONENT_NAME", overflow="fold")
    for component_type, components in stack.components.items():
        rich_table.add_row(component_type, components[0].name)

    # capitalize entries in first column
    rich_table.columns[0]._cells = [
        component.upper()  # type: ignore[union-attr]
        for component in rich_table.columns[0]._cells
    ]
    console.print(rich_table)

    if not stack.labels:
        declare("No labels are set for this stack.")
    else:
        rich_table = table.Table(
            box=box.HEAVY_EDGE,
            title="Labels",
            show_lines=True,
        )
        rich_table.add_column("LABEL")
        rich_table.add_column("VALUE", overflow="fold")

        for label, value in stack.labels.items():
            rich_table.add_row(label, str(value))

        console.print(rich_table)

    declare(
        f"Stack '{stack.name}' with id '{stack.id}' is "
        f"{f'owned by user {stack.user.name}.' if stack.user else 'unowned.'}"
    )
print_stacks_table(client: Client, stacks: Sequence[StackResponse], show_active: bool = False) -> None

Print a prettified list of all stacks supplied to this method.

Parameters:

Name Type Description Default
client Client

Repository instance

required
stacks Sequence[StackResponse]

List of stacks

required
show_active bool

Flag to decide whether to append the active stack on the top of the list.

False
Source code in src/zenml/cli/utils.py
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
def print_stacks_table(
    client: "Client",
    stacks: Sequence["StackResponse"],
    show_active: bool = False,
) -> None:
    """Print a prettified list of all stacks supplied to this method.

    Args:
        client: Repository instance
        stacks: List of stacks
        show_active: Flag to decide whether to append the active stack on the
            top of the list.
    """
    stack_dicts = []

    stacks = list(stacks)
    active_stack = client.active_stack_model
    if show_active:
        if active_stack.id not in [s.id for s in stacks]:
            stacks.append(active_stack)

        stacks = [s for s in stacks if s.id == active_stack.id] + [
            s for s in stacks if s.id != active_stack.id
        ]

    active_stack_model_id = client.active_stack_model.id
    for stack in stacks:
        is_active = stack.id == active_stack_model_id

        if stack.user:
            user_name = stack.user.name
        else:
            user_name = "-"

        stack_config = {
            "ACTIVE": ":point_right:" if is_active else "",
            "STACK NAME": stack.name,
            "STACK ID": stack.id,
            "OWNER": user_name,
            **{
                component_type.upper(): components[0].name
                for component_type, components in stack.components.items()
            },
        }
        stack_dicts.append(stack_config)

    print_table(stack_dicts)
print_table(obj: List[Dict[str, Any]], title: Optional[str] = None, caption: Optional[str] = None, **columns: table.Column) -> None

Prints the list of dicts in a table format.

The input object should be a List of Dicts. Each item in that list represent a line in the Table. Each dict should have the same keys. The keys of the dict will be used as headers of the resulting table.

Parameters:

Name Type Description Default
obj List[Dict[str, Any]]

A List containing dictionaries.

required
title Optional[str]

Title of the table.

None
caption Optional[str]

Caption of the table.

None
columns Column

Optional column configurations to be used in the table.

{}
Source code in src/zenml/cli/utils.py
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
def print_table(
    obj: List[Dict[str, Any]],
    title: Optional[str] = None,
    caption: Optional[str] = None,
    **columns: table.Column,
) -> None:
    """Prints the list of dicts in a table format.

    The input object should be a List of Dicts. Each item in that list represent
    a line in the Table. Each dict should have the same keys. The keys of the
    dict will be used as headers of the resulting table.

    Args:
        obj: A List containing dictionaries.
        title: Title of the table.
        caption: Caption of the table.
        columns: Optional column configurations to be used in the table.
    """
    from rich.text import Text

    column_keys = {key: None for dict_ in obj for key in dict_}
    column_names = [columns.get(key, key.upper()) for key in column_keys]
    rich_table = table.Table(
        box=box.HEAVY_EDGE, show_lines=True, title=title, caption=caption
    )
    for col_name in column_names:
        if isinstance(col_name, str):
            rich_table.add_column(str(col_name), overflow="fold")
        else:
            rich_table.add_column(
                str(col_name.header).upper(), overflow="fold"
            )
    for dict_ in obj:
        values = []
        for key in column_keys:
            if key is None:
                values.append(None)
            else:
                v = dict_.get(key) or " "
                if isinstance(v, str) and (
                    v.startswith("http://") or v.startswith("https://")
                ):
                    # Display the URL as a hyperlink in a way that doesn't break
                    # the URL when it needs to be wrapped over multiple lines
                    value: Union[str, Text] = Text(v, style=f"link {v}")
                else:
                    value = str(v)
                    # Escape text when square brackets are used, but allow
                    # links to be decorated as rich style links
                    if "[" in value and "[link=" not in value:
                        value = escape(value)
                values.append(value)
        rich_table.add_row(*values)
    if len(rich_table.columns) > 1:
        rich_table.columns[0].justify = "center"
    console.print(rich_table)
print_user_info(info: Dict[str, Any]) -> None

Print user information to the terminal.

Parameters:

Name Type Description Default
info Dict[str, Any]

The information to print.

required
Source code in src/zenml/cli/utils.py
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
def print_user_info(info: Dict[str, Any]) -> None:
    """Print user information to the terminal.

    Args:
        info: The information to print.
    """
    for key, value in info.items():
        if key in ["packages", "query_packages"] and not bool(value):
            continue

        declare(f"{key.upper()}: {value}")
prompt_configuration(config_schema: Dict[str, Any], show_secrets: bool = False, existing_config: Optional[Dict[str, str]] = None) -> Dict[str, str]

Prompt the user for configuration values using the provided schema.

Parameters:

Name Type Description Default
config_schema Dict[str, Any]

The configuration schema.

required
show_secrets bool

Whether to show secrets in the terminal.

False
existing_config Optional[Dict[str, str]]

The existing configuration values.

None

Returns:

Type Description
Dict[str, str]

The configuration values provided by the user.

Source code in src/zenml/cli/utils.py
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
def prompt_configuration(
    config_schema: Dict[str, Any],
    show_secrets: bool = False,
    existing_config: Optional[Dict[str, str]] = None,
) -> Dict[str, str]:
    """Prompt the user for configuration values using the provided schema.

    Args:
        config_schema: The configuration schema.
        show_secrets: Whether to show secrets in the terminal.
        existing_config: The existing configuration values.

    Returns:
        The configuration values provided by the user.
    """
    is_update = False
    if existing_config is not None:
        is_update = True
    existing_config = existing_config or {}

    config_dict = {}
    for attr_name, attr_schema in config_schema.get("properties", {}).items():
        title = attr_schema.get("title", attr_name)
        attr_type_name = attr_type = attr_schema.get("type", "string")
        if attr_type == "array":
            attr_type_name = "list (CSV or JSON)"
        title = f"[{attr_name}] {title}"
        required = attr_name in config_schema.get("required", [])
        hidden = attr_schema.get("format", "") == "password"
        subtitles: List[str] = []
        subtitles.append(attr_type_name)
        if hidden:
            subtitles.append("secret")
        if required:
            subtitles.append("required")
        else:
            subtitles.append("optional")
        if subtitles:
            title += f" {{{', '.join(subtitles)}}}"

        existing_value = existing_config.get(attr_name)
        if is_update:
            if existing_value:
                if isinstance(existing_value, SecretStr):
                    existing_value = existing_value.get_secret_value()
                if hidden and not show_secrets:
                    title += " is currently set to: [HIDDEN]"
                else:
                    if attr_type == "array":
                        existing_value = json.dumps(existing_value)
                    title += f" is currently set to: '{existing_value}'"
            else:
                title += " is not currently set"

            click.echo(title)

            if existing_value:
                title = (
                    "Please enter a new value or press Enter to keep the "
                    "existing one"
                )
            elif required:
                title = "Please enter a new value"
            else:
                title = "Please enter a new value or press Enter to skip it"

        while True:
            # Ask the user to enter a value for the attribute
            value = click.prompt(
                title,
                type=str,
                hide_input=hidden and not show_secrets,
                default=existing_value or ("" if not required else None),
                show_default=False,
            )
            if not value:
                if required:
                    warning(
                        f"The attribute '{title}' is mandatory. "
                        "Please enter a non-empty value."
                    )
                    continue
                else:
                    value = None
                    break
            else:
                break

        if (
            is_update
            and value is not None
            and value == existing_value
            and not required
        ):
            confirm = click.confirm(
                "You left this optional attribute unchanged. Would you "
                "like to remove its value instead?",
                default=False,
            )
            if confirm:
                value = None

        if value:
            config_dict[attr_name] = value

    return config_dict
replace_emojis(text: str) -> str

Replaces emoji shortcuts with their unicode equivalent.

Parameters:

Name Type Description Default
text str

Text to expand.

required

Returns:

Type Description
str

Text with expanded emojis.

Source code in src/zenml/cli/utils.py
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
def replace_emojis(text: str) -> str:
    """Replaces emoji shortcuts with their unicode equivalent.

    Args:
        text: Text to expand.

    Returns:
        Text with expanded emojis.
    """
    emoji_pattern = r":(\w+):"
    emojis = re.findall(emoji_pattern, text)
    for emoji in emojis:
        try:
            text = text.replace(f":{emoji}:", str(Emoji(emoji)))
        except NoEmoji:
            # If the emoji text is not a valid emoji, just ignore it
            pass
    return text
requires_mac_env_var_warning() -> bool

Checks if a warning needs to be shown for a local Mac server.

This is for the case where a user is on a macOS system, trying to run a local server but is missing the OBJC_DISABLE_INITIALIZE_FORK_SAFETY environment variable.

Returns:

Name Type Description
bool bool

True if a warning needs to be shown, False otherwise.

Source code in src/zenml/cli/utils.py
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
def requires_mac_env_var_warning() -> bool:
    """Checks if a warning needs to be shown for a local Mac server.

    This is for the case where a user is on a macOS system, trying to run a
    local server but is missing the `OBJC_DISABLE_INITIALIZE_FORK_SAFETY`
    environment variable.

    Returns:
        bool: True if a warning needs to be shown, False otherwise.
    """
    if sys.platform == "darwin":
        mac_version_tuple = tuple(map(int, platform.release().split(".")[:2]))
        return not os.getenv(
            "OBJC_DISABLE_INITIALIZE_FORK_SAFETY"
        ) and mac_version_tuple >= (10, 13)
    return False
temporary_active_stack(stack_name_or_id: Union[UUID, str, None] = None) -> Iterator[Stack]

Contextmanager to temporarily activate a stack.

Parameters:

Name Type Description Default
stack_name_or_id Union[UUID, str, None]

The name or ID of the stack to activate. If not given, this contextmanager will not do anything.

None

Yields:

Type Description
Stack

The active stack.

Source code in src/zenml/cli/utils.py
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
@contextlib.contextmanager
def temporary_active_stack(
    stack_name_or_id: Union["UUID", str, None] = None,
) -> Iterator["Stack"]:
    """Contextmanager to temporarily activate a stack.

    Args:
        stack_name_or_id: The name or ID of the stack to activate. If not given,
            this contextmanager will not do anything.

    Yields:
        The active stack.
    """
    from zenml.client import Client

    try:
        if stack_name_or_id:
            old_stack_id = Client().active_stack_model.id
            Client().activate_stack(stack_name_or_id)
        else:
            old_stack_id = None
        yield Client().active_stack
    finally:
        if old_stack_id:
            Client().activate_stack(old_stack_id)
title(text: str) -> None

Echo a title formatted string on the CLI.

Parameters:

Name Type Description Default
text str

Input text string.

required
Source code in src/zenml/cli/utils.py
116
117
118
119
120
121
122
def title(text: str) -> None:
    """Echo a title formatted string on the CLI.

    Args:
        text: Input text string.
    """
    console.print(text.upper(), style=zenml_style_defaults["title"])
uninstall_package(package: str, use_uv: bool = False) -> None

Uninstalls pypi package from the current environment with pip or uv.

Parameters:

Name Type Description Default
package str

The package to uninstall.

required
use_uv bool

Whether to use uv for package uninstallation.

False
Source code in src/zenml/cli/utils.py
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
def uninstall_package(package: str, use_uv: bool = False) -> None:
    """Uninstalls pypi package from the current environment with pip or uv.

    Args:
        package: The package to uninstall.
        use_uv: Whether to use uv for package uninstallation.
    """
    if use_uv and not is_installed_in_python_environment("uv"):
        # If uv is installed globally, don't run as a python module
        command = []
    else:
        command = [sys.executable, "-m"]

    command += (
        ["uv", "pip", "uninstall", "-q"]
        if use_uv
        else ["pip", "uninstall", "-y", "-qqq"]
    )
    command += [package]

    subprocess.check_call(command)
validate_keys(key: str) -> None

Validates key if it is a valid python string.

Parameters:

Name Type Description Default
key str

key to validate

required
Source code in src/zenml/cli/utils.py
880
881
882
883
884
885
886
887
def validate_keys(key: str) -> None:
    """Validates key if it is a valid python string.

    Args:
        key: key to validate
    """
    if not key.isidentifier():
        error("Please provide args with a proper identifier as the key.")
warning(text: str, bold: Optional[bool] = None, italic: Optional[bool] = None, **kwargs: Any) -> None

Echo a warning string on the CLI.

Parameters:

Name Type Description Default
text str

Input text string.

required
bold Optional[bool]

Optional boolean to bold the text.

None
italic Optional[bool]

Optional boolean to italicize the text.

None
**kwargs Any

Optional kwargs to be passed to console.print().

{}
Source code in src/zenml/cli/utils.py
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
def warning(
    text: str,
    bold: Optional[bool] = None,
    italic: Optional[bool] = None,
    **kwargs: Any,
) -> None:
    """Echo a warning string on the CLI.

    Args:
        text: Input text string.
        bold: Optional boolean to bold the text.
        italic: Optional boolean to italicize the text.
        **kwargs: Optional kwargs to be passed to console.print().
    """
    base_style = zenml_style_defaults["warning"]
    style = Style.chain(base_style, Style(bold=bold, italic=italic))
    console.print(text, style=style, **kwargs)
Modules

config

CLI for manipulating ZenML local and global config file.

Classes
Functions
analytics() -> None

Analytics for opt-in and opt-out.

Source code in src/zenml/cli/config.py
27
28
29
@cli.group(cls=TagGroup, tag=CliCategories.MANAGEMENT_TOOLS)
def analytics() -> None:
    """Analytics for opt-in and opt-out."""
is_analytics_opted_in() -> None

Check whether user is opt-in or opt-out of analytics.

Source code in src/zenml/cli/config.py
32
33
34
35
36
@analytics.command("get")
def is_analytics_opted_in() -> None:
    """Check whether user is opt-in or opt-out of analytics."""
    gc = GlobalConfiguration()
    cli_utils.declare(f"Analytics opt-in: {gc.analytics_opt_in}")
logging() -> None

Configuration of logging for ZenML pipelines.

Source code in src/zenml/cli/config.py
62
63
64
@cli.group(cls=TagGroup, tag=CliCategories.MANAGEMENT_TOOLS)
def logging() -> None:
    """Configuration of logging for ZenML pipelines."""
opt_in() -> None

Opt-in to analytics.

Source code in src/zenml/cli/config.py
39
40
41
42
43
44
45
46
47
@analytics.command(
    "opt-in", context_settings=dict(ignore_unknown_options=True)
)
@track_decorator(AnalyticsEvent.OPT_IN_ANALYTICS)
def opt_in() -> None:
    """Opt-in to analytics."""
    gc = GlobalConfiguration()
    gc.analytics_opt_in = True
    cli_utils.declare("Opted in to analytics.")
opt_out() -> None

Opt-out of analytics.

Source code in src/zenml/cli/config.py
50
51
52
53
54
55
56
57
58
@analytics.command(
    "opt-out", context_settings=dict(ignore_unknown_options=True)
)
@track_decorator(AnalyticsEvent.OPT_OUT_ANALYTICS)
def opt_out() -> None:
    """Opt-out of analytics."""
    gc = GlobalConfiguration()
    gc.analytics_opt_in = False
    cli_utils.declare("Opted out of analytics.")
set_logging_verbosity(verbosity: str) -> None

Set logging level.

Parameters:

Name Type Description Default
verbosity str

The logging level.

required

Raises:

Type Description
KeyError

If the logging level is not supported.

Source code in src/zenml/cli/config.py
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
@logging.command("set-verbosity")
@click.argument(
    "verbosity",
    type=click.Choice(
        list(map(lambda x: x.name, LoggingLevels)), case_sensitive=False
    ),
)
def set_logging_verbosity(verbosity: str) -> None:
    """Set logging level.

    Args:
        verbosity: The logging level.

    Raises:
        KeyError: If the logging level is not supported.
    """
    verbosity = verbosity.upper()
    if verbosity not in LoggingLevels.__members__:
        raise KeyError(
            f"Verbosity must be one of {list(LoggingLevels.__members__.keys())}"
        )
    cli_utils.declare(f"Set verbosity to: {verbosity}")
Modules

downgrade

CLI command to downgrade the ZenML Global Configuration version.

Classes
Functions
disconnect_server() -> None

Downgrade zenml version in global config to match the current version.

Source code in src/zenml/cli/downgrade.py
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
@cli.command("downgrade", help="Downgrade zenml version in global config.")
def disconnect_server() -> None:
    """Downgrade zenml version in global config to match the current version."""
    gc = GlobalConfiguration()

    if gc.version == __version__:
        cli_utils.declare(
            "The ZenML Global Configuration version is already "
            "set to the same version as the current ZenML client."
        )
        return

    if cli_utils.confirmation(
        "Are you sure you want to downgrade the ZenML Global Configuration "
        "version to match the current ZenML client version? It is "
        "recommended to upgrade the ZenML Global Configuration version "
        "instead. Otherwise, you might experience unexpected behavior "
        "such as model schema validation failures or even data loss."
    ):
        gc.version = __version__
        cli_utils.declare(
            "The ZenML Global Configuration version has been "
            "downgraded to match the current ZenML client version."
        )
Modules

feature

Functionality to generate stack component CLI commands.

Classes
Functions
register_feature_store_subcommands() -> None

Registers CLI subcommands for the Feature Store.

Source code in src/zenml/cli/feature.py
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
def register_feature_store_subcommands() -> None:
    """Registers CLI subcommands for the Feature Store."""
    feature_store_group = cast(TagGroup, cli.commands.get("feature-store"))
    if not feature_store_group:
        return

    @feature_store_group.group(
        cls=TagGroup,
        help="Commands for interacting with your features.",
    )
    @click.pass_context
    def feature(ctx: click.Context) -> None:
        """Features as obtained from a feature store.

        Args:
            ctx: The click context.
        """
        from zenml.client import Client
        from zenml.stack.stack_component import StackComponent

        client = Client()
        feature_store_models = client.active_stack_model.components[
            StackComponentType.FEATURE_STORE
        ]
        if feature_store_models is None:
            error(
                "No active feature store found. Please create a feature store "
                "first and add it to your stack."
            )
            return
        ctx.obj = StackComponent.from_model(feature_store_models[0])

    @feature.command("get-data-sources")
    @click.pass_obj
    def get_data_sources(feature_store: "BaseFeatureStore") -> None:
        """Get all data sources from the feature store.

        Args:
            feature_store: The feature store.
        """
        data_sources = feature_store.get_data_sources()  # type: ignore[attr-defined]
        declare(f"Data sources: {data_sources}")

    @feature.command("get-entities")
    @click.pass_obj
    def get_entities(feature_store: "BaseFeatureStore") -> None:
        """Get all entities from the feature store.

        Args:
            feature_store: The feature store.
        """
        entities = feature_store.get_entities()  # type: ignore[attr-defined]
        declare(f"Entities: {entities}")

    @feature.command("get-feature-services")
    @click.pass_obj
    def get_feature_services(feature_store: "BaseFeatureStore") -> None:
        """Get all feature services from the feature store.

        Args:
            feature_store: The feature store.
        """
        feature_services = feature_store.get_feature_services()  # type: ignore[attr-defined]
        declare(f"Feature services: {feature_services}")

    @feature.command("get-feature-views")
    @click.pass_obj
    def get_feature_views(feature_store: "BaseFeatureStore") -> None:
        """Get all feature views from the feature store.

        Args:
            feature_store: The feature store.
        """
        feature_views = feature_store.get_feature_views()  # type: ignore[attr-defined]
        declare(f"Feature views: {feature_views}")

    @feature.command("get-project")
    @click.pass_obj
    def get_project(feature_store: "BaseFeatureStore") -> None:
        """Get the current project name from the feature store.

        Args:
            feature_store: The feature store.
        """
        project = feature_store.get_project()  # type: ignore[attr-defined]
        declare(f"Project name: {project}")

    @feature.command("get-feast-version")
    @click.pass_obj
    def get_feast_version(feature_store: "BaseFeatureStore") -> None:
        """Get the current Feast version being used.

        Args:
            feature_store: The feature store.
        """
        version = feature_store.get_feast_version()  # type: ignore[attr-defined]
        declare(f"Feast version: {version}")

fileio

Functionality for reading, writing and managing files.

Classes
Functions
convert_to_str(path: PathType) -> str

Converts a "PathType" to a str using UTF-8.

Parameters:

Name Type Description Default
path PathType

The path to convert.

required

Returns:

Type Description
str

The path as a string.

Source code in src/zenml/io/fileio.py
40
41
42
43
44
45
46
47
48
49
50
51
52
def convert_to_str(path: "PathType") -> str:
    """Converts a "PathType" to a str using UTF-8.

    Args:
        path: The path to convert.

    Returns:
        The path as a string.
    """
    if isinstance(path, str):
        return path
    else:
        return path.decode("utf-8")
copy(src: PathType, dst: PathType, overwrite: bool = False) -> None

Copy a file from the source to the destination.

Parameters:

Name Type Description Default
src PathType

The path of the file to copy.

required
dst PathType

The path to copy the source file to.

required
overwrite bool

Whether to overwrite the destination file if it exists.

False

Raises:

Type Description
FileExistsError

If a file already exists at the destination and overwrite is not set to True.

Source code in src/zenml/io/fileio.py
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
def copy(src: "PathType", dst: "PathType", overwrite: bool = False) -> None:
    """Copy a file from the source to the destination.

    Args:
        src: The path of the file to copy.
        dst: The path to copy the source file to.
        overwrite: Whether to overwrite the destination file if it exists.

    Raises:
        FileExistsError: If a file already exists at the destination and
            `overwrite` is not set to `True`.
    """
    src_fs = _get_filesystem(src)
    dst_fs = _get_filesystem(dst)
    if src_fs is dst_fs:
        src_fs.copyfile(src, dst, overwrite=overwrite)
    else:
        if not overwrite and exists(dst):
            raise FileExistsError(
                f"Destination file '{convert_to_str(dst)}' already exists "
                f"and `overwrite` is false."
            )
        with open(src, mode="rb") as f:
            contents = f.read()

        with open(dst, mode="wb") as f:
            f.write(contents)
exists(path: PathType) -> bool

Check whether a given path exists.

Parameters:

Name Type Description Default
path PathType

The path to check.

required

Returns:

Type Description
bool

True if the given path exists, False otherwise.

Source code in src/zenml/io/fileio.py
 97
 98
 99
100
101
102
103
104
105
106
def exists(path: "PathType") -> bool:
    """Check whether a given path exists.

    Args:
        path: The path to check.

    Returns:
        `True` if the given path exists, `False` otherwise.
    """
    return _get_filesystem(path).exists(path)
glob(pattern: PathType) -> List[PathType]

Find all files matching the given pattern.

Parameters:

Name Type Description Default
pattern PathType

The pattern to match.

required

Returns:

Type Description
List[PathType]

A list of paths matching the pattern.

Source code in src/zenml/io/fileio.py
109
110
111
112
113
114
115
116
117
118
def glob(pattern: "PathType") -> List["PathType"]:
    """Find all files matching the given pattern.

    Args:
        pattern: The pattern to match.

    Returns:
        A list of paths matching the pattern.
    """
    return _get_filesystem(pattern).glob(pattern)
isdir(path: PathType) -> bool

Check whether the given path is a directory.

Parameters:

Name Type Description Default
path PathType

The path to check.

required

Returns:

Type Description
bool

True if the given path is a directory, False otherwise.

Source code in src/zenml/io/fileio.py
121
122
123
124
125
126
127
128
129
130
def isdir(path: "PathType") -> bool:
    """Check whether the given path is a directory.

    Args:
        path: The path to check.

    Returns:
        `True` if the given path is a directory, `False` otherwise.
    """
    return _get_filesystem(path).isdir(path)
listdir(path: str, only_file_names: bool = True) -> List[str]

Lists all files in a directory.

Parameters:

Name Type Description Default
path str

The path to the directory.

required
only_file_names bool

If True, only return the file names, not the full path.

True

Returns:

Type Description
List[str]

A list of files in the directory.

Source code in src/zenml/io/fileio.py
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
def listdir(path: str, only_file_names: bool = True) -> List[str]:
    """Lists all files in a directory.

    Args:
        path: The path to the directory.
        only_file_names: If True, only return the file names, not the full path.

    Returns:
        A list of files in the directory.
    """
    try:
        return [
            os.path.join(path, convert_to_str(f))
            if not only_file_names
            else convert_to_str(f)
            for f in _get_filesystem(path).listdir(path)
        ]
    except IOError:
        logger.debug(f"Dir {path} not found.")
        return []
makedirs(path: PathType) -> None

Make a directory at the given path, recursively creating parents.

Parameters:

Name Type Description Default
path PathType

The path to the directory.

required
Source code in src/zenml/io/fileio.py
155
156
157
158
159
160
161
def makedirs(path: "PathType") -> None:
    """Make a directory at the given path, recursively creating parents.

    Args:
        path: The path to the directory.
    """
    _get_filesystem(path).makedirs(path)
mkdir(path: PathType) -> None

Make a directory at the given path; parent directory must exist.

Parameters:

Name Type Description Default
path PathType

The path to the directory.

required
Source code in src/zenml/io/fileio.py
164
165
166
167
168
169
170
def mkdir(path: "PathType") -> None:
    """Make a directory at the given path; parent directory must exist.

    Args:
        path: The path to the directory.
    """
    _get_filesystem(path).mkdir(path)
open(path: PathType, mode: str = 'r') -> Any

Opens a file.

Parameters:

Name Type Description Default
path PathType

The path to the file.

required
mode str

The mode to open the file in.

'r'

Returns:

Type Description
Any

The opened file.

Source code in src/zenml/io/fileio.py
55
56
57
58
59
60
61
62
63
64
65
def open(path: "PathType", mode: str = "r") -> Any:  # noqa
    """Opens a file.

    Args:
        path: The path to the file.
        mode: The mode to open the file in.

    Returns:
        The opened file.
    """
    return _get_filesystem(path).open(path, mode=mode)
remove(path: PathType) -> None

Remove the file at the given path. Dangerous operation.

Parameters:

Name Type Description Default
path PathType

The path to the file to remove.

required

Raises:

Type Description
FileNotFoundError

If the file does not exist.

Source code in src/zenml/io/fileio.py
173
174
175
176
177
178
179
180
181
182
183
184
def remove(path: "PathType") -> None:
    """Remove the file at the given path. Dangerous operation.

    Args:
        path: The path to the file to remove.

    Raises:
        FileNotFoundError: If the file does not exist.
    """
    if not exists(path):
        raise FileNotFoundError(f"{convert_to_str(path)} does not exist!")
    _get_filesystem(path).remove(path)
rename(src: PathType, dst: PathType, overwrite: bool = False) -> None

Rename a file.

Parameters:

Name Type Description Default
src PathType

The path of the file to rename.

required
dst PathType

The path to rename the source file to.

required
overwrite bool

If a file already exists at the destination, this method will overwrite it if overwrite=True and raise a FileExistsError otherwise.

False

Raises:

Type Description
NotImplementedError

If the source and destination file systems are not the same.

Source code in src/zenml/io/fileio.py
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
def rename(src: "PathType", dst: "PathType", overwrite: bool = False) -> None:
    """Rename a file.

    Args:
        src: The path of the file to rename.
        dst: The path to rename the source file to.
        overwrite: If a file already exists at the destination, this
            method will overwrite it if overwrite=`True` and
            raise a FileExistsError otherwise.

    Raises:
        NotImplementedError: If the source and destination file systems are not
            the same.
    """
    src_fs = _get_filesystem(src)
    dst_fs = _get_filesystem(dst)
    if src_fs is dst_fs:
        src_fs.rename(src, dst, overwrite=overwrite)
    else:
        raise NotImplementedError(
            f"Renaming from {convert_to_str(src)} to {convert_to_str(dst)} "
            f"using different file systems plugins is currently not supported."
        )
rmtree(dir_path: str) -> None

Deletes a directory recursively. Dangerous operation.

Parameters:

Name Type Description Default
dir_path str

The path to the directory to delete.

required

Raises:

Type Description
TypeError

If the path is not pointing to a directory.

Source code in src/zenml/io/fileio.py
212
213
214
215
216
217
218
219
220
221
222
223
224
def rmtree(dir_path: str) -> None:
    """Deletes a directory recursively. Dangerous operation.

    Args:
        dir_path: The path to the directory to delete.

    Raises:
        TypeError: If the path is not pointing to a directory.
    """
    if not isdir(dir_path):
        raise TypeError(f"Path '{dir_path}' is not a directory.")

    _get_filesystem(dir_path).rmtree(dir_path)
size(path: PathType) -> Optional[int]

Get the size of a file or directory in bytes.

Parameters:

Name Type Description Default
path PathType

The path to the file.

required

Returns:

Type Description
Optional[int]

The size of the file or directory in bytes or None if the responsible

Optional[int]

file system does not implement the size method.

Source code in src/zenml/io/fileio.py
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
def size(path: "PathType") -> Optional[int]:
    """Get the size of a file or directory in bytes.

    Args:
        path: The path to the file.

    Returns:
        The size of the file or directory in bytes or `None` if the responsible
        file system does not implement the `size` method.
    """
    file_system = _get_filesystem(path)

    # If the file system does not implement the `size` method, return `None`.
    if file_system.size == BaseFilesystem.size:
        logger.warning(
            "Cannot get size of file or directory '%s' since the responsible "
            "file system `%s` does not implement the `size` method.",
            path,
            file_system.__name__,
        )
        return None

    # If the path does not exist, return 0.
    if not exists(path):
        return 0

    # If the path is a file, return its size.
    if not file_system.isdir(path):
        return file_system.size(path)

    # If the path is a directory, recursively sum the sizes of everything in it.
    files = file_system.listdir(path)
    file_sizes = [size(os.path.join(str(path), str(file))) for file in files]
    return sum(
        [file_size for file_size in file_sizes if file_size is not None]
    )
stat(path: PathType) -> Any

Get the stat descriptor for a given file path.

Parameters:

Name Type Description Default
path PathType

The path to the file.

required

Returns:

Type Description
Any

The stat descriptor.

Source code in src/zenml/io/fileio.py
227
228
229
230
231
232
233
234
235
236
def stat(path: "PathType") -> Any:
    """Get the stat descriptor for a given file path.

    Args:
        path: The path to the file.

    Returns:
        The stat descriptor.
    """
    return _get_filesystem(path).stat(path)
walk(top: PathType, topdown: bool = True, onerror: Optional[Callable[..., None]] = None) -> Iterable[Tuple[PathType, List[PathType], List[PathType]]]

Return an iterator that walks the contents of the given directory.

Parameters:

Name Type Description Default
top PathType

The path of directory to walk.

required
topdown bool

Whether to walk directories topdown or bottom-up.

True
onerror Optional[Callable[..., None]]

Callable that gets called if an error occurs.

None

Returns:

Type Description
Iterable[Tuple[PathType, List[PathType], List[PathType]]]

An Iterable of Tuples, each of which contain the path of the current

Iterable[Tuple[PathType, List[PathType], List[PathType]]]

directory path, a list of directories inside the current directory

Iterable[Tuple[PathType, List[PathType], List[PathType]]]

and a list of files inside the current directory.

Source code in src/zenml/io/fileio.py
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
def walk(
    top: "PathType",
    topdown: bool = True,
    onerror: Optional[Callable[..., None]] = None,
) -> Iterable[Tuple["PathType", List["PathType"], List["PathType"]]]:
    """Return an iterator that walks the contents of the given directory.

    Args:
        top: The path of directory to walk.
        topdown: Whether to walk directories topdown or bottom-up.
        onerror: Callable that gets called if an error occurs.

    Returns:
        An Iterable of Tuples, each of which contain the path of the current
        directory path, a list of directories inside the current directory
        and a list of files inside the current directory.
    """
    return _get_filesystem(top).walk(top, topdown=topdown, onerror=onerror)
Modules

formatter

Helper functions to format output for CLI.

Classes
ZenFormatter(indent_increment: int = 2, width: Optional[int] = None, max_width: Optional[int] = None)

Bases: HelpFormatter

Override the default HelpFormatter to add a custom format for the help command output.

Initialize the formatter.

Parameters:

Name Type Description Default
indent_increment int

The number of spaces to indent each level of nesting.

2
width Optional[int]

The maximum width of the help output.

None
max_width Optional[int]

The maximum width of the help output.

None
Source code in src/zenml/cli/formatter.py
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
def __init__(
    self,
    indent_increment: int = 2,
    width: Optional[int] = None,
    max_width: Optional[int] = None,
) -> None:
    """Initialize the formatter.

    Args:
        indent_increment: The number of spaces to indent each level of
            nesting.
        width: The maximum width of the help output.
        max_width: The maximum width of the help output.
    """
    super(ZenFormatter, self).__init__(indent_increment, width, max_width)
    self.current_indent = 0
Functions
write_dl(rows: Sequence[Tuple[str, ...]], col_max: int = 30, col_spacing: int = 2) -> None

Writes a definition list into the buffer.

This is how options and commands are usually formatted.

Parameters:

Name Type Description Default
rows Sequence[Tuple[str, ...]]

a list of items as tuples for the terms and values.

required
col_max int

the maximum width of the first column.

30
col_spacing int

the number of spaces between the first and second column (and third).

2

The default behavior is to format the rows in a definition list with rows of 2 columns following the format (term, value). But for new CLI commands, we want to format the rows in a definition list with rows of 3 columns following the format (term, value, description).

Raises:

Type Description
TypeError

if the number of columns is not 2 or 3.

Source code in src/zenml/cli/formatter.py
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
def write_dl(
    self,
    rows: Sequence[Tuple[str, ...]],
    col_max: int = 30,
    col_spacing: int = 2,
) -> None:
    """Writes a definition list into the buffer.

    This is how options and commands are usually formatted.

    Arguments:
        rows: a list of items as tuples for the terms and values.
        col_max: the maximum width of the first column.
        col_spacing: the number of spaces between the first and
                        second column (and third).

    The default behavior is to format the rows in a definition list
    with rows of 2 columns following the format ``(term, value)``.
    But for new CLI commands, we want to format the rows in a definition
    list with rows of 3 columns following the format
    ``(term, value, description)``.

    Raises:
        TypeError: if the number of columns is not 2 or 3.
    """
    rows = list(rows)
    widths = measure_table(rows)

    if len(widths) == 2:
        first_col = min(widths[0], col_max) + col_spacing

        for first, second in iter_rows(rows, len(widths)):
            self.write(f"{'':>{self.current_indent}}{first}")
            if not second:
                self.write("\n")
                continue
            if term_len(first) <= first_col - col_spacing:
                self.write(" " * (first_col - term_len(first)))
            else:
                self.write("\n")
                self.write(" " * (first_col + self.current_indent))

            text_width = max(self.width - first_col - 2, 10)
            wrapped_text = formatting.wrap_text(
                second, text_width, preserve_paragraphs=True
            )
            lines = wrapped_text.splitlines()

            if lines:
                self.write(f"{lines[0]}\n")

                for line in lines[1:]:
                    self.write(
                        f"{'':>{first_col + self.current_indent}}{line}\n"
                    )
            else:
                self.write("\n")

    elif len(widths) == 3:
        first_col = min(widths[0], col_max) + col_spacing
        second_col = min(widths[1], col_max) + col_spacing * 2

        current_tag = None
        for first, second, third in iter_rows(rows, len(widths)):
            if current_tag != first:
                current_tag = first
                self.write("\n")
                # Adding [#431d93] [/#431d93] makes the tag colorful when
                # it is printed by rich print
                self.write(
                    f"[#431d93]{'':>{self.current_indent}}{first}:[/#431d93]\n"
                )

            if not third:
                self.write("\n")
                continue

            if term_len(first) <= first_col - col_spacing:
                self.write(" " * self.current_indent * 2)
            else:
                self.write("\n")
                self.write(" " * (first_col + self.current_indent))

            self.write(f"{'':>{self.current_indent}}{second}")

            text_width = max(self.width - second_col - 4, 10)
            wrapped_text = formatting.wrap_text(
                third, text_width, preserve_paragraphs=True
            )
            lines = wrapped_text.splitlines()

            if lines:
                self.write(
                    " "
                    * (second_col - term_len(second) + self.current_indent)
                )
                self.write(f"{lines[0]}\n")

                for line in lines[1:]:
                    self.write(
                        f"{'':>{second_col + self.current_indent * 4}}{line}\n"
                    )
            else:
                self.write("\n")
    else:
        raise TypeError(
            "Expected either three or two columns for definition list"
        )
Functions
iter_rows(rows: Iterable[Tuple[str, ...]], col_count: int) -> Iterator[Tuple[str, ...]]

Iterate over rows of a table.

Parameters:

Name Type Description Default
rows Iterable[Tuple[str, ...]]

The rows of the table.

required
col_count int

The number of columns in the table.

required

Yields:

Type Description
Tuple[str, ...]

An iterator over the rows of the table.

Source code in src/zenml/cli/formatter.py
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
def iter_rows(
    rows: Iterable[Tuple[str, ...]],
    col_count: int,
) -> Iterator[Tuple[str, ...]]:
    """Iterate over rows of a table.

    Args:
        rows: The rows of the table.
        col_count: The number of columns in the table.

    Yields:
        An iterator over the rows of the table.
    """
    for row in rows:
        yield row + ("",) * (col_count - len(row))
measure_table(rows: Iterable[Tuple[str, ...]]) -> Tuple[int, ...]

Measure the width of each column in a table.

Parameters:

Name Type Description Default
rows Iterable[Tuple[str, ...]]

The rows of the table.

required

Returns:

Type Description
Tuple[int, ...]

A tuple of the width of each column.

Source code in src/zenml/cli/formatter.py
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
def measure_table(rows: Iterable[Tuple[str, ...]]) -> Tuple[int, ...]:
    """Measure the width of each column in a table.

    Args:
        rows: The rows of the table.

    Returns:
        A tuple of the width of each column.
    """
    widths: Dict[int, int] = {}
    for row in rows:
        for idx, col in enumerate(row):
            widths[idx] = max(widths.get(idx, 0), term_len(col))

    return tuple(y for x, y in sorted(widths.items()))

model_registry

Functionality for model deployer CLI subcommands.

Classes
Functions
register_model_registry_subcommands() -> None

Registers CLI subcommands for the Model Registry.

Source code in src/zenml/cli/model_registry.py
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
def register_model_registry_subcommands() -> None:  # noqa: C901
    """Registers CLI subcommands for the Model Registry."""
    model_registry_group = cast(TagGroup, cli.commands.get("model-registry"))
    if not model_registry_group:
        return

    @model_registry_group.group(
        cls=TagGroup,
        help="Commands for interacting with registered models group of commands.",
    )
    @click.pass_context
    def models(ctx: click.Context) -> None:
        """List and manage models with the active model registry.

        Args:
            ctx: The click context.
        """
        from zenml.client import Client
        from zenml.stack.stack_component import StackComponent

        client = Client()
        model_registry_models = client.active_stack_model.components.get(
            StackComponentType.MODEL_REGISTRY
        )
        if model_registry_models is None:
            cli_utils.error(
                "No active model registry found. Please add a model_registry "
                "to your stack."
            )
            return
        ctx.obj = StackComponent.from_model(model_registry_models[0])

    @models.command(
        "list",
        help="Get a list of all registered models within the model registry.",
    )
    @click.option(
        "--metadata",
        "-m",
        type=(str, str),
        default=None,
        help="Filter models by metadata. can be used like: -m key1 value1 -m key2 value",
        multiple=True,
    )
    @click.pass_obj
    def list_registered_models(
        model_registry: "BaseModelRegistry",
        metadata: Optional[Dict[str, str]],
    ) -> None:
        """List of all registered models within the model registry.

        The list can be filtered by metadata (tags) using the --metadata flag.
        Example: zenml model-registry models list-versions -m key1 value1 -m key2 value2

        Args:
            model_registry: The model registry stack component.
            metadata: Filter models by Metadata (Tags).
        """
        metadata = dict(metadata) if metadata else None
        registered_models = model_registry.list_models(metadata=metadata)
        # Print registered models if any
        if registered_models:
            cli_utils.pretty_print_registered_model_table(registered_models)
        else:
            cli_utils.declare("No models found.")

    @models.command(
        "register",
        help="Register a model with the active model registry.",
    )
    @click.argument(
        "name",
        type=click.STRING,
        required=True,
    )
    @click.option(
        "--description",
        "-d",
        type=str,
        default=None,
        help="Description of the model to register.",
    )
    @click.option(
        "--metadata",
        "-t",
        type=(str, str),
        default=None,
        help="Metadata or Tags to add to the model. can be used like: -m key1 value1 -m key2 value",
        multiple=True,
    )
    @click.pass_obj
    def register_model(
        model_registry: "BaseModelRegistry",
        name: str,
        description: Optional[str],
        metadata: Optional[Dict[str, str]],
    ) -> None:
        """Register a model with the active model registry.

        Args:
            model_registry: The model registry stack component.
            name: Name of the model to register.
            description: Description of the model to register.
            metadata: Metadata or Tags to add to the registered model.
        """
        try:
            model_registry.get_model(name)
            cli_utils.error(f"Model with name {name} already exists.")
        except KeyError:
            pass
        metadata = dict(metadata) if metadata else None
        model_registry.register_model(
            name=name,
            description=description,
            metadata=metadata,
        )
        cli_utils.declare(f"Model {name} registered successfully.")

    @models.command(
        "delete",
        help="Delete a model from the active model registry.",
    )
    @click.argument(
        "name",
        type=click.STRING,
        required=True,
    )
    @click.option(
        "--yes",
        "-y",
        is_flag=True,
        help="Don't ask for confirmation.",
    )
    @click.pass_obj
    def delete_model(
        model_registry: "BaseModelRegistry",
        name: str,
        yes: bool = False,
    ) -> None:
        """Delete a model from the active model registry.

        Args:
            model_registry: The model registry stack component.
            name: Name of the model to delete.
            yes: If set, don't ask for confirmation.
        """
        try:
            model_registry.get_model(name)
        except KeyError:
            cli_utils.error(f"Model with name {name} does not exist.")
            return
        if not yes:
            confirmation = cli_utils.confirmation(
                f"Found Model with name {name}. Do you want to delete them?"
            )
            if not confirmation:
                cli_utils.declare("Model deletion canceled.")
                return
        model_registry.delete_model(name)
        cli_utils.declare(f"Model {name} deleted successfully.")

    @models.command(
        "update",
        help="Update a model in the active model registry.",
    )
    @click.argument(
        "name",
        type=click.STRING,
        required=True,
    )
    @click.option(
        "--description",
        "-d",
        type=str,
        default=None,
        help="Description of the model to update.",
    )
    @click.option(
        "--metadata",
        "-t",
        type=(str, str),
        default=None,
        help="Metadata or Tags to add to the model. Can be used like: -m key1 value1 -m key2 value",
        multiple=True,
    )
    @click.pass_obj
    def update_model(
        model_registry: "BaseModelRegistry",
        name: str,
        description: Optional[str],
        metadata: Optional[Dict[str, str]],
    ) -> None:
        """Update a model in the active model registry.

        Args:
            model_registry: The model registry stack component.
            name: Name of the model to update.
            description: Description of the model to update.
            metadata: Metadata or Tags to add to the model.
        """
        try:
            model_registry.get_model(name)
        except KeyError:
            cli_utils.error(f"Model with name {name} does not exist.")
            return
        metadata = dict(metadata) if metadata else None
        model_registry.update_model(
            name=name,
            description=description,
            metadata=metadata,
        )
        cli_utils.declare(f"Model {name} updated successfully.")

    @models.command(
        "get",
        help="Get a model from the active model registry.",
    )
    @click.argument(
        "name",
        type=click.STRING,
        required=True,
    )
    @click.pass_obj
    def get_model(
        model_registry: "BaseModelRegistry",
        name: str,
    ) -> None:
        """Get a model from the active model registry.

        Args:
            model_registry: The model registry stack component.
            name: Name of the model to get.
        """
        try:
            model = model_registry.get_model(name)
        except KeyError:
            cli_utils.error(f"Model with name {name} does not exist.")
            return
        cli_utils.pretty_print_registered_model_table([model])

    @models.command(
        "get-version",
        help="Get a model version from the active model registry.",
    )
    @click.argument(
        "name",
        type=click.STRING,
        required=True,
    )
    @click.option(
        "--version",
        "-v",
        type=str,
        default=None,
        help="Version of the model to get.",
        required=True,
    )
    @click.pass_obj
    def get_model_version(
        model_registry: "BaseModelRegistry",
        name: str,
        version: str,
    ) -> None:
        """Get a model version from the active model registry.

        Args:
            model_registry: The model registry stack component.
            name: Name of the model to get.
            version: Version of the model to get.
        """
        try:
            model_version = model_registry.get_model_version(name, version)
        except KeyError:
            cli_utils.error(
                f"Model with name {name} and version {version} does not exist."
            )
            return
        cli_utils.pretty_print_model_version_details(model_version)

    @models.command(
        "delete-version",
        help="Delete a model version from the active model registry.",
    )
    @click.argument(
        "name",
        type=click.STRING,
        required=True,
    )
    @click.option(
        "--version",
        "-v",
        type=str,
        default=None,
        help="Version of the model to delete.",
        required=True,
    )
    @click.option(
        "--yes",
        "-y",
        is_flag=True,
        help="Don't ask for confirmation.",
    )
    @click.pass_obj
    def delete_model_version(
        model_registry: "BaseModelRegistry",
        name: str,
        version: str,
        yes: bool = False,
    ) -> None:
        """Delete a model version from the active model registry.

        Args:
            model_registry: The model registry stack component.
            name: Name of the model to delete.
            version: Version of the model to delete.
            yes: If set, don't ask for confirmation.
        """
        try:
            model_registry.get_model_version(name, version)
        except KeyError:
            cli_utils.error(
                f"Model with name {name} and version {version} does not exist."
            )
            return
        if not yes:
            confirmation = cli_utils.confirmation(
                f"Found Model with the name `{name}` and the version `{version}`."
                f"Do you want to delete it?"
            )
            if not confirmation:
                cli_utils.declare("Model version deletion canceled.")
                return
        model_registry.delete_model_version(name, version)
        cli_utils.declare(
            f"Model {name} version {version} deleted successfully."
        )

    @models.command(
        "update-version",
        help="Update a model version in the active model registry.",
    )
    @click.argument(
        "name",
        type=click.STRING,
        required=True,
    )
    @click.option(
        "--version",
        "-v",
        type=str,
        default=None,
        help="Version of the model to update.",
        required=True,
    )
    @click.option(
        "--description",
        "-d",
        type=str,
        default=None,
        help="Description of the model to update.",
    )
    @click.option(
        "--metadata",
        "-m",
        type=(str, str),
        default=None,
        help="Metadata or Tags to add to the model. can be used like: --m key1 value1 -m key2 value",
        multiple=True,
    )
    @click.option(
        "--stage",
        "-s",
        type=click.Choice(["None", "Staging", "Production", "Archived"]),
        default=None,
        help="Stage of the model to update.",
    )
    @click.option(
        "--remove_metadata",
        "-rm",
        default=None,
        help="Metadata or Tags to remove from the model. Can be used like: -rm key1 -rm key2",
        multiple=True,
    )
    @click.pass_obj
    def update_model_version(
        model_registry: "BaseModelRegistry",
        name: str,
        version: str,
        description: Optional[str],
        metadata: Optional[Dict[str, str]],
        stage: Optional[str],
        remove_metadata: Optional[List[str]],
    ) -> None:
        """Update a model version in the active model registry.

        Args:
            model_registry: The model registry stack component.
            name: Name of the model to update.
            version: Version of the model to update.
            description: Description of the model to update.
            metadata: Metadata to add to the model version.
            stage: Stage of the model to update.
            remove_metadata: Metadata to remove from the model version.
        """
        try:
            model_registry.get_model_version(name, version)
        except KeyError:
            cli_utils.error(
                f"Model with name {name} and version {version} does not exist."
            )
            return
        metadata = dict(metadata) if metadata else {}
        remove_metadata = list(remove_metadata) if remove_metadata else []
        updated_version = model_registry.update_model_version(
            name=name,
            version=version,
            description=description,
            metadata=ModelRegistryModelMetadata(**metadata),
            stage=ModelVersionStage(stage) if stage else None,
            remove_metadata=remove_metadata,
        )
        cli_utils.declare(
            f"Model {name} version {version} updated successfully."
        )
        cli_utils.pretty_print_model_version_details(updated_version)

    @models.command(
        "list-versions",
        help="List all model versions in the active model registry.",
    )
    @click.argument(
        "name",
        type=click.STRING,
        required=True,
    )
    @click.option(
        "--model-uri",
        "-m",
        type=str,
        default=None,
        help="Model URI of the model to list versions for.",
    )
    @click.option(
        "--metadata",
        "-m",
        type=(str, str),
        default=None,
        help="Metadata or Tags to filter the model versions by. Can be used like: -m key1 value1 -m key2 value",
        multiple=True,
    )
    @click.option(
        "--count",
        "-c",
        type=int,
        help="Number of model versions to list.",
    )
    @click.option(
        "--order-by-date",
        type=click.Choice(["asc", "desc"]),
        default="desc",
        help="Order by date.",
    )
    @click.option(
        "--created-after",
        type=click.DateTime(formats=["%Y-%m-%d"]),
        default=None,
        help="List model versions created after this date.",
    )
    @click.option(
        "--created-before",
        type=click.DateTime(formats=["%Y-%m-%d"]),
        default=None,
        help="List model versions created before this date.",
    )
    @click.pass_obj
    def list_model_versions(
        model_registry: "BaseModelRegistry",
        name: str,
        model_uri: Optional[str],
        count: Optional[int],
        metadata: Optional[Dict[str, str]],
        order_by_date: str,
        created_after: Optional[datetime],
        created_before: Optional[datetime],
    ) -> None:
        """List all model versions in the active model registry.

        Args:
            model_registry: The model registry stack component.
            name: Name of the model to list versions for.
            model_uri: Model URI of the model to list versions for.
            metadata: Metadata or Tags to filter the model versions by.
            count: Number of model versions to list.
            order_by_date: Order by date.
            created_after: List model versions created after this date.
            created_before: List model versions created before this date.
        """
        metadata = dict(metadata) if metadata else {}
        model_versions = model_registry.list_model_versions(
            name=name,
            model_source_uri=model_uri,
            metadata=ModelRegistryModelMetadata(**metadata),
            count=count,
            order_by_date=order_by_date,
            created_after=created_after,
            created_before=created_before,
        )
        if not model_versions:
            cli_utils.declare("No model versions found.")
            return
        cli_utils.pretty_print_model_version_table(model_versions)

    @models.command(
        "register-version",
        help="Register a model version in the active model registry.",
    )
    @click.argument(
        "name",
        type=click.STRING,
        required=True,
    )
    @click.option(
        "--description",
        "-d",
        type=str,
        default=None,
        help="Description of the model version.",
    )
    @click.option(
        "--metadata",
        "-m",
        type=(str, str),
        default=None,
        help="Metadata or Tags to add to the model version. Can be used like: -m key1 value1 -m key2 value",
        multiple=True,
    )
    @click.option(
        "--version",
        "-v",
        type=str,
        required=True,
        default=None,
        help="Version of the model to register.",
    )
    @click.option(
        "--model-uri",
        "-u",
        type=str,
        default=None,
        help="Model URI of the model to register.",
        required=True,
    )
    @click.option(
        "--zenml-version",
        type=str,
        default=None,
        help="ZenML version of the model to register.",
    )
    @click.option(
        "--zenml-run-name",
        type=str,
        default=None,
        help="ZenML run name of the model to register.",
    )
    @click.option(
        "--zenml-pipeline-run-id",
        type=str,
        default=None,
        help="ZenML pipeline run ID of the model to register.",
    )
    @click.option(
        "--zenml-pipeline-name",
        type=str,
        default=None,
        help="ZenML pipeline name of the model to register.",
    )
    @click.option(
        "--zenml-step-name",
        type=str,
        default=None,
        help="ZenML step name of the model to register.",
    )
    @click.pass_obj
    def register_model_version(
        model_registry: "BaseModelRegistry",
        name: str,
        version: str,
        model_uri: str,
        description: Optional[str],
        metadata: Optional[Dict[str, str]],
        zenml_version: Optional[str],
        zenml_run_name: Optional[str],
        zenml_pipeline_name: Optional[str],
        zenml_step_name: Optional[str],
    ) -> None:
        """Register a model version in the active model registry.

        Args:
            model_registry: The model registry stack component.
            name: Name of the model to register.
            version: Version of the model to register.
            model_uri: Model URI of the model to register.
            description: Description of the model to register.
            metadata: Model version metadata.
            zenml_version: ZenML version of the model to register.
            zenml_run_name: ZenML pipeline run name of the model to register.
            zenml_pipeline_name: ZenML pipeline name of the model to register.
            zenml_step_name: ZenML step name of the model to register.
        """
        # Parse metadata
        metadata = dict(metadata) if metadata else {}
        registered_metadata = ModelRegistryModelMetadata(**dict(metadata))
        registered_metadata.zenml_version = zenml_version
        registered_metadata.zenml_run_name = zenml_run_name
        registered_metadata.zenml_pipeline_name = zenml_pipeline_name
        registered_metadata.zenml_step_name = zenml_step_name
        model_version = model_registry.register_model_version(
            name=name,
            version=version,
            model_source_uri=model_uri,
            description=description,
            metadata=registered_metadata,
        )
        cli_utils.declare(
            f"Model {name} version {version} registered successfully."
        )
        cli_utils.pretty_print_model_version_details(model_version)
Modules

requirements_utils

Requirement utils.

Classes
Functions
get_requirements_for_component(component: ComponentResponse, python_version: Optional[str] = None) -> Tuple[List[str], List[str]]

Get requirements for a component model.

Parameters:

Name Type Description Default
component ComponentResponse

The component for which to get the requirements.

required
python_version Optional[str]

The Python version to use for the requirements.

None

Returns:

Type Description
Tuple[List[str], List[str]]

Tuple of PyPI and APT requirements of the component.

Source code in src/zenml/utils/requirements_utils.py
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
def get_requirements_for_component(
    component: "ComponentResponse",
    python_version: Optional[str] = None,
) -> Tuple[List[str], List[str]]:
    """Get requirements for a component model.

    Args:
        component: The component for which to get the requirements.
        python_version: The Python version to use for the requirements.

    Returns:
        Tuple of PyPI and APT requirements of the component.
    """
    integration = get_integration_for_module(
        module_name=component.flavor.source
    )

    if integration:
        return integration.get_requirements(
            python_version=python_version
        ), integration.APT_PACKAGES
    else:
        return [], []
get_requirements_for_stack(stack: StackResponse, python_version: Optional[str] = None) -> Tuple[List[str], List[str]]

Get requirements for a stack model.

Parameters:

Name Type Description Default
stack StackResponse

The stack for which to get the requirements.

required
python_version Optional[str]

The Python version to use for the requirements.

None

Returns:

Type Description
Tuple[List[str], List[str]]

Tuple of PyPI and APT requirements of the stack.

Source code in src/zenml/utils/requirements_utils.py
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
def get_requirements_for_stack(
    stack: "StackResponse",
    python_version: Optional[str] = None,
) -> Tuple[List[str], List[str]]:
    """Get requirements for a stack model.

    Args:
        stack: The stack for which to get the requirements.
        python_version: The Python version to use for the requirements.

    Returns:
        Tuple of PyPI and APT requirements of the stack.
    """
    pypi_requirements: Set[str] = set()
    apt_packages: Set[str] = set()

    for component_list in stack.components.values():
        assert len(component_list) == 1
        component = component_list[0]
        (
            component_pypi_requirements,
            component_apt_packages,
        ) = get_requirements_for_component(
            component=component,
            python_version=python_version,
        )
        pypi_requirements = pypi_requirements.union(
            component_pypi_requirements
        )
        apt_packages = apt_packages.union(component_apt_packages)

    return sorted(pypi_requirements), sorted(apt_packages)

served_model

Functionality for model-deployer CLI subcommands.

Classes
Functions
register_model_deployer_subcommands() -> None

Registers CLI subcommands for the Model Deployer.

Source code in src/zenml/cli/served_model.py
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
def register_model_deployer_subcommands() -> None:  # noqa: C901
    """Registers CLI subcommands for the Model Deployer."""
    model_deployer_group = cast(TagGroup, cli.commands.get("model-deployer"))
    if not model_deployer_group:
        return

    @model_deployer_group.group(
        cls=TagGroup,
        help="Commands for interacting with served models.",
    )
    @click.pass_context
    def models(ctx: click.Context) -> None:
        """List and manage served models with the active model deployer.

        Args:
            ctx: The click context.
        """
        from zenml.client import Client
        from zenml.stack.stack_component import StackComponent

        client = Client()
        model_deployer_models = client.active_stack_model.components.get(
            StackComponentType.MODEL_DEPLOYER
        )
        if model_deployer_models is None:
            error(
                "No active model deployer found. Please add a model_deployer "
                "to your stack."
            )
            return
        ctx.obj = StackComponent.from_model(model_deployer_models[0])

    @models.command(
        "list",
        help="Get a list of all served models within the model-deployer stack "
        "component.",
    )
    @click.option(
        "--step",
        "-s",
        type=click.STRING,
        default=None,
        help="Show only served models that were deployed by the indicated "
        "pipeline step.",
    )
    @click.option(
        "--pipeline-run-id",
        "-r",
        type=click.STRING,
        default=None,
        help="Show only served models that were deployed by the indicated "
        "pipeline run.",
    )
    @click.option(
        "--pipeline-name",
        "-p",
        type=click.STRING,
        default=None,
        help="Show only served models that were deployed by the indicated "
        "pipeline.",
    )
    @click.option(
        "--model",
        "-m",
        type=click.STRING,
        default=None,
        help="Show only served model versions for the given model name.",
    )
    @click.option(
        "--model-version",
        "-v",
        type=click.STRING,
        default=None,
        help="Show only served model versions for the given model version.",
    )
    @click.option(
        "--flavor",
        "-f",
        type=click.STRING,
        default=None,
        help="Show only served model versions for the given model flavor.",
    )
    @click.option(
        "--running",
        is_flag=True,
        help="Show only model servers that are currently running.",
    )
    @click.pass_obj
    def list_models(
        model_deployer: "BaseModelDeployer",
        step: Optional[str],
        pipeline_name: Optional[str],
        pipeline_run_id: Optional[str],
        model: Optional[str],
        model_version: Optional[str],
        flavor: Optional[str],
        running: bool,
    ) -> None:
        """List of all served models within the model-deployer stack component.

        Args:
            model_deployer: The model-deployer stack component.
            step: Show only served models that were deployed by the indicated
                pipeline step.
            pipeline_run_id: Show only served models that were deployed by the
                indicated pipeline run.
            pipeline_name: Show only served models that were deployed by the
                indicated pipeline.
            model: Show only served model versions for the given model name.
            running: Show only model servers that are currently running.
            model_version: Show only served model versions for the given model
                version.
            flavor: Show only served model versions for the given model flavor.
        """
        services = model_deployer.find_model_server(
            running=running,
            pipeline_name=pipeline_name,
            pipeline_run_id=pipeline_run_id if pipeline_run_id else None,
            pipeline_step_name=step,
            model_name=model,
            model_version=model_version,
            flavor=flavor,
        )
        if services:
            pretty_print_model_deployer(
                services,
                model_deployer,
            )
        else:
            warning("No served models found.")

    @models.command("describe", help="Describe a specified served model.")
    @click.argument("served_model_uuid", type=click.STRING)
    @click.pass_obj
    def describe_model(
        model_deployer: "BaseModelDeployer", served_model_uuid: str
    ) -> None:
        """Describe a specified served model.

        Args:
            model_deployer: The model-deployer stack component.
            served_model_uuid: The UUID of the served model.
        """
        served_models = model_deployer.find_model_server(
            service_uuid=uuid.UUID(served_model_uuid)
        )
        if served_models:
            print_served_model_configuration(served_models[0], model_deployer)
            return
        warning(f"No model with uuid: '{served_model_uuid}' could be found.")
        return

    @models.command(
        "get-url",
        help="Return the prediction URL to a specified model server.",
    )
    @click.argument("served_model_uuid", type=click.STRING)
    @click.pass_obj
    def get_url(
        model_deployer: "BaseModelDeployer", served_model_uuid: str
    ) -> None:
        """Return the prediction URL to a specified model server.

        Args:
            model_deployer: The model-deployer stack component.
            served_model_uuid: The UUID of the served model.
        """
        served_models = model_deployer.find_model_server(
            service_uuid=uuid.UUID(served_model_uuid)
        )
        if served_models:
            try:
                prediction_url = model_deployer.get_model_server_info(
                    served_models[0]
                ).get("PREDICTION_URL")
                prediction_hostname = (
                    model_deployer.get_model_server_info(served_models[0]).get(
                        "PREDICTION_HOSTNAME"
                    )
                    or "No hostname specified for this service"
                )
                prediction_apis_urls = (
                    model_deployer.get_model_server_info(served_models[0]).get(
                        "PREDICTION_APIS_URLS"
                    )
                    or "No prediction APIs URLs specified for this service"
                )
                declare(
                    f"  Prediction URL of Served Model {served_model_uuid} "
                    f"is:\n"
                    f"  {prediction_url}\n"
                    f"  and the hostname is: {prediction_hostname}\n"
                    f"  and the prediction APIs URLs are: {prediction_apis_urls}\n"
                )
            except KeyError:
                warning("The deployed model instance has no 'prediction_url'.")
            return
        warning(f"No model with uuid: '{served_model_uuid}' could be found.")
        return

    @models.command("start", help="Start a specified model server.")
    @click.argument("served_model_uuid", type=click.STRING)
    @click.option(
        "--timeout",
        "-t",
        type=click.INT,
        default=300,
        help="Time in seconds to wait for the model to start. Set to 0 to "
        "return immediately after telling the server to start, without "
        "waiting for it to become fully active (default: 300s).",
    )
    @click.pass_obj
    def start_model_service(
        model_deployer: "BaseModelDeployer",
        served_model_uuid: str,
        timeout: int,
    ) -> None:
        """Start a specified model server.

        Args:
            model_deployer: The model-deployer stack component.
            served_model_uuid: The UUID of the served model.
            timeout: Time in seconds to wait for the model to start.
        """
        served_models = model_deployer.find_model_server(
            service_uuid=uuid.UUID(served_model_uuid)
        )
        if served_models:
            model_deployer.start_model_server(
                served_models[0].uuid, timeout=timeout
            )
            declare(f"Model server {served_models[0]} was started.")
            return

        warning(f"No model with uuid: '{served_model_uuid}' could be found.")
        return

    @models.command("stop", help="Stop a specified model server.")
    @click.argument("served_model_uuid", type=click.STRING)
    @click.option(
        "--timeout",
        "-t",
        type=click.INT,
        default=300,
        help="Time in seconds to wait for the model to start. Set to 0 to "
        "return immediately after telling the server to stop, without "
        "waiting for it to become inactive (default: 300s).",
    )
    @click.option(
        "--yes",
        "-y",
        "force",
        is_flag=True,
        help="Force the model server to stop. This will bypass any graceful "
        "shutdown processes and try to force the model server to stop "
        "immediately, if possible.",
    )
    @click.pass_obj
    def stop_model_service(
        model_deployer: "BaseModelDeployer",
        served_model_uuid: str,
        timeout: int,
        force: bool,
    ) -> None:
        """Stop a specified model server.

        Args:
            model_deployer: The model-deployer stack component.
            served_model_uuid: The UUID of the served model.
            timeout: Time in seconds to wait for the model to stop.
            force: Force the model server to stop.
        """
        served_models = model_deployer.find_model_server(
            service_uuid=uuid.UUID(served_model_uuid)
        )
        if served_models:
            model_deployer.stop_model_server(
                served_models[0].uuid, timeout=timeout, force=force
            )
            declare(f"Model server {served_models[0]} was stopped.")
            return

        warning(f"No model with uuid: '{served_model_uuid}' could be found.")
        return

    @models.command("delete", help="Delete a specified model server.")
    @click.argument("served_model_uuid", type=click.STRING)
    @click.option(
        "--timeout",
        "-t",
        type=click.INT,
        default=300,
        help="Time in seconds to wait for the model to be deleted. Set to 0 to "
        "return immediately after stopping and deleting the model server, "
        "without waiting for it to release all allocated resources.",
    )
    @click.option(
        "--yes",
        "-y",
        "force",
        is_flag=True,
        help="Force the model server to stop and delete. This will bypass any "
        "graceful shutdown processes and try to force the model server to "
        "stop and delete immediately, if possible.",
    )
    @click.pass_obj
    def delete_model_service(
        model_deployer: "BaseModelDeployer",
        served_model_uuid: str,
        timeout: int,
        force: bool,
    ) -> None:
        """Delete a specified model server.

        Args:
            model_deployer: The model-deployer stack component.
            served_model_uuid: The UUID of the served model.
            timeout: Time in seconds to wait for the model to be deleted.
            force: Force the model server to stop and delete.
        """
        served_models = model_deployer.find_model_server(
            service_uuid=uuid.UUID(served_model_uuid)
        )
        if served_models:
            model_deployer.delete_model_server(
                served_models[0].uuid, timeout=timeout, force=force
            )
            declare(f"Model server {served_models[0]} was deleted.")
            return

        warning(f"No model with uuid: '{served_model_uuid}' could be found.")
        return

    @models.command("logs", help="Show the logs for a model server.")
    @click.argument("served_model_uuid", type=click.STRING)
    @click.option(
        "--follow",
        "-f",
        is_flag=True,
        help="Continue to output new log data as it becomes available.",
    )
    @click.option(
        "--tail",
        "-t",
        type=click.INT,
        default=None,
        help="Only show the last NUM lines of log output.",
    )
    @click.option(
        "--raw",
        "-r",
        is_flag=True,
        help="Show raw log contents (don't pretty-print logs).",
    )
    @click.pass_obj
    def get_model_service_logs(
        model_deployer: "BaseModelDeployer",
        served_model_uuid: str,
        follow: bool,
        tail: Optional[int],
        raw: bool,
    ) -> None:
        """Display the logs for a model server.

        Args:
            model_deployer: The model-deployer stack component.
            served_model_uuid: The UUID of the served model.
            follow: Continue to output new log data as it becomes available.
            tail: Only show the last NUM lines of log output.
            raw: Show raw log contents (don't pretty-print logs).
        """
        served_models = model_deployer.find_model_server(
            service_uuid=uuid.UUID(served_model_uuid)
        )
        if not served_models:
            warning(
                f"No model with uuid: '{served_model_uuid}' could be found."
            )
            return

        model_logs = model_deployer.get_model_server_logs(
            served_models[0].uuid, follow=follow, tail=tail
        )
        if model_logs:
            for line in model_logs:
                # don't pretty-print log lines that are already pretty-printed
                if raw or line.startswith("\x1b["):
                    console.print(line, markup=False)
                else:
                    try:
                        console.print(line)
                    except MarkupError:
                        console.print(line, markup=False)

service_accounts

CLI functionality to interact with API keys.

Classes
Functions
api_key(ctx: click.Context, service_account_name_or_id: str) -> None

List and manage the API keys associated with a service account.

Parameters:

Name Type Description Default
ctx Context

The click context.

required
service_account_name_or_id str

The name or ID of the service account.

required
Source code in src/zenml/cli/service_accounts.py
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
@service_account.group(
    cls=TagGroup,
    help="Commands for interacting with API keys.",
)
@click.pass_context
@click.argument("service_account_name_or_id", type=str, required=True)
def api_key(
    ctx: click.Context,
    service_account_name_or_id: str,
) -> None:
    """List and manage the API keys associated with a service account.

    Args:
        ctx: The click context.
        service_account_name_or_id: The name or ID of the service account.
    """
    ctx.obj = service_account_name_or_id
create_api_key(service_account_name_or_id: str, name: str, description: Optional[str], set_key: bool = False, output_file: Optional[str] = None) -> None

Create an API key.

Parameters:

Name Type Description Default
service_account_name_or_id str

The name or ID of the service account to which the API key should be added.

required
name str

Name of the API key

required
description Optional[str]

The API key description.

required
set_key bool

Configure the local client with the generated key.

False
output_file Optional[str]

Output file to write the API key to.

None
Source code in src/zenml/cli/service_accounts.py
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
@api_key.command(
    "create",
    help="Create an API key and print its value.",
)
@click.argument("name", type=click.STRING)
@click.option(
    "--description",
    "-d",
    type=str,
    required=False,
    help="The API key description.",
)
@click.option(
    "--set-key",
    is_flag=True,
    help="Configure the local client with the generated key.",
)
@click.option(
    "--output-file",
    type=str,
    required=False,
    help="File to write the API key to.",
)
@click.pass_obj
def create_api_key(
    service_account_name_or_id: str,
    name: str,
    description: Optional[str],
    set_key: bool = False,
    output_file: Optional[str] = None,
) -> None:
    """Create an API key.

    Args:
        service_account_name_or_id: The name or ID of the service account to
            which the API key should be added.
        name: Name of the API key
        description: The API key description.
        set_key: Configure the local client with the generated key.
        output_file: Output file to write the API key to.
    """
    _create_api_key(
        service_account_name_or_id=service_account_name_or_id,
        name=name,
        description=description,
        set_key=set_key,
        output_file=output_file,
    )
create_service_account(service_account_name: str, description: str = '', create_api_key: bool = True, set_api_key: bool = False, output_file: Optional[str] = None) -> None

Create a new service account.

Parameters:

Name Type Description Default
service_account_name str

The name of the service account to create.

required
description str

The API key description.

''
create_api_key bool

Create an API key for the service account.

True
set_api_key bool

Configure the local client to use the generated API key.

False
output_file Optional[str]

Output file to write the API key to.

None
Source code in src/zenml/cli/service_accounts.py
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
@service_account.command(
    "create", help="Create a new service account and optional API key."
)
@click.argument("service_account_name", type=str, required=True)
@click.option(
    "--description",
    "-d",
    type=str,
    required=False,
    default="",
    help="The API key description.",
)
@click.option(
    "--create-api-key",
    help=("Create an API key for the service account."),
    type=bool,
    default=True,
)
@click.option(
    "--set-api-key",
    help=("Configure the local client to use the generated API key."),
    is_flag=True,
)
@click.option(
    "--output-file",
    type=str,
    required=False,
    help="File to write the API key to.",
)
def create_service_account(
    service_account_name: str,
    description: str = "",
    create_api_key: bool = True,
    set_api_key: bool = False,
    output_file: Optional[str] = None,
) -> None:
    """Create a new service account.

    Args:
        service_account_name: The name of the service account to create.
        description: The API key description.
        create_api_key: Create an API key for the service account.
        set_api_key: Configure the local client to use the generated API key.
        output_file: Output file to write the API key to.
    """
    client = Client()
    try:
        service_account = client.create_service_account(
            name=service_account_name,
            description=description,
        )

        cli_utils.declare(f"Created service account '{service_account.name}'.")
    except EntityExistsError as err:
        cli_utils.error(str(err))

    if create_api_key:
        _create_api_key(
            service_account_name_or_id=service_account.name,
            name="default",
            description="Default API key.",
            set_key=set_api_key,
            output_file=output_file,
        )
delete_api_key(service_account_name_or_id: str, name_or_id: str, yes: bool = False) -> None

Delete an API key.

Parameters:

Name Type Description Default
service_account_name_or_id str

The name or ID of the service account to which the API key belongs.

required
name_or_id str

The name or ID of the API key to delete.

required
yes bool

If set, don't ask for confirmation.

False
Source code in src/zenml/cli/service_accounts.py
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
@api_key.command("delete")
@click.argument("name_or_id", type=str, required=True)
@click.option(
    "--yes",
    "-y",
    is_flag=True,
    help="Don't ask for confirmation.",
)
@click.pass_obj
def delete_api_key(
    service_account_name_or_id: str, name_or_id: str, yes: bool = False
) -> None:
    """Delete an API key.

    Args:
        service_account_name_or_id: The name or ID of the service account to
            which the API key belongs.
        name_or_id: The name or ID of the API key to delete.
        yes: If set, don't ask for confirmation.
    """
    if not yes:
        confirmation = cli_utils.confirmation(
            f"Are you sure you want to delete API key `{name_or_id}`?"
        )
        if not confirmation:
            cli_utils.declare("API key deletion canceled.")
            return

    try:
        Client().delete_api_key(
            service_account_name_id_or_prefix=service_account_name_or_id,
            name_id_or_prefix=name_or_id,
        )
    except KeyError as e:
        cli_utils.error(str(e))
    else:
        cli_utils.declare(f"Deleted API key `{name_or_id}`.")
delete_service_account(service_account_name_or_id: str) -> None

Delete a service account.

Parameters:

Name Type Description Default
service_account_name_or_id str

The name or ID of the service account.

required
Source code in src/zenml/cli/service_accounts.py
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
@service_account.command("delete")
@click.argument("service_account_name_or_id", type=str, required=True)
def delete_service_account(service_account_name_or_id: str) -> None:
    """Delete a service account.

    Args:
        service_account_name_or_id: The name or ID of the service account.
    """
    client = Client()
    try:
        client.delete_service_account(service_account_name_or_id)
    except (KeyError, IllegalOperationError) as err:
        cli_utils.error(str(err))

    cli_utils.declare(
        f"Deleted service account '{service_account_name_or_id}'."
    )
describe_api_key(service_account_name_or_id: str, name_or_id: str) -> None

Describe an API key.

Parameters:

Name Type Description Default
service_account_name_or_id str

The name or ID of the service account to which the API key belongs.

required
name_or_id str

The name or ID of the API key to describe.

required
Source code in src/zenml/cli/service_accounts.py
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
@api_key.command("describe", help="Describe an API key.")
@click.argument("name_or_id", type=str, required=True)
@click.pass_obj
def describe_api_key(service_account_name_or_id: str, name_or_id: str) -> None:
    """Describe an API key.

    Args:
        service_account_name_or_id: The name or ID of the service account to
            which the API key belongs.
        name_or_id: The name or ID of the API key to describe.
    """
    with console.status(f"Getting API key `{name_or_id}`...\n"):
        try:
            api_key = Client().get_api_key(
                service_account_name_id_or_prefix=service_account_name_or_id,
                name_id_or_prefix=name_or_id,
            )
        except KeyError as e:
            cli_utils.error(str(e))

        cli_utils.print_pydantic_model(
            title=f"API key '{api_key.name}'",
            model=api_key,
            exclude_columns={
                "key",
            },
        )
describe_service_account(service_account_name_or_id: str) -> None

Describe a service account.

Parameters:

Name Type Description Default
service_account_name_or_id str

The name or ID of the service account.

required
Source code in src/zenml/cli/service_accounts.py
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
@service_account.command("describe")
@click.argument("service_account_name_or_id", type=str, required=True)
def describe_service_account(service_account_name_or_id: str) -> None:
    """Describe a service account.

    Args:
        service_account_name_or_id: The name or ID of the service account.
    """
    client = Client()
    try:
        service_account = client.get_service_account(
            service_account_name_or_id
        )
    except KeyError as err:
        cli_utils.error(str(err))
    else:
        cli_utils.print_pydantic_model(
            title=f"Service account '{service_account.name}'",
            model=service_account,
        )
list_api_keys(service_account_name_or_id: str, /, **kwargs: Any) -> None

List all API keys.

Parameters:

Name Type Description Default
service_account_name_or_id str

The name or ID of the service account for which to list the API keys.

required
**kwargs Any

Keyword arguments to filter API keys.

{}
Source code in src/zenml/cli/service_accounts.py
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
@api_key.command("list", help="List all API keys.")
@list_options(APIKeyFilter)
@click.pass_obj
def list_api_keys(service_account_name_or_id: str, /, **kwargs: Any) -> None:
    """List all API keys.

    Args:
        service_account_name_or_id: The name or ID of the service account for
            which to list the API keys.
        **kwargs: Keyword arguments to filter API keys.
    """
    with console.status("Listing API keys...\n"):
        try:
            api_keys = Client().list_api_keys(
                service_account_name_id_or_prefix=service_account_name_or_id,
                **kwargs,
            )
        except KeyError as e:
            cli_utils.error(str(e))

        if not api_keys.items:
            cli_utils.declare("No API keys found for this filter.")
            return

        cli_utils.print_pydantic_models(
            api_keys,
            exclude_columns=[
                "created",
                "updated",
                "key",
                "retain_period_minutes",
            ],
        )
list_service_accounts(ctx: click.Context, /, **kwargs: Any) -> None

List all users.

Parameters:

Name Type Description Default
ctx Context

The click context object

required
kwargs Any

Keyword arguments to filter the list of users.

{}
Source code in src/zenml/cli/service_accounts.py
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
@service_account.command("list")
@list_options(ServiceAccountFilter)
@click.pass_context
def list_service_accounts(ctx: click.Context, /, **kwargs: Any) -> None:
    """List all users.

    Args:
        ctx: The click context object
        kwargs: Keyword arguments to filter the list of users.
    """
    client = Client()
    with console.status("Listing service accounts...\n"):
        service_accounts = client.list_service_accounts(**kwargs)
        if not service_accounts:
            cli_utils.declare(
                "No service accounts found for the given filters."
            )
            return

        cli_utils.print_pydantic_models(
            service_accounts,
            exclude_columns=[
                "created",
                "updated",
            ],
        )
rotate_api_key(service_account_name_or_id: str, name_or_id: str, retain: int = 0, set_key: bool = False, output_file: Optional[str] = None) -> None

Rotate an API key.

Parameters:

Name Type Description Default
service_account_name_or_id str

The name or ID of the service account to which the API key belongs.

required
name_or_id str

The name or ID of the API key to rotate.

required
retain int

Number of minutes for which the previous key is still valid after it has been rotated.

0
set_key bool

Configure the local client with the newly generated key.

False
output_file Optional[str]

Output file to write the API key to.

None
Source code in src/zenml/cli/service_accounts.py
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
@api_key.command("rotate", help="Rotate an API key.")
@click.argument("name_or_id", type=str, required=True)
@click.option(
    "--retain",
    type=int,
    required=False,
    default=0,
    help="Number of minutes for which the previous key is still valid after it "
    "has been rotated.",
)
@click.option(
    "--set-key",
    is_flag=True,
    help="Configure the local client with the generated key.",
)
@click.option(
    "--output-file",
    type=str,
    required=False,
    help="File to write the API key to.",
)
@click.pass_obj
def rotate_api_key(
    service_account_name_or_id: str,
    name_or_id: str,
    retain: int = 0,
    set_key: bool = False,
    output_file: Optional[str] = None,
) -> None:
    """Rotate an API key.

    Args:
        service_account_name_or_id: The name or ID of the service account to
            which the API key belongs.
        name_or_id: The name or ID of the API key to rotate.
        retain: Number of minutes for which the previous key is still valid
            after it has been rotated.
        set_key: Configure the local client with the newly generated key.
        output_file: Output file to write the API key to.
    """
    client = Client()
    zen_store = client.zen_store

    try:
        api_key = client.rotate_api_key(
            service_account_name_id_or_prefix=service_account_name_or_id,
            name_id_or_prefix=name_or_id,
            retain_period_minutes=retain,
        )
    except KeyError as e:
        cli_utils.error(str(e))

    cli_utils.declare(f"Successfully rotated API key `{name_or_id}`.")
    if retain:
        cli_utils.declare(
            f"The previous API key will remain valid for {retain} minutes."
        )

    if set_key and api_key.key:
        if zen_store.TYPE != StoreType.REST:
            cli_utils.warning(
                "Could not configure the local ZenML client with the generated "
                "API key. This type of authentication is only supported if "
                "connected to a ZenML server."
            )
        else:
            client.set_api_key(api_key.key)
            cli_utils.declare(
                "The local client has been configured with the new API key."
            )
            return

    if output_file and api_key.key:
        with open(output_file, "w") as f:
            f.write(api_key.key)

        cli_utils.declare(f"Wrote API key value to {output_file}")
    else:
        cli_utils.declare(
            f"The new API key value is: '{api_key.key}'\nPlease store it "
            "safely as it will not be shown again.\nTo configure a ZenML "
            "client to use this API key, run:\n\n"
            f"zenml login {zen_store.config.url} --api-key \n\n"
            f"and enter the following API key when prompted: {api_key.key}\n"
        )
service_account() -> None

Commands for service account management.

Source code in src/zenml/cli/service_accounts.py
94
95
96
@cli.group(cls=TagGroup, tag=CliCategories.IDENTITY_AND_SECURITY)
def service_account() -> None:
    """Commands for service account management."""
update_api_key(service_account_name_or_id: str, name_or_id: str, name: Optional[str] = None, description: Optional[str] = None, active: Optional[bool] = None) -> None

Update an API key.

Parameters:

Name Type Description Default
service_account_name_or_id str

The name or ID of the service account to which the API key belongs.

required
name_or_id str

The name or ID of the API key to update.

required
name Optional[str]

The new name of the API key.

None
description Optional[str]

The new description of the API key.

None
active Optional[bool]

Set an API key to active/inactive.

None
Source code in src/zenml/cli/service_accounts.py
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
@api_key.command("update", help="Update an API key.")
@click.argument("name_or_id", type=str, required=True)
@click.option("--name", type=str, required=False, help="The new name.")
@click.option(
    "--description", type=str, required=False, help="The new description."
)
@click.option(
    "--active",
    type=bool,
    required=False,
    help="Activate or deactivate an API key.",
)
@click.pass_obj
def update_api_key(
    service_account_name_or_id: str,
    name_or_id: str,
    name: Optional[str] = None,
    description: Optional[str] = None,
    active: Optional[bool] = None,
) -> None:
    """Update an API key.

    Args:
        service_account_name_or_id: The name or ID of the service account to
            which the API key belongs.
        name_or_id: The name or ID of the API key to update.
        name: The new name of the API key.
        description: The new description of the API key.
        active: Set an API key to active/inactive.
    """
    try:
        Client().update_api_key(
            service_account_name_id_or_prefix=service_account_name_or_id,
            name_id_or_prefix=name_or_id,
            name=name,
            description=description,
            active=active,
        )
    except (KeyError, EntityExistsError) as e:
        cli_utils.error(str(e))

    cli_utils.declare(f"Successfully updated API key `{name_or_id}`.")
update_service_account(service_account_name_or_id: str, updated_name: Optional[str] = None, description: Optional[str] = None, active: Optional[bool] = None) -> None

Update an existing service account.

Parameters:

Name Type Description Default
service_account_name_or_id str

The name or ID of the service account to update.

required
updated_name Optional[str]

The new name of the service account.

None
description Optional[str]

The new API key description.

None
active Optional[bool]

Activate or deactivate a service account.

None
Source code in src/zenml/cli/service_accounts.py
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
@service_account.command(
    "update",
    help="Update a service account.",
)
@click.argument("service_account_name_or_id", type=str, required=True)
@click.option(
    "--name",
    "-n",
    "updated_name",
    type=str,
    required=False,
    help="New service account name.",
)
@click.option(
    "--description",
    "-d",
    type=str,
    required=False,
    help="The API key description.",
)
@click.option(
    "--active",
    type=bool,
    required=False,
    help="Activate or deactivate a service account.",
)
def update_service_account(
    service_account_name_or_id: str,
    updated_name: Optional[str] = None,
    description: Optional[str] = None,
    active: Optional[bool] = None,
) -> None:
    """Update an existing service account.

    Args:
        service_account_name_or_id: The name or ID of the service account to
            update.
        updated_name: The new name of the service account.
        description: The new API key description.
        active: Activate or deactivate a service account.
    """
    try:
        Client().update_service_account(
            name_id_or_prefix=service_account_name_or_id,
            updated_name=updated_name,
            description=description,
            active=active,
        )
    except (KeyError, EntityExistsError) as err:
        cli_utils.error(str(err))
Modules

service_connectors

Service connector CLI commands.

Classes
Functions
delete_service_connector(name_id_or_prefix: str) -> None

Deletes a service connector.

Parameters:

Name Type Description Default
name_id_or_prefix str

The name of the service connector to delete.

required
Source code in src/zenml/cli/service_connectors.py
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
@service_connector.command(
    "delete",
    help="""Delete a service connector.
""",
)
@click.argument("name_id_or_prefix", type=str)
def delete_service_connector(name_id_or_prefix: str) -> None:
    """Deletes a service connector.

    Args:
        name_id_or_prefix: The name of the service connector to delete.
    """
    client = Client()

    with console.status(
        f"Deleting service connector '{name_id_or_prefix}'...\n"
    ):
        try:
            client.delete_service_connector(
                name_id_or_prefix=name_id_or_prefix,
            )
        except (KeyError, IllegalOperationError) as err:
            cli_utils.error(str(err))
        cli_utils.declare(f"Deleted service connector: {name_id_or_prefix}")
describe_service_connector(name_id_or_prefix: str, show_secrets: bool = False, describe_client: bool = False, resource_type: Optional[str] = None, resource_id: Optional[str] = None) -> None

Prints details about a service connector.

Parameters:

Name Type Description Default
name_id_or_prefix str

Name or id of the service connector to describe.

required
show_secrets bool

Whether to show security sensitive configuration attributes in the terminal.

False
describe_client bool

Fetch and describe a service connector client instead of the base connector if possible.

False
resource_type Optional[str]

Resource type to use when fetching the service connector client.

None
resource_id Optional[str]

Resource ID to use when fetching the service connector client.

None
Source code in src/zenml/cli/service_connectors.py
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
@service_connector.command(
    "describe",
    help="""Show detailed information about a service connector.

Display detailed information about a service connector configuration, or about
a service connector client generated from it to access a specific resource
(explained below).

Service connector clients are connector configurations generated from the
original service connectors that are actually used by clients to access a
specific target resource (e.g. an AWS connector generates a Kubernetes connector
client to access a specific EKS Kubernetes cluster). Unlike main service
connectors, connector clients are not persisted in the database. They have a
limited lifetime and may contain temporary credentials to access the target
resource (e.g. an AWS connector configured with an AWS secret key and IAM role
generates a connector client containing temporary STS credentials).

Asking to see service connector client details is equivalent to asking to see
the final configuration that the client sees, as opposed to the configuration
that was configured by the user. In some cases, they are the same, in others
they are completely different.

To show the details of a service connector client instead of the base connector
use the `--client` flag. If the service connector is configured to provide
access to multiple resources, you also need to use the `--resource-type` and
`--resource-id` flags to specify the scope of the connector client.

Secret configuration attributes are not shown by default. Use the
`-x|--show-secrets` flag to show them.
""",
)
@click.argument(
    "name_id_or_prefix",
    type=str,
    required=True,
)
@click.option(
    "--show-secrets",
    "-x",
    "show_secrets",
    is_flag=True,
    default=False,
    help="Show security sensitive configuration attributes in the terminal.",
    type=click.BOOL,
)
@click.option(
    "--client",
    "-c",
    "describe_client",
    is_flag=True,
    default=False,
    help="Fetch and describe a service connector client instead of the base "
    "connector.",
    type=click.BOOL,
)
@click.option(
    "--resource-type",
    "-r",
    "resource_type",
    help="Resource type to use when fetching the service connector client.",
    required=False,
    type=str,
)
@click.option(
    "--resource-id",
    "-ri",
    "resource_id",
    help="Resource ID to use when fetching the service connector client.",
    required=False,
    type=str,
)
def describe_service_connector(
    name_id_or_prefix: str,
    show_secrets: bool = False,
    describe_client: bool = False,
    resource_type: Optional[str] = None,
    resource_id: Optional[str] = None,
) -> None:
    """Prints details about a service connector.

    Args:
        name_id_or_prefix: Name or id of the service connector to describe.
        show_secrets: Whether to show security sensitive configuration
            attributes in the terminal.
        describe_client: Fetch and describe a service connector client
            instead of the base connector if possible.
        resource_type: Resource type to use when fetching the service connector
            client.
        resource_id: Resource ID to use when fetching the service connector
            client.
    """
    client = Client()

    if resource_type or resource_id:
        describe_client = True

    if describe_client:
        try:
            connector_client = client.get_service_connector_client(
                name_id_or_prefix=name_id_or_prefix,
                resource_type=resource_type,
                resource_id=resource_id,
                verify=True,
            )
        except (
            KeyError,
            ValueError,
            IllegalOperationError,
            NotImplementedError,
            AuthorizationException,
        ) as e:
            resource_type = resource_type or "<unspecified>"
            resource_id = resource_id or "<unspecified>"
            cli_utils.error(
                f"Failed fetching a service connector client for connector "
                f"'{name_id_or_prefix}', resource type '{resource_type}' and "
                f"resource ID '{resource_id}': {e}"
            )

        connector = connector_client.to_response_model(
            user=client.active_user,
        )
    else:
        try:
            connector = client.get_service_connector(
                name_id_or_prefix=name_id_or_prefix,
                load_secrets=True,
            )
        except KeyError as err:
            cli_utils.error(str(err))

    with console.status(f"Describing connector '{connector.name}'..."):
        active_stack = client.active_stack_model
        active_connector_ids: List[UUID] = []
        for components in active_stack.components.values():
            active_connector_ids.extend(
                [
                    component.connector.id
                    for component in components
                    if component.connector
                ]
            )

        cli_utils.print_service_connector_configuration(
            connector=connector,
            active_status=connector.id in active_connector_ids,
            show_secrets=show_secrets,
        )
describe_service_connector_type(type: str, resource_type: Optional[str] = None, auth_method: Optional[str] = None) -> None

Describes a service connector type.

Parameters:

Name Type Description Default
type str

The connector type to describe.

required
resource_type Optional[str]

The resource type to describe.

None
auth_method Optional[str]

The authentication method to describe.

None
Source code in src/zenml/cli/service_connectors.py
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
@service_connector.command(
    "describe-type",
    help="""Describe a service connector type.
""",
)
@click.argument(
    "type",
    type=str,
    required=True,
)
@click.option(
    "--resource-type",
    "-r",
    "resource_type",
    help="Resource type to describe.",
    required=False,
    type=str,
)
@click.option(
    "--auth-method",
    "-a",
    "auth_method",
    help="Authentication method to describe.",
    required=False,
    type=str,
)
def describe_service_connector_type(
    type: str,
    resource_type: Optional[str] = None,
    auth_method: Optional[str] = None,
) -> None:
    """Describes a service connector type.

    Args:
        type: The connector type to describe.
        resource_type: The resource type to describe.
        auth_method: The authentication method to describe.
    """
    client = Client()

    try:
        connector_type = client.get_service_connector_type(type)
    except KeyError:
        cli_utils.error(f"Service connector type '{type}' not found.")

    if resource_type:
        if resource_type not in connector_type.resource_type_dict:
            cli_utils.error(
                f"Resource type '{resource_type}' not found for service "
                f"connector type '{type}'."
            )
        cli_utils.print_service_connector_resource_type(
            connector_type.resource_type_dict[resource_type]
        )
    elif auth_method:
        if auth_method not in connector_type.auth_method_dict:
            cli_utils.error(
                f"Authentication method '{auth_method}' not found for service"
                f" connector type '{type}'."
            )
        cli_utils.print_service_connector_auth_method(
            connector_type.auth_method_dict[auth_method]
        )
    else:
        cli_utils.print_service_connector_type(
            connector_type,
            include_resource_types=False,
            include_auth_methods=False,
        )
list_service_connector_resources(connector_type: Optional[str] = None, resource_type: Optional[str] = None, resource_id: Optional[str] = None, exclude_errors: bool = False) -> None

List resources that can be accessed by service connectors.

Parameters:

Name Type Description Default
connector_type Optional[str]

The type of service connector to filter by.

None
resource_type Optional[str]

The type of resource to filter by.

None
resource_id Optional[str]

The name of a resource to filter by.

None
exclude_errors bool

Exclude resources that cannot be accessed due to errors.

False
Source code in src/zenml/cli/service_connectors.py
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
@service_connector.command(
    "list-resources",
    help="""List all resources accessible by service connectors.

This command can be used to list all resources that can be accessed by the
currently registered service connectors. You can filter the list by connector
type and/or resource type.

Use this command to answer questions like:

- show a list of all Kubernetes clusters that can be accessed by way of service
connectors
- show a list of all connectors along with all the resources they can access or
the error state they are in, if any

NOTE: since this command exercises all service connectors currently registered
with ZenML, it may take a while to complete.

Examples:

- show a list of all S3 buckets that can be accessed by service connectors:

    $ zenml service-connector list-resources --resource-type s3-bucket

- show a list of all resources that the AWS connectors currently registered
with ZenML can access:

    $ zenml service-connector list-resources --connector-type aws

""",
)
@click.option(
    "--connector-type",
    "-c",
    "connector_type",
    help="The type of service connector to filter by.",
    required=False,
    type=str,
)
@click.option(
    "--resource-type",
    "-r",
    "resource_type",
    help="The type of resource to filter by.",
    required=False,
    type=str,
)
@click.option(
    "--resource-id",
    "-ri",
    "resource_id",
    help="The name of a resource to filter by.",
    required=False,
    type=str,
)
@click.option(
    "--exclude-errors",
    "-e",
    "exclude_errors",
    help="Exclude resources that cannot be accessed due to errors.",
    required=False,
    is_flag=True,
)
def list_service_connector_resources(
    connector_type: Optional[str] = None,
    resource_type: Optional[str] = None,
    resource_id: Optional[str] = None,
    exclude_errors: bool = False,
) -> None:
    """List resources that can be accessed by service connectors.

    Args:
        connector_type: The type of service connector to filter by.
        resource_type: The type of resource to filter by.
        resource_id: The name of a resource to filter by.
        exclude_errors: Exclude resources that cannot be accessed due to
            errors.
    """
    client = Client()

    if not resource_type and not resource_id:
        cli_utils.warning(
            "Fetching all service connector resources can take a long time, "
            "depending on the number of connectors currently registered with "
            "ZenML. Consider using the '--connector-type', '--resource-type' "
            "and '--resource-id' options to narrow down the list of resources "
            "to fetch."
        )

    with console.status(
        "Fetching all service connector resources (this could take a while)...\n"
    ):
        try:
            resource_list = client.list_service_connector_resources(
                connector_type=connector_type,
                resource_type=resource_type,
                resource_id=resource_id,
            )
        except (
            KeyError,
            ValueError,
            IllegalOperationError,
            NotImplementedError,
            AuthorizationException,
        ) as e:
            cli_utils.error(
                f"Could not fetch service connector resources: {e}"
            )

        if exclude_errors:
            resource_list = [r for r in resource_list if r.error is None]

        if not resource_list:
            cli_utils.declare(
                "No service connector resources match the given filters."
            )
            return

    resource_str = ""
    if resource_type:
        resource_str = f" '{resource_type}'"
    connector_str = ""
    if connector_type:
        connector_str = f" '{connector_type}'"
    if resource_id:
        resource_str = f"{resource_str} resource with name '{resource_id}'"
    else:
        resource_str = f"following{resource_str} resources"

    click.echo(
        f"The {resource_str} can be accessed by"
        f"{connector_str} service connectors:"
    )

    cli_utils.print_service_connector_resource_table(
        resources=resource_list,
    )
list_service_connector_types(type: Optional[str] = None, resource_type: Optional[str] = None, auth_method: Optional[str] = None, detailed: bool = False) -> None

List service connector types.

Parameters:

Name Type Description Default
type Optional[str]

Filter by service connector type.

None
resource_type Optional[str]

Filter by the type of resource to connect to.

None
auth_method Optional[str]

Filter by the supported authentication method.

None
detailed bool

Show detailed information about the service connectors.

False
Source code in src/zenml/cli/service_connectors.py
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
@service_connector.command(
    "list-types",
    help="""List available service connector types.
""",
)
@click.option(
    "--type",
    "-t",
    "type",
    help="Filter by service connector type.",
    required=False,
    type=str,
)
@click.option(
    "--resource-type",
    "-r",
    "resource_type",
    help="Filter by the type of resource to connect to.",
    required=False,
    type=str,
)
@click.option(
    "--auth-method",
    "-a",
    "auth_method",
    help="Filter by the supported authentication method.",
    required=False,
    type=str,
)
@click.option(
    "--detailed",
    "-d",
    "detailed",
    help="Show detailed information about the service connector types.",
    required=False,
    is_flag=True,
)
def list_service_connector_types(
    type: Optional[str] = None,
    resource_type: Optional[str] = None,
    auth_method: Optional[str] = None,
    detailed: bool = False,
) -> None:
    """List service connector types.

    Args:
        type: Filter by service connector type.
        resource_type: Filter by the type of resource to connect to.
        auth_method: Filter by the supported authentication method.
        detailed: Show detailed information about the service connectors.
    """
    client = Client()

    service_connector_types = client.list_service_connector_types(
        connector_type=type,
        resource_type=resource_type,
        auth_method=auth_method,
    )

    if not service_connector_types:
        cli_utils.error(
            "No service connector types found matching the criteria."
        )

    if detailed:
        for connector_type in service_connector_types:
            cli_utils.print_service_connector_type(connector_type)
    else:
        cli_utils.print_service_connector_types_table(
            connector_types=service_connector_types
        )
list_service_connectors(ctx: click.Context, /, labels: Optional[List[str]] = None, **kwargs: Any) -> None

List all service connectors.

Parameters:

Name Type Description Default
ctx Context

The click context object

required
labels Optional[List[str]]

Labels to filter by.

None
kwargs Any

Keyword arguments to filter the components.

{}
Source code in src/zenml/cli/service_connectors.py
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
@service_connector.command(
    "list",
    help="""List available service connectors.
""",
)
@list_options(ServiceConnectorFilter)
@click.option(
    "--label",
    "-l",
    "labels",
    help="Label to filter by. Takes the form `-l key1=value1` or `-l key` and "
    "can be used multiple times.",
    multiple=True,
)
@click.pass_context
def list_service_connectors(
    ctx: click.Context, /, labels: Optional[List[str]] = None, **kwargs: Any
) -> None:
    """List all service connectors.

    Args:
        ctx: The click context object
        labels: Labels to filter by.
        kwargs: Keyword arguments to filter the components.
    """
    client = Client()

    if labels:
        kwargs["labels"] = cli_utils.get_parsed_labels(
            labels, allow_label_only=True
        )

    connectors = client.list_service_connectors(**kwargs)
    if not connectors:
        cli_utils.declare("No service connectors found for the given filters.")
        return

    cli_utils.print_service_connectors_table(
        client=client,
        connectors=connectors.items,
        show_active=not is_sorted_or_filtered(ctx),
    )
    print_page_info(connectors)
login_service_connector(name_id_or_prefix: str, resource_type: Optional[str] = None, resource_id: Optional[str] = None) -> None

Authenticate the local client/SDK with connector credentials.

Parameters:

Name Type Description Default
name_id_or_prefix str

The name or id of the service connector to use.

required
resource_type Optional[str]

The type of resource to connect to.

None
resource_id Optional[str]

Explicit resource ID to connect to.

None
Source code in src/zenml/cli/service_connectors.py
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
@service_connector.command(
    "login",
    help="""Configure the local client/SDK with credentials.

Some service connectors have the ability to configure clients or SDKs installed
on your local machine with credentials extracted from or generated by the
service connector. This command can be used to do that.

For connectors that are configured to access multiple types of resources or 
multiple resource instances, the resource type and resource ID must be
specified to indicate which resource is targeted by this command.

Examples:

- configure the local Kubernetes (kubectl) CLI with credentials generated from
a generic, multi-type, multi-instance AWS service connector:

    $ zenml service-connector login my-generic-aws-connector \\             
--resource-type kubernetes-cluster --resource-id my-eks-cluster

- configure the local Docker CLI with credentials configured in a Docker
service connector:

    $ zenml service-connector login my-docker-connector
""",
)
@click.option(
    "--resource-type",
    "-r",
    "resource_type",
    help="The type of resource to connect to.",
    required=False,
    type=str,
)
@click.option(
    "--resource-id",
    "-ri",
    "resource_id",
    help="Explicit resource ID to connect to.",
    required=False,
    type=str,
)
@click.argument("name_id_or_prefix", type=str, required=True)
def login_service_connector(
    name_id_or_prefix: str,
    resource_type: Optional[str] = None,
    resource_id: Optional[str] = None,
) -> None:
    """Authenticate the local client/SDK with connector credentials.

    Args:
        name_id_or_prefix: The name or id of the service connector to use.
        resource_type: The type of resource to connect to.
        resource_id: Explicit resource ID to connect to.
    """
    client = Client()

    with console.status(
        "Attempting to configure local client using service connector "
        f"'{name_id_or_prefix}'...\n"
    ):
        try:
            connector = client.login_service_connector(
                name_id_or_prefix=name_id_or_prefix,
                resource_type=resource_type,
                resource_id=resource_id,
            )
        except (
            KeyError,
            ValueError,
            IllegalOperationError,
            NotImplementedError,
            AuthorizationException,
        ) as e:
            cli_utils.error(
                f"Service connector '{name_id_or_prefix}' could not configure "
                f"the local client/SDK: {e}"
            )

        spec = connector.get_type()
        resource_type = resource_type or connector.resource_type
        assert resource_type is not None
        resource_name = spec.resource_type_dict[resource_type].name
        cli_utils.declare(
            f"The '{name_id_or_prefix}' {spec.name} connector was used to "
            f"successfully configure the local {resource_name} client/SDK."
        )
prompt_connector_name(default_name: Optional[str] = None, connector: Optional[UUID] = None) -> str

Prompt the user for a service connector name.

Parameters:

Name Type Description Default
default_name Optional[str]

The default name to use if the user doesn't provide one.

None
connector Optional[UUID]

The UUID of a service connector being renamed.

None

Returns:

Type Description
str

The name provided by the user.

Source code in src/zenml/cli/service_connectors.py
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
def prompt_connector_name(
    default_name: Optional[str] = None, connector: Optional[UUID] = None
) -> str:
    """Prompt the user for a service connector name.

    Args:
        default_name: The default name to use if the user doesn't provide one.
        connector: The UUID of a service connector being renamed.

    Returns:
        The name provided by the user.
    """
    client = Client()

    while True:
        # Ask for a name
        title = "Please enter a name for the service connector"
        if connector:
            title += " or press Enter to keep the current name"

        name = click.prompt(
            title,
            type=str,
            default=default_name,
        )
        if not name:
            cli_utils.warning("The name cannot be empty")
            continue
        assert isinstance(name, str)

        # Check if the name is taken
        try:
            existing_connector = client.get_service_connector(
                name_id_or_prefix=name, allow_name_prefix_match=False
            )
        except KeyError:
            break
        else:
            if existing_connector.id == connector:
                break
            cli_utils.warning(
                f"A service connector with the name '{name}' already "
                "exists. Please choose a different name."
            )

    return name
prompt_expiration_time(min: Optional[int] = None, max: Optional[int] = None, default: Optional[int] = None) -> int

Prompt the user for an expiration time.

Parameters:

Name Type Description Default
min Optional[int]

The minimum allowed expiration time.

None
max Optional[int]

The maximum allowed expiration time.

None
default Optional[int]

The default expiration time.

None

Returns:

Type Description
int

The expiration time provided by the user.

Source code in src/zenml/cli/service_connectors.py
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
def prompt_expiration_time(
    min: Optional[int] = None,
    max: Optional[int] = None,
    default: Optional[int] = None,
) -> int:
    """Prompt the user for an expiration time.

    Args:
        min: The minimum allowed expiration time.
        max: The maximum allowed expiration time.
        default: The default expiration time.

    Returns:
        The expiration time provided by the user.
    """
    if min is None:
        min = 0
    min_str = f"min: {min} = {seconds_to_human_readable(min)}; "
    if max is not None:
        max_str = str(max)
        max_str = f"max: {max} = {seconds_to_human_readable(max)}"
    else:
        max = -1
        max_str = "max: unlimited"
    if default:
        default_str = (
            f"; default: {default} = {seconds_to_human_readable(default)}"
        )
    else:
        default_str = ""

    while True:
        expiration_seconds = click.prompt(
            "The authentication method involves generating "
            "temporary credentials. Please enter the time that "
            "the credentials should be valid for, in seconds "
            f"({min_str}{max_str}{default_str})",
            type=int,
            default=default,
        )

        assert expiration_seconds is not None
        assert isinstance(expiration_seconds, int)
        if expiration_seconds < min:
            cli_utils.warning(
                f"The expiration time must be at least "
                f"{min} seconds. Please enter a larger value."
            )
            continue
        if max > 0 and expiration_seconds > max:
            cli_utils.warning(
                f"The expiration time must not exceed "
                f"{max} seconds. Please enter a smaller value."
            )
            continue

        confirm = click.confirm(
            f"Credentials will be valid for "
            f"{seconds_to_human_readable(expiration_seconds)}. Keep this "
            "value?",
            default=True,
        )
        if confirm:
            break

    return expiration_seconds
prompt_expires_at(default: Optional[datetime] = None) -> Optional[datetime]

Prompt the user for an expiration timestamp.

Parameters:

Name Type Description Default
default Optional[datetime]

The default expiration time.

None

Returns:

Type Description
Optional[datetime]

The expiration time provided by the user.

Source code in src/zenml/cli/service_connectors.py
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
def prompt_expires_at(
    default: Optional[datetime] = None,
) -> Optional[datetime]:
    """Prompt the user for an expiration timestamp.

    Args:
        default: The default expiration time.

    Returns:
        The expiration time provided by the user.
    """
    if default is None:
        confirm = click.confirm(
            "Are the credentials you configured temporary? If so, you'll be asked "
            "to provide an expiration time in the next step.",
            default=False,
        )
        if not confirm:
            return None

    while True:
        default_str = ""
        if default is not None:
            seconds = int(
                (default - utc_now(tz_aware=default)).total_seconds()
            )
            default_str = (
                f" [{str(default)} i.e. in "
                f"{seconds_to_human_readable(seconds)}]"
            )

        expires_at = click.prompt(
            "Please enter the exact UTC date and time when the credentials "
            f"will expire e.g. '2023-12-31 23:59:59'{default_str}",
            type=click.DateTime(),
            default=default,
            show_default=False,
        )

        assert expires_at is not None
        assert isinstance(expires_at, datetime)
        if expires_at < utc_now(tz_aware=expires_at):
            cli_utils.warning(
                "The expiration time must be in the future. Please enter a "
                "later date and time."
            )
            continue

        seconds = int(
            (expires_at - utc_now(tz_aware=expires_at)).total_seconds()
        )

        confirm = click.confirm(
            f"Credentials will be valid until {str(expires_at)} UTC (i.e. "
            f"in {seconds_to_human_readable(seconds)}. Keep this value?",
            default=True,
        )
        if confirm:
            break

    return expires_at
prompt_resource_id(resource_name: str, resource_ids: List[str]) -> Optional[str]

Prompt the user for a resource ID.

Parameters:

Name Type Description Default
resource_name str

The name of the resource.

required
resource_ids List[str]

The list of available resource IDs.

required

Returns:

Type Description
Optional[str]

The resource ID provided by the user.

Source code in src/zenml/cli/service_connectors.py
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
def prompt_resource_id(
    resource_name: str, resource_ids: List[str]
) -> Optional[str]:
    """Prompt the user for a resource ID.

    Args:
        resource_name: The name of the resource.
        resource_ids: The list of available resource IDs.

    Returns:
        The resource ID provided by the user.
    """
    resource_id: Optional[str] = None
    if resource_ids:
        resource_ids_list = "\n - " + "\n - ".join(resource_ids)
        prompt = (
            f"The following {resource_name} instances "
            "are reachable through this connector:"
            f"{resource_ids_list}\n"
            "Please select one or leave it empty to create a "
            "connector that can be used to access any of them"
        )
        while True:
            # Ask the user to enter an optional resource ID
            resource_id = click.prompt(
                prompt,
                default="",
                type=str,
            )
            if (
                not resource_ids
                or not resource_id
                or resource_id in resource_ids
            ):
                break

            cli_utils.warning(
                f"The selected '{resource_id}' value is not one of "
                "the listed values. Please try again."
            )
    else:
        prompt = (
            "The connector configuration can be used to access "
            f"multiple {resource_name} instances. If you "
            "would like to limit the scope of the connector to one "
            "instance, please enter the name of a particular "
            f"{resource_name} instance. Or leave it "
            "empty to create a multi-instance connector that can "
            f"be used to access any {resource_name}"
        )
        resource_id = click.prompt(
            prompt,
            default="",
            type=str,
        )

    if resource_id == "":
        resource_id = None

    return resource_id
prompt_resource_type(available_resource_types: List[str]) -> Optional[str]

Prompt the user for a resource type.

Parameters:

Name Type Description Default
available_resource_types List[str]

The list of available resource types.

required

Returns:

Type Description
Optional[str]

The resource type provided by the user.

Source code in src/zenml/cli/service_connectors.py
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
def prompt_resource_type(available_resource_types: List[str]) -> Optional[str]:
    """Prompt the user for a resource type.

    Args:
        available_resource_types: The list of available resource types.

    Returns:
        The resource type provided by the user.
    """
    resource_type = None
    if len(available_resource_types) == 1:
        # Default to the first resource type if only one type is available
        click.echo(
            "Only one resource type is available for this connector"
            f" ({available_resource_types[0]})."
        )
        resource_type = available_resource_types[0]
    else:
        # Ask the user to select a resource type
        while True:
            resource_type = click.prompt(
                "Please select a resource type or leave it empty to create "
                "a connector that can be used to access any of the "
                "supported resource types "
                f"({', '.join(available_resource_types)}).",
                type=str,
                default="",
            )
            if resource_type and resource_type not in available_resource_types:
                cli_utils.warning(
                    f"The entered resource type '{resource_type}' is not "
                    "one of the listed values. Please try again."
                )
                continue
            break

        if resource_type == "":
            resource_type = None

    return resource_type
register_service_connector(name: Optional[str], args: List[str], description: Optional[str] = None, connector_type: Optional[str] = None, resource_type: Optional[str] = None, resource_id: Optional[str] = None, auth_method: Optional[str] = None, expires_at: Optional[datetime] = None, expires_skew_tolerance: Optional[int] = None, expiration_seconds: Optional[int] = None, no_verify: bool = False, labels: Optional[List[str]] = None, interactive: bool = False, no_docs: bool = False, show_secrets: bool = False, auto_configure: bool = False) -> None

Registers a service connector.

Parameters:

Name Type Description Default
name Optional[str]

The name to use for the service connector.

required
args List[str]

Configuration arguments for the service connector.

required
description Optional[str]

Short description for the service connector.

None
connector_type Optional[str]

The service connector type.

None
resource_type Optional[str]

The type of resource to connect to.

None
resource_id Optional[str]

The ID of the resource to connect to.

None
auth_method Optional[str]

The authentication method to use.

None
expires_at Optional[datetime]

The exact UTC date and time when the credentials configured for this connector will expire.

None
expires_skew_tolerance Optional[int]

The tolerance, in seconds, allowed when determining when the credentials configured for or generated by this connector will expire.

None
expiration_seconds Optional[int]

The duration, in seconds, that the temporary credentials generated by this connector should remain valid.

None
no_verify bool

Do not verify the service connector before registering.

False
labels Optional[List[str]]

Labels to be associated with the service connector.

None
interactive bool

Register a new service connector interactively.

False
no_docs bool

Don't show documentation details during the interactive configuration.

False
show_secrets bool

Show security sensitive configuration attributes in the terminal.

False
auto_configure bool

Auto configure the service connector.

False

Raises:

Type Description
TypeError

If the connector_model does not have the correct type.

Source code in src/zenml/cli/service_connectors.py
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
@service_connector.command(
    "register",
    context_settings={"ignore_unknown_options": True},
    help="""Configure, validate and register a service connector.

This command can be used to configure and register a ZenML service connector and
to optionally verify that the service connector configuration and credentials
are valid and can be used to access the specified resource(s).

If the `-i|--interactive` flag is set, it will prompt the user for all the
information required to configure a service connector in a wizard-like fashion:

    $ zenml service-connector register -i

To trim down the amount of information displayed in interactive mode, pass the
`-n|--no-docs` flag:

    $ zenml service-connector register -ni

Secret configuration attributes are not shown by default. Use the
`-x|--show-secrets` flag to show them:

    $ zenml service-connector register -ix

Non-interactive examples:

- register a multi-purpose AWS service connector capable of accessing
any of the resource types that it supports (e.g. S3 buckets, EKS Kubernetes
clusters) using auto-configured credentials (i.e. extracted from the environment
variables or AWS CLI configuration files):

    $ zenml service-connector register aws-auto-multi --description \\
"Multi-purpose AWS connector" --type aws --auto-configure \\
--label auto=true --label purpose=multi

- register a Docker service connector providing access to a single DockerHub
repository named `dockerhub-hyppo` using explicit credentials:

    $ zenml service-connector register dockerhub-hyppo --description \\
"Hyppo's DockerHub repo" --type docker --resource-id dockerhub-hyppo \\
--username=hyppo --password=mypassword

- register an AWS service connector providing access to all the S3 buckets
that it's authorized to access using IAM role credentials:

    $ zenml service-connector register aws-s3-multi --description \\   
"Multi-bucket S3 connector" --type aws --resource-type s3-bucket \\    
--auth_method iam-role --role_arn=arn:aws:iam::<account>:role/<role> \\
--aws_region=us-east-1 --aws-access-key-id=<aws-key-id> \\            
--aws_secret_access_key=<aws-secret-key> --expiration-seconds 3600

All registered service connectors are validated before being registered. To
skip validation, pass the `--no-verify` flag.
""",
)
@click.argument(
    "name",
    type=str,
    required=False,
)
@click.option(
    "--description",
    "description",
    help="Short description for the connector instance.",
    required=False,
    type=str,
)
@click.option(
    "--type",
    "-t",
    "connector_type",
    help="The service connector type.",
    required=False,
    type=str,
)
@click.option(
    "--resource-type",
    "-r",
    "resource_type",
    help="The type of resource to connect to.",
    required=False,
    type=str,
)
@click.option(
    "--resource-id",
    "-ri",
    "resource_id",
    help="The ID of the resource to connect to.",
    required=False,
    type=str,
)
@click.option(
    "--auth-method",
    "-a",
    "auth_method",
    help="The authentication method to use.",
    required=False,
    type=str,
)
@click.option(
    "--expires-at",
    "expires_at",
    help="The exact UTC date and time when the credentials configured for this "
    "connector will expire. Takes the form 'YYYY-MM-DD HH:MM:SS'. This is only "
    "required if you are configuring a service connector with expiring "
    "credentials.",
    required=False,
    type=click.DateTime(),
)
@click.option(
    "--expires-skew-tolerance",
    "expires_skew_tolerance",
    help="The tolerance, in seconds, allowed when determining when the "
    "credentials configured for or generated by this connector will expire.",
    required=False,
    type=int,
)
@click.option(
    "--expiration-seconds",
    "expiration_seconds",
    help="The duration, in seconds, that the temporary credentials "
    "generated by this connector should remain valid.",
    required=False,
    type=int,
)
@click.option(
    "--label",
    "-l",
    "labels",
    help="Labels to be associated with the service connector. Takes the form "
    "-l key1=value1 and can be used multiple times.",
    multiple=True,
)
@click.option(
    "--no-verify",
    "no_verify",
    is_flag=True,
    default=False,
    help="Do not verify the service connector before registering.",
    type=click.BOOL,
)
@click.option(
    "--interactive",
    "-i",
    "interactive",
    is_flag=True,
    default=False,
    help="Register a new service connector interactively.",
    type=click.BOOL,
)
@click.option(
    "--no-docs",
    "-n",
    "no_docs",
    is_flag=True,
    default=False,
    help="Don't show documentation details during the interactive "
    "configuration.",
    type=click.BOOL,
)
@click.option(
    "--show-secrets",
    "-x",
    "show_secrets",
    is_flag=True,
    default=False,
    help="Show security sensitive configuration attributes in the terminal.",
    type=click.BOOL,
)
@click.option(
    "--auto-configure",
    "auto_configure",
    is_flag=True,
    default=False,
    help="Auto configure the service connector.",
    type=click.BOOL,
)
@click.argument("args", nargs=-1, type=click.UNPROCESSED)
def register_service_connector(
    name: Optional[str],
    args: List[str],
    description: Optional[str] = None,
    connector_type: Optional[str] = None,
    resource_type: Optional[str] = None,
    resource_id: Optional[str] = None,
    auth_method: Optional[str] = None,
    expires_at: Optional[datetime] = None,
    expires_skew_tolerance: Optional[int] = None,
    expiration_seconds: Optional[int] = None,
    no_verify: bool = False,
    labels: Optional[List[str]] = None,
    interactive: bool = False,
    no_docs: bool = False,
    show_secrets: bool = False,
    auto_configure: bool = False,
) -> None:
    """Registers a service connector.

    Args:
        name: The name to use for the service connector.
        args: Configuration arguments for the service connector.
        description: Short description for the service connector.
        connector_type: The service connector type.
        resource_type: The type of resource to connect to.
        resource_id: The ID of the resource to connect to.
        auth_method: The authentication method to use.
        expires_at: The exact UTC date and time when the credentials configured
            for this connector will expire.
        expires_skew_tolerance: The tolerance, in seconds, allowed when
            determining when the credentials configured for or generated by
            this connector will expire.
        expiration_seconds: The duration, in seconds, that the temporary
            credentials generated by this connector should remain valid.
        no_verify: Do not verify the service connector before
            registering.
        labels: Labels to be associated with the service connector.
        interactive: Register a new service connector interactively.
        no_docs: Don't show documentation details during the interactive
            configuration.
        show_secrets: Show security sensitive configuration attributes in
            the terminal.
        auto_configure: Auto configure the service connector.

    Raises:
        TypeError: If the connector_model does not have the correct type.
    """
    from rich.markdown import Markdown

    client = Client()

    # Parse the given args
    name, parsed_args = cli_utils.parse_name_and_extra_arguments(
        list(args) + [name or ""],
        expand_args=True,
        name_mandatory=not interactive,
    )

    # Parse the given labels
    parsed_labels = cast(Dict[str, str], cli_utils.get_parsed_labels(labels))

    if interactive:
        # Get the list of available service connector types
        connector_types = client.list_service_connector_types(
            connector_type=connector_type,
            resource_type=resource_type,
            auth_method=auth_method,
        )
        if not connector_types:
            cli_utils.error(
                "No service connectors found with the given parameters: "
                + f"type={connector_type} "
                if connector_type
                else "" + f"resource_type={resource_type} "
                if resource_type
                else "" + f"auth_method={auth_method} "
                if auth_method
                else "",
            )

        # Ask for a connector name
        name = prompt_connector_name(name)

        # Ask for a description
        description = click.prompt(
            "Please enter a description for the service connector",
            type=str,
            default="",
        )

        available_types = {c.connector_type: c for c in connector_types}
        if len(available_types) == 1:
            # Default to the first connector type if not supplied and if
            # only one type is available
            connector_type = connector_type or list(available_types.keys())[0]

        # Print the name, type and description of all available service
        # connectors
        if not no_docs:
            message = "# Available service connector types\n"
            for spec in connector_types:
                message += cli_utils.print_service_connector_type(
                    connector_type=spec,
                    heading="##",
                    footer="",
                    include_auth_methods=False,
                    include_resource_types=False,
                    print=False,
                )
            console.print(Markdown(f"{message}---"), justify="left", width=80)

        # Ask the user to select a service connector type
        connector_type = click.prompt(
            "Please select a service connector type",
            type=click.Choice(list(available_types.keys())),
            default=connector_type,
        )

        assert connector_type is not None
        connector_type_spec = available_types[connector_type]

        available_resource_types = [
            t.resource_type for t in connector_type_spec.resource_types
        ]

        if not no_docs:
            # Print the name, resource type identifiers and description of all
            # available resource types
            message = "# Available resource types\n"
            for r in connector_type_spec.resource_types:
                message += cli_utils.print_service_connector_resource_type(
                    resource_type=r,
                    heading="##",
                    footer="",
                    print=False,
                )
            console.print(Markdown(f"{message}---"), justify="left", width=80)

        # Ask the user to select a resource type
        resource_type = prompt_resource_type(
            available_resource_types=available_resource_types
        )

        # Ask the user whether to use autoconfiguration, if the connector
        # implementation is locally available and if autoconfiguration is
        # supported
        if (
            connector_type_spec.supports_auto_configuration
            and connector_type_spec.local
        ):
            auto_configure = click.confirm(
                "Would you like to attempt auto-configuration to extract the "
                "authentication configuration from your local environment ?",
                default=False,
            )
        else:
            auto_configure = False

        connector_model: Optional[
            Union[ServiceConnectorRequest, ServiceConnectorResponse]
        ] = None
        connector_resources: Optional[ServiceConnectorResourcesModel] = None
        if auto_configure:
            # Try to autoconfigure the service connector
            try:
                with console.status("Auto-configuring service connector...\n"):
                    (
                        connector_model,
                        connector_resources,
                    ) = client.create_service_connector(
                        name=name,
                        description=description or "",
                        connector_type=connector_type,
                        resource_type=resource_type,
                        auth_method=auth_method,
                        expires_skew_tolerance=expires_skew_tolerance,
                        auto_configure=True,
                        verify=True,
                        register=False,
                    )

                assert connector_model is not None
                assert connector_resources is not None
            except (
                KeyError,
                ValueError,
                IllegalOperationError,
                NotImplementedError,
                AuthorizationException,
            ) as e:
                cli_utils.warning(
                    f"Auto-configuration was not successful: {e} "
                )
                # Ask the user whether to continue with manual configuration
                manual = click.confirm(
                    "Would you like to continue with manual configuration ?",
                    default=True,
                )
                if not manual:
                    return
            else:
                auth_method = connector_model.auth_method
                expiration_seconds = connector_model.expiration_seconds
                expires_at = connector_model.expires_at
                cli_utils.declare(
                    "Service connector auto-configured successfully with the "
                    "following configuration:"
                )

                # Print the configuration detected by the autoconfiguration
                # process
                # TODO: Normally, this could have been handled with setter
                #   functions over the connector type property in the response
                #   model. However, pydantic breaks property setter functions.
                #   We can find a more elegant solution here.
                if isinstance(connector_model, ServiceConnectorResponse):
                    connector_model.set_connector_type(connector_type_spec)
                elif isinstance(connector_model, ServiceConnectorRequest):
                    connector_model.connector_type = connector_type_spec
                else:
                    raise TypeError(
                        "The service connector must be an instance of either"
                        "`ServiceConnectorResponse` or "
                        "`ServiceConnectorRequest`."
                    )

                cli_utils.print_service_connector_configuration(
                    connector_model,
                    active_status=False,
                    show_secrets=show_secrets,
                )
                cli_utils.declare(
                    "The service connector configuration has access to the "
                    "following resources:"
                )
                cli_utils.print_service_connector_resource_table(
                    [connector_resources],
                    show_resources_only=True,
                )

                # Ask the user whether to continue with the autoconfiguration
                choice = click.prompt(
                    "Would you like to continue with the auto-discovered "
                    "configuration or switch to manual ?",
                    type=click.Choice(["auto", "manual"]),
                    default="auto",
                )
                if choice == "manual":
                    # Reset the connector configuration to default to let the
                    # manual configuration kick in the next step
                    connector_model = None
                    connector_resources = None
                    expires_at = None

        if connector_model is not None and connector_resources is not None:
            assert auth_method is not None
            auth_method_spec = connector_type_spec.auth_method_dict[
                auth_method
            ]
        else:
            # In this branch, we are either not using autoconfiguration or the
            # autoconfiguration failed or was dismissed. In all cases, we need
            # to ask the user for the authentication method to use and then
            # prompt for the configuration

            auth_methods = list(connector_type_spec.auth_method_dict.keys())

            if not no_docs:
                # Print the name, identifier and description of all available
                # auth methods
                message = "# Available authentication methods\n"
                for a in auth_methods:
                    message += cli_utils.print_service_connector_auth_method(
                        auth_method=connector_type_spec.auth_method_dict[a],
                        heading="##",
                        footer="",
                        print=False,
                    )
                console.print(
                    Markdown(f"{message}---"), justify="left", width=80
                )

            if len(auth_methods) == 1:
                # Default to the first auth method if only one method is
                # available
                confirm = click.confirm(
                    "Only one authentication method is available for this "
                    f"connector ({auth_methods[0]}). Would you like to use it?",
                    default=True,
                )
                if not confirm:
                    return

                auth_method = auth_methods[0]
            else:
                # Ask the user to select an authentication method
                auth_method = click.prompt(
                    "Please select an authentication method",
                    type=click.Choice(auth_methods),
                    default=auth_method,
                )

            assert auth_method is not None
            auth_method_spec = connector_type_spec.auth_method_dict[
                auth_method
            ]

            cli_utils.declare(
                f"Please enter the configuration for the {auth_method_spec.name} "
                "authentication method."
            )

            # Prompt for the configuration of the selected authentication method
            # field by field
            config_schema = auth_method_spec.config_schema or {}
            config_dict = cli_utils.prompt_configuration(
                config_schema=config_schema,
                show_secrets=show_secrets,
            )

            # Prompt for an expiration time if the auth method supports it
            if auth_method_spec.supports_temporary_credentials():
                expiration_seconds = prompt_expiration_time(
                    min=auth_method_spec.min_expiration_seconds,
                    max=auth_method_spec.max_expiration_seconds,
                    default=auth_method_spec.default_expiration_seconds,
                )

            # Prompt for the time when the credentials will expire
            expires_at = prompt_expires_at(expires_at)

            try:
                # Validate the connector configuration and fetch all available
                # resources that are accessible with the provided configuration
                # in the process
                with console.status(
                    "Validating service connector configuration...\n"
                ):
                    (
                        connector_model,
                        connector_resources,
                    ) = client.create_service_connector(
                        name=name,
                        description=description or "",
                        connector_type=connector_type,
                        auth_method=auth_method,
                        resource_type=resource_type,
                        configuration=config_dict,
                        expires_at=expires_at,
                        expires_skew_tolerance=expires_skew_tolerance,
                        expiration_seconds=expiration_seconds,
                        auto_configure=False,
                        verify=True,
                        register=False,
                    )
                assert connector_model is not None
                assert connector_resources is not None
            except (
                KeyError,
                ValueError,
                IllegalOperationError,
                NotImplementedError,
                AuthorizationException,
            ) as e:
                cli_utils.error(f"Failed to configure service connector: {e}")

        if resource_type:
            # Finally, for connectors that are configured with a particular
            # resource type, prompt the user to select one of the available
            # resources that can be accessed with the connector. We don't do
            # need to do this for resource types that don't support instances.
            resource_type_spec = connector_type_spec.resource_type_dict[
                resource_type
            ]
            if resource_type_spec.supports_instances:
                assert len(connector_resources.resources) == 1
                resource_ids = connector_resources.resources[0].resource_ids
                assert resource_ids is not None
                resource_id = prompt_resource_id(
                    resource_name=resource_type_spec.name,
                    resource_ids=resource_ids,
                )
            else:
                resource_id = None
        else:
            resource_id = None

        # Prepare the rest of the variables to fall through to the
        # non-interactive configuration case
        parsed_args = connector_model.configuration
        parsed_args.update(
            {
                k: s.get_secret_value()
                for k, s in connector_model.secrets.items()
                if s is not None
            }
        )
        auto_configure = False
        no_verify = False
        expiration_seconds = connector_model.expiration_seconds

    if not connector_type:
        cli_utils.error(
            "The connector type must be specified when using non-interactive "
            "configuration."
        )

    with console.status(f"Registering service connector '{name}'...\n"):
        try:
            # Create a new service connector
            assert name is not None
            (
                connector_model,
                connector_resources,
            ) = client.create_service_connector(
                name=name,
                connector_type=connector_type,
                auth_method=auth_method,
                resource_type=resource_type,
                configuration=parsed_args,
                resource_id=resource_id,
                description=description or "",
                expires_skew_tolerance=expires_skew_tolerance,
                expiration_seconds=expiration_seconds,
                expires_at=expires_at,
                labels=parsed_labels,
                verify=not no_verify,
                auto_configure=auto_configure,
                register=True,
            )
        except (
            KeyError,
            ValueError,
            IllegalOperationError,
            NotImplementedError,
            AuthorizationException,
        ) as e:
            cli_utils.error(f"Failed to register service connector: {e}")

    if connector_resources is not None:
        cli_utils.declare(
            f"Successfully registered service connector `{name}` with access "
            "to the following resources:"
        )

        cli_utils.print_service_connector_resource_table(
            [connector_resources],
            show_resources_only=True,
        )

    else:
        cli_utils.declare(
            f"Successfully registered service connector `{name}`."
        )
service_connector() -> None

Configure and manage service connectors.

Source code in src/zenml/cli/service_connectors.py
43
44
45
46
47
48
@cli.group(
    cls=TagGroup,
    tag=CliCategories.IDENTITY_AND_SECURITY,
)
def service_connector() -> None:
    """Configure and manage service connectors."""
update_service_connector(args: List[str], name_id_or_prefix: Optional[str] = None, name: Optional[str] = None, description: Optional[str] = None, connector_type: Optional[str] = None, resource_type: Optional[str] = None, resource_id: Optional[str] = None, auth_method: Optional[str] = None, expires_at: Optional[datetime] = None, expires_skew_tolerance: Optional[int] = None, expiration_seconds: Optional[int] = None, no_verify: bool = False, labels: Optional[List[str]] = None, interactive: bool = False, show_secrets: bool = False, remove_attrs: Optional[List[str]] = None) -> None

Updates a service connector.

Parameters:

Name Type Description Default
args List[str]

Configuration arguments for the service connector.

required
name_id_or_prefix Optional[str]

The name or ID of the service connector to update.

None
name Optional[str]

New connector name.

None
description Optional[str]

Short description for the service connector.

None
connector_type Optional[str]

The service connector type.

None
resource_type Optional[str]

The type of resource to connect to.

None
resource_id Optional[str]

The ID of the resource to connect to.

None
auth_method Optional[str]

The authentication method to use.

None
expires_at Optional[datetime]

The time at which the credentials configured for this connector will expire.

None
expires_skew_tolerance Optional[int]

The tolerance, in seconds, allowed when determining when the credentials configured for or generated by this connector will expire.

None
expiration_seconds Optional[int]

The duration, in seconds, that the temporary credentials generated by this connector should remain valid.

None
no_verify bool

Do not verify the service connector before updating.

False
labels Optional[List[str]]

Labels to be associated with the service connector.

None
interactive bool

Register a new service connector interactively.

False
show_secrets bool

Show security sensitive configuration attributes in the terminal.

False
remove_attrs Optional[List[str]]

Configuration attributes to be removed from the configuration.

None
Source code in src/zenml/cli/service_connectors.py
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
@service_connector.command(
    "update",
    context_settings={"ignore_unknown_options": True},
    help="""Update and verify an existing service connector.

This command can be used to update an existing ZenML service connector and
to optionally verify that the updated service connector configuration and
credentials are still valid and can be used to access the specified resource(s).

If the `-i|--interactive` flag is set, it will prompt the user for all the
information required to update the service connector configuration:

    $ zenml service-connector update -i <connector-name-or-id>

For consistency reasons, the connector type cannot be changed. If you need to
change the connector type, you need to create a new service connector.
You also cannot change the authentication method, resource type and resource ID
of a service connector that is already actively being used by one or more stack
components.

Secret configuration attributes are not shown by default. Use the
`-x|--show-secrets` flag to show them:

    $ zenml service-connector update -ix <connector-name-or-id>

Non-interactive examples:

- update the DockerHub repository that a Docker service connector is configured
to provide access to:

    $ zenml service-connector update dockerhub-hyppo --resource-id lylemcnew

- update the AWS credentials that an AWS service connector is configured to
use from an STS token to an AWS secret key. This involves updating some config
values and deleting others:

    $ zenml service-connector update aws-auto-multi \\
--aws_access_key_id=<aws-key-id> \\
--aws_secret_access_key=<aws-secret-key>  \\
--remove-attr aws-sts-token

- update the foo label to a new value and delete the baz label from a connector:

    $ zenml service-connector update gcp-eu-multi \\                          
--label foo=bar --label baz

All service connectors updates are validated before being applied. To skip
validation, pass the `--no-verify` flag.
""",
)
@click.argument(
    "name_id_or_prefix",
    type=str,
    required=True,
)
@click.option(
    "--name",
    "name",
    help="New connector name.",
    required=False,
    type=str,
)
@click.option(
    "--description",
    "description",
    help="Short description for the connector instance.",
    required=False,
    type=str,
)
@click.option(
    "--resource-type",
    "-r",
    "resource_type",
    help="The type of resource to connect to.",
    required=False,
    type=str,
)
@click.option(
    "--resource-id",
    "-ri",
    "resource_id",
    help="The ID of the resource to connect to.",
    required=False,
    type=str,
)
@click.option(
    "--auth-method",
    "-a",
    "auth_method",
    help="The authentication method to use.",
    required=False,
    type=str,
)
@click.option(
    "--expires-at",
    "expires_at",
    help="The time at which the credentials configured for this connector "
    "will expire.",
    required=False,
    type=click.DateTime(),
)
@click.option(
    "--expires-skew-tolerance",
    "expires_skew_tolerance",
    help="The tolerance, in seconds, allowed when determining when the "
    "credentials configured for or generated by this connector will expire.",
    required=False,
    type=int,
)
@click.option(
    "--expiration-seconds",
    "expiration_seconds",
    help="The duration, in seconds, that the temporary credentials "
    "generated by this connector should remain valid.",
    required=False,
    type=int,
)
@click.option(
    "--label",
    "-l",
    "labels",
    help="Labels to be associated with the service connector. Takes the form "
    "`-l key1=value1` or `-l key1` and can be used multiple times.",
    multiple=True,
)
@click.option(
    "--no-verify",
    "no_verify",
    is_flag=True,
    default=False,
    help="Do not verify the service connector before registering.",
    type=click.BOOL,
)
@click.option(
    "--interactive",
    "-i",
    "interactive",
    is_flag=True,
    default=False,
    help="Register a new service connector interactively.",
    type=click.BOOL,
)
@click.option(
    "--show-secrets",
    "-x",
    "show_secrets",
    is_flag=True,
    default=False,
    help="Show security sensitive configuration attributes in the terminal.",
    type=click.BOOL,
)
@click.option(
    "--remove-attr",
    "-r",
    "remove_attrs",
    help="Configuration attributes to be removed from the configuration. Takes "
    "the form `-r attr-name` and can be used multiple times.",
    multiple=True,
)
@click.argument("args", nargs=-1, type=click.UNPROCESSED)
def update_service_connector(
    args: List[str],
    name_id_or_prefix: Optional[str] = None,
    name: Optional[str] = None,
    description: Optional[str] = None,
    connector_type: Optional[str] = None,
    resource_type: Optional[str] = None,
    resource_id: Optional[str] = None,
    auth_method: Optional[str] = None,
    expires_at: Optional[datetime] = None,
    expires_skew_tolerance: Optional[int] = None,
    expiration_seconds: Optional[int] = None,
    no_verify: bool = False,
    labels: Optional[List[str]] = None,
    interactive: bool = False,
    show_secrets: bool = False,
    remove_attrs: Optional[List[str]] = None,
) -> None:
    """Updates a service connector.

    Args:
        args: Configuration arguments for the service connector.
        name_id_or_prefix: The name or ID of the service connector to
            update.
        name: New connector name.
        description: Short description for the service connector.
        connector_type: The service connector type.
        resource_type: The type of resource to connect to.
        resource_id: The ID of the resource to connect to.
        auth_method: The authentication method to use.
        expires_at: The time at which the credentials configured for this
            connector will expire.
        expires_skew_tolerance: The tolerance, in seconds, allowed when
            determining when the credentials configured for or generated by
            this connector will expire.
        expiration_seconds: The duration, in seconds, that the temporary
            credentials generated by this connector should remain valid.
        no_verify: Do not verify the service connector before
            updating.
        labels: Labels to be associated with the service connector.
        interactive: Register a new service connector interactively.
        show_secrets: Show security sensitive configuration attributes in
            the terminal.
        remove_attrs: Configuration attributes to be removed from the
            configuration.
    """
    client = Client()

    # Parse the given args
    name_id_or_prefix, parsed_args = cli_utils.parse_name_and_extra_arguments(
        list(args) + [name_id_or_prefix or ""],
        expand_args=True,
        name_mandatory=True,
    )
    assert name_id_or_prefix is not None

    # Parse the given labels
    parsed_labels = cli_utils.get_parsed_labels(labels, allow_label_only=True)

    # Start by fetching the existing connector configuration
    try:
        connector = client.get_service_connector(
            name_id_or_prefix,
            allow_name_prefix_match=False,
            load_secrets=True,
        )
    except KeyError as e:
        cli_utils.error(str(e))

    if interactive:
        # Fetch the connector type specification if not already embedded
        # into the connector model
        if isinstance(connector.connector_type, str):
            try:
                connector_type_spec = client.get_service_connector_type(
                    connector.connector_type
                )
            except KeyError as e:
                cli_utils.error(
                    "Could not find the connector type "
                    f"'{connector.connector_type}' associated with the "
                    f"'{connector.name}' connector: {e}."
                )
        else:
            connector_type_spec = connector.connector_type

        # Ask for a new name, if needed
        name = prompt_connector_name(connector.name, connector=connector.id)

        # Ask for a new description, if needed
        description = click.prompt(
            "Updated service connector description",
            type=str,
            default=connector.description,
        )

        # Ask for a new authentication method
        auth_method = click.prompt(
            "If you would like to update the authentication method, please "
            "select a new one from the following options, otherwise press "
            "enter to keep the existing one. Please note that changing "
            "the authentication method may invalidate the existing "
            "configuration and credentials and may require you to reconfigure "
            "the connector from scratch",
            type=click.Choice(
                list(connector_type_spec.auth_method_dict.keys()),
            ),
            default=connector.auth_method,
        )

        assert auth_method is not None
        auth_method_spec = connector_type_spec.auth_method_dict[auth_method]

        # If the authentication method has changed, we need to reconfigure
        # the connector from scratch; otherwise, we ask the user if they
        # want to update the existing configuration
        if auth_method != connector.auth_method:
            confirm = True
        else:
            confirm = click.confirm(
                "Would you like to update the authentication configuration?",
                default=False,
            )

        existing_config = connector.full_configuration

        if confirm:
            # Here we reconfigure the connector or update the existing
            # configuration. The existing configuration is used as much
            # as possible to avoid the user having to re-enter the same
            # values from scratch.

            cli_utils.declare(
                f"Please update or verify the existing configuration for the "
                f"'{auth_method_spec.name}' authentication method."
            )

            # Prompt for the configuration of the selected authentication method
            # field by field
            config_schema = auth_method_spec.config_schema or {}
            config_dict = cli_utils.prompt_configuration(
                config_schema=config_schema,
                show_secrets=show_secrets,
                existing_config=existing_config,
            )

        else:
            config_dict = existing_config

        # Next, we address resource type updates. If the connector is
        # configured to access a single resource type, we don't need to
        # ask the user for a new resource type. We only look at the
        # resource types that support the selected authentication method.
        available_resource_types = [
            r.resource_type
            for r in connector_type_spec.resource_types
            if auth_method in r.auth_methods
        ]
        if len(available_resource_types) == 1:
            resource_type = available_resource_types[0]
        else:
            if connector.is_multi_type:
                resource_type = None
                title = (
                    "The connector is configured to access any of the supported "
                    f"resource types ({', '.join(available_resource_types)}). "
                    "Would you like to restrict it to a single resource type?"
                )
            else:
                resource_type = connector.resource_types[0]
                title = (
                    "The connector is configured to access the "
                    f"{resource_type} resource type. "
                    "Would you like to change that?"
                )
            confirm = click.confirm(title, default=False)

            if confirm:
                # Prompt for a new resource type, if needed
                resource_type = prompt_resource_type(
                    available_resource_types=available_resource_types
                )

        # Prompt for a new expiration time if the auth method supports it
        expiration_seconds = None
        if auth_method_spec.supports_temporary_credentials():
            expiration_seconds = prompt_expiration_time(
                min=auth_method_spec.min_expiration_seconds,
                max=auth_method_spec.max_expiration_seconds,
                default=connector.expiration_seconds
                or auth_method_spec.default_expiration_seconds,
            )

        # Prompt for the time when the credentials will expire
        expires_at = prompt_expires_at(expires_at or connector.expires_at)

        try:
            # Validate the connector configuration and fetch all available
            # resources that are accessible with the provided configuration
            # in the process
            with console.status("Validating service connector update...\n"):
                (
                    connector_model,
                    connector_resources,
                ) = client.update_service_connector(
                    name_id_or_prefix=connector.id,
                    name=name,
                    description=description,
                    auth_method=auth_method,
                    # Use empty string to indicate that the resource type
                    # should be removed in the update if not set here
                    resource_type=resource_type or "",
                    configuration=config_dict,
                    expires_at=expires_at,
                    # Use zero value to indicate that the expiration time
                    # should be removed in the update if not set here
                    expiration_seconds=expiration_seconds or 0,
                    expires_skew_tolerance=expires_skew_tolerance,
                    verify=True,
                    update=False,
                )
            assert connector_model is not None
            assert connector_resources is not None
        except (
            KeyError,
            ValueError,
            IllegalOperationError,
            NotImplementedError,
            AuthorizationException,
        ) as e:
            cli_utils.error(f"Failed to verify service connector update: {e}")

        if resource_type:
            # Finally, for connectors that are configured with a particular
            # resource type, prompt the user to select one of the available
            # resources that can be accessed with the connector. We don't need
            # to do this for resource types that don't support instances.
            resource_type_spec = connector_type_spec.resource_type_dict[
                resource_type
            ]
            if resource_type_spec.supports_instances:
                assert len(connector_resources.resources) == 1
                resource_ids = connector_resources.resources[0].resource_ids
                assert resource_ids is not None
                resource_id = prompt_resource_id(
                    resource_name=resource_type_spec.name,
                    resource_ids=resource_ids,
                )
            else:
                resource_id = None
        else:
            resource_id = None

        # Prepare the rest of the variables to fall through to the
        # non-interactive configuration case
        no_verify = False

    else:
        # Non-interactive configuration

        # Apply the configuration from the command line arguments
        config_dict = connector.full_configuration
        config_dict.update(parsed_args)

        if not resource_type and not connector.is_multi_type:
            resource_type = connector.resource_types[0]

        resource_id = resource_id or connector.resource_id
        expiration_seconds = expiration_seconds or connector.expiration_seconds

        # Remove attributes that the user has indicated should be removed
        if remove_attrs:
            for remove_attr in remove_attrs:
                config_dict.pop(remove_attr, None)
            if "resource_id" in remove_attrs or "resource-id" in remove_attrs:
                resource_id = None
            if (
                "resource_type" in remove_attrs
                or "resource-type" in remove_attrs
            ):
                resource_type = None
            if (
                "expiration_seconds" in remove_attrs
                or "expiration-seconds" in remove_attrs
            ):
                expiration_seconds = None

    with console.status(
        f"Updating service connector {name_id_or_prefix}...\n"
    ):
        try:
            (
                connector_model,
                connector_resources,
            ) = client.update_service_connector(
                name_id_or_prefix=connector.id,
                name=name,
                auth_method=auth_method,
                # Use empty string to indicate that the resource type
                # should be removed in the update if not set here
                resource_type=resource_type or "",
                configuration=config_dict,
                # Use empty string to indicate that the resource ID
                # should be removed in the update if not set here
                resource_id=resource_id or "",
                description=description,
                expires_at=expires_at,
                # Use empty string to indicate that the expiration time
                # should be removed in the update if not set here
                expiration_seconds=expiration_seconds or 0,
                expires_skew_tolerance=expires_skew_tolerance,
                labels=parsed_labels,
                verify=not no_verify,
                update=True,
            )
        except (
            KeyError,
            ValueError,
            IllegalOperationError,
            NotImplementedError,
            AuthorizationException,
        ) as e:
            cli_utils.error(f"Failed to update service connector: {e}")

    if connector_resources is not None:
        cli_utils.declare(
            f"Successfully updated service connector `{connector.name}`. It "
            "can now be used to access the following resources:"
        )

        cli_utils.print_service_connector_resource_table(
            [connector_resources],
            show_resources_only=True,
        )

    else:
        cli_utils.declare(
            f"Successfully updated service connector `{connector.name}` "
        )
verify_service_connector(name_id_or_prefix: str, resource_type: Optional[str] = None, resource_id: Optional[str] = None, verify_only: bool = False) -> None

Verifies if a service connector has access to one or more resources.

Parameters:

Name Type Description Default
name_id_or_prefix str

The name or id of the service connector to verify.

required
resource_type Optional[str]

The type of resource for which to verify access.

None
resource_id Optional[str]

The ID of the resource for which to verify access.

None
verify_only bool

Only verify the service connector, do not list resources.

False
Source code in src/zenml/cli/service_connectors.py
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
@service_connector.command(
    "verify",
    help="""Verify and list resources for a service connector.

Use this command to check if a registered ZenML service connector is correctly
configured with valid credentials and is able to actively access one or more
resources.

This command has a double purpose:

1. first, it can be used to check if a service connector is correctly configured
and has valid credentials, by actively exercising its credentials and trying to
gain access to the remote service or resource it is configured for.

2. second, it is used to fetch the list of resources that a service connector
has access to. This is useful when the service connector is configured to access
multiple resources, and you want to know which ones it has access to, or even
as a confirmation that it has access to the single resource that it is
configured for. 

You can use this command to answer questions like:

- is this connector valid and correctly configured?
- have I configured this connector to access the correct resource?
- which resources can this connector give me access to?

For connectors that are configured to access multiple types of resources, a
list of resources is not fetched, because it would be too expensive to list
all resources of all types that the connector has access to. In this case,
you can use the `--resource-type` argument to scope down the verification to
a particular resource type.

Examples:

- check if a Kubernetes service connector has access to the cluster it is
configured for:

    $ zenml service-connector verify my-k8s-connector

- check if a generic, multi-type, multi-instance AWS service connector has
access to a particular S3 bucket:

    $ zenml service-connector verify my-generic-aws-connector \\               
--resource-type s3-bucket --resource-id my-bucket

""",
)
@click.option(
    "--resource-type",
    "-r",
    "resource_type",
    help="The type of the resource for which to verify access.",
    required=False,
    type=str,
)
@click.option(
    "--resource-id",
    "-ri",
    "resource_id",
    help="The ID of the resource for which to verify access.",
    required=False,
    type=str,
)
@click.option(
    "--verify-only",
    "-v",
    "verify_only",
    help="Only verify the service connector, do not list resources.",
    required=False,
    is_flag=True,
)
@click.argument("name_id_or_prefix", type=str, required=True)
def verify_service_connector(
    name_id_or_prefix: str,
    resource_type: Optional[str] = None,
    resource_id: Optional[str] = None,
    verify_only: bool = False,
) -> None:
    """Verifies if a service connector has access to one or more resources.

    Args:
        name_id_or_prefix: The name or id of the service connector to verify.
        resource_type: The type of resource for which to verify access.
        resource_id: The ID of the resource for which to verify access.
        verify_only: Only verify the service connector, do not list resources.
    """
    client = Client()

    with console.status(
        f"Verifying service connector '{name_id_or_prefix}'...\n"
    ):
        try:
            resources = client.verify_service_connector(
                name_id_or_prefix=name_id_or_prefix,
                resource_type=resource_type,
                resource_id=resource_id,
                list_resources=not verify_only,
            )
        except (
            KeyError,
            ValueError,
            IllegalOperationError,
            NotImplementedError,
            AuthorizationException,
        ) as e:
            cli_utils.error(
                f"Service connector '{name_id_or_prefix}' verification failed: "
                f"{e}"
            )

    click.echo(
        f"Service connector '{name_id_or_prefix}' is correctly configured "
        f"with valid credentials and has access to the following resources:"
    )

    cli_utils.print_service_connector_resource_table(
        resources=[resources],
        show_resources_only=True,
    )
Modules

source_utils

Utilities for loading/resolving objects.

Classes
Functions
get_implicit_source_root() -> str

Get the implicit source root (the parent directory of the main module).

Raises:

Type Description
RuntimeError

If the main module file can't be found.

Returns:

Type Description
str

The implicit source root.

Source code in src/zenml/utils/source_utils.py
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
def get_implicit_source_root() -> str:
    """Get the implicit source root (the parent directory of the main module).

    Raises:
        RuntimeError: If the main module file can't be found.

    Returns:
        The implicit source root.
    """
    main_module = sys.modules.get("__main__")
    if main_module is None:
        raise RuntimeError(
            "Unable to determine source root because the main module could not "
            "be found."
        )

    if not hasattr(main_module, "__file__") or not main_module.__file__:
        raise RuntimeError(
            "Unable to determine source root because the main module does not "
            "have an associated file. This could be because you're running in "
            "an interactive Python environment. If you are trying to run from "
            "within a Jupyter notebook, please run `zenml init` from the root "
            "where your notebook is located and restart your notebook server."
        )

    path = Path(main_module.__file__).resolve().parent
    return str(path)
get_resolved_notebook_sources() -> Dict[str, str]

Get all notebook sources that were resolved in this process.

Returns:

Type Description
Dict[str, str]

Dictionary mapping the import path of notebook sources to the code

Dict[str, str]

of their notebook cell.

Source code in src/zenml/utils/source_utils.py
806
807
808
809
810
811
812
813
def get_resolved_notebook_sources() -> Dict[str, str]:
    """Get all notebook sources that were resolved in this process.

    Returns:
        Dictionary mapping the import path of notebook sources to the code
        of their notebook cell.
    """
    return _resolved_notebook_sources.copy()
get_source_root() -> str

Get the source root.

The source root will be determined in the following order: - The manually specified custom source root if it was set. - The ZenML repository directory if one exists in the current working directory or any parent directories. - The parent directory of the main module file.

Returns:

Type Description
str

The source root.

Source code in src/zenml/utils/source_utils.py
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
def get_source_root() -> str:
    """Get the source root.

    The source root will be determined in the following order:
    - The manually specified custom source root if it was set.
    - The ZenML repository directory if one exists in the current working
      directory or any parent directories.
    - The parent directory of the main module file.

    Returns:
        The source root.
    """
    if _CUSTOM_SOURCE_ROOT:
        logger.debug("Using custom source root: %s", _CUSTOM_SOURCE_ROOT)
        return _CUSTOM_SOURCE_ROOT

    from zenml.client import Client

    repo_root = Client.find_repository()
    if repo_root:
        logger.debug("Using repository root as source root: %s", repo_root)
        return str(repo_root.resolve())

    implicit_source_root = get_implicit_source_root()
    logger.debug(
        "Using main module parent directory as source root: %s",
        implicit_source_root,
    )
    return implicit_source_root
get_source_type(module: ModuleType) -> SourceType

Get the type of a source.

Parameters:

Name Type Description Default
module ModuleType

The module for which to get the source type.

required

Returns:

Type Description
SourceType

The source type.

Source code in src/zenml/utils/source_utils.py
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
def get_source_type(module: ModuleType) -> SourceType:
    """Get the type of a source.

    Args:
        module: The module for which to get the source type.

    Returns:
        The source type.
    """
    if module.__name__ in _notebook_modules:
        return SourceType.NOTEBOOK

    try:
        file_path = inspect.getfile(module)
    except (TypeError, OSError):
        if module.__name__ == "__main__" and Environment.in_notebook():
            return SourceType.NOTEBOOK

        return SourceType.BUILTIN

    if is_internal_module(module_name=module.__name__):
        return SourceType.INTERNAL

    if is_distribution_package_file(
        file_path=file_path, module_name=module.__name__
    ):
        return SourceType.DISTRIBUTION_PACKAGE

    if is_standard_lib_file(file_path=file_path):
        return SourceType.BUILTIN

    # Make sure to check for distribution packages before this to catch the
    # case when a virtual environment is inside our source root
    if is_user_file(file_path=file_path):
        return SourceType.USER

    return SourceType.UNKNOWN
is_distribution_package_file(file_path: str, module_name: str) -> bool

Checks if a file/module belongs to a distribution package.

Parameters:

Name Type Description Default
file_path str

The file path to check.

required
module_name str

The module name.

required

Returns:

Type Description
bool

True if the file/module belongs to a distribution package, False

bool

otherwise.

Source code in src/zenml/utils/source_utils.py
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
def is_distribution_package_file(file_path: str, module_name: str) -> bool:
    """Checks if a file/module belongs to a distribution package.

    Args:
        file_path: The file path to check.
        module_name: The module name.

    Returns:
        True if the file/module belongs to a distribution package, False
        otherwise.
    """
    absolute_file_path = Path(file_path).resolve()

    for path in site.getsitepackages() + [site.getusersitepackages()]:
        if Path(path).resolve() in absolute_file_path.parents:
            return True

    # TODO: The previous check does not detect editable installs because
    # the site packages dir only contains a reference to the source files,
    # not the actual files. That means currently editable installs get a
    # source type UNKNOWN which might or might not lead to issues.

    return False
is_internal_module(module_name: str) -> bool

Checks if a module is internal (=part of the zenml package).

Parameters:

Name Type Description Default
module_name str

Name of the module to check.

required

Returns:

Type Description
bool

True if the module is internal, False otherwise.

Source code in src/zenml/utils/source_utils.py
352
353
354
355
356
357
358
359
360
361
def is_internal_module(module_name: str) -> bool:
    """Checks if a module is internal (=part of the zenml package).

    Args:
        module_name: Name of the module to check.

    Returns:
        True if the module is internal, False otherwise.
    """
    return module_name.split(".", maxsplit=1)[0] == "zenml"
is_standard_lib_file(file_path: str) -> bool

Checks if a file belongs to the Python standard library.

Parameters:

Name Type Description Default
file_path str

The file path to check.

required

Returns:

Type Description
bool

True if the file belongs to the Python standard library, False

bool

otherwise.

Source code in src/zenml/utils/source_utils.py
377
378
379
380
381
382
383
384
385
386
387
388
389
def is_standard_lib_file(file_path: str) -> bool:
    """Checks if a file belongs to the Python standard library.

    Args:
        file_path: The file path to check.

    Returns:
        True if the file belongs to the Python standard library, False
        otherwise.
    """
    stdlib_root = get_python_lib(standard_lib=True)
    logger.debug("Standard library root: %s", stdlib_root)
    return Path(stdlib_root).resolve() in Path(file_path).resolve().parents
is_user_file(file_path: str) -> bool

Checks if a file is a user file.

Parameters:

Name Type Description Default
file_path str

The file path to check.

required

Returns:

Type Description
bool

True if the file is a user file, False otherwise.

Source code in src/zenml/utils/source_utils.py
364
365
366
367
368
369
370
371
372
373
374
def is_user_file(file_path: str) -> bool:
    """Checks if a file is a user file.

    Args:
        file_path: The file path to check.

    Returns:
        True if the file is a user file, False otherwise.
    """
    source_root = get_source_root()
    return Path(source_root) in Path(file_path).resolve().parents
load(source: Union[Source, str]) -> Any

Load a source or import path.

Parameters:

Name Type Description Default
source Union[Source, str]

The source to load.

required

Returns:

Type Description
Any

The loaded object.

Source code in src/zenml/utils/source_utils.py
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
def load(source: Union[Source, str]) -> Any:
    """Load a source or import path.

    Args:
        source: The source to load.

    Returns:
        The loaded object.
    """
    if isinstance(source, str):
        source = Source.from_import_path(source)

    # The types of some objects don't exist in the `builtin` module
    # so we need to manually handle it here
    if source.import_path == NoneTypeSource.import_path:
        return NoneType
    elif source.import_path == FunctionTypeSource.import_path:
        return FunctionType
    elif source.import_path == BuiltinFunctionTypeSource.import_path:
        return BuiltinFunctionType

    import_root = None
    if source.type == SourceType.CODE_REPOSITORY:
        source = CodeRepositorySource.model_validate(dict(source))
        _warn_about_potential_source_loading_issues(source=source)
        import_root = get_source_root()
    elif source.type == SourceType.DISTRIBUTION_PACKAGE:
        source = DistributionPackageSource.model_validate(dict(source))
        if source.version:
            current_package_version = _get_package_version(
                package_name=source.package_name
            )
            if current_package_version != source.version:
                logger.warning(
                    "The currently installed version `%s` of package `%s` "
                    "does not match the source version `%s`. This might lead "
                    "to unexpected behavior when using the source object `%s`.",
                    current_package_version,
                    source.package_name,
                    source.version,
                    source.import_path,
                )
    elif source.type == SourceType.NOTEBOOK:
        if Environment.in_notebook():
            # If we're in a notebook, we don't need to do anything as the
            # loading from the __main__ module should work just fine.
            pass
        else:
            notebook_source = NotebookSource.model_validate(dict(source))
            return _try_to_load_notebook_source(notebook_source)
    elif source.type in {SourceType.USER, SourceType.UNKNOWN}:
        # Unknown source might also refer to a user file, include source
        # root in python path just to be sure
        import_root = get_source_root()

    if _should_load_from_main_module(source):
        # This source points to the __main__ module of the current process.
        # If we were to load the module here, we would load the same python
        # file with a different module name, which would rerun all top-level
        # code. To avoid this, we instead load the source from the __main__
        # module which is already loaded.
        module = sys.modules["__main__"]
    else:
        module = _load_module(
            module_name=source.module, import_root=import_root
        )

    if source.attribute:
        obj = getattr(module, source.attribute)
    else:
        obj = module

    return obj
load_and_validate_class(source: Union[str, Source], expected_class: Type[Any]) -> Type[Any]

Loads a source class and validates its class.

Parameters:

Name Type Description Default
source Union[str, Source]

The source.

required
expected_class Type[Any]

The class that the source should resolve to.

required

Raises:

Type Description
TypeError

If the source does not resolve to the expected class.

Returns:

Type Description
Type[Any]

The resolved source class.

Source code in src/zenml/utils/source_utils.py
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
def load_and_validate_class(
    source: Union[str, Source], expected_class: Type[Any]
) -> Type[Any]:
    """Loads a source class and validates its class.

    Args:
        source: The source.
        expected_class: The class that the source should resolve to.

    Raises:
        TypeError: If the source does not resolve to the expected class.

    Returns:
        The resolved source class.
    """
    obj = load(source)

    if isinstance(obj, type) and issubclass(obj, expected_class):
        return obj
    else:
        raise TypeError(
            f"Error while loading `{source}`. Expected class "
            f"{expected_class.__name__}, got {obj} instead."
        )
prepend_python_path(path: str) -> Iterator[None]

Context manager to temporarily prepend a path to the python path.

Parameters:

Name Type Description Default
path str

Path that will be prepended to sys.path for the duration of the context manager.

required

Yields:

Type Description
None

None

Source code in src/zenml/utils/source_utils.py
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
@contextlib.contextmanager
def prepend_python_path(path: str) -> Iterator[None]:
    """Context manager to temporarily prepend a path to the python path.

    Args:
        path: Path that will be prepended to sys.path for the duration of
            the context manager.

    Yields:
        None
    """
    try:
        sys.path.insert(0, path)
        yield
    finally:
        sys.path.remove(path)
resolve(obj: Union[Type[Any], Callable[..., Any], ModuleType, FunctionType, BuiltinFunctionType, NoneType], skip_validation: bool = False) -> Source

Resolve an object.

Parameters:

Name Type Description Default
obj Union[Type[Any], Callable[..., Any], ModuleType, FunctionType, BuiltinFunctionType, NoneType]

The object to resolve.

required
skip_validation bool

If True, the validation that the object exist in the module is skipped.

False

Raises:

Type Description
RuntimeError

If the object can't be resolved.

Returns:

Type Description
Source

The source of the resolved object.

Source code in src/zenml/utils/source_utils.py
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
def resolve(
    obj: Union[
        Type[Any],
        Callable[..., Any],
        ModuleType,
        FunctionType,
        BuiltinFunctionType,
        NoneType,
    ],
    skip_validation: bool = False,
) -> Source:
    """Resolve an object.

    Args:
        obj: The object to resolve.
        skip_validation: If True, the validation that the object exist in the
            module is skipped.

    Raises:
        RuntimeError: If the object can't be resolved.

    Returns:
        The source of the resolved object.
    """
    # The types of some objects don't exist in the `builtin` module
    # so we need to manually handle it here
    if obj is NoneType:
        return NoneTypeSource
    elif obj is FunctionType:
        return FunctionTypeSource
    elif obj is BuiltinFunctionType:
        return BuiltinFunctionTypeSource
    elif source := getattr(obj, ZENML_SOURCE_ATTRIBUTE_NAME, None):
        assert isinstance(source, Source)
        return source
    elif isinstance(obj, ModuleType):
        module = obj
        attribute_name = None
    else:
        module = sys.modules[obj.__module__]
        attribute_name = obj.__name__  # type: ignore[union-attr]

    if (
        not (skip_validation or getattr(obj, "_DOCS_BUILDING_MODE", False))
        and attribute_name
        and getattr(module, attribute_name, None) is not obj
    ):
        raise RuntimeError(
            f"Unable to resolve object `{obj}`. For the resolving to work, the "
            "class or function must be defined as top-level code (= it must "
            "get defined when importing the module) and not inside a function/"
            f"if-condition. Please make sure that your `{module.__name__}` "
            f"module has a top-level attribute `{attribute_name}` that "
            "holds the object you want to resolve."
        )

    module_name = module.__name__
    if module_name == "__main__":
        module_name = _resolve_module(module)

    source_type = get_source_type(module=module)

    if source_type == SourceType.USER:
        from zenml.utils import code_repository_utils

        local_repo_context = (
            code_repository_utils.find_active_code_repository()
        )

        if local_repo_context and not local_repo_context.has_local_changes:
            module_name = _resolve_module(module)

            source_root = get_source_root()
            subdir = PurePath(source_root).relative_to(local_repo_context.root)

            return CodeRepositorySource(
                repository_id=local_repo_context.code_repository.id,
                commit=local_repo_context.current_commit,
                subdirectory=subdir.as_posix(),
                module=module_name,
                attribute=attribute_name,
                type=SourceType.CODE_REPOSITORY,
            )

        module_name = _resolve_module(module)
    elif source_type == SourceType.DISTRIBUTION_PACKAGE:
        package_name = _get_package_for_module(module_name=module_name)
        if package_name:
            package_version = _get_package_version(package_name=package_name)
            return DistributionPackageSource(
                module=module_name,
                attribute=attribute_name,
                package_name=package_name,
                version=package_version,
                type=source_type,
            )
        else:
            # Fallback to an unknown source if we can't find the package
            source_type = SourceType.UNKNOWN
    elif source_type == SourceType.NOTEBOOK:
        source = NotebookSource(
            module="__main__",
            attribute=attribute_name,
            type=source_type,
        )

        if module_name in _notebook_modules:
            source.replacement_module = module_name
            source.artifact_store_id = _notebook_modules[module_name]
        elif cell_code := notebook_utils.load_notebook_cell_code(obj):
            replacement_module = (
                notebook_utils.compute_cell_replacement_module_name(
                    cell_code=cell_code
                )
            )
            source.replacement_module = replacement_module
            _resolved_notebook_sources[source.import_path] = cell_code

        return source

    return Source(
        module=module_name, attribute=attribute_name, type=source_type
    )
set_custom_source_root(source_root: Optional[str]) -> None

Sets a custom source root.

If set this has the highest priority and will always be used as the source root.

Parameters:

Name Type Description Default
source_root Optional[str]

The source root to use.

required
Source code in src/zenml/utils/source_utils.py
338
339
340
341
342
343
344
345
346
347
348
349
def set_custom_source_root(source_root: Optional[str]) -> None:
    """Sets a custom source root.

    If set this has the highest priority and will always be used as the source
    root.

    Args:
        source_root: The source root to use.
    """
    logger.debug("Setting custom source root: %s", source_root)
    global _CUSTOM_SOURCE_ROOT
    _CUSTOM_SOURCE_ROOT = source_root
validate_source_class(source: Union[Source, str], expected_class: Type[Any]) -> bool

Validates that a source resolves to a certain class.

Parameters:

Name Type Description Default
source Union[Source, str]

The source to validate.

required
expected_class Type[Any]

The class that the source should resolve to.

required

Returns:

Type Description
bool

True if the source resolves to the expected class, False otherwise.

Source code in src/zenml/utils/source_utils.py
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
def validate_source_class(
    source: Union[Source, str], expected_class: Type[Any]
) -> bool:
    """Validates that a source resolves to a certain class.

    Args:
        source: The source to validate.
        expected_class: The class that the source should resolve to.

    Returns:
        True if the source resolves to the expected class, False otherwise.
    """
    try:
        obj = load(source)
    except Exception:
        return False

    if isinstance(obj, type) and issubclass(obj, expected_class):
        return True
    else:
        return False
Modules

stack_components

Functionality to generate stack component CLI commands.

Classes
Functions
connect_stack_component_with_service_connector(component_type: StackComponentType, name_id_or_prefix: Optional[str] = None, connector: Optional[str] = None, resource_id: Optional[str] = None, interactive: bool = False, no_verify: bool = False) -> None

Connect the stack component to a resource through a service connector.

Parameters:

Name Type Description Default
component_type StackComponentType

Type of the component to generate the command for.

required
name_id_or_prefix Optional[str]

The name of the stack component to connect.

None
connector Optional[str]

The name, ID or prefix of the connector to use.

None
resource_id Optional[str]

The resource ID to use connect to. Only required for multi-instance connectors that are not already configured with a particular resource ID.

None
interactive bool

Configure a service connector resource interactively.

False
no_verify bool

Do not verify whether the resource is accessible.

False
Source code in src/zenml/cli/stack_components.py
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
def connect_stack_component_with_service_connector(
    component_type: StackComponentType,
    name_id_or_prefix: Optional[str] = None,
    connector: Optional[str] = None,
    resource_id: Optional[str] = None,
    interactive: bool = False,
    no_verify: bool = False,
) -> None:
    """Connect the stack component to a resource through a service connector.

    Args:
        component_type: Type of the component to generate the command for.
        name_id_or_prefix: The name of the stack component to connect.
        connector: The name, ID or prefix of the connector to use.
        resource_id: The resource ID to use connect to. Only
            required for multi-instance connectors that are not already
            configured with a particular resource ID.
        interactive: Configure a service connector resource interactively.
        no_verify: Do not verify whether the resource is accessible.
    """
    display_name = _component_display_name(component_type)

    if not connector and not interactive:
        cli_utils.error(
            "Please provide either a connector ID or set the interactive flag."
        )

    if connector and interactive:
        cli_utils.error(
            "Please provide either a connector ID or set the interactive "
            "flag, not both."
        )

    client = Client()

    try:
        component_model = client.get_stack_component(
            name_id_or_prefix=name_id_or_prefix,
            component_type=component_type,
        )
    except KeyError as err:
        cli_utils.error(str(err))

    requirements = component_model.flavor.connector_requirements

    if not requirements:
        cli_utils.error(
            f"The '{component_model.name}' {display_name} implementation "
            "does not support using a service connector to connect to "
            "resources."
        )

    resource_type = requirements.resource_type
    if requirements.resource_id_attr is not None:
        # Check if an attribute is set in the component configuration
        resource_id = component_model.configuration.get(
            requirements.resource_id_attr
        )

    if interactive:
        # Fetch the list of connectors that have resources compatible with
        # the stack component's flavor's resource requirements
        with console.status(
            "Finding all resources matching the stack component "
            "requirements (this could take a while)...\n"
        ):
            resource_list = client.list_service_connector_resources(
                connector_type=requirements.connector_type,
                resource_type=resource_type,
                resource_id=resource_id,
            )

        resource_list = [
            resource
            for resource in resource_list
            if resource.resources[0].resource_ids
        ]

        error_resource_list = [
            resource
            for resource in resource_list
            if not resource.resources[0].resource_ids
        ]

        if not resource_list:
            # No compatible resources were found
            additional_info = ""
            if error_resource_list:
                additional_info = (
                    f"{len(error_resource_list)} connectors can be used "
                    f"to gain access to {resource_type} resources required "
                    "for the stack component, but they are in an error "
                    "state or they didn't list any matching resources. "
                )
            command_args = ""
            if requirements.connector_type:
                command_args += (
                    f" --connector-type {requirements.connector_type}"
                )
            command_args += f" --resource-type {requirements.resource_type}"
            if resource_id:
                command_args += f" --resource-id {resource_id}"

            cli_utils.error(
                f"No compatible valid resources were found for the "
                f"'{component_model.name}' {display_name}. "
                f"{additional_info}You can create a new "
                "connector using the 'zenml service-connector register' "
                "command or list the compatible resources using the "
                f"'zenml service-connector list-resources{command_args}' "
                "command."
            )

        # Prompt the user to select a connector and a resource ID, if
        # applicable
        connector_id, resource_id = prompt_select_resource(resource_list)
        no_verify = False
    else:
        # Non-interactive mode: we need to fetch the connector model first

        assert connector is not None
        try:
            connector_model = client.get_service_connector(connector)
        except KeyError as err:
            cli_utils.error(
                f"Could not find a connector '{connector}': {str(err)}"
            )

        connector_id = connector_model.id

        satisfied, msg = requirements.is_satisfied_by(
            connector_model, component_model
        )
        if not satisfied:
            cli_utils.error(
                f"The connector with ID {connector_id} does not match the "
                f"component's `{name_id_or_prefix}` of type `{component_type}`"
                f" connector requirements: {msg}. Please pick a connector that "
                f"is compatible with the component flavor and try again, or "
                f"use the interactive mode to select a compatible connector."
            )

        if not resource_id:
            if connector_model.resource_id:
                resource_id = connector_model.resource_id
            elif connector_model.supports_instances:
                cli_utils.error(
                    f"Multiple {resource_type} resources are available for "
                    "the selected connector. Please use the "
                    "`--resource-id` command line argument to configure a "
                    f"{resource_type} resource or use the interactive mode "
                    "to select a resource interactively."
                )

    connector_resources: Optional[ServiceConnectorResourcesModel] = None
    if not no_verify:
        with console.status(
            "Validating service connector resource configuration...\n"
        ):
            try:
                connector_resources = client.verify_service_connector(
                    connector_id,
                    resource_type=requirements.resource_type,
                    resource_id=resource_id,
                )
            except (
                KeyError,
                ValueError,
                IllegalOperationError,
                NotImplementedError,
                AuthorizationException,
            ) as e:
                cli_utils.error(
                    f"Access to the resource could not be verified: {e}"
                )
        resources = connector_resources.resources[0]
        if resources.resource_ids:
            if len(resources.resource_ids) > 1:
                cli_utils.error(
                    f"Multiple {resource_type} resources are available for "
                    "the selected connector. Please use the "
                    "`--resource-id` command line argument to configure a "
                    f"{resource_type} resource or use the interactive mode "
                    "to select a resource interactively."
                )
            else:
                resource_id = resources.resource_ids[0]

    with console.status(f"Updating {display_name} '{name_id_or_prefix}'...\n"):
        try:
            client.update_stack_component(
                name_id_or_prefix=name_id_or_prefix,
                component_type=component_type,
                connector_id=connector_id,
                connector_resource_id=resource_id,
            )
        except (KeyError, IllegalOperationError) as err:
            cli_utils.error(str(err))

    if connector_resources is not None:
        cli_utils.declare(
            f"Successfully connected {display_name} "
            f"`{component_model.name}` to the following resources:"
        )

        cli_utils.print_service_connector_resource_table([connector_resources])

    else:
        cli_utils.declare(
            f"Successfully connected {display_name} "
            f"`{component_model.name}` to resource."
        )
generate_stack_component_connect_command(component_type: StackComponentType) -> Callable[[str, str], None]

Generates a connect command for the specific stack component type.

Parameters:

Name Type Description Default
component_type StackComponentType

Type of the component to generate the command for.

required

Returns:

Type Description
Callable[[str, str], None]

A function that can be used as a click command.

Source code in src/zenml/cli/stack_components.py
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
def generate_stack_component_connect_command(
    component_type: StackComponentType,
) -> Callable[[str, str], None]:
    """Generates a `connect` command for the specific stack component type.

    Args:
        component_type: Type of the component to generate the command for.

    Returns:
        A function that can be used as a `click` command.
    """
    _component_display_name(component_type)

    @click.argument(
        "name_id_or_prefix",
        type=str,
        required=False,
    )
    @click.option(
        "--connector",
        "-c",
        "connector",
        help="The name, ID or prefix of the connector to use.",
        required=False,
        type=str,
    )
    @click.option(
        "--resource-id",
        "-r",
        "resource_id",
        help="The resource ID to use with the connector. Only required for "
        "multi-instance connectors that are not already configured with a "
        "particular resource ID.",
        required=False,
        type=str,
    )
    @click.option(
        "--interactive",
        "-i",
        "interactive",
        is_flag=True,
        default=False,
        help="Configure a service connector resource interactively.",
        type=click.BOOL,
    )
    @click.option(
        "--no-verify",
        "no_verify",
        is_flag=True,
        default=False,
        help="Skip verification of the connector resource.",
        type=click.BOOL,
    )
    def connect_stack_component_command(
        name_id_or_prefix: Optional[str],
        connector: Optional[str] = None,
        resource_id: Optional[str] = None,
        interactive: bool = False,
        no_verify: bool = False,
    ) -> None:
        """Connect the stack component to a resource through a service connector.

        Args:
            name_id_or_prefix: The name of the stack component to connect.
            connector: The name, ID or prefix of the connector to use.
            resource_id: The resource ID to use connect to. Only
                required for multi-instance connectors that are not already
                configured with a particular resource ID.
            interactive: Configure a service connector resource interactively.
            no_verify: Do not verify whether the resource is accessible.
        """
        connect_stack_component_with_service_connector(
            component_type=component_type,
            name_id_or_prefix=name_id_or_prefix,
            connector=connector,
            resource_id=resource_id,
            interactive=interactive,
            no_verify=no_verify,
        )

    return connect_stack_component_command
generate_stack_component_copy_command(component_type: StackComponentType) -> Callable[[str, str], None]

Generates a copy command for the specific stack component type.

Parameters:

Name Type Description Default
component_type StackComponentType

Type of the component to generate the command for.

required

Returns:

Type Description
Callable[[str, str], None]

A function that can be used as a click command.

Source code in src/zenml/cli/stack_components.py
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
def generate_stack_component_copy_command(
    component_type: StackComponentType,
) -> Callable[[str, str], None]:
    """Generates a `copy` command for the specific stack component type.

    Args:
        component_type: Type of the component to generate the command for.

    Returns:
        A function that can be used as a `click` command.
    """
    display_name = _component_display_name(component_type)

    @click.argument(
        "source_component_name_id_or_prefix", type=str, required=True
    )
    @click.argument("target_component", type=str, required=True)
    def copy_stack_component_command(
        source_component_name_id_or_prefix: str,
        target_component: str,
    ) -> None:
        """Copies a stack component.

        Args:
            source_component_name_id_or_prefix: Name or id prefix of the
                                         component to copy.
            target_component: Name of the copied component.
        """
        client = Client()

        with console.status(
            f"Copying {display_name} "
            f"`{source_component_name_id_or_prefix}`..\n"
        ):
            try:
                component_to_copy = client.get_stack_component(
                    name_id_or_prefix=source_component_name_id_or_prefix,
                    component_type=component_type,
                )
            except KeyError as err:
                cli_utils.error(str(err))

            copied_component = client.create_stack_component(
                name=target_component,
                flavor=component_to_copy.flavor_name,
                component_type=component_to_copy.type,
                configuration=component_to_copy.configuration,
                labels=component_to_copy.labels,
            )
            print_model_url(get_component_url(copied_component))

    return copy_stack_component_command
generate_stack_component_delete_command(component_type: StackComponentType) -> Callable[[str], None]

Generates a delete command for the specific stack component type.

Parameters:

Name Type Description Default
component_type StackComponentType

Type of the component to generate the command for.

required

Returns:

Type Description
Callable[[str], None]

A function that can be used as a click command.

Source code in src/zenml/cli/stack_components.py
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
def generate_stack_component_delete_command(
    component_type: StackComponentType,
) -> Callable[[str], None]:
    """Generates a `delete` command for the specific stack component type.

    Args:
        component_type: Type of the component to generate the command for.

    Returns:
        A function that can be used as a `click` command.
    """
    display_name = _component_display_name(component_type)

    @click.argument("name_id_or_prefix", type=str)
    def delete_stack_component_command(name_id_or_prefix: str) -> None:
        """Deletes a stack component.

        Args:
            name_id_or_prefix: The name of the stack component to delete.
        """
        client = Client()

        with console.status(
            f"Deleting {display_name} '{name_id_or_prefix}'...\n"
        ):
            try:
                client.delete_stack_component(
                    name_id_or_prefix=name_id_or_prefix,
                    component_type=component_type,
                )
            except (KeyError, IllegalOperationError) as err:
                cli_utils.error(str(err))
            cli_utils.declare(f"Deleted {display_name}: {name_id_or_prefix}")

    return delete_stack_component_command
generate_stack_component_describe_command(component_type: StackComponentType) -> Callable[[str], None]

Generates a describe command for the specific stack component type.

Parameters:

Name Type Description Default
component_type StackComponentType

Type of the component to generate the command for.

required

Returns:

Type Description
Callable[[str], None]

A function that can be used as a click command.

Source code in src/zenml/cli/stack_components.py
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
def generate_stack_component_describe_command(
    component_type: StackComponentType,
) -> Callable[[str], None]:
    """Generates a `describe` command for the specific stack component type.

    Args:
        component_type: Type of the component to generate the command for.

    Returns:
        A function that can be used as a `click` command.
    """

    @click.argument(
        "name_id_or_prefix",
        type=str,
        required=False,
    )
    def describe_stack_component_command(name_id_or_prefix: str) -> None:
        """Prints details about the active/specified component.

        Args:
            name_id_or_prefix: Name or id of the component to describe.
        """
        client = Client()
        try:
            component_ = client.get_stack_component(
                name_id_or_prefix=name_id_or_prefix,
                component_type=component_type,
            )
        except KeyError as err:
            cli_utils.error(str(err))

        with console.status(f"Describing component '{component_.name}'..."):
            active_component_id = None
            active_components = client.active_stack_model.components.get(
                component_type, None
            )
            if active_components:
                active_component_id = active_components[0].id

            if component_.connector:
                connector_requirements = (
                    component_.flavor.connector_requirements
                )
            else:
                connector_requirements = None

            cli_utils.print_stack_component_configuration(
                component=component_,
                active_status=component_.id == active_component_id,
                connector_requirements=connector_requirements,
            )

            print_model_url(get_component_url(component_))

    return describe_stack_component_command
generate_stack_component_disconnect_command(component_type: StackComponentType) -> Callable[[str], None]

Generates a disconnect command for the specific stack component type.

Parameters:

Name Type Description Default
component_type StackComponentType

Type of the component to generate the command for.

required

Returns:

Type Description
Callable[[str], None]

A function that can be used as a click command.

Source code in src/zenml/cli/stack_components.py
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
def generate_stack_component_disconnect_command(
    component_type: StackComponentType,
) -> Callable[[str], None]:
    """Generates a `disconnect` command for the specific stack component type.

    Args:
        component_type: Type of the component to generate the command for.

    Returns:
        A function that can be used as a `click` command.
    """
    display_name = _component_display_name(component_type)

    @click.argument(
        "name_id_or_prefix",
        type=str,
        required=True,
    )
    def disconnect_stack_component_command(name_id_or_prefix: str) -> None:
        """Disconnect a stack component from a service connector.

        Args:
            name_id_or_prefix: The name of the stack component to disconnect.
        """
        client = Client()

        with console.status(
            f"Disconnecting service-connector from {display_name} '{name_id_or_prefix}'...\n"
        ):
            try:
                updated_component = client.update_stack_component(
                    name_id_or_prefix=name_id_or_prefix,
                    component_type=component_type,
                    disconnect=True,
                )
            except (KeyError, IllegalOperationError) as err:
                cli_utils.error(str(err))

            cli_utils.declare(
                f"Successfully disconnected the service-connector from {display_name} `{name_id_or_prefix}`."
            )
            print_model_url(get_component_url(updated_component))

    return disconnect_stack_component_command
generate_stack_component_explain_command(component_type: StackComponentType) -> Callable[[], None]

Generates an explain command for the specific stack component type.

Parameters:

Name Type Description Default
component_type StackComponentType

Type of the component to generate the command for.

required

Returns:

Type Description
Callable[[], None]

A function that can be used as a click command.

Source code in src/zenml/cli/stack_components.py
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
def generate_stack_component_explain_command(
    component_type: StackComponentType,
) -> Callable[[], None]:
    """Generates an `explain` command for the specific stack component type.

    Args:
        component_type: Type of the component to generate the command for.

    Returns:
        A function that can be used as a `click` command.
    """

    def explain_stack_components_command() -> None:
        """Explains the concept of the stack component."""
        component_module = import_module(f"zenml.{component_type.plural}")

        if component_module.__doc__ is not None:
            md = Markdown(component_module.__doc__)
            console.print(md)
        else:
            console.print(
                "The explain subcommand is yet not available for "
                "this stack component. For more information, you can "
                "visit our docs page: https://docs.zenml.io/ and "
                "stay tuned for future releases."
            )

    return explain_stack_components_command
generate_stack_component_flavor_delete_command(component_type: StackComponentType) -> Callable[[str], None]

Generates a delete command for a single flavor of a component.

Parameters:

Name Type Description Default
component_type StackComponentType

Type of the component to generate the command for.

required

Returns:

Type Description
Callable[[str], None]

A function that can be used as a click command.

Source code in src/zenml/cli/stack_components.py
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
def generate_stack_component_flavor_delete_command(
    component_type: StackComponentType,
) -> Callable[[str], None]:
    """Generates a `delete` command for a single flavor of a component.

    Args:
        component_type: Type of the component to generate the command for.

    Returns:
        A function that can be used as a `click` command.
    """
    display_name = _component_display_name(component_type)

    @click.argument(
        "name_or_id",
        type=str,
        required=True,
    )
    def delete_stack_component_flavor_command(name_or_id: str) -> None:
        """Deletes a flavor.

        Args:
            name_or_id: The name of the flavor.
        """
        client = Client()

        with console.status(
            f"Deleting a {display_name} flavor: {name_or_id}`...\n"
        ):
            client.delete_flavor(name_or_id)

            cli_utils.declare(f"Successfully deleted flavor '{name_or_id}'.")

    return delete_stack_component_flavor_command
generate_stack_component_flavor_describe_command(component_type: StackComponentType) -> Callable[[str], None]

Generates a describe command for a single flavor of a component.

Parameters:

Name Type Description Default
component_type StackComponentType

Type of the component to generate the command for.

required

Returns:

Type Description
Callable[[str], None]

A function that can be used as a click command.

Source code in src/zenml/cli/stack_components.py
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
def generate_stack_component_flavor_describe_command(
    component_type: StackComponentType,
) -> Callable[[str], None]:
    """Generates a `describe` command for a single flavor of a component.

    Args:
        component_type: Type of the component to generate the command for.

    Returns:
        A function that can be used as a `click` command.
    """
    display_name = _component_display_name(component_type)

    @click.argument(
        "name",
        type=str,
        required=True,
    )
    def describe_stack_component_flavor_command(name: str) -> None:
        """Describes a flavor based on its config schema.

        Args:
            name: The name of the flavor.
        """
        client = Client()

        with console.status(f"Describing {display_name} flavor: {name}`...\n"):
            flavor_model = client.get_flavor_by_name_and_type(
                name=name, component_type=component_type
            )

            cli_utils.describe_pydantic_object(flavor_model.config_schema)
            resources = flavor_model.connector_requirements
            if resources:
                resources_str = f"a '{resources.resource_type}' resource"
                cli_args = f"--resource-type {resources.resource_type}"
                if resources.connector_type:
                    resources_str += (
                        f" provided by a '{resources.connector_type}' "
                        "connector"
                    )
                    cli_args += f"--connector-type {resources.connector_type}"

                cli_utils.declare(
                    f"This flavor supports connecting to external resources "
                    f"with a Service Connector. It requires {resources_str}. "
                    "You can get a list of all available connectors and the "
                    "compatible resources that they can access by running:\n\n"
                    f"'zenml service-connector list-resources {cli_args}'\n"
                    "If no compatible Service Connectors are yet registered, "
                    "you can can register a new one by running:\n\n"
                    f"'zenml service-connector register -i'"
                )
            else:
                cli_utils.declare(
                    "This flavor does not support connecting to external "
                    "resources with a Service Connector."
                )

    return describe_stack_component_flavor_command
generate_stack_component_flavor_list_command(component_type: StackComponentType) -> Callable[[], None]

Generates a list command for the flavors of a stack component.

Parameters:

Name Type Description Default
component_type StackComponentType

Type of the component to generate the command for.

required

Returns:

Type Description
Callable[[], None]

A function that can be used as a click command.

Source code in src/zenml/cli/stack_components.py
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
def generate_stack_component_flavor_list_command(
    component_type: StackComponentType,
) -> Callable[[], None]:
    """Generates a `list` command for the flavors of a stack component.

    Args:
        component_type: Type of the component to generate the command for.

    Returns:
        A function that can be used as a `click` command.
    """
    display_name = _component_display_name(component_type)

    def list_stack_component_flavor_command() -> None:
        """Lists the flavors for a single type of stack component."""
        client = Client()

        with console.status(f"Listing {display_name} flavors`...\n"):
            flavors = client.get_flavors_by_type(component_type=component_type)

            cli_utils.print_flavor_list(flavors=flavors)
            cli_utils.print_page_info(flavors)

    return list_stack_component_flavor_command
generate_stack_component_flavor_register_command(component_type: StackComponentType) -> Callable[[str], None]

Generates a register command for the flavors of a stack component.

Parameters:

Name Type Description Default
component_type StackComponentType

Type of the component to generate the command for.

required

Returns:

Type Description
Callable[[str], None]

A function that can be used as a click command.

Source code in src/zenml/cli/stack_components.py
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
def generate_stack_component_flavor_register_command(
    component_type: StackComponentType,
) -> Callable[[str], None]:
    """Generates a `register` command for the flavors of a stack component.

    Args:
        component_type: Type of the component to generate the command for.

    Returns:
        A function that can be used as a `click` command.
    """
    command_name = component_type.value.replace("_", "-")
    display_name = _component_display_name(component_type)

    @click.argument(
        "source",
        type=str,
        required=True,
    )
    def register_stack_component_flavor_command(source: str) -> None:
        """Adds a flavor for a stack component type.

        Example:
            Let's say you create an artifact store flavor class `MyArtifactStoreFlavor`
            in the file path `flavors/my_flavor.py`. You would register it as:

            ```shell
            zenml artifact-store flavor register flavors.my_flavor.MyArtifactStoreFlavor
            ```

        Args:
            source: The source path of the flavor class in dot notation format.
        """
        client = Client()

        if not client.root:
            cli_utils.warning(
                f"You're running the `zenml {command_name} flavor register` "
                "command without a ZenML repository. Your current working "
                "directory will be used as the source root relative to which "
                "the `source` argument is expected. To silence this warning, "
                "run `zenml init` at your source code root."
            )

        with console.status(f"Registering a new {display_name} flavor`...\n"):
            try:
                # Register the new model
                new_flavor = client.create_flavor(
                    source=source,
                    component_type=component_type,
                )
            except ValueError as e:
                source_root = source_utils.get_source_root()

                cli_utils.error(
                    f"Flavor registration failed! ZenML tried loading the "
                    f"module `{source}` from path `{source_root}`. If this is "
                    "not what you expect, then please ensure you have run "
                    "`zenml init` at the root of your repository.\n\n"
                    f"Original exception: {str(e)}"
                )

            cli_utils.declare(
                f"Successfully registered new flavor '{new_flavor.name}' "
                f"for stack component '{new_flavor.type}'."
            )

    return register_stack_component_flavor_command
generate_stack_component_get_command(component_type: StackComponentType) -> Callable[[], None]

Generates a get command for the specific stack component type.

Parameters:

Name Type Description Default
component_type StackComponentType

Type of the component to generate the command for.

required

Returns:

Type Description
Callable[[], None]

A function that can be used as a click command.

Source code in src/zenml/cli/stack_components.py
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
def generate_stack_component_get_command(
    component_type: StackComponentType,
) -> Callable[[], None]:
    """Generates a `get` command for the specific stack component type.

    Args:
        component_type: Type of the component to generate the command for.

    Returns:
        A function that can be used as a `click` command.
    """

    def get_stack_component_command() -> None:
        """Prints the name of the active component."""
        client = Client()
        display_name = _component_display_name(component_type)

        with console.status(f"Getting the active `{display_name}`...\n"):
            active_stack = client.active_stack_model
            components = active_stack.components.get(component_type, None)

            if components:
                cli_utils.declare(
                    f"Active {display_name}: '{components[0].name}'"
                )
                print_model_url(get_component_url(components[0]))
            else:
                cli_utils.warning(
                    f"No {display_name} set for active stack "
                    f"('{active_stack.name}')."
                )

    return get_stack_component_command
generate_stack_component_list_command(component_type: StackComponentType) -> Callable[..., None]

Generates a list command for the specific stack component type.

Parameters:

Name Type Description Default
component_type StackComponentType

Type of the component to generate the command for.

required

Returns:

Type Description
Callable[..., None]

A function that can be used as a click command.

Source code in src/zenml/cli/stack_components.py
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
def generate_stack_component_list_command(
    component_type: StackComponentType,
) -> Callable[..., None]:
    """Generates a `list` command for the specific stack component type.

    Args:
        component_type: Type of the component to generate the command for.

    Returns:
        A function that can be used as a `click` command.
    """

    @list_options(ComponentFilter)
    @click.pass_context
    def list_stack_components_command(
        ctx: click.Context, /, **kwargs: Any
    ) -> None:
        """Prints a table of stack components.

        Args:
            ctx: The click context object
            kwargs: Keyword arguments to filter the components.
        """
        client = Client()
        with console.status(f"Listing {component_type.plural}..."):
            kwargs["type"] = component_type
            components = client.list_stack_components(**kwargs)
            if not components:
                cli_utils.declare("No components found for the given filters.")
                return

            cli_utils.print_components_table(
                client=client,
                component_type=component_type,
                components=components.items,
                show_active=not is_sorted_or_filtered(ctx),
            )
            print_page_info(components)

    return list_stack_components_command
generate_stack_component_logs_command(component_type: StackComponentType) -> Callable[[str, bool], None]

Generates a logs command for the specific stack component type.

Parameters:

Name Type Description Default
component_type StackComponentType

Type of the component to generate the command for.

required

Returns:

Type Description
Callable[[str, bool], None]

A function that can be used as a click command.

Source code in src/zenml/cli/stack_components.py
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
def generate_stack_component_logs_command(
    component_type: StackComponentType,
) -> Callable[[str, bool], None]:
    """Generates a `logs` command for the specific stack component type.

    Args:
        component_type: Type of the component to generate the command for.

    Returns:
        A function that can be used as a `click` command.
    """
    display_name = _component_display_name(component_type)

    @click.argument("name_id_or_prefix", type=str, required=False)
    @click.option(
        "--follow",
        "-f",
        is_flag=True,
        help="Follow the log file instead of just displaying the current logs.",
    )
    def stack_component_logs_command(
        name_id_or_prefix: str, follow: bool = False
    ) -> None:
        """Displays stack component logs.

        Args:
            name_id_or_prefix: The name of the stack component to display logs
                for.
            follow: Follow the log file instead of just displaying the current
                logs.
        """
        client = Client()

        with console.status(
            f"Fetching the logs for the {display_name} "
            f"'{name_id_or_prefix}'...\n"
        ):
            try:
                component_model = client.get_stack_component(
                    name_id_or_prefix=name_id_or_prefix,
                    component_type=component_type,
                )
            except KeyError as err:
                cli_utils.error(str(err))

            from zenml.stack import StackComponent

            component = StackComponent.from_model(
                component_model=component_model
            )
            log_file = component.log_file

            if not log_file or not fileio.exists(log_file):
                cli_utils.warning(
                    f"Unable to find log file for {display_name} "
                    f"'{name_id_or_prefix}'."
                )
                return

        if not log_file or not fileio.exists(log_file):
            cli_utils.warning(
                f"Unable to find log file for {display_name} "
                f"'{component.name}'."
            )
            return

        if follow:
            try:
                with open(log_file, "r") as f:
                    # seek to the end of the file
                    f.seek(0, 2)

                    while True:
                        line = f.readline()
                        if not line:
                            time.sleep(0.1)
                            continue
                        line = line.rstrip("\n")
                        click.echo(line)
            except KeyboardInterrupt:
                cli_utils.declare(f"Stopped following {display_name} logs.")
        else:
            with open(log_file, "r") as f:
                click.echo(f.read())

    return stack_component_logs_command
generate_stack_component_register_command(component_type: StackComponentType) -> Callable[[str, str, List[str]], None]

Generates a register command for the specific stack component type.

Parameters:

Name Type Description Default
component_type StackComponentType

Type of the component to generate the command for.

required

Returns:

Type Description
Callable[[str, str, List[str]], None]

A function that can be used as a click command.

Source code in src/zenml/cli/stack_components.py
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
def generate_stack_component_register_command(
    component_type: StackComponentType,
) -> Callable[[str, str, List[str]], None]:
    """Generates a `register` command for the specific stack component type.

    Args:
        component_type: Type of the component to generate the command for.

    Returns:
        A function that can be used as a `click` command.
    """
    display_name = _component_display_name(component_type)

    @click.argument(
        "name",
        type=str,
    )
    @click.option(
        "--flavor",
        "-f",
        "flavor",
        help=f"The flavor of the {display_name} to register.",
        required=True,
        type=str,
    )
    @click.option(
        "--label",
        "-l",
        "labels",
        help="Labels to be associated with the component, in the form "
        "-l key1=value1 -l key2=value2.",
        multiple=True,
    )
    @click.option(
        "--connector",
        "-c",
        "connector",
        help="Use this flag to connect this stack component to a service connector.",
        type=str,
    )
    @click.option(
        "--resource-id",
        "-r",
        "resource_id",
        help="The resource ID to use with the connector. Only required for "
        "multi-instance connectors that are not already configured with a "
        "particular resource ID.",
        required=False,
        type=str,
    )
    @click.argument("args", nargs=-1, type=click.UNPROCESSED)
    def register_stack_component_command(
        name: str,
        flavor: str,
        args: List[str],
        labels: Optional[List[str]] = None,
        connector: Optional[str] = None,
        resource_id: Optional[str] = None,
    ) -> None:
        """Registers a stack component.

        Args:
            name: Name of the component to register.
            flavor: Flavor of the component to register.
            args: Additional arguments to pass to the component.
            labels: Labels to be associated with the component.
            connector: Name of the service connector to connect the component to.
            resource_id: The resource ID to use with the connector.
        """
        client = Client()

        # Parse the given args
        # name is guaranteed to be set by parse_name_and_extra_arguments
        name, parsed_args = cli_utils.parse_name_and_extra_arguments(  # type: ignore[assignment]
            list(args) + [name], expand_args=True
        )

        parsed_labels = cli_utils.get_parsed_labels(labels)

        if connector:
            try:
                client.get_service_connector(connector)
            except KeyError as err:
                cli_utils.error(
                    f"Could not find a connector '{connector}': {str(err)}"
                )

        with console.status(f"Registering {display_name} '{name}'...\n"):
            # Create a new stack component model
            component = client.create_stack_component(
                name=name,
                flavor=flavor,
                component_type=component_type,
                configuration=parsed_args,
                labels=parsed_labels,
            )

            cli_utils.declare(
                f"Successfully registered {component.type} `{component.name}`."
            )
            print_model_url(get_component_url(component))

        if connector:
            connect_stack_component_with_service_connector(
                component_type=component_type,
                name_id_or_prefix=name,
                connector=connector,
                interactive=False,
                no_verify=False,
                resource_id=resource_id,
            )

    return register_stack_component_command
generate_stack_component_remove_attribute_command(component_type: StackComponentType) -> Callable[[str, List[str]], None]

Generates remove_attribute command for a specific stack component type.

Parameters:

Name Type Description Default
component_type StackComponentType

Type of the component to generate the command for.

required

Returns:

Type Description
Callable[[str, List[str]], None]

A function that can be used as a click command.

Source code in src/zenml/cli/stack_components.py
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
def generate_stack_component_remove_attribute_command(
    component_type: StackComponentType,
) -> Callable[[str, List[str]], None]:
    """Generates `remove_attribute` command for a specific stack component type.

    Args:
        component_type: Type of the component to generate the command for.

    Returns:
        A function that can be used as a `click` command.
    """
    display_name = _component_display_name(component_type)

    @click.argument(
        "name_id_or_prefix",
        type=str,
        required=True,
    )
    @click.option(
        "--label",
        "-l",
        "labels",
        help="Labels to be removed from the component.",
        multiple=True,
    )
    @click.argument("args", nargs=-1, type=click.UNPROCESSED)
    def remove_attribute_stack_component_command(
        name_id_or_prefix: str,
        args: List[str],
        labels: Optional[List[str]] = None,
    ) -> None:
        """Removes one or more attributes from a stack component.

        Args:
            name_id_or_prefix: The name of the stack component to remove the
                attribute from.
            args: Additional arguments to pass to the remove_attribute command.
            labels: Labels to be removed from the component.
        """
        client = Client()

        with console.status(
            f"Updating {display_name} '{name_id_or_prefix}'...\n"
        ):
            try:
                updated_component = client.update_stack_component(
                    name_id_or_prefix=name_id_or_prefix,
                    component_type=component_type,
                    configuration={k: None for k in args},
                    labels={k: None for k in labels} if labels else None,
                )
            except (KeyError, IllegalOperationError) as err:
                cli_utils.error(str(err))

            cli_utils.declare(
                f"Successfully updated {display_name} `{name_id_or_prefix}`."
            )
            print_model_url(get_component_url(updated_component))

    return remove_attribute_stack_component_command
generate_stack_component_rename_command(component_type: StackComponentType) -> Callable[[str, str], None]

Generates a rename command for the specific stack component type.

Parameters:

Name Type Description Default
component_type StackComponentType

Type of the component to generate the command for.

required

Returns:

Type Description
Callable[[str, str], None]

A function that can be used as a click command.

Source code in src/zenml/cli/stack_components.py
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
def generate_stack_component_rename_command(
    component_type: StackComponentType,
) -> Callable[[str, str], None]:
    """Generates a `rename` command for the specific stack component type.

    Args:
        component_type: Type of the component to generate the command for.

    Returns:
        A function that can be used as a `click` command.
    """
    display_name = _component_display_name(component_type)

    @click.argument(
        "name_id_or_prefix",
        type=str,
        required=True,
    )
    @click.argument(
        "new_name",
        type=str,
        required=True,
    )
    def rename_stack_component_command(
        name_id_or_prefix: str, new_name: str
    ) -> None:
        """Rename a stack component.

        Args:
            name_id_or_prefix: The name of the stack component to rename.
            new_name: The new name of the stack component.
        """
        client = Client()

        with console.status(
            f"Renaming {display_name} '{name_id_or_prefix}'...\n"
        ):
            try:
                updated_component = client.update_stack_component(
                    name_id_or_prefix=name_id_or_prefix,
                    component_type=component_type,
                    name=new_name,
                )
            except (KeyError, IllegalOperationError) as err:
                cli_utils.error(str(err))

            cli_utils.declare(
                f"Successfully renamed {display_name} `{name_id_or_prefix}` to"
                f" `{new_name}`."
            )
            print_model_url(get_component_url(updated_component))

    return rename_stack_component_command
generate_stack_component_update_command(component_type: StackComponentType) -> Callable[[str, List[str]], None]

Generates an update command for the specific stack component type.

Parameters:

Name Type Description Default
component_type StackComponentType

Type of the component to generate the command for.

required

Returns:

Type Description
Callable[[str, List[str]], None]

A function that can be used as a click command.

Source code in src/zenml/cli/stack_components.py
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
def generate_stack_component_update_command(
    component_type: StackComponentType,
) -> Callable[[str, List[str]], None]:
    """Generates an `update` command for the specific stack component type.

    Args:
        component_type: Type of the component to generate the command for.

    Returns:
        A function that can be used as a `click` command.
    """
    display_name = _component_display_name(component_type)

    @click.argument(
        "name_id_or_prefix",
        type=str,
        required=False,
    )
    @click.option(
        "--label",
        "-l",
        "labels",
        help="Labels to be associated with the component, in the form "
        "-l key1=value1 -l key2=value2.",
        multiple=True,
    )
    @click.argument("args", nargs=-1, type=click.UNPROCESSED)
    def update_stack_component_command(
        name_id_or_prefix: Optional[str],
        args: List[str],
        labels: Optional[List[str]] = None,
    ) -> None:
        """Updates a stack component.

        Args:
            name_id_or_prefix: The name or id of the stack component to update.
            args: Additional arguments to pass to the update command.
            labels: Labels to be associated with the component.
        """
        client = Client()

        # Parse the given args
        args = list(args)
        if name_id_or_prefix:
            args.append(name_id_or_prefix)

        name_or_id, parsed_args = cli_utils.parse_name_and_extra_arguments(
            args,
            expand_args=True,
            name_mandatory=False,
        )

        parsed_labels = cli_utils.get_parsed_labels(labels)

        with console.status(f"Updating {display_name}...\n"):
            try:
                updated_component = client.update_stack_component(
                    name_id_or_prefix=name_or_id,
                    component_type=component_type,
                    configuration=parsed_args,
                    labels=parsed_labels,
                )
            except KeyError as err:
                cli_utils.error(str(err))

            cli_utils.declare(
                f"Successfully updated {display_name} "
                f"`{updated_component.name}`."
            )
            print_model_url(get_component_url(updated_component))

    return update_stack_component_command
prompt_select_resource(resource_list: List[ServiceConnectorResourcesModel]) -> Tuple[UUID, str]

Prompts the user to select a resource ID from a list of resources.

Parameters:

Name Type Description Default
resource_list List[ServiceConnectorResourcesModel]

List of resources to select from.

required

Returns:

Type Description
UUID

The ID of a selected connector and the ID of the selected resource

str

instance.

Source code in src/zenml/cli/stack_components.py
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
def prompt_select_resource(
    resource_list: List[ServiceConnectorResourcesModel],
) -> Tuple[UUID, str]:
    """Prompts the user to select a resource ID from a list of resources.

    Args:
        resource_list: List of resources to select from.

    Returns:
        The ID of a selected connector and the ID of the selected resource
        instance.
    """
    if len(resource_list) == 1:
        click.echo("Only one connector has compatible resources:")
    else:
        click.echo("The following connectors have compatible resources:")

    cli_utils.print_service_connector_resource_table(resource_list)

    if len(resource_list) == 1:
        connect = click.confirm(
            "Would you like to use this connector?",
            default=True,
        )
        if not connect:
            cli_utils.error("Aborting.")
        resources = resource_list[0]
    else:
        # Prompt the user to select a connector by its name or ID
        while True:
            connector_id = click.prompt(
                "Please enter the name or ID of the connector you want to use",
                type=click.Choice(
                    [
                        str(connector.id)
                        for connector in resource_list
                        if connector.id is not None
                    ]
                    + [
                        connector.name
                        for connector in resource_list
                        if connector.name is not None
                    ]
                ),
                show_choices=False,
            )
            matches = [
                c
                for c in resource_list
                if str(c.id) == connector_id or c.name == connector_id
            ]
            if len(matches) > 1:
                cli_utils.declare(
                    f"Multiple connectors with name '{connector_id}' "
                    "were found. Please try again."
                )
            else:
                resources = matches[0]
                break

    connector_uuid = resources.id
    assert connector_uuid is not None

    assert len(resources.resources) == 1
    resource_name = resources.resources[0].resource_type
    if not isinstance(resources.connector_type, str):
        resource_type_spec = resources.connector_type.resource_type_dict[
            resource_name
        ]
        resource_name = resource_type_spec.name

    resource_id = prompt_select_resource_id(
        resources.resources[0].resource_ids or [], resource_name=resource_name
    )

    return connector_uuid, resource_id
prompt_select_resource_id(resource_ids: List[str], resource_name: str, interactive: bool = True) -> str

Prompts the user to select a resource ID from a list of available IDs.

Parameters:

Name Type Description Default
resource_ids List[str]

A list of available resource IDs.

required
resource_name str

The name of the resource type to select.

required
interactive bool

Whether to prompt the user for input or error out if user input is required.

True

Returns:

Type Description
str

The selected resource ID.

Source code in src/zenml/cli/stack_components.py
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
def prompt_select_resource_id(
    resource_ids: List[str],
    resource_name: str,
    interactive: bool = True,
) -> str:
    """Prompts the user to select a resource ID from a list of available IDs.

    Args:
        resource_ids: A list of available resource IDs.
        resource_name: The name of the resource type to select.
        interactive: Whether to prompt the user for input or error out if
            user input is required.

    Returns:
        The selected resource ID.
    """
    if len(resource_ids) == 1:
        # Only one resource ID is available, so we can select it
        # without prompting the user
        return resource_ids[0]

    if len(resource_ids) > 1:
        resource_ids_list = "\n - " + "\n - ".join(resource_ids)
        msg = (
            f"Multiple {resource_name} resources are available for the "
            f"selected connector:\n{resource_ids_list}\n"
        )
        # User needs to select a resource ID from the list
        if not interactive:
            cli_utils.error(
                f"{msg}Please use the `--resource-id` command line "  # nosec
                f"argument to select a {resource_name} resource from the "
                "list."
            )
        resource_id = click.prompt(
            f"{msg}Please select the {resource_name} that you want to use",
            type=click.Choice(resource_ids),
            show_choices=False,
        )

        return cast(str, resource_id)

    # We should never get here, but just in case...
    cli_utils.error(
        "Could not determine which resource to use. Please select a "
        "different connector."
    )
register_all_stack_component_cli_commands() -> None

Registers CLI commands for all stack components.

Source code in src/zenml/cli/stack_components.py
1314
1315
1316
1317
1318
1319
def register_all_stack_component_cli_commands() -> None:
    """Registers CLI commands for all stack components."""
    for component_type in StackComponentType:
        register_single_stack_component_cli_commands(
            component_type, parent_group=cli
        )
register_single_stack_component_cli_commands(component_type: StackComponentType, parent_group: click.Group) -> None

Registers all basic stack component CLI commands.

Parameters:

Name Type Description Default
component_type StackComponentType

Type of the component to generate the command for.

required
parent_group Group

The parent group to register the commands to.

required
Source code in src/zenml/cli/stack_components.py
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
def register_single_stack_component_cli_commands(
    component_type: StackComponentType, parent_group: click.Group
) -> None:
    """Registers all basic stack component CLI commands.

    Args:
        component_type: Type of the component to generate the command for.
        parent_group: The parent group to register the commands to.
    """
    command_name = component_type.value.replace("_", "-")
    singular_display_name = _component_display_name(component_type)
    plural_display_name = _component_display_name(component_type, plural=True)

    @parent_group.group(
        command_name,
        cls=TagGroup,
        help=f"Commands to interact with {plural_display_name}.",
        tag=CliCategories.STACK_COMPONENTS,
    )
    def command_group() -> None:
        """Group commands for a single stack component type."""

    # zenml stack-component get
    get_command = generate_stack_component_get_command(component_type)
    command_group.command(
        "get", help=f"Get the name of the active {singular_display_name}."
    )(get_command)

    # zenml stack-component describe
    describe_command = generate_stack_component_describe_command(
        component_type
    )
    command_group.command(
        "describe",
        help=f"Show details about the (active) {singular_display_name}.",
    )(describe_command)

    # zenml stack-component list
    list_command = generate_stack_component_list_command(component_type)
    command_group.command(
        "list", help=f"List all registered {plural_display_name}."
    )(list_command)

    # zenml stack-component register
    register_command = generate_stack_component_register_command(
        component_type
    )
    context_settings = {"ignore_unknown_options": True}
    command_group.command(
        "register",
        context_settings=context_settings,
        help=f"Register a new {singular_display_name}.",
    )(register_command)

    # zenml stack-component update
    update_command = generate_stack_component_update_command(component_type)
    context_settings = {"ignore_unknown_options": True}
    command_group.command(
        "update",
        context_settings=context_settings,
        help=f"Update a registered {singular_display_name}.",
    )(update_command)

    # zenml stack-component remove-attribute
    remove_attribute_command = (
        generate_stack_component_remove_attribute_command(component_type)
    )
    context_settings = {"ignore_unknown_options": True}
    command_group.command(
        "remove-attribute",
        context_settings=context_settings,
        help=f"Remove attributes from a registered {singular_display_name}.",
    )(remove_attribute_command)

    # zenml stack-component rename
    rename_command = generate_stack_component_rename_command(component_type)
    command_group.command(
        "rename", help=f"Rename a registered {singular_display_name}."
    )(rename_command)

    # zenml stack-component delete
    delete_command = generate_stack_component_delete_command(component_type)
    command_group.command(
        "delete", help=f"Delete a registered {singular_display_name}."
    )(delete_command)

    # zenml stack-component copy
    copy_command = generate_stack_component_copy_command(component_type)
    command_group.command(
        "copy", help=f"Copy a registered {singular_display_name}."
    )(copy_command)

    # zenml stack-component logs
    logs_command = generate_stack_component_logs_command(component_type)
    command_group.command(
        "logs", help=f"Display {singular_display_name} logs."
    )(logs_command)

    # zenml stack-component connect
    connect_command = generate_stack_component_connect_command(component_type)
    command_group.command(
        "connect",
        help=f"Connect {singular_display_name} to a service connector.",
    )(connect_command)

    # zenml stack-component connect
    disconnect_command = generate_stack_component_disconnect_command(
        component_type
    )
    command_group.command(
        "disconnect",
        help=f"Disconnect {singular_display_name} from a service connector.",
    )(disconnect_command)

    # zenml stack-component explain
    explain_command = generate_stack_component_explain_command(component_type)
    command_group.command(
        "explain", help=f"Explaining the {plural_display_name}."
    )(explain_command)

    # zenml stack-component flavor
    @command_group.group(
        "flavor", help=f"Commands to interact with {plural_display_name}."
    )
    def flavor_group() -> None:
        """Group commands to handle flavors for a stack component type."""

    # zenml stack-component flavor register
    register_flavor_command = generate_stack_component_flavor_register_command(
        component_type=component_type
    )
    flavor_group.command(
        "register",
        help=f"Register a new {singular_display_name} flavor.",
    )(register_flavor_command)

    # zenml stack-component flavor list
    list_flavor_command = generate_stack_component_flavor_list_command(
        component_type=component_type
    )
    flavor_group.command(
        "list",
        help=f"List all registered flavors for {plural_display_name}.",
    )(list_flavor_command)

    # zenml stack-component flavor describe
    describe_flavor_command = generate_stack_component_flavor_describe_command(
        component_type=component_type
    )
    flavor_group.command(
        "describe",
        help=f"Describe a {singular_display_name} flavor.",
    )(describe_flavor_command)

    # zenml stack-component flavor delete
    delete_flavor_command = generate_stack_component_flavor_delete_command(
        component_type=component_type
    )
    flavor_group.command(
        "delete",
        help=f"Delete a {plural_display_name} flavor.",
    )(delete_flavor_command)
Modules

text_utils

Utilities for CLI output.

Classes
OldSchoolMarkdownHeading

Bases: Heading

A traditional markdown heading.

Functions
zenml_go_notebook_tutorial_message(ipynb_files: List[str]) -> Markdown

Outputs a message to the user about the zenml go tutorial.

Parameters:

Name Type Description Default
ipynb_files List[str]

A list of IPython Notebook files.

required

Returns:

Type Description
Markdown

A Markdown object.

Source code in src/zenml/cli/text_utils.py
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
def zenml_go_notebook_tutorial_message(ipynb_files: List[str]) -> Markdown:
    """Outputs a message to the user about the `zenml go` tutorial.

    Args:
        ipynb_files: A list of IPython Notebook files.

    Returns:
        A Markdown object.
    """
    ipynb_files = [f"- {fi} \n" for fi in ipynb_files]
    return Markdown(
        f"""
## 🧑‍🏫 Get started with ZenML

The ZenML tutorial repository was cloned to your current working directory.
Within the repository you can get started on one of these notebooks:
{"".join(ipynb_files)}
Next we will start a Jupyter notebook server. Feel free to try your hand at our
tutorial notebooks. If your browser does not open automatically click one of the
links below.\n

"""
    )

user_management

Functionality to administer users of the ZenML CLI and server.

Classes
Functions
change_user_password(password: Optional[str] = None, old_password: Optional[str] = None) -> None

Change the password of the current user.

Parameters:

Name Type Description Default
password Optional[str]

The new password for the current user.

None
old_password Optional[str]

The old password for the current user.

None
Source code in src/zenml/cli/user_management.py
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
@user.command(
    "change-password",
    help="Change the password for the current user account.",
)
@click.option(
    "--password",
    help=(
        "The new user password. If omitted, a prompt will be shown to enter "
        "the password."
    ),
    required=False,
    type=str,
)
@click.option(
    "--old-password",
    help=(
        "The old user password. If omitted, a prompt will be shown to enter "
        "the old password."
    ),
    required=False,
    type=str,
)
def change_user_password(
    password: Optional[str] = None, old_password: Optional[str] = None
) -> None:
    """Change the password of the current user.

    Args:
        password: The new password for the current user.
        old_password: The old password for the current user.
    """
    active_user = Client().active_user

    if old_password is not None or password is not None:
        cli_utils.warning(
            "Supplying password values in the command line is not safe. "
            "Please consider using the prompt option."
        )

    if old_password is None:
        old_password = click.prompt(
            f"Current password for user {active_user.name}",
            hide_input=True,
        )
    if password is None:
        password = click.prompt(
            f"New password for user {active_user.name}",
            hide_input=True,
        )
        password_again = click.prompt(
            f"Please re-enter the new password for user {active_user.name}",
            hide_input=True,
        )
        if password != password_again:
            cli_utils.error("Passwords do not match.")

    try:
        Client().update_user(
            name_id_or_prefix=active_user.id,
            old_password=old_password,
            updated_password=password,
        )
    except (KeyError, IllegalOperationError, AuthorizationException) as err:
        cli_utils.error(str(err))

    cli_utils.declare(
        f"Successfully updated password for active user '{active_user.name}'."
    )
create_user(user_name: str, password: Optional[str] = None, is_admin: bool = False) -> None

Create a new user.

Parameters:

Name Type Description Default
user_name str

The name of the user to create.

required
password Optional[str]

The password of the user to create.

None
is_admin bool

Whether the user should be an admin.

False
Source code in src/zenml/cli/user_management.py
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
@user.command(
    "create",
    help="Create a new user. If an empty password is configured, an activation "
    "token is generated and a link to the dashboard is provided where the "
    "user can activate the account.",
)
@click.argument("user_name", type=str, required=True)
@click.option(
    "--password",
    help=(
        "The user password. If omitted, a prompt will be shown to enter the "
        "password. If an empty password is entered, an activation token is "
        "generated and a link to the dashboard is provided where the user can "
        "activate the account."
    ),
    required=False,
    type=str,
)
@click.option(
    "--is_admin",
    is_flag=True,
    help=(
        "Whether the user should be an admin. If not specified, the user will "
        "be a regular user."
    ),
    required=False,
    default=False,
)
def create_user(
    user_name: str,
    password: Optional[str] = None,
    is_admin: bool = False,
) -> None:
    """Create a new user.

    Args:
        user_name: The name of the user to create.
        password: The password of the user to create.
        is_admin: Whether the user should be an admin.
    """
    client = Client()
    if not password:
        if client.zen_store.type != StoreType.REST:
            password = click.prompt(
                f"Password for user {user_name}",
                hide_input=True,
            )
        else:
            password = click.prompt(
                f"Password for user {user_name}. Leave empty to generate an "
                f"activation token",
                default="",
                hide_input=True,
            )
    else:
        cli_utils.warning(
            "Supplying password values in the command line is not safe. "
            "Please consider using the prompt option."
        )

    try:
        new_user = client.create_user(
            name=user_name, password=password, is_admin=is_admin
        )

        cli_utils.declare(f"Created user '{new_user.name}'.")
    except EntityExistsError as err:
        cli_utils.error(str(err))
    else:
        if not new_user.active and new_user.activation_token is not None:
            user_info = f"?user={str(new_user.id)}&username={new_user.name}&token={new_user.activation_token}"
            cli_utils.declare(
                f"The created user account is currently inactive. You can "
                f"activate it by visiting the dashboard at the following URL:\n"
                # TODO: keep only `activate-user` once legacy dashboard is gone
                f"{client.zen_store.url}/activate-user{user_info}\n\n"
                "If you are using Legacy dashboard visit the following URL:\n"
                f"{client.zen_store.url}/signup{user_info}\n"
            )
deactivate_user(user_name_or_id: str) -> None

Reset the password of a user.

Parameters:

Name Type Description Default
user_name_or_id str

The name or ID of the user to reset the password for.

required
Source code in src/zenml/cli/user_management.py
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
@user.command(
    "deactivate",
    help="Generate an activation token to reset the password for a user account",
)
@click.argument("user_name_or_id", type=str, required=True)
def deactivate_user(
    user_name_or_id: str,
) -> None:
    """Reset the password of a user.

    Args:
        user_name_or_id: The name or ID of the user to reset the password for.
    """
    client = Client()

    store = GlobalConfiguration().store_configuration
    if store.type != StoreType.REST:
        cli_utils.error(
            "Deactivating users is only supported when connected to a ZenML "
            "server."
        )

    try:
        if not client.active_user.is_admin:
            cli_utils.error(
                "Only admins can reset the password of other users."
            )

        user = client.deactivate_user(
            name_id_or_prefix=user_name_or_id,
        )
    except (KeyError, IllegalOperationError) as err:
        cli_utils.error(str(err))

    user_info = f"?user={str(user.id)}&username={user.name}&token={user.activation_token}"
    cli_utils.declare(
        f"Successfully deactivated user account '{user.name}'."
        f"To reactivate the account, please visit the dashboard at the "
        "following URL:\n"
        # TODO: keep only `activate-user` once legacy dashboard is gone
        f"{client.zen_store.url}/activate-user{user_info}\n\n"
        "If you are using Legacy dashboard visit the following URL:\n"
        f"{client.zen_store.url}/signup{user_info}\n"
    )
delete_user(user_name_or_id: str) -> None

Delete a user.

Parameters:

Name Type Description Default
user_name_or_id str

The name or ID of the user to delete.

required
Source code in src/zenml/cli/user_management.py
417
418
419
420
421
422
423
424
425
426
427
428
429
@user.command("delete")
@click.argument("user_name_or_id", type=str, required=True)
def delete_user(user_name_or_id: str) -> None:
    """Delete a user.

    Args:
        user_name_or_id: The name or ID of the user to delete.
    """
    try:
        Client().delete_user(user_name_or_id)
    except (KeyError, IllegalOperationError) as err:
        cli_utils.error(str(err))
    cli_utils.declare(f"Deleted user '{user_name_or_id}'.")
describe_user(user_name_or_id: Optional[str] = None) -> None

Get the user.

Parameters:

Name Type Description Default
user_name_or_id Optional[str]

The name or ID of the user.

None
Source code in src/zenml/cli/user_management.py
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
@user.command("describe")
@click.argument("user_name_or_id", type=str, required=False)
def describe_user(user_name_or_id: Optional[str] = None) -> None:
    """Get the user.

    Args:
        user_name_or_id: The name or ID of the user.
    """
    client = Client()
    if not user_name_or_id:
        active_user = client.active_user
        cli_utils.print_pydantic_models(
            [active_user],
            exclude_columns=[
                "created",
                "updated",
                "email",
                "email_opted_in",
                "activation_token",
            ],
        )
    else:
        try:
            user = client.get_user(user_name_or_id)
        except KeyError as err:
            cli_utils.error(str(err))
        else:
            cli_utils.print_pydantic_models(
                [user],
                exclude_columns=[
                    "created",
                    "updated",
                    "email",
                    "email_opted_in",
                    "activation_token",
                ],
            )
list_users(ctx: click.Context, /, **kwargs: Any) -> None

List all users.

Parameters:

Name Type Description Default
ctx Context

The click context object

required
kwargs Any

Keyword arguments to filter the list of users.

{}
Source code in src/zenml/cli/user_management.py
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
@user.command("list")
@list_options(UserFilter)
@click.pass_context
def list_users(ctx: click.Context, /, **kwargs: Any) -> None:
    """List all users.

    Args:
        ctx: The click context object
        kwargs: Keyword arguments to filter the list of users.
    """
    client = Client()
    with console.status("Listing stacks...\n"):
        users = client.list_users(**kwargs)
        if not users:
            cli_utils.declare("No users found for the given filters.")
            return

        cli_utils.print_pydantic_models(
            users,
            exclude_columns=[
                "created",
                "updated",
                "email",
                "email_opted_in",
                "activation_token",
            ],
            active_models=[Client().active_user],
            show_active=not is_sorted_or_filtered(ctx),
        )
update_user(user_name_or_id: str, updated_name: Optional[str] = None, updated_full_name: Optional[str] = None, updated_email: Optional[str] = None, make_admin: Optional[bool] = None, make_user: Optional[bool] = None, active: Optional[bool] = None) -> None

Update an existing user.

Parameters:

Name Type Description Default
user_name_or_id str

The name of the user to create.

required
updated_name Optional[str]

The name of the user to create.

None
updated_full_name Optional[str]

The name of the user to create.

None
updated_email Optional[str]

The name of the user to create.

None
make_admin Optional[bool]

Whether the user should be an admin.

None
make_user Optional[bool]

Whether the user should be a regular user.

None
active Optional[bool]

Use to activate or deactivate a user account.

None
Source code in src/zenml/cli/user_management.py
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
@user.command(
    "update",
    help="Update user information through the cli.",
)
@click.argument("user_name_or_id", type=str, required=True)
@click.option(
    "--name",
    "-n",
    "updated_name",
    type=str,
    required=False,
    help="New user name.",
)
@click.option(
    "--full_name",
    "-f",
    "updated_full_name",
    type=str,
    required=False,
    help="New full name. If this contains an empty space make sure to surround "
    "the name with quotes '<Full Name>'.",
)
@click.option(
    "--email",
    "-e",
    "updated_email",
    type=str,
    required=False,
    help="New user email.",
)
@click.option(
    "--admin",
    "-a",
    "make_admin",
    is_flag=True,
    required=False,
    default=None,
    help="Whether the user should be an admin.",
)
@click.option(
    "--user",
    "-u",
    "make_user",
    is_flag=True,
    required=False,
    default=None,
    help="Whether the user should be a regular user.",
)
@click.option(
    "--active",
    "active",
    type=bool,
    required=False,
    default=None,
    help="Use to activate or deactivate a user account.",
)
def update_user(
    user_name_or_id: str,
    updated_name: Optional[str] = None,
    updated_full_name: Optional[str] = None,
    updated_email: Optional[str] = None,
    make_admin: Optional[bool] = None,
    make_user: Optional[bool] = None,
    active: Optional[bool] = None,
) -> None:
    """Update an existing user.

    Args:
        user_name_or_id: The name of the user to create.
        updated_name: The name of the user to create.
        updated_full_name: The name of the user to create.
        updated_email: The name of the user to create.
        make_admin: Whether the user should be an admin.
        make_user: Whether the user should be a regular user.
        active: Use to activate or deactivate a user account.
    """
    if make_admin is not None and make_user is not None:
        cli_utils.error(
            "Cannot set both --admin and --user flags as these are mutually exclusive."
        )
    try:
        current_user = Client().get_user(
            user_name_or_id, allow_name_prefix_match=False
        )
        if current_user.is_admin and make_user:
            confirmation = cli_utils.confirmation(
                f"Currently user `{current_user.name}` is an admin. Are you "
                "sure you want to make them a regular user?"
            )
            if not confirmation:
                cli_utils.declare("User update canceled.")
                return

        updated_is_admin = None
        if make_admin is True:
            updated_is_admin = True
        elif make_user is True:
            updated_is_admin = False
        Client().update_user(
            name_id_or_prefix=user_name_or_id,
            updated_name=updated_name,
            updated_full_name=updated_full_name,
            updated_email=updated_email,
            updated_is_admin=updated_is_admin,
            active=active,
        )
    except (KeyError, IllegalOperationError) as err:
        cli_utils.error(str(err))
user() -> None

Commands for user management.

Source code in src/zenml/cli/user_management.py
35
36
37
@cli.group(cls=TagGroup, tag=CliCategories.IDENTITY_AND_SECURITY)
def user() -> None:
    """Commands for user management."""
Modules

utils

Utility functions for the CLI.

Classes
Functions
check_zenml_pro_project_availability() -> None

Check if the ZenML Pro project feature is available.

Source code in src/zenml/cli/utils.py
2273
2274
2275
2276
2277
2278
2279
2280
def check_zenml_pro_project_availability() -> None:
    """Check if the ZenML Pro project feature is available."""
    client = Client()
    if not client.zen_store.get_store_info().is_pro_server():
        warning(
            "The ZenML projects feature is available only on ZenML Pro. "
            "Please visit https://zenml.io/pro to learn more."
        )
confirmation(text: str, *args: Any, **kwargs: Any) -> bool

Echo a confirmation string on the CLI.

Parameters:

Name Type Description Default
text str

Input text string.

required
*args Any

Args to be passed to click.confirm().

()
**kwargs Any

Kwargs to be passed to click.confirm().

{}

Returns:

Type Description
bool

Boolean based on user response.

Source code in src/zenml/cli/utils.py
125
126
127
128
129
130
131
132
133
134
135
136
def confirmation(text: str, *args: Any, **kwargs: Any) -> bool:
    """Echo a confirmation string on the CLI.

    Args:
        text: Input text string.
        *args: Args to be passed to click.confirm().
        **kwargs: Kwargs to be passed to click.confirm().

    Returns:
        Boolean based on user response.
    """
    return Confirm.ask(text, console=console)
convert_structured_str_to_dict(string: str) -> Dict[str, str]

Convert a structured string (JSON or YAML) into a dict.

Examples:

>>> convert_structured_str_to_dict('{"location": "Nevada", "aliens":"many"}')
{'location': 'Nevada', 'aliens': 'many'}
>>> convert_structured_str_to_dict('location: Nevada \naliens: many')
{'location': 'Nevada', 'aliens': 'many'}
>>> convert_structured_str_to_dict("{'location': 'Nevada', 'aliens': 'many'}")
{'location': 'Nevada', 'aliens': 'many'}

Parameters:

Name Type Description Default
string str

JSON or YAML string value

required

Returns:

Name Type Description
dict_ Dict[str, str]

dict from structured JSON or YAML str

Source code in src/zenml/cli/utils.py
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
def convert_structured_str_to_dict(string: str) -> Dict[str, str]:
    """Convert a structured string (JSON or YAML) into a dict.

    Examples:
        >>> convert_structured_str_to_dict('{"location": "Nevada", "aliens":"many"}')
        {'location': 'Nevada', 'aliens': 'many'}
        >>> convert_structured_str_to_dict('location: Nevada \\naliens: many')
        {'location': 'Nevada', 'aliens': 'many'}
        >>> convert_structured_str_to_dict("{'location': 'Nevada', 'aliens': 'many'}")
        {'location': 'Nevada', 'aliens': 'many'}

    Args:
        string: JSON or YAML string value

    Returns:
        dict_: dict from structured JSON or YAML str
    """
    try:
        dict_: Dict[str, str] = json.loads(string)
        return dict_
    except ValueError:
        pass

    try:
        # Here, Dict type in str is implicitly supported by yaml.safe_load()
        dict_ = yaml.safe_load(string)
        return dict_
    except yaml.YAMLError:
        pass

    error(
        f"Invalid argument: '{string}'. Please provide the value in JSON or YAML format."
    )
create_data_type_help_text(filter_model: Type[BaseFilter], field: str) -> str

Create a general help text for a fields datatype.

Parameters:

Name Type Description Default
filter_model Type[BaseFilter]

The filter model to use

required
field str

The field within that filter model

required

Returns:

Type Description
str

The help text.

Source code in src/zenml/cli/utils.py
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
def create_data_type_help_text(
    filter_model: Type[BaseFilter], field: str
) -> str:
    """Create a general help text for a fields datatype.

    Args:
        filter_model: The filter model to use
        field: The field within that filter model

    Returns:
        The help text.
    """
    filter_generator = FilterGenerator(filter_model)
    if filter_generator.is_datetime_field(field):
        return (
            f"[DATETIME] supported filter operators: "
            f"{[str(op) for op in NumericFilter.ALLOWED_OPS]}"
        )
    elif filter_generator.is_uuid_field(field):
        return (
            f"[UUID] supported filter operators: "
            f"{[str(op) for op in UUIDFilter.ALLOWED_OPS]}"
        )
    elif filter_generator.is_int_field(field):
        return (
            f"[INTEGER] supported filter operators: "
            f"{[str(op) for op in NumericFilter.ALLOWED_OPS]}"
        )
    elif filter_generator.is_bool_field(field):
        return (
            f"[BOOL] supported filter operators: "
            f"{[str(op) for op in BoolFilter.ALLOWED_OPS]}"
        )
    elif filter_generator.is_str_field(field):
        return (
            f"[STRING] supported filter operators: "
            f"{[str(op) for op in StrFilter.ALLOWED_OPS]}"
        )
    else:
        return f"{field}"
create_filter_help_text(filter_model: Type[BaseFilter], field: str) -> str

Create the help text used in the click option help text.

Parameters:

Name Type Description Default
filter_model Type[BaseFilter]

The filter model to use

required
field str

The field within that filter model

required

Returns:

Type Description
str

The help text.

Source code in src/zenml/cli/utils.py
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
def create_filter_help_text(filter_model: Type[BaseFilter], field: str) -> str:
    """Create the help text used in the click option help text.

    Args:
        filter_model: The filter model to use
        field: The field within that filter model

    Returns:
        The help text.
    """
    filter_generator = FilterGenerator(filter_model)
    if filter_generator.is_sort_by_field(field):
        return (
            "[STRING] Example: --sort_by='desc:name' to sort by name in "
            "descending order. "
        )
    if filter_generator.is_datetime_field(field):
        return (
            f"[DATETIME] The following datetime format is supported: "
            f"'{FILTERING_DATETIME_FORMAT}'. Make sure to keep it in "
            f"quotation marks. "
            f"Example: --{field}="
            f"'{GenericFilterOps.GTE}:{FILTERING_DATETIME_FORMAT}' to "
            f"filter for everything created on or after the given date."
        )
    elif filter_generator.is_uuid_field(field):
        return (
            f"[UUID] Example: --{field}='{GenericFilterOps.STARTSWITH}:ab53ca' "
            f"to filter for all UUIDs starting with that prefix."
        )
    elif filter_generator.is_int_field(field):
        return (
            f"[INTEGER] Example: --{field}='{GenericFilterOps.GTE}:25' to "
            f"filter for all entities where this field has a value greater than "
            f"or equal to the value."
        )
    elif filter_generator.is_bool_field(field):
        return (
            f"[BOOL] Example: --{field}='True' to "
            f"filter for all instances where this field is true."
        )
    elif filter_generator.is_str_field(field):
        return (
            f"[STRING] Example: --{field}='{GenericFilterOps.CONTAINS}:example' "
            f"to filter everything that contains the query string somewhere in "
            f"its {field}."
        )
    else:
        return ""
declare(text: Union[str, Text], bold: Optional[bool] = None, italic: Optional[bool] = None, **kwargs: Any) -> None

Echo a declaration on the CLI.

Parameters:

Name Type Description Default
text Union[str, Text]

Input text string.

required
bold Optional[bool]

Optional boolean to bold the text.

None
italic Optional[bool]

Optional boolean to italicize the text.

None
**kwargs Any

Optional kwargs to be passed to console.print().

{}
Source code in src/zenml/cli/utils.py
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
def declare(
    text: Union[str, "Text"],
    bold: Optional[bool] = None,
    italic: Optional[bool] = None,
    **kwargs: Any,
) -> None:
    """Echo a declaration on the CLI.

    Args:
        text: Input text string.
        bold: Optional boolean to bold the text.
        italic: Optional boolean to italicize the text.
        **kwargs: Optional kwargs to be passed to console.print().
    """
    base_style = zenml_style_defaults["info"]
    style = Style.chain(base_style, Style(bold=bold, italic=italic))
    console.print(text, style=style, **kwargs)
describe_pydantic_object(schema_json: Dict[str, Any]) -> None

Describes a Pydantic object based on the dict-representation of its schema.

Parameters:

Name Type Description Default
schema_json Dict[str, Any]

str, represents the schema of a Pydantic object, which can be obtained through BaseModelClass.schema_json()

required
Source code in src/zenml/cli/utils.py
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
def describe_pydantic_object(schema_json: Dict[str, Any]) -> None:
    """Describes a Pydantic object based on the dict-representation of its schema.

    Args:
        schema_json: str, represents the schema of a Pydantic object, which
            can be obtained through BaseModelClass.schema_json()
    """
    # Get the schema dict
    # Extract values with defaults
    schema_title = schema_json["title"]
    required = schema_json.get("required", [])
    description = schema_json.get("description", "")
    properties = schema_json.get("properties", {})

    # Pretty print the schema
    warning(f"Configuration class: {schema_title}\n", bold=True)

    if description:
        declare(f"{description}\n")

    if properties:
        warning("Properties", bold=True)
        for prop, prop_schema in properties.items():
            if "$ref" not in prop_schema.keys():
                if "type" in prop_schema.keys():
                    prop_type = prop_schema["type"]
                elif "anyOf" in prop_schema.keys():
                    prop_type = ", ".join(
                        [p.get("type", "object") for p in prop_schema["anyOf"]]
                    )
                    prop_type = f"one of: {prop_type}"
                else:
                    prop_type = "object"
                warning(
                    f"{prop}, {prop_type}"
                    f"{', REQUIRED' if prop in required else ''}"
                )

            if "description" in prop_schema:
                declare(f"  {prop_schema['description']}", width=80)
error(text: str) -> NoReturn

Echo an error string on the CLI.

Parameters:

Name Type Description Default
text str

Input text string.

required

Raises:

Type Description
ClickException

when called.

Source code in src/zenml/cli/utils.py
158
159
160
161
162
163
164
165
166
167
def error(text: str) -> NoReturn:
    """Echo an error string on the CLI.

    Args:
        text: Input text string.

    Raises:
        ClickException: when called.
    """
    raise click.ClickException(message=click.style(text, fg="red", bold=True))
expand_argument_value_from_file(name: str, value: str) -> str

Expands the value of an argument pointing to a file into the contents of that file.

Parameters:

Name Type Description Default
name str

Name of the argument. Used solely for logging purposes.

required
value str

The value of the argument. This is to be interpreted as a filename if it begins with a @ character.

required

Returns:

Type Description
str

The argument value expanded into the contents of the file, if the

str

argument value begins with a @ character. Otherwise, the argument

str

value is returned unchanged.

Raises:

Type Description
ValueError

If the argument value points to a file that doesn't exist, that cannot be read, or is too long(i.e. exceeds MAX_ARGUMENT_VALUE_SIZE bytes).

Source code in src/zenml/cli/utils.py
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
def expand_argument_value_from_file(name: str, value: str) -> str:
    """Expands the value of an argument pointing to a file into the contents of that file.

    Args:
        name: Name of the argument. Used solely for logging purposes.
        value: The value of the argument. This is to be interpreted as a
            filename if it begins with a `@` character.

    Returns:
        The argument value expanded into the contents of the file, if the
        argument value begins with a `@` character. Otherwise, the argument
        value is returned unchanged.

    Raises:
        ValueError: If the argument value points to a file that doesn't exist,
            that cannot be read, or is too long(i.e. exceeds
            `MAX_ARGUMENT_VALUE_SIZE` bytes).
    """
    if value.startswith("@@"):
        return value[1:]
    if not value.startswith("@"):
        return value
    filename = os.path.abspath(os.path.expanduser(value[1:]))
    logger.info(
        f"Expanding argument value `{name}` to contents of file `{filename}`."
    )
    if not os.path.isfile(filename):
        raise ValueError(
            f"Could not load argument '{name}' value: file "
            f"'{filename}' does not exist or is not readable."
        )
    try:
        if os.path.getsize(filename) > MAX_ARGUMENT_VALUE_SIZE:
            raise ValueError(
                f"Could not load argument '{name}' value: file "
                f"'{filename}' is too large (max size is "
                f"{MAX_ARGUMENT_VALUE_SIZE} bytes)."
            )

        with open(filename, "r") as f:
            return f.read()
    except OSError as e:
        raise ValueError(
            f"Could not load argument '{name}' value: file "
            f"'{filename}' could not be accessed: {str(e)}"
        )
format_integration_list(integrations: List[Tuple[str, Type[Integration]]]) -> List[Dict[str, str]]

Formats a list of integrations into a List of Dicts.

This list of dicts can then be printed in a table style using cli_utils.print_table.

Parameters:

Name Type Description Default
integrations List[Tuple[str, Type[Integration]]]

List of tuples containing the name of the integration and the integration metadata.

required

Returns:

Type Description
List[Dict[str, str]]

List of Dicts containing the name of the integration and the integration

Source code in src/zenml/cli/utils.py
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
def format_integration_list(
    integrations: List[Tuple[str, Type["Integration"]]],
) -> List[Dict[str, str]]:
    """Formats a list of integrations into a List of Dicts.

    This list of dicts can then be printed in a table style using
    cli_utils.print_table.

    Args:
        integrations: List of tuples containing the name of the integration and
            the integration metadata.

    Returns:
        List of Dicts containing the name of the integration and the integration
    """
    list_of_dicts = []
    for name, integration_impl in integrations:
        is_installed = integration_impl.check_installation()
        list_of_dicts.append(
            {
                "INSTALLED": ":white_check_mark:" if is_installed else ":x:",
                "INTEGRATION": name,
                "REQUIRED_PACKAGES": ", ".join(
                    integration_impl.get_requirements()
                ),
            }
        )
    return list_of_dicts
get_boolean_emoji(value: bool) -> str

Returns the emoji for displaying a boolean.

Parameters:

Name Type Description Default
value bool

The boolean value to display

required

Returns:

Type Description
str

The emoji for the boolean

Source code in src/zenml/cli/utils.py
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
def get_boolean_emoji(value: bool) -> str:
    """Returns the emoji for displaying a boolean.

    Args:
        value: The boolean value to display

    Returns:
        The emoji for the boolean
    """
    return ":white_heavy_check_mark:" if value else ":heavy_minus_sign:"
get_execution_status_emoji(status: ExecutionStatus) -> str

Returns an emoji representing the given execution status.

Parameters:

Name Type Description Default
status ExecutionStatus

The execution status to get the emoji for.

required

Returns:

Type Description
str

An emoji representing the given execution status.

Raises:

Type Description
RuntimeError

If the given execution status is not supported.

Source code in src/zenml/cli/utils.py
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
def get_execution_status_emoji(status: "ExecutionStatus") -> str:
    """Returns an emoji representing the given execution status.

    Args:
        status: The execution status to get the emoji for.

    Returns:
        An emoji representing the given execution status.

    Raises:
        RuntimeError: If the given execution status is not supported.
    """
    from zenml.enums import ExecutionStatus

    if status == ExecutionStatus.INITIALIZING:
        return ":hourglass_flowing_sand:"
    if status == ExecutionStatus.FAILED:
        return ":x:"
    if status == ExecutionStatus.RUNNING:
        return ":gear:"
    if status == ExecutionStatus.COMPLETED:
        return ":white_check_mark:"
    if status == ExecutionStatus.CACHED:
        return ":package:"
    raise RuntimeError(f"Unknown status: {status}")
get_package_information(package_names: Optional[List[str]] = None) -> Dict[str, str]

Get a dictionary of installed packages.

Parameters:

Name Type Description Default
package_names Optional[List[str]]

Specific package names to get the information for.

None

Returns:

Type Description
Dict[str, str]

A dictionary of the name:version for the package names passed in or all packages and their respective versions.

Source code in src/zenml/cli/utils.py
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
def get_package_information(
    package_names: Optional[List[str]] = None,
) -> Dict[str, str]:
    """Get a dictionary of installed packages.

    Args:
        package_names: Specific package names to get the information for.

    Returns:
        A dictionary of the name:version for the package names passed in or
            all packages and their respective versions.
    """
    import pkg_resources

    if package_names:
        return {
            pkg.key: pkg.version
            for pkg in pkg_resources.working_set
            if pkg.key in package_names
        }

    return {pkg.key: pkg.version for pkg in pkg_resources.working_set}
get_parsed_labels(labels: Optional[List[str]], allow_label_only: bool = False) -> Dict[str, Optional[str]]

Parse labels into a dictionary.

Parameters:

Name Type Description Default
labels Optional[List[str]]

The labels to parse.

required
allow_label_only bool

Whether to allow labels without values.

False

Returns:

Type Description
Dict[str, Optional[str]]

A dictionary of the metadata.

Raises:

Type Description
ValueError

If the labels are not in the correct format.

Source code in src/zenml/cli/utils.py
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
def get_parsed_labels(
    labels: Optional[List[str]], allow_label_only: bool = False
) -> Dict[str, Optional[str]]:
    """Parse labels into a dictionary.

    Args:
        labels: The labels to parse.
        allow_label_only: Whether to allow labels without values.

    Returns:
        A dictionary of the metadata.

    Raises:
        ValueError: If the labels are not in the correct format.
    """
    if not labels:
        return {}

    metadata_dict = {}
    for m in labels:
        try:
            key, value = m.split("=")
        except ValueError:
            if not allow_label_only:
                raise ValueError(
                    "Labels must be in the format key=value"
                ) from None
            key = m
            value = None
        metadata_dict[key] = value

    return metadata_dict
get_service_state_emoji(state: ServiceState) -> str

Get the rich emoji representing the operational state of a Service.

Parameters:

Name Type Description Default
state ServiceState

Service state to get emoji for.

required

Returns:

Type Description
str

String representing the emoji.

Source code in src/zenml/cli/utils.py
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
def get_service_state_emoji(state: "ServiceState") -> str:
    """Get the rich emoji representing the operational state of a Service.

    Args:
        state: Service state to get emoji for.

    Returns:
        String representing the emoji.
    """
    from zenml.enums import ServiceState

    if state == ServiceState.ACTIVE:
        return ":white_check_mark:"
    if state == ServiceState.INACTIVE:
        return ":pause_button:"
    if state == ServiceState.ERROR:
        return ":heavy_exclamation_mark:"
    if state == ServiceState.PENDING_STARTUP:
        return ":hourglass:"
    if state == ServiceState.SCALED_TO_ZERO:
        return ":chart_decreasing:"
    return ":hourglass_not_done:"
install_packages(packages: List[str], upgrade: bool = False, use_uv: bool = False) -> None

Installs pypi packages into the current environment with pip or uv.

When using with uv, a virtual environment is required.

Parameters:

Name Type Description Default
packages List[str]

List of packages to install.

required
upgrade bool

Whether to upgrade the packages if they are already installed.

False
use_uv bool

Whether to use uv for package installation.

False

Raises:

Type Description
e

If the package installation fails.

Source code in src/zenml/cli/utils.py
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
def install_packages(
    packages: List[str],
    upgrade: bool = False,
    use_uv: bool = False,
) -> None:
    """Installs pypi packages into the current environment with pip or uv.

    When using with `uv`, a virtual environment is required.

    Args:
        packages: List of packages to install.
        upgrade: Whether to upgrade the packages if they are already installed.
        use_uv: Whether to use uv for package installation.

    Raises:
        e: If the package installation fails.
    """
    if "neptune" in packages:
        declare(
            "Uninstalling legacy `neptune-client` package to avoid version "
            "conflicts with new `neptune` package..."
        )
        uninstall_package("neptune-client")

    if "prodigy" in packages:
        packages.remove("prodigy")
        declare(
            "The `prodigy` package should be installed manually using your "
            "license key. Please visit https://prodi.gy/docs/install for more "
            "information."
        )
    if not packages:
        # if user only tried to install prodigy, we can
        # just return without doing anything
        return

    if use_uv and not is_installed_in_python_environment("uv"):
        # If uv is installed globally, don't run as a python module
        command = []
    else:
        command = [sys.executable, "-m"]

    command += ["uv", "pip", "install"] if use_uv else ["pip", "install"]

    if upgrade:
        command += ["--upgrade"]

    command += packages

    if not IS_DEBUG_ENV:
        quiet_flag = "-q" if use_uv else "-qqq"
        command.append(quiet_flag)
        if not use_uv:
            command.append("--no-warn-conflicts")

    try:
        subprocess.check_call(command)
    except subprocess.CalledProcessError as e:
        if (
            use_uv
            and "Failed to locate a virtualenv or Conda environment" in str(e)
        ):
            error(
                "Failed to locate a virtualenv or Conda environment. "
                "When using uv, a virtual environment is required. "
                "Run `uv venv` to create a virtualenv and retry."
            )
        else:
            raise e
is_installed_in_python_environment(package: str) -> bool

Check if a package is installed in the current python environment.

Parameters:

Name Type Description Default
package str

The package to check.

required

Returns:

Type Description
bool

True if the package is installed, False otherwise.

Source code in src/zenml/cli/utils.py
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
def is_installed_in_python_environment(package: str) -> bool:
    """Check if a package is installed in the current python environment.

    Args:
        package: The package to check.

    Returns:
        True if the package is installed, False otherwise.
    """
    try:
        pkg_resources.get_distribution(package)
        return True
    except pkg_resources.DistributionNotFound:
        return False
is_jupyter_installed() -> bool

Checks if Jupyter notebook is installed.

Returns:

Name Type Description
bool bool

True if Jupyter notebook is installed, False otherwise.

Source code in src/zenml/cli/utils.py
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
def is_jupyter_installed() -> bool:
    """Checks if Jupyter notebook is installed.

    Returns:
        bool: True if Jupyter notebook is installed, False otherwise.
    """
    try:
        pkg_resources.get_distribution("notebook")
        return True
    except pkg_resources.DistributionNotFound:
        return False
is_pip_installed() -> bool

Check if pip is installed in the current environment.

Returns:

Type Description
bool

True if pip is installed, False otherwise.

Source code in src/zenml/cli/utils.py
1138
1139
1140
1141
1142
1143
1144
def is_pip_installed() -> bool:
    """Check if pip is installed in the current environment.

    Returns:
        True if pip is installed, False otherwise.
    """
    return is_installed_in_python_environment("pip")
is_sorted_or_filtered(ctx: click.Context) -> bool

Decides whether any filtering/sorting happens during a 'list' CLI call.

Parameters:

Name Type Description Default
ctx Context

the Click context of the CLI call.

required

Returns:

Type Description
bool

a boolean indicating whether any sorting or filtering parameters were

bool

used during the list CLI call.

Source code in src/zenml/cli/utils.py
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
def is_sorted_or_filtered(ctx: click.Context) -> bool:
    """Decides whether any filtering/sorting happens during a 'list' CLI call.

    Args:
        ctx: the Click context of the CLI call.

    Returns:
        a boolean indicating whether any sorting or filtering parameters were
        used during the list CLI call.
    """
    try:
        for _, source in ctx._parameter_source.items():
            if source != click.core.ParameterSource.DEFAULT:
                return True
        return False

    except Exception as e:
        logger.debug(
            f"There was a problem accessing the parameter source for "
            f'the "sort_by" option: {e}'
        )
        return False
is_uv_installed() -> bool

Check if uv is installed.

Returns:

Type Description
bool

True if uv is installed, False otherwise.

Source code in src/zenml/cli/utils.py
1129
1130
1131
1132
1133
1134
1135
def is_uv_installed() -> bool:
    """Check if uv is installed.

    Returns:
        True if uv is installed, False otherwise.
    """
    return shutil.which("uv") is not None
list_options(filter_model: Type[BaseFilter]) -> Callable[[F], F]

Create a decorator to generate the correct list of filter parameters.

The Outer decorator (list_options) is responsible for creating the inner decorator. This is necessary so that the type of FilterModel can be passed in as a parameter.

Based on the filter model, the inner decorator extracts all the click options that should be added to the decorated function (wrapper).

Parameters:

Name Type Description Default
filter_model Type[BaseFilter]

The filter model based on which to decorate the function.

required

Returns:

Type Description
Callable[[F], F]

The inner decorator.

Source code in src/zenml/cli/utils.py
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
def list_options(filter_model: Type[BaseFilter]) -> Callable[[F], F]:
    """Create a decorator to generate the correct list of filter parameters.

    The Outer decorator (`list_options`) is responsible for creating the inner
    decorator. This is necessary so that the type of `FilterModel` can be passed
    in as a parameter.

    Based on the filter model, the inner decorator extracts all the click
    options that should be added to the decorated function (wrapper).

    Args:
        filter_model: The filter model based on which to decorate the function.

    Returns:
        The inner decorator.
    """

    def inner_decorator(func: F) -> F:
        options = []
        data_type_descriptors = set()
        for k, v in filter_model.model_fields.items():
            if k not in filter_model.CLI_EXCLUDE_FIELDS:
                options.append(
                    click.option(
                        f"--{k}",
                        type=str,
                        default=v.default,
                        required=False,
                        multiple=_is_list_field(v),
                        help=create_filter_help_text(filter_model, k),
                    )
                )
            if k not in filter_model.FILTER_EXCLUDE_FIELDS:
                data_type_descriptors.add(
                    create_data_type_help_text(filter_model, k)
                )

        def wrapper(function: F) -> F:
            for option in reversed(options):
                function = option(function)
            return function

        func.__doc__ = (
            f"{func.__doc__} By default all filters are "
            f"interpreted as a check for equality. However advanced "
            f"filter operators can be used to tune the filtering by "
            f"writing the operator and separating it from the "
            f"query parameter with a colon `:`, e.g. "
            f"--field='operator:query'."
        )

        if data_type_descriptors:
            joined_data_type_descriptors = "\n\n".join(data_type_descriptors)

            func.__doc__ = (
                f"{func.__doc__} \n\n"
                f"\b Each datatype supports a specific "
                f"set of filter operations, here are the relevant "
                f"ones for the parameters of this command: \n\n"
                f"{joined_data_type_descriptors}"
            )

        return wrapper(func)

    return inner_decorator
multi_choice_prompt(object_type: str, choices: List[List[Any]], headers: List[str], prompt_text: str, allow_zero_be_a_new_object: bool = False, default_choice: Optional[str] = None) -> Optional[int]

Prompts the user to select a choice from a list of choices.

Parameters:

Name Type Description Default
object_type str

The type of the object

required
choices List[List[Any]]

The list of choices

required
prompt_text str

The prompt text

required
headers List[str]

The list of headers.

required
allow_zero_be_a_new_object bool

Whether to allow zero as a new object

False
default_choice Optional[str]

The default choice

None

Returns:

Type Description
Optional[int]

The selected choice index or None for new object

Raises:

Type Description
RuntimeError

If no choice is made.

Source code in src/zenml/cli/utils.py
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
def multi_choice_prompt(
    object_type: str,
    choices: List[List[Any]],
    headers: List[str],
    prompt_text: str,
    allow_zero_be_a_new_object: bool = False,
    default_choice: Optional[str] = None,
) -> Optional[int]:
    """Prompts the user to select a choice from a list of choices.

    Args:
        object_type: The type of the object
        choices: The list of choices
        prompt_text: The prompt text
        headers: The list of headers.
        allow_zero_be_a_new_object: Whether to allow zero as a new object
        default_choice: The default choice

    Returns:
        The selected choice index or None for new object

    Raises:
        RuntimeError: If no choice is made.
    """
    table = Table(
        title=f"Available {object_type}",
        show_header=True,
        border_style=None,
        expand=True,
        show_lines=True,
    )
    table.add_column("Choice", justify="left", width=1)
    for h in headers:
        table.add_column(
            h.replace("_", " ").capitalize(), justify="left", width=10
        )

    i_shift = 0
    if allow_zero_be_a_new_object:
        i_shift = 1
        table.add_row(
            "[0]",
            *([f"Create a new {object_type}"] * len(headers)),
        )
    for i, one_choice in enumerate(choices):
        table.add_row(f"[{i + i_shift}]", *[str(x) for x in one_choice])
    Console().print(table)

    selected = Prompt.ask(
        prompt_text,
        choices=[str(i) for i in range(0, len(choices) + 1)],
        default=default_choice,
        show_choices=False,
    )
    if selected is None:
        raise RuntimeError(f"No {object_type} was selected")

    if selected == "0" and allow_zero_be_a_new_object:
        return None
    else:
        return int(selected) - i_shift
parse_name_and_extra_arguments(args: List[str], expand_args: bool = False, name_mandatory: bool = True) -> Tuple[Optional[str], Dict[str, str]]

Parse a name and extra arguments from the CLI.

This is a utility function used to parse a variable list of optional CLI arguments of the form --key=value that must also include one mandatory free-form name argument. There is no restriction as to the order of the arguments.

Examples:

>>> parse_name_and_extra_arguments(['foo']])
('foo', {})
>>> parse_name_and_extra_arguments(['foo', '--bar=1'])
('foo', {'bar': '1'})
>>> parse_name_and_extra_arguments(['--bar=1', 'foo', '--baz=2'])
('foo', {'bar': '1', 'baz': '2'})
>>> parse_name_and_extra_arguments(['--bar=1'])
Traceback (most recent call last):
    ...
    ValueError: Missing required argument: name

Parameters:

Name Type Description Default
args List[str]

A list of command line arguments from the CLI.

required
expand_args bool

Whether to expand argument values into the contents of the files they may be pointing at using the special @ character.

False
name_mandatory bool

Whether the name argument is mandatory.

True

Returns:

Type Description
Tuple[Optional[str], Dict[str, str]]

The name and a dict of parsed args.

Source code in src/zenml/cli/utils.py
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
def parse_name_and_extra_arguments(
    args: List[str],
    expand_args: bool = False,
    name_mandatory: bool = True,
) -> Tuple[Optional[str], Dict[str, str]]:
    """Parse a name and extra arguments from the CLI.

    This is a utility function used to parse a variable list of optional CLI
    arguments of the form `--key=value` that must also include one mandatory
    free-form name argument. There is no restriction as to the order of the
    arguments.

    Examples:
        >>> parse_name_and_extra_arguments(['foo']])
        ('foo', {})
        >>> parse_name_and_extra_arguments(['foo', '--bar=1'])
        ('foo', {'bar': '1'})
        >>> parse_name_and_extra_arguments(['--bar=1', 'foo', '--baz=2'])
        ('foo', {'bar': '1', 'baz': '2'})
        >>> parse_name_and_extra_arguments(['--bar=1'])
        Traceback (most recent call last):
            ...
            ValueError: Missing required argument: name

    Args:
        args: A list of command line arguments from the CLI.
        expand_args: Whether to expand argument values into the contents of the
            files they may be pointing at using the special `@` character.
        name_mandatory: Whether the name argument is mandatory.

    Returns:
        The name and a dict of parsed args.
    """
    name: Optional[str] = None
    # The name was not supplied as the first argument, we have to
    # search the other arguments for the name.
    for i, arg in enumerate(args):
        if not arg:
            # Skip empty arguments.
            continue
        if arg.startswith("--"):
            continue
        name = args.pop(i)
        break
    else:
        if name_mandatory:
            error(
                "A name must be supplied. Please see the command help for more "
                "information."
            )

    message = (
        "Please provide args with a proper "
        "identifier as the key and the following structure: "
        '--custom_argument="value"'
    )
    args_dict: Dict[str, str] = {}
    for a in args:
        if not a:
            # Skip empty arguments.
            continue
        if not a.startswith("--") or "=" not in a:
            error(f"Invalid argument: '{a}'. {message}")
        key, value = a[2:].split("=", maxsplit=1)
        if not key.isidentifier():
            error(f"Invalid argument: '{a}'. {message}")
        args_dict[key] = value

    if expand_args:
        args_dict = {
            k: expand_argument_value_from_file(k, v)
            for k, v in args_dict.items()
        }

    return name, args_dict
parse_unknown_component_attributes(args: List[str]) -> List[str]

Parse unknown options from the CLI.

Parameters:

Name Type Description Default
args List[str]

A list of strings from the CLI.

required

Returns:

Type Description
List[str]

List of parsed args.

Source code in src/zenml/cli/utils.py
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
def parse_unknown_component_attributes(args: List[str]) -> List[str]:
    """Parse unknown options from the CLI.

    Args:
        args: A list of strings from the CLI.

    Returns:
        List of parsed args.
    """
    warning_message = (
        "Please provide args with a proper "
        "identifier as the key and the following structure: "
        "--custom_attribute"
    )

    assert all(a.startswith("--") for a in args), warning_message
    p_args = [a.lstrip("-") for a in args]
    assert all(v.isidentifier() for v in p_args), warning_message
    return p_args
pretty_print_model_deployer(model_services: List[BaseService], model_deployer: BaseModelDeployer) -> None

Given a list of served_models, print all associated key-value pairs.

Parameters:

Name Type Description Default
model_services List[BaseService]

list of model deployment services

required
model_deployer BaseModelDeployer

Active model deployer

required
Source code in src/zenml/cli/utils.py
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
def pretty_print_model_deployer(
    model_services: List["BaseService"], model_deployer: "BaseModelDeployer"
) -> None:
    """Given a list of served_models, print all associated key-value pairs.

    Args:
        model_services: list of model deployment services
        model_deployer: Active model deployer
    """
    model_service_dicts = []
    for model_service in model_services:
        dict_uuid = str(model_service.uuid)
        dict_pl_name = model_service.config.pipeline_name
        dict_pl_stp_name = model_service.config.pipeline_step_name
        dict_model_name = model_service.config.model_name
        type = model_service.SERVICE_TYPE.type
        flavor = model_service.SERVICE_TYPE.flavor
        model_service_dicts.append(
            {
                "STATUS": get_service_state_emoji(model_service.status.state),
                "UUID": dict_uuid,
                "TYPE": type,
                "FLAVOR": flavor,
                "PIPELINE_NAME": dict_pl_name,
                "PIPELINE_STEP_NAME": dict_pl_stp_name,
                "MODEL_NAME": dict_model_name,
            }
        )
    print_table(
        model_service_dicts, UUID=table.Column(header="UUID", min_width=36)
    )
pretty_print_model_version_details(model_version: RegistryModelVersion) -> None

Given a model_version, print all associated key-value pairs.

Parameters:

Name Type Description Default
model_version RegistryModelVersion

model version

required
Source code in src/zenml/cli/utils.py
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
def pretty_print_model_version_details(
    model_version: "RegistryModelVersion",
) -> None:
    """Given a model_version, print all associated key-value pairs.

    Args:
        model_version: model version
    """
    title_ = f"Properties of model `{model_version.registered_model.name}` version `{model_version.version}`"

    rich_table = table.Table(
        box=box.HEAVY_EDGE,
        title=title_,
        show_lines=True,
    )
    rich_table.add_column("MODEL VERSION PROPERTY", overflow="fold")
    rich_table.add_column("VALUE", overflow="fold")
    model_version_info = {
        "REGISTERED_MODEL_NAME": model_version.registered_model.name,
        "VERSION": model_version.version,
        "VERSION_DESCRIPTION": model_version.description,
        "CREATED_AT": (
            str(model_version.created_at)
            if model_version.created_at
            else "N/A"
        ),
        "UPDATED_AT": (
            str(model_version.last_updated_at)
            if model_version.last_updated_at
            else "N/A"
        ),
        "METADATA": (
            model_version.metadata.model_dump()
            if model_version.metadata
            else {}
        ),
        "MODEL_SOURCE_URI": model_version.model_source_uri,
        "STAGE": model_version.stage.value,
    }

    for item in model_version_info.items():
        rich_table.add_row(*[str(elem) for elem in item])

    # capitalize entries in first column
    rich_table.columns[0]._cells = [
        component.upper()  # type: ignore[union-attr]
        for component in rich_table.columns[0]._cells
    ]
    console.print(rich_table)
pretty_print_model_version_table(model_versions: List[RegistryModelVersion]) -> None

Given a list of model_versions, print all associated key-value pairs.

Parameters:

Name Type Description Default
model_versions List[RegistryModelVersion]

list of model versions

required
Source code in src/zenml/cli/utils.py
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
def pretty_print_model_version_table(
    model_versions: List["RegistryModelVersion"],
) -> None:
    """Given a list of model_versions, print all associated key-value pairs.

    Args:
        model_versions: list of model versions
    """
    model_version_dicts = [
        {
            "NAME": model_version.registered_model.name,
            "MODEL_VERSION": model_version.version,
            "VERSION_DESCRIPTION": model_version.description,
            "METADATA": (
                model_version.metadata.model_dump()
                if model_version.metadata
                else {}
            ),
        }
        for model_version in model_versions
    ]
    print_table(
        model_version_dicts, UUID=table.Column(header="UUID", min_width=36)
    )
pretty_print_registered_model_table(registered_models: List[RegisteredModel]) -> None

Given a list of registered_models, print all associated key-value pairs.

Parameters:

Name Type Description Default
registered_models List[RegisteredModel]

list of registered models

required
Source code in src/zenml/cli/utils.py
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
def pretty_print_registered_model_table(
    registered_models: List["RegisteredModel"],
) -> None:
    """Given a list of registered_models, print all associated key-value pairs.

    Args:
        registered_models: list of registered models
    """
    registered_model_dicts = [
        {
            "NAME": registered_model.name,
            "DESCRIPTION": registered_model.description,
            "METADATA": registered_model.metadata,
        }
        for registered_model in registered_models
    ]
    print_table(
        registered_model_dicts, UUID=table.Column(header="UUID", min_width=36)
    )
pretty_print_secret(secret: Dict[str, str], hide_secret: bool = True) -> None

Print all key-value pairs associated with a secret.

Parameters:

Name Type Description Default
secret Dict[str, str]

Secret values to print.

required
hide_secret bool

boolean that configures if the secret values are shown on the CLI

True
Source code in src/zenml/cli/utils.py
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
def pretty_print_secret(
    secret: Dict[str, str],
    hide_secret: bool = True,
) -> None:
    """Print all key-value pairs associated with a secret.

    Args:
        secret: Secret values to print.
        hide_secret: boolean that configures if the secret values are shown
            on the CLI
    """
    title: Optional[str] = None

    def get_secret_value(value: Any) -> str:
        if value is None:
            return ""
        return "***" if hide_secret else str(value)

    stack_dicts = [
        {
            "SECRET_KEY": key,
            "SECRET_VALUE": get_secret_value(value),
        }
        for key, value in secret.items()
    ]

    print_table(stack_dicts, title=title)
print_components_table(client: Client, component_type: StackComponentType, components: Sequence[ComponentResponse], show_active: bool = False) -> None

Prints a table with configuration options for a list of stack components.

If a component is active (its name matches the active_component_name), it will be highlighted in a separate table column.

Parameters:

Name Type Description Default
client Client

Instance of the Repository singleton

required
component_type StackComponentType

Type of stack component

required
components Sequence[ComponentResponse]

List of stack components to print.

required
show_active bool

Flag to decide whether to append the active stack component on the top of the list.

False
Source code in src/zenml/cli/utils.py
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
def print_components_table(
    client: "Client",
    component_type: StackComponentType,
    components: Sequence["ComponentResponse"],
    show_active: bool = False,
) -> None:
    """Prints a table with configuration options for a list of stack components.

    If a component is active (its name matches the `active_component_name`),
    it will be highlighted in a separate table column.

    Args:
        client: Instance of the Repository singleton
        component_type: Type of stack component
        components: List of stack components to print.
        show_active: Flag to decide whether to append the active stack component
            on the top of the list.
    """
    display_name = _component_display_name(component_type, plural=True)

    if len(components) == 0:
        warning(f"No {display_name} registered.")
        return

    active_stack = client.active_stack_model
    active_component = None
    if component_type in active_stack.components.keys():
        active_components = active_stack.components[component_type]
        active_component = active_components[0] if active_components else None

    components = list(components)
    if show_active and active_component is not None:
        if active_component.id not in [c.id for c in components]:
            components.append(active_component)

        components = [c for c in components if c.id == active_component.id] + [
            c for c in components if c.id != active_component.id
        ]

    configurations = []
    for component in components:
        is_active = False

        if active_component is not None:
            is_active = component.id == active_component.id

        component_config = {
            "ACTIVE": ":point_right:" if is_active else "",
            "NAME": component.name,
            "COMPONENT ID": component.id,
            "FLAVOR": component.flavor_name,
            "OWNER": f"{component.user.name if component.user else '-'}",
        }
        configurations.append(component_config)
    print_table(configurations)
print_debug_stack() -> None

Print active stack and components for debugging purposes.

Source code in src/zenml/cli/utils.py
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
def print_debug_stack() -> None:
    """Print active stack and components for debugging purposes."""
    from zenml.client import Client

    client = Client()
    stack = client.get_stack()

    declare("\nCURRENT STACK\n", bold=True)
    console.print(f"Name: {stack.name}")
    console.print(f"ID: {str(stack.id)}")
    if stack.user and stack.user.name and stack.user.id:  # mypy check
        console.print(f"User: {stack.user.name} / {str(stack.user.id)}")

    for component_type, components in stack.components.items():
        component = components[0]
        component_response = client.get_stack_component(
            name_id_or_prefix=component.id, component_type=component.type
        )
        declare(
            f"\n{component.type.value.upper()}: {component.name}\n", bold=True
        )
        console.print(f"Name: {component.name}")
        console.print(f"ID: {str(component.id)}")
        console.print(f"Type: {component.type.value}")
        console.print(f"Flavor: {component.flavor_name}")

        flavor = Flavor.from_model(component.flavor)
        config = flavor.config_class(**component.configuration)

        console.print(f"Configuration: {_scrub_secret(config)}")
        if (
            component_response.user
            and component_response.user.name
            and component_response.user.id
        ):  # mypy check
            console.print(
                f"User: {component_response.user.name} / {str(component_response.user.id)}"
            )
print_flavor_list(flavors: Page[FlavorResponse]) -> None

Prints the list of flavors.

Parameters:

Name Type Description Default
flavors Page[FlavorResponse]

List of flavors to print.

required
Source code in src/zenml/cli/utils.py
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
def print_flavor_list(flavors: Page["FlavorResponse"]) -> None:
    """Prints the list of flavors.

    Args:
        flavors: List of flavors to print.
    """
    flavor_table = []
    for f in flavors.items:
        flavor_table.append(
            {
                "FLAVOR": f.name,
                "INTEGRATION": f.integration,
                "SOURCE": f.source,
                "CONNECTOR TYPE": f.connector_type or "",
                "RESOURCE TYPE": f.connector_resource_type or "",
            }
        )

    print_table(flavor_table)
print_list_items(list_items: List[str], column_title: str) -> None

Prints the configuration options of a stack.

Parameters:

Name Type Description Default
list_items List[str]

List of items

required
column_title str

Title of the column

required
Source code in src/zenml/cli/utils.py
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
def print_list_items(list_items: List[str], column_title: str) -> None:
    """Prints the configuration options of a stack.

    Args:
        list_items: List of items
        column_title: Title of the column
    """
    rich_table = table.Table(
        box=box.HEAVY_EDGE,
        show_lines=True,
    )
    rich_table.add_column(column_title.upper(), overflow="fold")
    list_items.sort()
    for item in list_items:
        rich_table.add_row(item)

    console.print(rich_table)
print_markdown(text: str) -> None

Prints a string as markdown.

Parameters:

Name Type Description Default
text str

Markdown string to be printed.

required
Source code in src/zenml/cli/utils.py
189
190
191
192
193
194
195
196
def print_markdown(text: str) -> None:
    """Prints a string as markdown.

    Args:
        text: Markdown string to be printed.
    """
    markdown_text = Markdown(text)
    console.print(markdown_text)
print_markdown_with_pager(text: str) -> None

Prints a string as markdown with a pager.

Parameters:

Name Type Description Default
text str

Markdown string to be printed.

required
Source code in src/zenml/cli/utils.py
199
200
201
202
203
204
205
206
207
def print_markdown_with_pager(text: str) -> None:
    """Prints a string as markdown with a pager.

    Args:
        text: Markdown string to be printed.
    """
    markdown_text = Markdown(text)
    with console.pager():
        console.print(markdown_text)
print_model_url(url: Optional[str]) -> None

Pretty prints a given URL on the CLI.

Parameters:

Name Type Description Default
url Optional[str]

optional str, the URL to display.

required
Source code in src/zenml/cli/utils.py
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
def print_model_url(url: Optional[str]) -> None:
    """Pretty prints a given URL on the CLI.

    Args:
        url: optional str, the URL to display.
    """
    if url:
        declare(f"Dashboard URL: {url}")
    else:
        warning(
            "You can display various ZenML entities including pipelines, "
            "runs, stacks and much more on the ZenML Dashboard. "
            "You can try it locally, by running `zenml login --local`, or "
            "remotely, by deploying ZenML on the infrastructure of your choice."
        )
print_page_info(page: Page[T]) -> None

Print all page information showing the number of items and pages.

Parameters:

Name Type Description Default
page Page[T]

The page to print the information for.

required
Source code in src/zenml/cli/utils.py
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
def print_page_info(page: Page[T]) -> None:
    """Print all page information showing the number of items and pages.

    Args:
        page: The page to print the information for.
    """
    declare(
        f"Page `({page.index}/{page.total_pages})`, `{page.total}` items "
        f"found for the applied filters."
    )
print_pipeline_runs_table(pipeline_runs: Sequence[PipelineRunResponse]) -> None

Print a prettified list of all pipeline runs supplied to this method.

Parameters:

Name Type Description Default
pipeline_runs Sequence[PipelineRunResponse]

List of pipeline runs

required
Source code in src/zenml/cli/utils.py
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
def print_pipeline_runs_table(
    pipeline_runs: Sequence["PipelineRunResponse"],
) -> None:
    """Print a prettified list of all pipeline runs supplied to this method.

    Args:
        pipeline_runs: List of pipeline runs
    """
    runs_dicts = []
    for pipeline_run in pipeline_runs:
        if pipeline_run.user:
            user_name = pipeline_run.user.name
        else:
            user_name = "-"

        if pipeline_run.pipeline is None:
            pipeline_name = "unlisted"
        else:
            pipeline_name = pipeline_run.pipeline.name
        if pipeline_run.stack is None:
            stack_name = "[DELETED]"
        else:
            stack_name = pipeline_run.stack.name
        status = pipeline_run.status
        status_emoji = get_execution_status_emoji(status)
        run_dict = {
            "PIPELINE NAME": pipeline_name,
            "RUN NAME": pipeline_run.name,
            "RUN ID": pipeline_run.id,
            "STATUS": status_emoji,
            "STACK": stack_name,
            "OWNER": user_name,
        }
        runs_dicts.append(run_dict)
    print_table(runs_dicts)
print_pydantic_model(title: str, model: BaseModel, exclude_columns: Optional[AbstractSet[str]] = None, columns: Optional[AbstractSet[str]] = None) -> None

Prints a single Pydantic model in a table.

Parameters:

Name Type Description Default
title str

Title of the table.

required
model BaseModel

Pydantic model that will be represented as a row in the table.

required
exclude_columns Optional[AbstractSet[str]]

Optionally specify columns to exclude.

None
columns Optional[AbstractSet[str]]

Optionally specify subset and order of columns to display.

None
Source code in src/zenml/cli/utils.py
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
def print_pydantic_model(
    title: str,
    model: BaseModel,
    exclude_columns: Optional[AbstractSet[str]] = None,
    columns: Optional[AbstractSet[str]] = None,
) -> None:
    """Prints a single Pydantic model in a table.

    Args:
        title: Title of the table.
        model: Pydantic model that will be represented as a row in the table.
        exclude_columns: Optionally specify columns to exclude.
        columns: Optionally specify subset and order of columns to display.
    """
    rich_table = table.Table(
        box=box.HEAVY_EDGE,
        title=title,
        show_lines=True,
    )
    rich_table.add_column("PROPERTY", overflow="fold")
    rich_table.add_column("VALUE", overflow="fold")

    # TODO: This uses the same _dictify function up in the print_pydantic_models
    #   function. This 2 can be generalized.
    if exclude_columns is None:
        exclude_columns = set()

    if not columns:
        if isinstance(model, BaseIdentifiedResponse):
            include_columns = ["id"]

            if "name" in type(model).model_fields:
                include_columns.append("name")

            include_columns.extend(
                [
                    k
                    for k in type(model.get_body()).model_fields.keys()
                    if k not in exclude_columns
                ]
            )

            if model.metadata is not None:
                include_columns.extend(
                    [
                        k
                        for k in type(model.get_metadata()).model_fields.keys()
                        if k not in exclude_columns
                    ]
                )

        else:
            include_columns = [
                k
                for k in model.model_dump().keys()
                if k not in exclude_columns
            ]
    else:
        include_columns = list(columns)

    items: Dict[str, Any] = {}

    for k in include_columns:
        value = getattr(model, k)
        if isinstance(value, BaseIdentifiedResponse):
            if "name" in type(value).model_fields:
                items[k] = str(getattr(value, "name"))
            else:
                items[k] = str(value.id)

        # If it is a list of `BaseResponse`s access each Model within
        #  the list and extract either name or id
        elif isinstance(value, list):
            for v in value:
                if isinstance(v, BaseIdentifiedResponse):
                    if "name" in type(v).model_fields:
                        items.setdefault(k, []).append(str(getattr(v, "name")))
                    else:
                        items.setdefault(k, []).append(str(v.id))

                items[k] = str(items[k])
        elif isinstance(value, Set) or isinstance(value, List):
            items[k] = str([str(v) for v in value])
        else:
            items[k] = str(value)

    for k, v in items.items():
        rich_table.add_row(str(k).upper(), v)

    console.print(rich_table)
print_pydantic_models(models: Union[Page[T], List[T]], columns: Optional[List[str]] = None, exclude_columns: Optional[List[str]] = None, active_models: Optional[List[T]] = None, show_active: bool = False, rename_columns: Dict[str, str] = {}) -> None

Prints the list of Pydantic models in a table.

Parameters:

Name Type Description Default
models Union[Page[T], List[T]]

List of Pydantic models that will be represented as a row in the table.

required
columns Optional[List[str]]

Optionally specify subset and order of columns to display.

None
exclude_columns Optional[List[str]]

Optionally specify columns to exclude. (Note: columns takes precedence over exclude_columns.)

None
active_models Optional[List[T]]

Optional list of active models of the given type T.

None
show_active bool

Flag to decide whether to append the active model on the top of the list.

False
rename_columns Dict[str, str]

Optional dictionary to rename columns.

{}
Source code in src/zenml/cli/utils.py
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
def print_pydantic_models(
    models: Union[Page[T], List[T]],
    columns: Optional[List[str]] = None,
    exclude_columns: Optional[List[str]] = None,
    active_models: Optional[List[T]] = None,
    show_active: bool = False,
    rename_columns: Dict[str, str] = {},
) -> None:
    """Prints the list of Pydantic models in a table.

    Args:
        models: List of Pydantic models that will be represented as a row in
            the table.
        columns: Optionally specify subset and order of columns to display.
        exclude_columns: Optionally specify columns to exclude. (Note: `columns`
            takes precedence over `exclude_columns`.)
        active_models: Optional list of active models of the given type T.
        show_active: Flag to decide whether to append the active model on the
            top of the list.
        rename_columns: Optional dictionary to rename columns.
    """
    if exclude_columns is None:
        exclude_columns = list()

    show_active_column = True
    if active_models is None:
        show_active_column = False
        active_models = list()

    def __dictify(model: T) -> Dict[str, str]:
        """Helper function to map over the list to turn Models into dicts.

        Args:
            model: Pydantic model.

        Returns:
            Dict of model attributes.
        """
        # Explicitly defined columns take precedence over exclude columns
        if not columns:
            if isinstance(model, BaseIdentifiedResponse):
                include_columns = ["id"]

                if "name" in type(model).model_fields:
                    include_columns.append("name")

                include_columns.extend(
                    [
                        k
                        for k in type(model.get_body()).model_fields.keys()
                        if k not in exclude_columns
                    ]
                )

                if model.metadata is not None:
                    include_columns.extend(
                        [
                            k
                            for k in type(
                                model.get_metadata()
                            ).model_fields.keys()
                            if k not in exclude_columns
                        ]
                    )

            else:
                include_columns = [
                    k
                    for k in model.model_dump().keys()
                    if k not in exclude_columns
                ]
        else:
            include_columns = columns

        items: Dict[str, Any] = {}

        for k in include_columns:
            value = getattr(model, k)
            if k in rename_columns:
                k = rename_columns[k]
            # In case the response model contains nested `BaseResponse`s
            #  we want to attempt to represent them by name, if they contain
            #  such a field, else the id is used
            if isinstance(value, BaseIdentifiedResponse):
                if "name" in type(value).model_fields:
                    items[k] = str(getattr(value, "name"))
                else:
                    items[k] = str(value.id)

            # If it is a list of `BaseResponse`s access each Model within
            #  the list and extract either name or id
            elif isinstance(value, list):
                for v in value:
                    if isinstance(v, BaseIdentifiedResponse):
                        if "name" in type(v).model_fields:
                            items.setdefault(k, []).append(
                                str(getattr(v, "name"))
                            )
                        else:
                            items.setdefault(k, []).append(str(v.id))
            elif isinstance(value, Set) or isinstance(value, List):
                items[k] = [str(v) for v in value]
            else:
                items[k] = str(value)

        # prepend an active marker if a function to mark active was passed
        if not active_models and not show_active:
            return items

        marker = "active"
        if marker in items:
            marker = "current"
        if active_models is not None and show_active_column:
            return {
                marker: (
                    ":point_right:"
                    if any(model.id == a.id for a in active_models)
                    else ""
                ),
                **items,
            }

        return items

    active_ids = [a.id for a in active_models]
    if isinstance(models, Page):
        table_items = list(models.items)

        if show_active:
            for active_model in active_models:
                if active_model.id not in [i.id for i in table_items]:
                    table_items.append(active_model)

            table_items = [i for i in table_items if i.id in active_ids] + [
                i for i in table_items if i.id not in active_ids
            ]

        print_table([__dictify(model) for model in table_items])
        print_page_info(models)
    else:
        table_items = list(models)

        if show_active:
            for active_model in active_models:
                if active_model.id not in [i.id for i in table_items]:
                    table_items.append(active_model)

            table_items = [i for i in table_items if i.id in active_ids] + [
                i for i in table_items if i.id not in active_ids
            ]

        print_table([__dictify(model) for model in table_items])
print_served_model_configuration(model_service: BaseService, model_deployer: BaseModelDeployer) -> None

Prints the configuration of a model_service.

Parameters:

Name Type Description Default
model_service BaseService

Specific service instance to

required
model_deployer BaseModelDeployer

Active model deployer

required
Source code in src/zenml/cli/utils.py
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
def print_served_model_configuration(
    model_service: "BaseService", model_deployer: "BaseModelDeployer"
) -> None:
    """Prints the configuration of a model_service.

    Args:
        model_service: Specific service instance to
        model_deployer: Active model deployer
    """
    title_ = f"Properties of Served Model {model_service.uuid}"

    rich_table = table.Table(
        box=box.HEAVY_EDGE,
        title=title_,
        show_lines=True,
    )
    rich_table.add_column("MODEL SERVICE PROPERTY", overflow="fold")
    rich_table.add_column("VALUE", overflow="fold")

    # Get implementation specific info
    served_model_info = model_deployer.get_model_server_info(model_service)

    served_model_info = {
        **served_model_info,
        "UUID": str(model_service.uuid),
        "STATUS": get_service_state_emoji(model_service.status.state),
        "TYPE": model_service.SERVICE_TYPE.type,
        "FLAVOR": model_service.SERVICE_TYPE.flavor,
        "STATUS_MESSAGE": model_service.status.last_error,
        "PIPELINE_NAME": model_service.config.pipeline_name,
        "PIPELINE_STEP_NAME": model_service.config.pipeline_step_name,
    }

    # Sort fields alphabetically
    sorted_items = {k: v for k, v in sorted(served_model_info.items())}

    for item in sorted_items.items():
        rich_table.add_row(*[str(elem) for elem in item])

    # capitalize entries in first column
    rich_table.columns[0]._cells = [
        component.upper()  # type: ignore[union-attr]
        for component in rich_table.columns[0]._cells
    ]
    console.print(rich_table)
print_service_connector_auth_method(auth_method: AuthenticationMethodModel, title: str = '', heading: str = '#', footer: str = '---', print: bool = True) -> str

Prints details for a service connector authentication method.

Parameters:

Name Type Description Default
auth_method AuthenticationMethodModel

Service connector authentication method to print.

required
title str

Markdown title to use for the authentication method details.

''
heading str

Markdown heading to use for the authentication method title.

'#'
footer str

Markdown footer to use for the authentication method description.

'---'
print bool

Whether to print the authentication method details to the console or just return the message as a string.

True

Returns:

Type Description
str

The MarkDown authentication method details as a string.

Source code in src/zenml/cli/utils.py
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
def print_service_connector_auth_method(
    auth_method: "AuthenticationMethodModel",
    title: str = "",
    heading: str = "#",
    footer: str = "---",
    print: bool = True,
) -> str:
    """Prints details for a service connector authentication method.

    Args:
        auth_method: Service connector authentication method to print.
        title: Markdown title to use for the authentication method details.
        heading: Markdown heading to use for the authentication method title.
        footer: Markdown footer to use for the authentication method description.
        print: Whether to print the authentication method details to the console
            or just return the message as a string.

    Returns:
        The MarkDown authentication method details as a string.
    """
    message = f"{title}\n" if title else ""
    emoji = Emoji("lock")
    message += (
        f"{heading} {emoji} {auth_method.name} "
        f"(auth method: {auth_method.auth_method})\n"
    )
    message += (
        f"**Supports issuing temporary credentials**: "
        f"{auth_method.supports_temporary_credentials()}\n\n"
    )
    message += f"{auth_method.description}\n"

    attributes: List[str] = []
    for attr_name, attr_schema in auth_method.config_schema.get(
        "properties", {}
    ).items():
        title = attr_schema.get("title", "<no description>")
        attr_type = attr_schema.get("type", "string")
        required = attr_name in auth_method.config_schema.get("required", [])
        hidden = attr_schema.get("format", "") == "password"
        subtitles: List[str] = []
        subtitles.append(attr_type)
        if hidden:
            subtitles.append("secret")
        if required:
            subtitles.append("required")
        else:
            subtitles.append("optional")

        description = f"- `{attr_name}`"
        if subtitles:
            description = f"{description} {{{', '.join(subtitles)}}}"
        description = f"{description}: _{title}_"
        attributes.append(description)
    if attributes:
        message += "\n**Attributes**:\n"
        message += "\n".join(attributes) + "\n"

    message += footer

    if print:
        console.print(Markdown(message), justify="left", width=80)

    return message
print_service_connector_configuration(connector: Union[ServiceConnectorResponse, ServiceConnectorRequest], active_status: bool, show_secrets: bool) -> None

Prints the configuration options of a service connector.

Parameters:

Name Type Description Default
connector Union[ServiceConnectorResponse, ServiceConnectorRequest]

The service connector to print.

required
active_status bool

Whether the connector is active.

required
show_secrets bool

Whether to show secrets.

required
Source code in src/zenml/cli/utils.py
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
def print_service_connector_configuration(
    connector: Union["ServiceConnectorResponse", "ServiceConnectorRequest"],
    active_status: bool,
    show_secrets: bool,
) -> None:
    """Prints the configuration options of a service connector.

    Args:
        connector: The service connector to print.
        active_status: Whether the connector is active.
        show_secrets: Whether to show secrets.
    """
    from uuid import UUID

    from zenml.models import ServiceConnectorResponse

    if connector.user:
        if isinstance(connector.user, UUID):
            user_name = str(connector.user)
        else:
            user_name = connector.user.name
    else:
        user_name = "-"

    if isinstance(connector, ServiceConnectorResponse):
        declare(
            f"Service connector '{connector.name}' of type "
            f"'{connector.type}' with id '{connector.id}' is owned by "
            f"user '{user_name}'."
        )
    else:
        declare(
            f"Service connector '{connector.name}' of type '{connector.type}'."
        )

    title_ = f"'{connector.name}' {connector.type} Service Connector Details"

    if active_status:
        title_ += " (ACTIVE)"
    rich_table = table.Table(
        box=box.HEAVY_EDGE,
        title=title_,
        show_lines=True,
    )
    rich_table.add_column("PROPERTY")
    rich_table.add_column("VALUE", overflow="fold")

    if connector.expiration_seconds is None:
        expiration = "N/A"
    else:
        expiration = str(connector.expiration_seconds) + "s"

    if isinstance(connector, ServiceConnectorResponse):
        properties = {
            "ID": connector.id,
            "NAME": connector.name,
            "TYPE": connector.emojified_connector_type,
            "AUTH METHOD": connector.auth_method,
            "RESOURCE TYPES": ", ".join(connector.emojified_resource_types),
            "RESOURCE NAME": connector.resource_id or "<multiple>",
            "SESSION DURATION": expiration,
            "EXPIRES IN": (
                expires_in(
                    connector.expires_at,
                    ":name_badge: Expired!",
                    connector.expires_skew_tolerance,
                )
                if connector.expires_at
                else "N/A"
            ),
            "EXPIRES_SKEW_TOLERANCE": (
                connector.expires_skew_tolerance
                if connector.expires_skew_tolerance
                else "N/A"
            ),
            "OWNER": user_name,
            "CREATED_AT": connector.created,
            "UPDATED_AT": connector.updated,
        }
    else:
        properties = {
            "NAME": connector.name,
            "TYPE": connector.emojified_connector_type,
            "AUTH METHOD": connector.auth_method,
            "RESOURCE TYPES": ", ".join(connector.emojified_resource_types),
            "RESOURCE NAME": connector.resource_id or "<multiple>",
            "SESSION DURATION": expiration,
            "EXPIRES IN": (
                expires_in(
                    connector.expires_at,
                    ":name_badge: Expired!",
                    connector.expires_skew_tolerance,
                )
                if connector.expires_at
                else "N/A"
            ),
            "EXPIRES_SKEW_TOLERANCE": (
                connector.expires_skew_tolerance
                if connector.expires_skew_tolerance
                else "N/A"
            ),
        }

    for item in properties.items():
        elements = [str(elem) for elem in item]
        rich_table.add_row(*elements)

    console.print(rich_table)

    if len(connector.configuration) == 0 and len(connector.secrets) == 0:
        declare("No configuration options are set for this connector.")

    else:
        rich_table = table.Table(
            box=box.HEAVY_EDGE,
            title="Configuration",
            show_lines=True,
        )
        rich_table.add_column("PROPERTY")
        rich_table.add_column("VALUE", overflow="fold")

        config = connector.configuration.copy()
        secrets = connector.secrets.copy()
        for key, value in secrets.items():
            if not show_secrets:
                config[key] = "[HIDDEN]"
            elif value is None:
                config[key] = "[UNAVAILABLE]"
            else:
                config[key] = value.get_secret_value()

        for item in config.items():
            elements = [str(elem) for elem in item]
            rich_table.add_row(*elements)

        console.print(rich_table)

    if not connector.labels:
        declare("No labels are set for this service connector.")
        return

    rich_table = table.Table(
        box=box.HEAVY_EDGE,
        title="Labels",
        show_lines=True,
    )
    rich_table.add_column("LABEL")
    rich_table.add_column("VALUE", overflow="fold")

    items = connector.labels.items()
    for item in items:
        elements = [str(elem) for elem in item]
        rich_table.add_row(*elements)

    console.print(rich_table)
print_service_connector_resource_table(resources: List[ServiceConnectorResourcesModel], show_resources_only: bool = False) -> None

Prints a table with details for a list of service connector resources.

Parameters:

Name Type Description Default
resources List[ServiceConnectorResourcesModel]

List of service connector resources to print.

required
show_resources_only bool

If True, only the resources will be printed.

False
Source code in src/zenml/cli/utils.py
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
def print_service_connector_resource_table(
    resources: List["ServiceConnectorResourcesModel"],
    show_resources_only: bool = False,
) -> None:
    """Prints a table with details for a list of service connector resources.

    Args:
        resources: List of service connector resources to print.
        show_resources_only: If True, only the resources will be printed.
    """
    resource_table = []
    for resource_model in resources:
        printed_connector = False
        resource_row: Dict[str, Any] = {}

        if resource_model.error:
            # Global error
            if not show_resources_only:
                resource_row = {
                    "CONNECTOR ID": str(resource_model.id),
                    "CONNECTOR NAME": resource_model.name,
                    "CONNECTOR TYPE": resource_model.emojified_connector_type,
                }
            resource_row.update(
                {
                    "RESOURCE TYPE": "\n".join(
                        resource_model.get_emojified_resource_types()
                    ),
                    "RESOURCE NAMES": f":collision: error: {resource_model.error}",
                }
            )
            resource_table.append(resource_row)
            continue

        for resource in resource_model.resources:
            resource_type = resource_model.get_emojified_resource_types(
                resource.resource_type
            )[0]
            if resource.error:
                # Error fetching resources
                resource_ids = [f":collision: error: {resource.error}"]
            elif resource.resource_ids:
                resource_ids = resource.resource_ids
            else:
                resource_ids = [":person_shrugging: none listed"]

            resource_row = {}
            if not show_resources_only:
                resource_row = {
                    "CONNECTOR ID": (
                        str(resource_model.id) if not printed_connector else ""
                    ),
                    "CONNECTOR NAME": (
                        resource_model.name if not printed_connector else ""
                    ),
                    "CONNECTOR TYPE": (
                        resource_model.emojified_connector_type
                        if not printed_connector
                        else ""
                    ),
                }
            resource_row.update(
                {
                    "RESOURCE TYPE": resource_type,
                    "RESOURCE NAMES": "\n".join(resource_ids),
                }
            )
            resource_table.append(resource_row)
            printed_connector = True
    print_table(resource_table)
print_service_connector_resource_type(resource_type: ResourceTypeModel, title: str = '', heading: str = '#', footer: str = '---', print: bool = True) -> str

Prints details for a service connector resource type.

Parameters:

Name Type Description Default
resource_type ResourceTypeModel

Service connector resource type to print.

required
title str

Markdown title to use for the resource type details.

''
heading str

Markdown heading to use for the resource type title.

'#'
footer str

Markdown footer to use for the resource type description.

'---'
print bool

Whether to print the resource type details to the console or just return the message as a string.

True

Returns:

Type Description
str

The MarkDown resource type details as a string.

Source code in src/zenml/cli/utils.py
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
def print_service_connector_resource_type(
    resource_type: "ResourceTypeModel",
    title: str = "",
    heading: str = "#",
    footer: str = "---",
    print: bool = True,
) -> str:
    """Prints details for a service connector resource type.

    Args:
        resource_type: Service connector resource type to print.
        title: Markdown title to use for the resource type details.
        heading: Markdown heading to use for the resource type title.
        footer: Markdown footer to use for the resource type description.
        print: Whether to print the resource type details to the console or
            just return the message as a string.

    Returns:
        The MarkDown resource type details as a string.
    """
    message = f"{title}\n" if title else ""
    emoji = replace_emojis(resource_type.emoji) if resource_type.emoji else ""
    supported_auth_methods = [
        f"{Emoji('lock')} {a}" for a in resource_type.auth_methods
    ]
    message += (
        f"{heading} {emoji} {resource_type.name} "
        f"(resource type: {resource_type.resource_type})\n"
    )
    message += (
        f"**Authentication methods**: "
        f"{', '.join(resource_type.auth_methods)}\n\n"
    )
    message += (
        f"**Supports resource instances**: "
        f"{resource_type.supports_instances}\n\n"
    )
    message += (
        "**Authentication methods**:\n\n- "
        + "\n- ".join(supported_auth_methods)
        + "\n\n"
    )
    message += f"{resource_type.description}\n"

    message += footer

    if print:
        console.print(Markdown(message), justify="left", width=80)

    return message
print_service_connector_type(connector_type: ServiceConnectorTypeModel, title: str = '', heading: str = '#', footer: str = '---', include_resource_types: bool = True, include_auth_methods: bool = True, print: bool = True) -> str

Prints details for a service connector type.

Parameters:

Name Type Description Default
connector_type ServiceConnectorTypeModel

Service connector type to print.

required
title str

Markdown title to use for the service connector type details.

''
heading str

Markdown heading to use for the service connector type title.

'#'
footer str

Markdown footer to use for the service connector type description.

'---'
include_resource_types bool

Whether to include the resource types for the service connector type.

True
include_auth_methods bool

Whether to include the authentication methods for the service connector type.

True
print bool

Whether to print the service connector type details to the console or just return the message as a string.

True

Returns:

Type Description
str

The MarkDown service connector type details as a string.

Source code in src/zenml/cli/utils.py
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
def print_service_connector_type(
    connector_type: "ServiceConnectorTypeModel",
    title: str = "",
    heading: str = "#",
    footer: str = "---",
    include_resource_types: bool = True,
    include_auth_methods: bool = True,
    print: bool = True,
) -> str:
    """Prints details for a service connector type.

    Args:
        connector_type: Service connector type to print.
        title: Markdown title to use for the service connector type details.
        heading: Markdown heading to use for the service connector type title.
        footer: Markdown footer to use for the service connector type
            description.
        include_resource_types: Whether to include the resource types for the
            service connector type.
        include_auth_methods: Whether to include the authentication methods for
            the service connector type.
        print: Whether to print the service connector type details to the
            console or just return the message as a string.

    Returns:
        The MarkDown service connector type details as a string.
    """
    message = f"{title}\n" if title else ""
    supported_auth_methods = [
        f"{Emoji('lock')} {a.auth_method}" for a in connector_type.auth_methods
    ]
    supported_resource_types = [
        f"{replace_emojis(r.emoji)} {r.resource_type}"
        if r.emoji
        else r.resource_type
        for r in connector_type.resource_types
    ]

    emoji = (
        replace_emojis(connector_type.emoji) if connector_type.emoji else ""
    )

    message += (
        f"{heading} {emoji} {connector_type.name} "
        f"(connector type: {connector_type.connector_type})\n"
    )
    message += (
        "**Authentication methods**:\n\n- "
        + "\n- ".join(supported_auth_methods)
        + "\n\n"
    )
    message += (
        "**Resource types**:\n\n- "
        + "\n- ".join(supported_resource_types)
        + "\n\n"
    )
    message += (
        f"**Supports auto-configuration**: "
        f"{connector_type.supports_auto_configuration}\n\n"
    )
    message += f"**Available locally**: {connector_type.local}\n\n"
    message += f"**Available remotely**: {connector_type.remote}\n\n"
    message += f"{connector_type.description}\n"

    if include_resource_types:
        for r in connector_type.resource_types:
            message += print_service_connector_resource_type(
                r,
                heading=heading + "#",
                footer="",
                print=False,
            )

    if include_auth_methods:
        for a in connector_type.auth_methods:
            message += print_service_connector_auth_method(
                a,
                heading=heading + "#",
                footer="",
                print=False,
            )

    message += footer

    if print:
        console.print(Markdown(message), justify="left", width=80)

    return message
print_service_connector_types_table(connector_types: Sequence[ServiceConnectorTypeModel]) -> None

Prints a table with details for a list of service connectors types.

Parameters:

Name Type Description Default
connector_types Sequence[ServiceConnectorTypeModel]

List of service connector types to print.

required
Source code in src/zenml/cli/utils.py
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
def print_service_connector_types_table(
    connector_types: Sequence["ServiceConnectorTypeModel"],
) -> None:
    """Prints a table with details for a list of service connectors types.

    Args:
        connector_types: List of service connector types to print.
    """
    if len(connector_types) == 0:
        warning("No service connector types found.")
        return

    configurations = []
    for connector_type in connector_types:
        supported_auth_methods = list(connector_type.auth_method_dict.keys())

        connector_type_config = {
            "NAME": connector_type.name,
            "TYPE": connector_type.emojified_connector_type,
            "RESOURCE TYPES": "\n".join(
                connector_type.emojified_resource_types
            ),
            "AUTH METHODS": "\n".join(supported_auth_methods),
            "LOCAL": get_boolean_emoji(connector_type.local),
            "REMOTE": get_boolean_emoji(connector_type.remote),
        }
        configurations.append(connector_type_config)
    print_table(configurations)
print_service_connectors_table(client: Client, connectors: Sequence[ServiceConnectorResponse], show_active: bool = False) -> None

Prints a table with details for a list of service connectors.

Parameters:

Name Type Description Default
client Client

Instance of the Repository singleton

required
connectors Sequence[ServiceConnectorResponse]

List of service connectors to print.

required
show_active bool

lag to decide whether to append the active connectors on the top of the list.

False
Source code in src/zenml/cli/utils.py
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
def print_service_connectors_table(
    client: "Client",
    connectors: Sequence["ServiceConnectorResponse"],
    show_active: bool = False,
) -> None:
    """Prints a table with details for a list of service connectors.

    Args:
        client: Instance of the Repository singleton
        connectors: List of service connectors to print.
        show_active: lag to decide whether to append the active connectors
            on the top of the list.
    """
    if len(connectors) == 0:
        return

    active_connectors: List["ServiceConnectorResponse"] = []
    for components in client.active_stack_model.components.values():
        for component in components:
            if component.connector:
                connector = component.connector
                if connector.id not in [c.id for c in active_connectors]:
                    if isinstance(connector.connector_type, str):
                        # The connector embedded within the stack component
                        # does not include a hydrated connector type. We need
                        # that to print its emojis.
                        connector.set_connector_type(
                            client.get_service_connector_type(
                                connector.connector_type
                            )
                        )
                    active_connectors.append(connector)

    connectors = list(connectors)
    if show_active:
        active_ids = [c.id for c in connectors]
        for active_connector in active_connectors:
            if active_connector.id not in active_ids:
                connectors.append(active_connector)

            connectors = [c for c in connectors if c.id in active_ids] + [
                c for c in connectors if c.id not in active_ids
            ]

    configurations = []
    for connector in connectors:
        is_active = connector.id in [c.id for c in active_connectors]
        labels = [
            f"{label}:{value}" for label, value in connector.labels.items()
        ]
        resource_name = connector.resource_id or "<multiple>"

        connector_config = {
            "ACTIVE": ":point_right:" if is_active else "",
            "NAME": connector.name,
            "ID": connector.id,
            "TYPE": connector.emojified_connector_type,
            "RESOURCE TYPES": "\n".join(connector.emojified_resource_types),
            "RESOURCE NAME": resource_name,
            "OWNER": f"{connector.user.name if connector.user else '-'}",
            "EXPIRES IN": (
                expires_in(
                    connector.expires_at,
                    ":name_badge: Expired!",
                    connector.expires_skew_tolerance,
                )
                if connector.expires_at
                else ""
            ),
            "LABELS": "\n".join(labels),
        }
        configurations.append(connector_config)
    print_table(configurations)
print_stack_component_configuration(component: ComponentResponse, active_status: bool, connector_requirements: Optional[ServiceConnectorRequirements] = None) -> None

Prints the configuration options of a stack component.

Parameters:

Name Type Description Default
component ComponentResponse

The stack component to print.

required
active_status bool

Whether the stack component is active.

required
connector_requirements Optional[ServiceConnectorRequirements]

Connector requirements for the component, taken from the component flavor. Only needed if the component has a connector.

None
Source code in src/zenml/cli/utils.py
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
def print_stack_component_configuration(
    component: "ComponentResponse",
    active_status: bool,
    connector_requirements: Optional[ServiceConnectorRequirements] = None,
) -> None:
    """Prints the configuration options of a stack component.

    Args:
        component: The stack component to print.
        active_status: Whether the stack component is active.
        connector_requirements: Connector requirements for the component, taken
            from the component flavor. Only needed if the component has a
            connector.
    """
    if component.user:
        user_name = component.user.name
    else:
        user_name = "-"

    declare(
        f"{component.type.value.title()} '{component.name}' of flavor "
        f"'{component.flavor_name}' with id '{component.id}' is owned by "
        f"user '{user_name}'."
    )

    if len(component.configuration) == 0:
        declare("No configuration options are set for this component.")

    else:
        title_ = (
            f"'{component.name}' {component.type.value.upper()} "
            f"Component Configuration"
        )

        if active_status:
            title_ += " (ACTIVE)"
        rich_table = table.Table(
            box=box.HEAVY_EDGE,
            title=title_,
            show_lines=True,
        )
        rich_table.add_column("COMPONENT_PROPERTY")
        rich_table.add_column("VALUE", overflow="fold")

        items = component.configuration.items()
        for item in items:
            elements = []
            for idx, elem in enumerate(item):
                if idx == 0:
                    elements.append(f"{elem.upper()}")
                else:
                    elements.append(str(elem))
            rich_table.add_row(*elements)

        console.print(rich_table)

    if not component.labels:
        declare("No labels are set for this component.")
    else:
        rich_table = table.Table(
            box=box.HEAVY_EDGE,
            title="Labels",
            show_lines=True,
        )
        rich_table.add_column("LABEL")
        rich_table.add_column("VALUE", overflow="fold")

        for label, value in component.labels.items():
            rich_table.add_row(label, str(value))

        console.print(rich_table)

    if not component.connector:
        declare("No connector is set for this component.")
    else:
        rich_table = table.Table(
            box=box.HEAVY_EDGE,
            title="Service Connector",
            show_lines=True,
        )
        rich_table.add_column("PROPERTY")
        rich_table.add_column("VALUE", overflow="fold")

        resource_type = (
            connector_requirements.resource_type
            if connector_requirements
            else component.connector.resource_types[0]
        )

        connector_dict = {
            "ID": str(component.connector.id),
            "NAME": component.connector.name,
            "TYPE": component.connector.type,
            "RESOURCE TYPE": resource_type,
            "RESOURCE NAME": component.connector_resource_id
            or component.connector.resource_id
            or "N/A",
        }

        for label, value in connector_dict.items():
            rich_table.add_row(label, value)

        console.print(rich_table)
print_stack_configuration(stack: StackResponse, active: bool) -> None

Prints the configuration options of a stack.

Parameters:

Name Type Description Default
stack StackResponse

Instance of a stack model.

required
active bool

Whether the stack is active.

required
Source code in src/zenml/cli/utils.py
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
def print_stack_configuration(stack: "StackResponse", active: bool) -> None:
    """Prints the configuration options of a stack.

    Args:
        stack: Instance of a stack model.
        active: Whether the stack is active.
    """
    stack_caption = f"'{stack.name}' stack"
    if active:
        stack_caption += " (ACTIVE)"
    rich_table = table.Table(
        box=box.HEAVY_EDGE,
        title="Stack Configuration",
        caption=stack_caption,
        show_lines=True,
    )
    rich_table.add_column("COMPONENT_TYPE", overflow="fold")
    rich_table.add_column("COMPONENT_NAME", overflow="fold")
    for component_type, components in stack.components.items():
        rich_table.add_row(component_type, components[0].name)

    # capitalize entries in first column
    rich_table.columns[0]._cells = [
        component.upper()  # type: ignore[union-attr]
        for component in rich_table.columns[0]._cells
    ]
    console.print(rich_table)

    if not stack.labels:
        declare("No labels are set for this stack.")
    else:
        rich_table = table.Table(
            box=box.HEAVY_EDGE,
            title="Labels",
            show_lines=True,
        )
        rich_table.add_column("LABEL")
        rich_table.add_column("VALUE", overflow="fold")

        for label, value in stack.labels.items():
            rich_table.add_row(label, str(value))

        console.print(rich_table)

    declare(
        f"Stack '{stack.name}' with id '{stack.id}' is "
        f"{f'owned by user {stack.user.name}.' if stack.user else 'unowned.'}"
    )
print_stacks_table(client: Client, stacks: Sequence[StackResponse], show_active: bool = False) -> None

Print a prettified list of all stacks supplied to this method.

Parameters:

Name Type Description Default
client Client

Repository instance

required
stacks Sequence[StackResponse]

List of stacks

required
show_active bool

Flag to decide whether to append the active stack on the top of the list.

False
Source code in src/zenml/cli/utils.py
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
def print_stacks_table(
    client: "Client",
    stacks: Sequence["StackResponse"],
    show_active: bool = False,
) -> None:
    """Print a prettified list of all stacks supplied to this method.

    Args:
        client: Repository instance
        stacks: List of stacks
        show_active: Flag to decide whether to append the active stack on the
            top of the list.
    """
    stack_dicts = []

    stacks = list(stacks)
    active_stack = client.active_stack_model
    if show_active:
        if active_stack.id not in [s.id for s in stacks]:
            stacks.append(active_stack)

        stacks = [s for s in stacks if s.id == active_stack.id] + [
            s for s in stacks if s.id != active_stack.id
        ]

    active_stack_model_id = client.active_stack_model.id
    for stack in stacks:
        is_active = stack.id == active_stack_model_id

        if stack.user:
            user_name = stack.user.name
        else:
            user_name = "-"

        stack_config = {
            "ACTIVE": ":point_right:" if is_active else "",
            "STACK NAME": stack.name,
            "STACK ID": stack.id,
            "OWNER": user_name,
            **{
                component_type.upper(): components[0].name
                for component_type, components in stack.components.items()
            },
        }
        stack_dicts.append(stack_config)

    print_table(stack_dicts)
print_table(obj: List[Dict[str, Any]], title: Optional[str] = None, caption: Optional[str] = None, **columns: table.Column) -> None

Prints the list of dicts in a table format.

The input object should be a List of Dicts. Each item in that list represent a line in the Table. Each dict should have the same keys. The keys of the dict will be used as headers of the resulting table.

Parameters:

Name Type Description Default
obj List[Dict[str, Any]]

A List containing dictionaries.

required
title Optional[str]

Title of the table.

None
caption Optional[str]

Caption of the table.

None
columns Column

Optional column configurations to be used in the table.

{}
Source code in src/zenml/cli/utils.py
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
def print_table(
    obj: List[Dict[str, Any]],
    title: Optional[str] = None,
    caption: Optional[str] = None,
    **columns: table.Column,
) -> None:
    """Prints the list of dicts in a table format.

    The input object should be a List of Dicts. Each item in that list represent
    a line in the Table. Each dict should have the same keys. The keys of the
    dict will be used as headers of the resulting table.

    Args:
        obj: A List containing dictionaries.
        title: Title of the table.
        caption: Caption of the table.
        columns: Optional column configurations to be used in the table.
    """
    from rich.text import Text

    column_keys = {key: None for dict_ in obj for key in dict_}
    column_names = [columns.get(key, key.upper()) for key in column_keys]
    rich_table = table.Table(
        box=box.HEAVY_EDGE, show_lines=True, title=title, caption=caption
    )
    for col_name in column_names:
        if isinstance(col_name, str):
            rich_table.add_column(str(col_name), overflow="fold")
        else:
            rich_table.add_column(
                str(col_name.header).upper(), overflow="fold"
            )
    for dict_ in obj:
        values = []
        for key in column_keys:
            if key is None:
                values.append(None)
            else:
                v = dict_.get(key) or " "
                if isinstance(v, str) and (
                    v.startswith("http://") or v.startswith("https://")
                ):
                    # Display the URL as a hyperlink in a way that doesn't break
                    # the URL when it needs to be wrapped over multiple lines
                    value: Union[str, Text] = Text(v, style=f"link {v}")
                else:
                    value = str(v)
                    # Escape text when square brackets are used, but allow
                    # links to be decorated as rich style links
                    if "[" in value and "[link=" not in value:
                        value = escape(value)
                values.append(value)
        rich_table.add_row(*values)
    if len(rich_table.columns) > 1:
        rich_table.columns[0].justify = "center"
    console.print(rich_table)
print_user_info(info: Dict[str, Any]) -> None

Print user information to the terminal.

Parameters:

Name Type Description Default
info Dict[str, Any]

The information to print.

required
Source code in src/zenml/cli/utils.py
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
def print_user_info(info: Dict[str, Any]) -> None:
    """Print user information to the terminal.

    Args:
        info: The information to print.
    """
    for key, value in info.items():
        if key in ["packages", "query_packages"] and not bool(value):
            continue

        declare(f"{key.upper()}: {value}")
prompt_configuration(config_schema: Dict[str, Any], show_secrets: bool = False, existing_config: Optional[Dict[str, str]] = None) -> Dict[str, str]

Prompt the user for configuration values using the provided schema.

Parameters:

Name Type Description Default
config_schema Dict[str, Any]

The configuration schema.

required
show_secrets bool

Whether to show secrets in the terminal.

False
existing_config Optional[Dict[str, str]]

The existing configuration values.

None

Returns:

Type Description
Dict[str, str]

The configuration values provided by the user.

Source code in src/zenml/cli/utils.py
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
def prompt_configuration(
    config_schema: Dict[str, Any],
    show_secrets: bool = False,
    existing_config: Optional[Dict[str, str]] = None,
) -> Dict[str, str]:
    """Prompt the user for configuration values using the provided schema.

    Args:
        config_schema: The configuration schema.
        show_secrets: Whether to show secrets in the terminal.
        existing_config: The existing configuration values.

    Returns:
        The configuration values provided by the user.
    """
    is_update = False
    if existing_config is not None:
        is_update = True
    existing_config = existing_config or {}

    config_dict = {}
    for attr_name, attr_schema in config_schema.get("properties", {}).items():
        title = attr_schema.get("title", attr_name)
        attr_type_name = attr_type = attr_schema.get("type", "string")
        if attr_type == "array":
            attr_type_name = "list (CSV or JSON)"
        title = f"[{attr_name}] {title}"
        required = attr_name in config_schema.get("required", [])
        hidden = attr_schema.get("format", "") == "password"
        subtitles: List[str] = []
        subtitles.append(attr_type_name)
        if hidden:
            subtitles.append("secret")
        if required:
            subtitles.append("required")
        else:
            subtitles.append("optional")
        if subtitles:
            title += f" {{{', '.join(subtitles)}}}"

        existing_value = existing_config.get(attr_name)
        if is_update:
            if existing_value:
                if isinstance(existing_value, SecretStr):
                    existing_value = existing_value.get_secret_value()
                if hidden and not show_secrets:
                    title += " is currently set to: [HIDDEN]"
                else:
                    if attr_type == "array":
                        existing_value = json.dumps(existing_value)
                    title += f" is currently set to: '{existing_value}'"
            else:
                title += " is not currently set"

            click.echo(title)

            if existing_value:
                title = (
                    "Please enter a new value or press Enter to keep the "
                    "existing one"
                )
            elif required:
                title = "Please enter a new value"
            else:
                title = "Please enter a new value or press Enter to skip it"

        while True:
            # Ask the user to enter a value for the attribute
            value = click.prompt(
                title,
                type=str,
                hide_input=hidden and not show_secrets,
                default=existing_value or ("" if not required else None),
                show_default=False,
            )
            if not value:
                if required:
                    warning(
                        f"The attribute '{title}' is mandatory. "
                        "Please enter a non-empty value."
                    )
                    continue
                else:
                    value = None
                    break
            else:
                break

        if (
            is_update
            and value is not None
            and value == existing_value
            and not required
        ):
            confirm = click.confirm(
                "You left this optional attribute unchanged. Would you "
                "like to remove its value instead?",
                default=False,
            )
            if confirm:
                value = None

        if value:
            config_dict[attr_name] = value

    return config_dict
replace_emojis(text: str) -> str

Replaces emoji shortcuts with their unicode equivalent.

Parameters:

Name Type Description Default
text str

Text to expand.

required

Returns:

Type Description
str

Text with expanded emojis.

Source code in src/zenml/cli/utils.py
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
def replace_emojis(text: str) -> str:
    """Replaces emoji shortcuts with their unicode equivalent.

    Args:
        text: Text to expand.

    Returns:
        Text with expanded emojis.
    """
    emoji_pattern = r":(\w+):"
    emojis = re.findall(emoji_pattern, text)
    for emoji in emojis:
        try:
            text = text.replace(f":{emoji}:", str(Emoji(emoji)))
        except NoEmoji:
            # If the emoji text is not a valid emoji, just ignore it
            pass
    return text
requires_mac_env_var_warning() -> bool

Checks if a warning needs to be shown for a local Mac server.

This is for the case where a user is on a macOS system, trying to run a local server but is missing the OBJC_DISABLE_INITIALIZE_FORK_SAFETY environment variable.

Returns:

Name Type Description
bool bool

True if a warning needs to be shown, False otherwise.

Source code in src/zenml/cli/utils.py
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
def requires_mac_env_var_warning() -> bool:
    """Checks if a warning needs to be shown for a local Mac server.

    This is for the case where a user is on a macOS system, trying to run a
    local server but is missing the `OBJC_DISABLE_INITIALIZE_FORK_SAFETY`
    environment variable.

    Returns:
        bool: True if a warning needs to be shown, False otherwise.
    """
    if sys.platform == "darwin":
        mac_version_tuple = tuple(map(int, platform.release().split(".")[:2]))
        return not os.getenv(
            "OBJC_DISABLE_INITIALIZE_FORK_SAFETY"
        ) and mac_version_tuple >= (10, 13)
    return False
temporary_active_stack(stack_name_or_id: Union[UUID, str, None] = None) -> Iterator[Stack]

Contextmanager to temporarily activate a stack.

Parameters:

Name Type Description Default
stack_name_or_id Union[UUID, str, None]

The name or ID of the stack to activate. If not given, this contextmanager will not do anything.

None

Yields:

Type Description
Stack

The active stack.

Source code in src/zenml/cli/utils.py
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
@contextlib.contextmanager
def temporary_active_stack(
    stack_name_or_id: Union["UUID", str, None] = None,
) -> Iterator["Stack"]:
    """Contextmanager to temporarily activate a stack.

    Args:
        stack_name_or_id: The name or ID of the stack to activate. If not given,
            this contextmanager will not do anything.

    Yields:
        The active stack.
    """
    from zenml.client import Client

    try:
        if stack_name_or_id:
            old_stack_id = Client().active_stack_model.id
            Client().activate_stack(stack_name_or_id)
        else:
            old_stack_id = None
        yield Client().active_stack
    finally:
        if old_stack_id:
            Client().activate_stack(old_stack_id)
title(text: str) -> None

Echo a title formatted string on the CLI.

Parameters:

Name Type Description Default
text str

Input text string.

required
Source code in src/zenml/cli/utils.py
116
117
118
119
120
121
122
def title(text: str) -> None:
    """Echo a title formatted string on the CLI.

    Args:
        text: Input text string.
    """
    console.print(text.upper(), style=zenml_style_defaults["title"])
uninstall_package(package: str, use_uv: bool = False) -> None

Uninstalls pypi package from the current environment with pip or uv.

Parameters:

Name Type Description Default
package str

The package to uninstall.

required
use_uv bool

Whether to use uv for package uninstallation.

False
Source code in src/zenml/cli/utils.py
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
def uninstall_package(package: str, use_uv: bool = False) -> None:
    """Uninstalls pypi package from the current environment with pip or uv.

    Args:
        package: The package to uninstall.
        use_uv: Whether to use uv for package uninstallation.
    """
    if use_uv and not is_installed_in_python_environment("uv"):
        # If uv is installed globally, don't run as a python module
        command = []
    else:
        command = [sys.executable, "-m"]

    command += (
        ["uv", "pip", "uninstall", "-q"]
        if use_uv
        else ["pip", "uninstall", "-y", "-qqq"]
    )
    command += [package]

    subprocess.check_call(command)
validate_keys(key: str) -> None

Validates key if it is a valid python string.

Parameters:

Name Type Description Default
key str

key to validate

required
Source code in src/zenml/cli/utils.py
880
881
882
883
884
885
886
887
def validate_keys(key: str) -> None:
    """Validates key if it is a valid python string.

    Args:
        key: key to validate
    """
    if not key.isidentifier():
        error("Please provide args with a proper identifier as the key.")
warning(text: str, bold: Optional[bool] = None, italic: Optional[bool] = None, **kwargs: Any) -> None

Echo a warning string on the CLI.

Parameters:

Name Type Description Default
text str

Input text string.

required
bold Optional[bool]

Optional boolean to bold the text.

None
italic Optional[bool]

Optional boolean to italicize the text.

None
**kwargs Any

Optional kwargs to be passed to console.print().

{}
Source code in src/zenml/cli/utils.py
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
def warning(
    text: str,
    bold: Optional[bool] = None,
    italic: Optional[bool] = None,
    **kwargs: Any,
) -> None:
    """Echo a warning string on the CLI.

    Args:
        text: Input text string.
        bold: Optional boolean to bold the text.
        italic: Optional boolean to italicize the text.
        **kwargs: Optional kwargs to be passed to console.print().
    """
    base_style = zenml_style_defaults["warning"]
    style = Style.chain(base_style, Style(bold=bold, italic=italic))
    console.print(text, style=style, **kwargs)
Modules

uuid_utils

Utility functions for handling UUIDs.

Functions
generate_uuid_from_string(value: str) -> UUID

Deterministically generates a UUID from a string seed.

Parameters:

Name Type Description Default
value str

The string from which to generate the UUID.

required

Returns:

Type Description
UUID

The generated UUID.

Source code in src/zenml/utils/uuid_utils.py
62
63
64
65
66
67
68
69
70
71
72
73
def generate_uuid_from_string(value: str) -> UUID:
    """Deterministically generates a UUID from a string seed.

    Args:
        value: The string from which to generate the UUID.

    Returns:
        The generated UUID.
    """
    hash_ = hashlib.md5()  # nosec
    hash_.update(value.encode("utf-8"))
    return UUID(hex=hash_.hexdigest(), version=4)
is_valid_uuid(value: Any, version: int = 4) -> bool

Checks if a string is a valid UUID.

Parameters:

Name Type Description Default
value Any

String to check.

required
version int

Version of UUID to check for.

4

Returns:

Type Description
bool

True if string is a valid UUID, False otherwise.

Source code in src/zenml/utils/uuid_utils.py
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
def is_valid_uuid(value: Any, version: int = 4) -> bool:
    """Checks if a string is a valid UUID.

    Args:
        value: String to check.
        version: Version of UUID to check for.

    Returns:
        True if string is a valid UUID, False otherwise.
    """
    if isinstance(value, UUID):
        return True
    if isinstance(value, str):
        try:
            UUID(value, version=version)
            return True
        except ValueError:
            return False
    return False
parse_name_or_uuid(name_or_id: Optional[str]) -> Optional[Union[str, UUID]]

Convert a "name or id" string value to a string or UUID.

Parameters:

Name Type Description Default
name_or_id Optional[str]

Name or id to convert.

required

Returns:

Type Description
Optional[Union[str, UUID]]

A UUID if name_or_id is a UUID, string otherwise.

Source code in src/zenml/utils/uuid_utils.py
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
def parse_name_or_uuid(
    name_or_id: Optional[str],
) -> Optional[Union[str, UUID]]:
    """Convert a "name or id" string value to a string or UUID.

    Args:
        name_or_id: Name or id to convert.

    Returns:
        A UUID if name_or_id is a UUID, string otherwise.
    """
    if name_or_id:
        try:
            return UUID(name_or_id)
        except ValueError:
            return name_or_id
    else:
        return name_or_id

zenml

Initialization for ZenML.

Classes
APIKey

Bases: BaseModel

Encoded model for API keys.

Functions
decode_api_key(encoded_key: str) -> APIKey classmethod

Decodes an API key from a base64 string.

Parameters:

Name Type Description Default
encoded_key str

The encoded API key.

required

Returns:

Type Description
APIKey

The decoded API key.

Raises:

Type Description
ValueError

If the key is not valid.

Source code in src/zenml/models/v2/core/api_key.py
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
@classmethod
def decode_api_key(cls, encoded_key: str) -> "APIKey":
    """Decodes an API key from a base64 string.

    Args:
        encoded_key: The encoded API key.

    Returns:
        The decoded API key.

    Raises:
        ValueError: If the key is not valid.
    """
    if encoded_key.startswith(ZENML_API_KEY_PREFIX):
        encoded_key = encoded_key[len(ZENML_API_KEY_PREFIX) :]
    try:
        json_key = b64_decode(encoded_key)
        return cls.model_validate_json(json_key)
    except Exception:
        raise ValueError("Invalid API key.")
encode() -> str

Encodes the API key in a base64 string that includes the key ID and prefix.

Returns:

Type Description
str

The encoded API key.

Source code in src/zenml/models/v2/core/api_key.py
72
73
74
75
76
77
78
79
def encode(self) -> str:
    """Encodes the API key in a base64 string that includes the key ID and prefix.

    Returns:
        The encoded API key.
    """
    encoded_key = b64_encode(self.model_dump_json())
    return f"{ZENML_API_KEY_PREFIX}{encoded_key}"
APIKeyFilter

Bases: BaseFilter

Filter model for API keys.

Functions
apply_filter(query: AnyQuery, table: Type[AnySchema]) -> AnyQuery

Override to apply the service account scope as an additional filter.

Parameters:

Name Type Description Default
query AnyQuery

The query to which to apply the filter.

required
table Type[AnySchema]

The query table.

required

Returns:

Type Description
AnyQuery

The query with filter applied.

Source code in src/zenml/models/v2/core/api_key.py
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
def apply_filter(
    self,
    query: AnyQuery,
    table: Type["AnySchema"],
) -> AnyQuery:
    """Override to apply the service account scope as an additional filter.

    Args:
        query: The query to which to apply the filter.
        table: The query table.

    Returns:
        The query with filter applied.
    """
    query = super().apply_filter(query=query, table=table)

    if self.service_account:
        scope_filter = (
            getattr(table, "service_account_id") == self.service_account
        )
        query = query.where(scope_filter)

    return query
set_service_account(service_account_id: UUID) -> None

Set the service account by which to scope this query.

Parameters:

Name Type Description Default
service_account_id UUID

The service account ID.

required
Source code in src/zenml/models/v2/core/api_key.py
377
378
379
380
381
382
383
def set_service_account(self, service_account_id: UUID) -> None:
    """Set the service account by which to scope this query.

    Args:
        service_account_id: The service account ID.
    """
    self.service_account = service_account_id
APIKeyInternalResponse

Bases: APIKeyResponse

Response model for API keys used internally.

Functions
verify_key(key: str) -> bool

Verifies a given key against the stored (hashed) key(s).

Parameters:

Name Type Description Default
key str

Input key to be verified.

required

Returns:

Type Description
bool

True if the keys match.

Source code in src/zenml/models/v2/core/api_key.py
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
def verify_key(
    self,
    key: str,
) -> bool:
    """Verifies a given key against the stored (hashed) key(s).

    Args:
        key: Input key to be verified.

    Returns:
        True if the keys match.
    """
    # even when the hashed key is not set, we still want to execute
    # the hash verification to protect against response discrepancy
    # attacks (https://cwe.mitre.org/data/definitions/204.html)
    key_hash: Optional[str] = None
    context = CryptContext(schemes=["bcrypt"], deprecated="auto")
    if self.key is not None and self.active:
        key_hash = self.key
    result = context.verify(key, key_hash)

    # same for the previous key, if set and if it's still valid
    key_hash = None
    if (
        self.previous_key is not None
        and self.last_rotated is not None
        and self.active
        and self.retain_period_minutes > 0
    ):
        # check if the previous key is still valid
        if utc_now(
            tz_aware=self.last_rotated
        ) - self.last_rotated < timedelta(
            minutes=self.retain_period_minutes
        ):
            key_hash = self.previous_key
    previous_result = context.verify(key, key_hash)

    return result or previous_result
APIKeyInternalUpdate

Bases: APIKeyUpdate

Update model for API keys used internally.

APIKeyRequest

Bases: BaseRequest

Request model for API keys.

APIKeyResponse

Bases: BaseIdentifiedResponse[APIKeyResponseBody, APIKeyResponseMetadata, APIKeyResponseResources]

Response model for API keys.

Attributes
active: bool property

The active property.

Returns:

Type Description
bool

the value of the property.

description: str property

The description property.

Returns:

Type Description
str

the value of the property.

key: Optional[str] property

The key property.

Returns:

Type Description
Optional[str]

the value of the property.

last_login: Optional[datetime] property

The last_login property.

Returns:

Type Description
Optional[datetime]

the value of the property.

last_rotated: Optional[datetime] property

The last_rotated property.

Returns:

Type Description
Optional[datetime]

the value of the property.

retain_period_minutes: int property

The retain_period_minutes property.

Returns:

Type Description
int

the value of the property.

service_account: ServiceAccountResponse property

The service_account property.

Returns:

Type Description
ServiceAccountResponse

the value of the property.

Functions
get_hydrated_version() -> APIKeyResponse

Get the hydrated version of this API key.

Returns:

Type Description
APIKeyResponse

an instance of the same entity with the metadata field attached.

Source code in src/zenml/models/v2/core/api_key.py
198
199
200
201
202
203
204
205
206
207
208
209
def get_hydrated_version(self) -> "APIKeyResponse":
    """Get the hydrated version of this API key.

    Returns:
        an instance of the same entity with the metadata field attached.
    """
    from zenml.client import Client

    return Client().zen_store.get_api_key(
        service_account_id=self.service_account.id,
        api_key_name_or_id=self.id,
    )
set_key(key: str) -> None

Sets the API key and encodes it.

Parameters:

Name Type Description Default
key str

The API key value to be set.

required
Source code in src/zenml/models/v2/core/api_key.py
212
213
214
215
216
217
218
def set_key(self, key: str) -> None:
    """Sets the API key and encodes it.

    Args:
        key: The API key value to be set.
    """
    self.get_body().key = APIKey(id=self.id, key=key).encode()
APIKeyResponseBody

Bases: BaseDatedResponseBody

Response body for API keys.

APIKeyResponseMetadata

Bases: BaseResponseMetadata

Response metadata for API keys.

APIKeyRotateRequest

Bases: BaseRequest

Request model for API key rotation.

APIKeyUpdate

Bases: BaseUpdate

Update model for API keys.

ActionFilter

Bases: ProjectScopedFilter

Model to enable advanced filtering of all actions.

ActionFlavorResponse

Bases: BasePluginFlavorResponse[ActionFlavorResponseBody, ActionFlavorResponseMetadata, ActionFlavorResponseResources]

Response model for Action Flavors.

Attributes
config_schema: Dict[str, Any] property

The source_config_schema property.

Returns:

Type Description
Dict[str, Any]

the value of the property.

ActionFlavorResponseBody

Bases: BasePluginResponseBody

Response body for action flavors.

ActionFlavorResponseMetadata

Bases: BasePluginResponseMetadata

Response metadata for action flavors.

ActionFlavorResponseResources

Bases: BasePluginResponseResources

Response resources for action flavors.

ActionRequest

Bases: ProjectScopedRequest

Model for creating a new action.

ActionResponse

Bases: ProjectScopedResponse[ActionResponseBody, ActionResponseMetadata, ActionResponseResources]

Response model for actions.

Attributes
auth_window: int property

The auth_window property.

Returns:

Type Description
int

the value of the property.

configuration: Dict[str, Any] property

The configuration property.

Returns:

Type Description
Dict[str, Any]

the value of the property.

description: str property

The description property.

Returns:

Type Description
str

the value of the property.

flavor: str property

The flavor property.

Returns:

Type Description
str

the value of the property.

plugin_subtype: PluginSubType property

The plugin_subtype property.

Returns:

Type Description
PluginSubType

the value of the property.

service_account: UserResponse property

The service_account property.

Returns:

Type Description
UserResponse

the value of the property.

Functions
get_hydrated_version() -> ActionResponse

Get the hydrated version of this action.

Returns:

Type Description
ActionResponse

An instance of the same entity with the metadata field attached.

Source code in src/zenml/models/v2/core/action.py
184
185
186
187
188
189
190
191
192
def get_hydrated_version(self) -> "ActionResponse":
    """Get the hydrated version of this action.

    Returns:
        An instance of the same entity with the metadata field attached.
    """
    from zenml.client import Client

    return Client().zen_store.get_action(self.id)
set_configuration(configuration: Dict[str, Any]) -> None

Set the configuration property.

Parameters:

Name Type Description Default
configuration Dict[str, Any]

The value to set.

required
Source code in src/zenml/models/v2/core/action.py
240
241
242
243
244
245
246
def set_configuration(self, configuration: Dict[str, Any]) -> None:
    """Set the `configuration` property.

    Args:
        configuration: The value to set.
    """
    self.get_metadata().configuration = configuration
ActionResponseBody

Bases: ProjectScopedResponseBody

Response body for actions.

ActionResponseMetadata

Bases: ProjectScopedResponseMetadata

Response metadata for actions.

ActionResponseResources

Bases: ProjectScopedResponseResources

Class for all resource models associated with the action entity.

ActionUpdate

Bases: BaseUpdate

Update model for actions.

Functions
from_response(response: ActionResponse) -> ActionUpdate classmethod

Create an update model from a response model.

Parameters:

Name Type Description Default
response ActionResponse

The response model to create the update model from.

required

Returns:

Type Description
ActionUpdate

The update model.

Source code in src/zenml/models/v2/core/action.py
116
117
118
119
120
121
122
123
124
125
126
127
128
@classmethod
def from_response(cls, response: "ActionResponse") -> "ActionUpdate":
    """Create an update model from a response model.

    Args:
        response: The response model to create the update model from.

    Returns:
        The update model.
    """
    return ActionUpdate(
        configuration=copy.deepcopy(response.configuration),
    )
ArtifactConfig

Bases: BaseModel

Artifact configuration class.

Can be used in step definitions to define various artifact properties.

Example:

@step
def my_step() -> Annotated[
    int, ArtifactConfig(
        name="my_artifact",  # override the default artifact name
        version=42,  # set a custom version
        artifact_type=ArtifactType.MODEL,  # Specify the artifact type
        tags=["tag1", "tag2"],  # set custom tags
    )
]:
    return ...

Attributes:

Name Type Description
name Optional[str]

The name of the artifact: - static string e.g. "name" - dynamic string e.g. "name_{date}{time}{custom_placeholder}" If you use any placeholders besides date and time, you need to provide the values for them in the substitutions argument of the step decorator or the substitutions argument of with_options of the step.

version Optional[Union[str, int]]

The version of the artifact.

tags Optional[List[str]]

The tags of the artifact.

run_metadata Optional[Dict[str, MetadataType]]

Metadata to add to the artifact.

artifact_type Optional[ArtifactType]

Optional type of the artifact. If not given, the type specified by the materializer that is used to save this artifact is used.

ArtifactFilter

Bases: ProjectScopedFilter, TaggableFilter

Model to enable advanced filtering of artifacts.

Functions
apply_sorting(query: AnyQuery, table: Type[AnySchema]) -> AnyQuery

Apply sorting to the query for Artifacts.

Parameters:

Name Type Description Default
query AnyQuery

The query to which to apply the sorting.

required
table Type[AnySchema]

The query table.

required

Returns:

Type Description
AnyQuery

The query with sorting applied.

Source code in src/zenml/models/v2/core/artifact.py
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
def apply_sorting(
    self,
    query: AnyQuery,
    table: Type["AnySchema"],
) -> AnyQuery:
    """Apply sorting to the query for Artifacts.

    Args:
        query: The query to which to apply the sorting.
        table: The query table.

    Returns:
        The query with sorting applied.
    """
    from sqlmodel import asc, case, col, desc, func, select

    from zenml.enums import SorterOps
    from zenml.zen_stores.schemas import (
        ArtifactSchema,
        ArtifactVersionSchema,
    )

    sort_by, operand = self.sorting_params

    if sort_by == SORT_BY_LATEST_VERSION_KEY:
        # Subquery to find the latest version per artifact
        latest_version_subquery = (
            select(
                ArtifactSchema.id,
                case(
                    (
                        func.max(ArtifactVersionSchema.created).is_(None),
                        ArtifactSchema.created,
                    ),
                    else_=func.max(ArtifactVersionSchema.created),
                ).label("latest_version_created"),
            )
            .outerjoin(
                ArtifactVersionSchema,
                ArtifactSchema.id == ArtifactVersionSchema.artifact_id,  # type: ignore[arg-type]
            )
            .group_by(col(ArtifactSchema.id))
            .subquery()
        )

        query = query.add_columns(
            latest_version_subquery.c.latest_version_created,
        ).where(ArtifactSchema.id == latest_version_subquery.c.id)

        # Apply sorting based on the operand
        if operand == SorterOps.ASCENDING:
            query = query.order_by(
                asc(latest_version_subquery.c.latest_version_created),
                asc(ArtifactSchema.id),
            )
        else:
            query = query.order_by(
                desc(latest_version_subquery.c.latest_version_created),
                desc(ArtifactSchema.id),
            )
        return query

    # For other sorting cases, delegate to the parent class
    return super().apply_sorting(query=query, table=table)
ArtifactRequest

Bases: ProjectScopedRequest

Artifact request model.

ArtifactResponse

Bases: ProjectScopedResponse[ArtifactResponseBody, ArtifactResponseMetadata, ArtifactResponseResources]

Artifact response model.

Attributes
has_custom_name: bool property

The has_custom_name property.

Returns:

Type Description
bool

the value of the property.

latest_version_id: Optional[UUID] property

The latest_version_id property.

Returns:

Type Description
Optional[UUID]

the value of the property.

latest_version_name: Optional[str] property

The latest_version_name property.

Returns:

Type Description
Optional[str]

the value of the property.

tags: List[TagResponse] property

The tags property.

Returns:

Type Description
List[TagResponse]

the value of the property.

versions: Dict[str, ArtifactVersionResponse] property

Get a list of all versions of this artifact.

Returns:

Type Description
Dict[str, ArtifactVersionResponse]

A list of all versions of this artifact.

Functions
get_hydrated_version() -> ArtifactResponse

Get the hydrated version of this artifact.

Returns:

Type Description
ArtifactResponse

an instance of the same entity with the metadata field attached.

Source code in src/zenml/models/v2/core/artifact.py
119
120
121
122
123
124
125
126
127
def get_hydrated_version(self) -> "ArtifactResponse":
    """Get the hydrated version of this artifact.

    Returns:
        an instance of the same entity with the metadata field attached.
    """
    from zenml.client import Client

    return Client().zen_store.get_artifact(self.id)
ArtifactResponseBody

Bases: ProjectScopedResponseBody

Response body for artifacts.

ArtifactResponseMetadata

Bases: ProjectScopedResponseMetadata

Response metadata for artifacts.

ArtifactUpdate

Bases: BaseUpdate

Artifact update model.

ArtifactVersionFilter

Bases: ProjectScopedFilter, TaggableFilter, RunMetadataFilterMixin

Model to enable advanced filtering of artifact versions.

Functions
get_custom_filters(table: Type[AnySchema]) -> List[Union[ColumnElement[bool]]]

Get custom filters.

Parameters:

Name Type Description Default
table Type[AnySchema]

The query table.

required

Returns:

Type Description
List[Union[ColumnElement[bool]]]

A list of custom filters.

Source code in src/zenml/models/v2/core/artifact_version.py
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
def get_custom_filters(
    self, table: Type["AnySchema"]
) -> List[Union["ColumnElement[bool]"]]:
    """Get custom filters.

    Args:
        table: The query table.

    Returns:
        A list of custom filters.
    """
    custom_filters = super().get_custom_filters(table)

    from sqlmodel import and_, or_, select

    from zenml.zen_stores.schemas import (
        ArtifactSchema,
        ArtifactVersionSchema,
        ModelSchema,
        ModelVersionArtifactSchema,
        ModelVersionSchema,
        PipelineRunSchema,
        StepRunInputArtifactSchema,
        StepRunOutputArtifactSchema,
        StepRunSchema,
    )

    if self.artifact:
        value, operator = self._resolve_operator(self.artifact)
        artifact_filter = and_(
            ArtifactVersionSchema.artifact_id == ArtifactSchema.id,
            self.generate_name_or_id_query_conditions(
                value=self.artifact, table=ArtifactSchema
            ),
        )
        custom_filters.append(artifact_filter)

    if self.only_unused:
        unused_filter = and_(
            ArtifactVersionSchema.id.notin_(  # type: ignore[attr-defined]
                select(StepRunOutputArtifactSchema.artifact_id)
            ),
            ArtifactVersionSchema.id.notin_(  # type: ignore[attr-defined]
                select(StepRunInputArtifactSchema.artifact_id)
            ),
        )
        custom_filters.append(unused_filter)

    if self.model_version_id:
        value, operator = self._resolve_operator(self.model_version_id)

        model_version_filter = and_(
            ArtifactVersionSchema.id
            == ModelVersionArtifactSchema.artifact_version_id,
            ModelVersionArtifactSchema.model_version_id
            == ModelVersionSchema.id,
            FilterGenerator(ModelVersionSchema)
            .define_filter(column="id", value=value, operator=operator)
            .generate_query_conditions(ModelVersionSchema),
        )
        custom_filters.append(model_version_filter)

    if self.has_custom_name is not None:
        custom_name_filter = and_(
            ArtifactVersionSchema.artifact_id == ArtifactSchema.id,
            ArtifactSchema.has_custom_name == self.has_custom_name,
        )
        custom_filters.append(custom_name_filter)

    if self.model:
        model_filter = and_(
            ArtifactVersionSchema.id
            == ModelVersionArtifactSchema.artifact_version_id,
            ModelVersionArtifactSchema.model_version_id
            == ModelVersionSchema.id,
            ModelVersionSchema.model_id == ModelSchema.id,
            self.generate_name_or_id_query_conditions(
                value=self.model, table=ModelSchema
            ),
        )
        custom_filters.append(model_filter)

    if self.pipeline_run:
        pipeline_run_filter = and_(
            or_(
                and_(
                    ArtifactVersionSchema.id
                    == StepRunOutputArtifactSchema.artifact_id,
                    StepRunOutputArtifactSchema.step_id
                    == StepRunSchema.id,
                ),
                and_(
                    ArtifactVersionSchema.id
                    == StepRunInputArtifactSchema.artifact_id,
                    StepRunInputArtifactSchema.step_id == StepRunSchema.id,
                ),
            ),
            StepRunSchema.pipeline_run_id == PipelineRunSchema.id,
            self.generate_name_or_id_query_conditions(
                value=self.pipeline_run, table=PipelineRunSchema
            ),
        )
        custom_filters.append(pipeline_run_filter)

    return custom_filters
ArtifactVersionRequest

Bases: ProjectScopedRequest

Request model for artifact versions.

Functions
str_field_max_length_check(value: Any) -> Any classmethod

Checks if the length of the value exceeds the maximum str length.

Parameters:

Name Type Description Default
value Any

the value set in the field

required

Returns:

Type Description
Any

the value itself.

Raises:

Type Description
AssertionError

if the length of the field is longer than the maximum threshold.

Source code in src/zenml/models/v2/core/artifact_version.py
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
@field_validator("version")
@classmethod
def str_field_max_length_check(cls, value: Any) -> Any:
    """Checks if the length of the value exceeds the maximum str length.

    Args:
        value: the value set in the field

    Returns:
        the value itself.

    Raises:
        AssertionError: if the length of the field is longer than the
            maximum threshold.
    """
    assert len(str(value)) < STR_FIELD_MAX_LENGTH, (
        "The length of the value for this field can not "
        f"exceed {STR_FIELD_MAX_LENGTH}"
    )
    return value
ArtifactVersionResponse

Bases: ProjectScopedResponse[ArtifactVersionResponseBody, ArtifactVersionResponseMetadata, ArtifactVersionResponseResources]

Response model for artifact versions.

Attributes
artifact: ArtifactResponse property

The artifact property.

Returns:

Type Description
ArtifactResponse

the value of the property.

artifact_store_id: Optional[UUID] property

The artifact_store_id property.

Returns:

Type Description
Optional[UUID]

the value of the property.

data_type: Source property

The data_type property.

Returns:

Type Description
Source

the value of the property.

materializer: Source property

The materializer property.

Returns:

Type Description
Source

the value of the property.

name: str property

The name property.

Returns:

Type Description
str

the value of the property.

producer_pipeline_run_id: Optional[UUID] property

The producer_pipeline_run_id property.

Returns:

Type Description
Optional[UUID]

the value of the property.

producer_step_run_id: Optional[UUID] property

The producer_step_run_id property.

Returns:

Type Description
Optional[UUID]

the value of the property.

run: PipelineRunResponse property

Get the pipeline run that produced this artifact.

Returns:

Type Description
PipelineRunResponse

The pipeline run that produced this artifact.

run_metadata: Dict[str, MetadataType] property

The metadata property.

Returns:

Type Description
Dict[str, MetadataType]

the value of the property.

save_type: ArtifactSaveType property

The save_type property.

Returns:

Type Description
ArtifactSaveType

the value of the property.

step: StepRunResponse property

Get the step that produced this artifact.

Returns:

Type Description
StepRunResponse

The step that produced this artifact.

tags: List[TagResponse] property

The tags property.

Returns:

Type Description
List[TagResponse]

the value of the property.

type: ArtifactType property

The type property.

Returns:

Type Description
ArtifactType

the value of the property.

uri: str property

The uri property.

Returns:

Type Description
str

the value of the property.

version: Union[str, int] property

The version property.

Returns:

Type Description
Union[str, int]

the value of the property.

visualizations: Optional[List[ArtifactVisualizationResponse]] property

The visualizations property.

Returns:

Type Description
Optional[List[ArtifactVisualizationResponse]]

the value of the property.

Functions
download_files(path: str, overwrite: bool = False) -> None

Downloads data for an artifact with no materializing.

Any artifacts will be saved as a zip file to the given path.

Parameters:

Name Type Description Default
path str

The path to save the binary data to.

required
overwrite bool

Whether to overwrite the file if it already exists.

False

Raises:

Type Description
ValueError

If the path does not end with '.zip'.

Source code in src/zenml/models/v2/core/artifact_version.py
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
def download_files(self, path: str, overwrite: bool = False) -> None:
    """Downloads data for an artifact with no materializing.

    Any artifacts will be saved as a zip file to the given path.

    Args:
        path: The path to save the binary data to.
        overwrite: Whether to overwrite the file if it already exists.

    Raises:
        ValueError: If the path does not end with '.zip'.
    """
    if not path.endswith(".zip"):
        raise ValueError(
            "The path should end with '.zip' to save the binary data."
        )
    from zenml.artifacts.utils import (
        download_artifact_files_from_response,
    )

    download_artifact_files_from_response(
        self,
        path=path,
        overwrite=overwrite,
    )
get_hydrated_version() -> ArtifactVersionResponse

Get the hydrated version of this artifact version.

Returns:

Type Description
ArtifactVersionResponse

an instance of the same entity with the metadata field attached.

Source code in src/zenml/models/v2/core/artifact_version.py
262
263
264
265
266
267
268
269
270
def get_hydrated_version(self) -> "ArtifactVersionResponse":
    """Get the hydrated version of this artifact version.

    Returns:
        an instance of the same entity with the metadata field attached.
    """
    from zenml.client import Client

    return Client().zen_store.get_artifact_version(self.id)
load() -> Any

Materializes (loads) the data stored in this artifact.

Returns:

Type Description
Any

The materialized data.

Source code in src/zenml/models/v2/core/artifact_version.py
424
425
426
427
428
429
430
431
432
def load(self) -> Any:
    """Materializes (loads) the data stored in this artifact.

    Returns:
        The materialized data.
    """
    from zenml.artifacts.utils import load_artifact_from_response

    return load_artifact_from_response(self)
visualize(title: Optional[str] = None) -> None

Visualize the artifact in notebook environments.

Parameters:

Name Type Description Default
title Optional[str]

Optional title to show before the visualizations.

None
Source code in src/zenml/models/v2/core/artifact_version.py
460
461
462
463
464
465
466
467
468
def visualize(self, title: Optional[str] = None) -> None:
    """Visualize the artifact in notebook environments.

    Args:
        title: Optional title to show before the visualizations.
    """
    from zenml.utils.visualization_utils import visualize_artifact

    visualize_artifact(self, title=title)
ArtifactVersionResponseBody

Bases: ProjectScopedResponseBody

Response body for artifact versions.

Functions
str_field_max_length_check(value: Any) -> Any classmethod

Checks if the length of the value exceeds the maximum str length.

Parameters:

Name Type Description Default
value Any

the value set in the field

required

Returns:

Type Description
Any

the value itself.

Raises:

Type Description
AssertionError

if the length of the field is longer than the maximum threshold.

Source code in src/zenml/models/v2/core/artifact_version.py
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
@field_validator("version")
@classmethod
def str_field_max_length_check(cls, value: Any) -> Any:
    """Checks if the length of the value exceeds the maximum str length.

    Args:
        value: the value set in the field

    Returns:
        the value itself.

    Raises:
        AssertionError: if the length of the field is longer than the
            maximum threshold.
    """
    assert len(str(value)) < STR_FIELD_MAX_LENGTH, (
        "The length of the value for this field can not "
        f"exceed {STR_FIELD_MAX_LENGTH}"
    )
    return value
ArtifactVersionResponseMetadata

Bases: ProjectScopedResponseMetadata

Response metadata for artifact versions.

ArtifactVersionUpdate

Bases: BaseUpdate

Artifact version update model.

ArtifactVisualizationRequest

Bases: BaseRequest

Request model for artifact visualization.

ArtifactVisualizationResponse

Bases: BaseIdentifiedResponse[ArtifactVisualizationResponseBody, ArtifactVisualizationResponseMetadata, ArtifactVisualizationResponseResources]

Response model for artifact visualizations.

Attributes
artifact_version_id: UUID property

The artifact_version_id property.

Returns:

Type Description
UUID

the value of the property.

type: VisualizationType property

The type property.

Returns:

Type Description
VisualizationType

the value of the property.

uri: str property

The uri property.

Returns:

Type Description
str

the value of the property.

Functions
get_hydrated_version() -> ArtifactVisualizationResponse

Get the hydrated version of this artifact visualization.

Returns:

Type Description
ArtifactVisualizationResponse

an instance of the same entity with the metadata field attached.

Source code in src/zenml/models/v2/core/artifact_visualization.py
70
71
72
73
74
75
76
77
78
def get_hydrated_version(self) -> "ArtifactVisualizationResponse":
    """Get the hydrated version of this artifact visualization.

    Returns:
        an instance of the same entity with the metadata field attached.
    """
    from zenml.client import Client

    return Client().zen_store.get_artifact_visualization(self.id)
ArtifactVisualizationResponseBody

Bases: BaseDatedResponseBody

Response body for artifact visualizations.

ArtifactVisualizationResponseMetadata

Bases: BaseResponseMetadata

Response metadata model for artifact visualizations.

AuthenticationMethodModel(config_class: Optional[Type[BaseModel]] = None, **values: Any)

Bases: BaseModel

Authentication method specification.

Describes the schema for the configuration and secrets that need to be provided to configure an authentication method.

Initialize the authentication method.

Parameters:

Name Type Description Default
config_class Optional[Type[BaseModel]]

The configuration class for the authentication method.

None
**values Any

The data to initialize the authentication method with.

{}
Source code in src/zenml/models/v2/misc/service_connector_type.py
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
def __init__(
    self, config_class: Optional[Type[BaseModel]] = None, **values: Any
):
    """Initialize the authentication method.

    Args:
        config_class: The configuration class for the authentication
            method.
        **values: The data to initialize the authentication method with.
    """
    if config_class:
        values["config_schema"] = config_class.model_json_schema()

    super().__init__(**values)
    self._config_class = config_class
Attributes
config_class: Optional[Type[BaseModel]] property

Get the configuration class for the authentication method.

Returns:

Type Description
Optional[Type[BaseModel]]

The configuration class for the authentication method.

Functions
supports_temporary_credentials() -> bool

Check if the authentication method supports temporary credentials.

Returns:

Type Description
bool

True if the authentication method supports temporary credentials,

bool

False otherwise.

Source code in src/zenml/models/v2/misc/service_connector_type.py
157
158
159
160
161
162
163
164
165
166
167
168
def supports_temporary_credentials(self) -> bool:
    """Check if the authentication method supports temporary credentials.

    Returns:
        True if the authentication method supports temporary credentials,
        False otherwise.
    """
    return (
        self.min_expiration_seconds is not None
        or self.max_expiration_seconds is not None
        or self.default_expiration_seconds is not None
    )
validate_expiration(expiration_seconds: Optional[int]) -> Optional[int]

Validate the expiration time.

Parameters:

Name Type Description Default
expiration_seconds Optional[int]

The expiration time in seconds. If None, the default expiration time is used, if applicable.

required

Returns:

Type Description
Optional[int]

The expiration time in seconds or None if not applicable.

Raises:

Type Description
ValueError

If the expiration time is not valid.

Source code in src/zenml/models/v2/misc/service_connector_type.py
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
def validate_expiration(
    self, expiration_seconds: Optional[int]
) -> Optional[int]:
    """Validate the expiration time.

    Args:
        expiration_seconds: The expiration time in seconds. If None, the
            default expiration time is used, if applicable.

    Returns:
        The expiration time in seconds or None if not applicable.

    Raises:
        ValueError: If the expiration time is not valid.
    """
    if not self.supports_temporary_credentials():
        if expiration_seconds is not None:
            # Expiration is not supported
            raise ValueError(
                "Expiration time is not supported for this authentication "
                f"method but a value was provided: {expiration_seconds}"
            )

        return None

    expiration_seconds = (
        expiration_seconds or self.default_expiration_seconds
    )

    if expiration_seconds is None:
        return None

    if self.min_expiration_seconds is not None:
        if expiration_seconds < self.min_expiration_seconds:
            raise ValueError(
                f"Expiration time must be at least "
                f"{self.min_expiration_seconds} seconds."
            )

    if self.max_expiration_seconds is not None:
        if expiration_seconds > self.max_expiration_seconds:
            raise ValueError(
                f"Expiration time must be at most "
                f"{self.max_expiration_seconds} seconds."
            )

    return expiration_seconds
BaseDatedResponseBody

Bases: BaseResponseBody

Base body model for entities that track a creation and update timestamp.

Used as a base class for all body models associated with responses. Features a creation and update timestamp.

BaseFilter

Bases: BaseModel

Class to unify all filter, paginate and sort request parameters.

This Model allows fine-grained filtering, sorting and pagination of resources.

Usage example for subclasses of this class:

ResourceListModel(
    name="contains:default",
    project="default"
    count_steps="gte:5"
    sort_by="created",
    page=2,
    size=20
)
Attributes
list_of_filters: List[Filter] property

Converts the class variables into a list of usable Filter Models.

Returns:

Type Description
List[Filter]

A list of Filter models.

offset: int property

Returns the offset needed for the query on the data persistence layer.

Returns:

Type Description
int

The offset for the query.

sorting_params: Tuple[str, SorterOps] property

Converts the class variables into a list of usable Filter Models.

Returns:

Type Description
Tuple[str, SorterOps]

A tuple of the column to sort by and the sorting operand.

Functions
apply_filter(query: AnyQuery, table: Type[AnySchema]) -> AnyQuery

Applies the filter to a query.

Parameters:

Name Type Description Default
query AnyQuery

The query to which to apply the filter.

required
table Type[AnySchema]

The query table.

required

Returns:

Type Description
AnyQuery

The query with filter applied.

Source code in src/zenml/models/v2/base/filter.py
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
def apply_filter(
    self,
    query: AnyQuery,
    table: Type["AnySchema"],
) -> AnyQuery:
    """Applies the filter to a query.

    Args:
        query: The query to which to apply the filter.
        table: The query table.

    Returns:
        The query with filter applied.
    """
    rbac_filter = self.generate_rbac_filter(table=table)

    if rbac_filter is not None:
        query = query.where(rbac_filter)

    filters = self.generate_filter(table=table)

    if filters is not None:
        query = query.where(filters)

    return query
apply_sorting(query: AnyQuery, table: Type[AnySchema]) -> AnyQuery

Apply sorting to the query.

Parameters:

Name Type Description Default
query AnyQuery

The query to which to apply the sorting.

required
table Type[AnySchema]

The query table.

required

Returns:

Type Description
AnyQuery

The query with sorting applied.

Source code in src/zenml/models/v2/base/filter.py
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
def apply_sorting(
    self,
    query: AnyQuery,
    table: Type["AnySchema"],
) -> AnyQuery:
    """Apply sorting to the query.

    Args:
        query: The query to which to apply the sorting.
        table: The query table.

    Returns:
        The query with sorting applied.
    """
    column, operand = self.sorting_params

    if operand == SorterOps.DESCENDING:
        sort_clause = desc(getattr(table, column))  # type: ignore[var-annotated]
    else:
        sort_clause = asc(getattr(table, column))

    # We always add the `id` column as a tiebreaker to ensure a stable,
    # repeatable order of items, otherwise subsequent pages might contain
    # the same items.
    query = query.order_by(sort_clause, asc(table.id))  # type: ignore[arg-type]

    return query
configure_rbac(authenticated_user_id: UUID, **column_allowed_ids: Optional[Set[UUID]]) -> None

Configure RBAC allowed column values.

Parameters:

Name Type Description Default
authenticated_user_id UUID

ID of the authenticated user. All entities owned by this user will be included.

required
column_allowed_ids Optional[Set[UUID]]

Set of IDs per column to limit the query to. If given, the remaining filters will be applied to entities within this set only. If None, the remaining filters will be applied to all entries in the table.

{}
Source code in src/zenml/models/v2/base/filter.py
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
def configure_rbac(
    self,
    authenticated_user_id: UUID,
    **column_allowed_ids: Optional[Set[UUID]],
) -> None:
    """Configure RBAC allowed column values.

    Args:
        authenticated_user_id: ID of the authenticated user. All entities
            owned by this user will be included.
        column_allowed_ids: Set of IDs per column to limit the query to.
            If given, the remaining filters will be applied to entities
            within this set only. If `None`, the remaining filters will
            be applied to all entries in the table.
    """
    self._rbac_configuration = (authenticated_user_id, column_allowed_ids)
filter_ops(data: Dict[str, Any]) -> Dict[str, Any] classmethod

Parse incoming filters to ensure all filters are legal.

Parameters:

Name Type Description Default
data Dict[str, Any]

The values of the class.

required

Returns:

Type Description
Dict[str, Any]

The values of the class.

Source code in src/zenml/models/v2/base/filter.py
645
646
647
648
649
650
651
652
653
654
655
656
657
658
@model_validator(mode="before")
@classmethod
@before_validator_handler
def filter_ops(cls, data: Dict[str, Any]) -> Dict[str, Any]:
    """Parse incoming filters to ensure all filters are legal.

    Args:
        data: The values of the class.

    Returns:
        The values of the class.
    """
    cls._generate_filter_list(data)
    return data
generate_custom_query_conditions_for_column(value: Any, table: Type[SQLModel], column: str) -> ColumnElement[bool] staticmethod

Generate custom filter conditions for a column of a table.

Parameters:

Name Type Description Default
value Any

The filter value.

required
table Type[SQLModel]

The table which contains the column.

required
column str

The column name.

required

Returns:

Type Description
ColumnElement[bool]

The query conditions.

Source code in src/zenml/models/v2/base/filter.py
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
@staticmethod
def generate_custom_query_conditions_for_column(
    value: Any,
    table: Type[SQLModel],
    column: str,
) -> "ColumnElement[bool]":
    """Generate custom filter conditions for a column of a table.

    Args:
        value: The filter value.
        table: The table which contains the column.
        column: The column name.

    Returns:
        The query conditions.
    """
    value, operator = BaseFilter._resolve_operator(value)
    filter_ = FilterGenerator(table).define_filter(
        column=column, value=value, operator=operator
    )
    return filter_.generate_query_conditions(table=table)
generate_filter(table: Type[AnySchema]) -> Union[ColumnElement[bool]]

Generate the filter for the query.

Parameters:

Name Type Description Default
table Type[AnySchema]

The Table that is being queried from.

required

Returns:

Type Description
Union[ColumnElement[bool]]

The filter expression for the query.

Raises:

Type Description
RuntimeError

If a valid logical operator is not supplied.

Source code in src/zenml/models/v2/base/filter.py
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
def generate_filter(
    self, table: Type["AnySchema"]
) -> Union["ColumnElement[bool]"]:
    """Generate the filter for the query.

    Args:
        table: The Table that is being queried from.

    Returns:
        The filter expression for the query.

    Raises:
        RuntimeError: If a valid logical operator is not supplied.
    """
    from sqlmodel import and_, or_

    filters = []
    for column_filter in self.list_of_filters:
        filters.append(
            column_filter.generate_query_conditions(table=table)
        )
    for custom_filter in self.get_custom_filters(table):
        filters.append(custom_filter)
    if self.logical_operator == LogicalOperators.OR:
        return or_(False, *filters)
    elif self.logical_operator == LogicalOperators.AND:
        return and_(True, *filters)
    else:
        raise RuntimeError("No valid logical operator was supplied.")
generate_name_or_id_query_conditions(value: Union[UUID, str], table: Type[NamedSchema], additional_columns: Optional[List[str]] = None) -> ColumnElement[bool]

Generate filter conditions for name or id of a table.

Parameters:

Name Type Description Default
value Union[UUID, str]

The filter value.

required
table Type[NamedSchema]

The table to filter.

required
additional_columns Optional[List[str]]

Additional table columns that should also filter for the given value as part of the or condition.

None

Returns:

Type Description
ColumnElement[bool]

The query conditions.

Source code in src/zenml/models/v2/base/filter.py
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
def generate_name_or_id_query_conditions(
    self,
    value: Union[UUID, str],
    table: Type["NamedSchema"],
    additional_columns: Optional[List[str]] = None,
) -> "ColumnElement[bool]":
    """Generate filter conditions for name or id of a table.

    Args:
        value: The filter value.
        table: The table to filter.
        additional_columns: Additional table columns that should also
            filter for the given value as part of the or condition.

    Returns:
        The query conditions.
    """
    from sqlmodel import or_

    value, operator = BaseFilter._resolve_operator(value)
    value = str(value)

    conditions = []

    filter_ = FilterGenerator(table).define_filter(
        column="id", value=value, operator=operator
    )
    conditions.append(filter_.generate_query_conditions(table=table))

    filter_ = FilterGenerator(table).define_filter(
        column="name", value=value, operator=operator
    )
    conditions.append(filter_.generate_query_conditions(table=table))

    for column in additional_columns or []:
        filter_ = FilterGenerator(table).define_filter(
            column=column, value=value, operator=operator
        )
        conditions.append(filter_.generate_query_conditions(table=table))

    return or_(*conditions)
generate_rbac_filter(table: Type[AnySchema]) -> Optional[ColumnElement[bool]]

Generates an optional RBAC filter.

Parameters:

Name Type Description Default
table Type[AnySchema]

The query table.

required

Returns:

Type Description
Optional[ColumnElement[bool]]

The RBAC filter.

Source code in src/zenml/models/v2/base/filter.py
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
def generate_rbac_filter(
    self,
    table: Type["AnySchema"],
) -> Optional["ColumnElement[bool]"]:
    """Generates an optional RBAC filter.

    Args:
        table: The query table.

    Returns:
        The RBAC filter.
    """
    from sqlmodel import or_

    if not self._rbac_configuration:
        return None

    expressions = []

    for column_name, allowed_ids in self._rbac_configuration[1].items():
        if allowed_ids is not None:
            expression = getattr(table, column_name).in_(allowed_ids)
            expressions.append(expression)

    if expressions and hasattr(table, "user_id"):
        # If `expressions` is not empty, we do not have full access to all
        # rows of the table. In this case, we also include rows which the
        # user owns.

        # Unowned entities are considered server-owned and can be seen
        # by anyone
        expressions.append(getattr(table, "user_id").is_(None))
        # The authenticated user owns this entity
        expressions.append(
            getattr(table, "user_id") == self._rbac_configuration[0]
        )

    if expressions:
        return or_(*expressions)
    else:
        return None
get_custom_filters(table: Type[AnySchema]) -> List[ColumnElement[bool]]

Get custom filters.

This can be overridden by subclasses to define custom filters that are not based on the columns of the underlying table.

Parameters:

Name Type Description Default
table Type[AnySchema]

The query table.

required

Returns:

Type Description
List[ColumnElement[bool]]

A list of custom filters.

Source code in src/zenml/models/v2/base/filter.py
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
def get_custom_filters(
    self, table: Type["AnySchema"]
) -> List["ColumnElement[bool]"]:
    """Get custom filters.

    This can be overridden by subclasses to define custom filters that are
    not based on the columns of the underlying table.

    Args:
        table: The query table.

    Returns:
        A list of custom filters.
    """
    return []
validate_sort_by(value: Any) -> Any classmethod

Validate that the sort_column is a valid column with a valid operand.

Parameters:

Name Type Description Default
value Any

The sort_by field value.

required

Returns:

Type Description
Any

The validated sort_by field value.

Raises:

Type Description
ValidationError

If the sort_by field is not a string.

ValueError

If the resource can't be sorted by this field.

Source code in src/zenml/models/v2/base/filter.py
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
@field_validator("sort_by", mode="before")
@classmethod
def validate_sort_by(cls, value: Any) -> Any:
    """Validate that the sort_column is a valid column with a valid operand.

    Args:
        value: The sort_by field value.

    Returns:
        The validated sort_by field value.

    Raises:
        ValidationError: If the sort_by field is not a string.
        ValueError: If the resource can't be sorted by this field.
    """
    # Somehow pydantic allows you to pass in int values, which will be
    #  interpreted as string, however within the validator they are still
    #  integers, which don't have a .split() method
    if not isinstance(value, str):
        raise ValidationError(
            f"str type expected for the sort_by field. "
            f"Received a {type(value)}"
        )
    column = value
    split_value = value.split(":", 1)
    if len(split_value) == 2:
        column = split_value[1]

        if split_value[0] not in SorterOps.values():
            logger.warning(
                "Invalid operand used for column sorting. "
                "Only the following operands are supported `%s`. "
                "Defaulting to 'asc' on column `%s`.",
                SorterOps.values(),
                column,
            )
            value = column

    if column in cls.CUSTOM_SORTING_OPTIONS:
        return value
    elif column in cls.FILTER_EXCLUDE_FIELDS:
        raise ValueError(
            f"This resource can not be sorted by this field: '{value}'"
        )
    if column in cls.model_fields:
        return value
    else:
        raise ValueError(
            "You can only sort by valid fields of this resource"
        )
BaseIdentifiedResponse

Bases: BaseResponse[AnyDatedBody, AnyMetadata, AnyResources], Generic[AnyDatedBody, AnyMetadata, AnyResources]

Base domain model for resources with DB representation.

Attributes
created: datetime property

The created property.

Returns:

Type Description
datetime

the value of the property.

updated: datetime property

The updated property.

Returns:

Type Description
datetime

the value of the property.

Functions
get_analytics_metadata() -> Dict[str, Any]

Fetches the analytics metadata for base response models.

Returns:

Type Description
Dict[str, Any]

The analytics metadata.

Source code in src/zenml/models/v2/base/base.py
456
457
458
459
460
461
462
463
464
def get_analytics_metadata(self) -> Dict[str, Any]:
    """Fetches the analytics metadata for base response models.

    Returns:
        The analytics metadata.
    """
    metadata = super().get_analytics_metadata()
    metadata["entity_id"] = self.id
    return metadata
get_body() -> AnyDatedBody

Fetch the body of the entity.

Returns:

Type Description
AnyDatedBody

The body field of the response.

Raises:

Type Description
IllegalOperationError

If the user lacks permission to access the entity represented by this response.

Source code in src/zenml/models/v2/base/base.py
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
def get_body(self) -> "AnyDatedBody":
    """Fetch the body of the entity.

    Returns:
        The body field of the response.

    Raises:
        IllegalOperationError: If the user lacks permission to access the
            entity represented by this response.
    """
    if self.permission_denied:
        raise IllegalOperationError(
            f"Missing permissions to access {type(self).__name__} with "
            f"ID {self.id}."
        )

    return super().get_body()
get_hydrated_version() -> BaseIdentifiedResponse[AnyDatedBody, AnyMetadata, AnyResources]

Abstract method to fetch the hydrated version of the model.

Raises:

Type Description
NotImplementedError

in case the method is not implemented.

Source code in src/zenml/models/v2/base/base.py
406
407
408
409
410
411
412
413
414
415
416
417
def get_hydrated_version(
    self,
) -> "BaseIdentifiedResponse[AnyDatedBody, AnyMetadata, AnyResources]":
    """Abstract method to fetch the hydrated version of the model.

    Raises:
        NotImplementedError: in case the method is not implemented.
    """
    raise NotImplementedError(
        "Please implement a `get_hydrated_version` method before "
        "using/hydrating the model."
    )
get_metadata() -> AnyMetadata

Fetch the metadata of the entity.

Returns:

Type Description
AnyMetadata

The metadata field of the response.

Raises:

Type Description
IllegalOperationError

If the user lacks permission to access this entity represented by this response.

Source code in src/zenml/models/v2/base/base.py
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
def get_metadata(self) -> "AnyMetadata":
    """Fetch the metadata of the entity.

    Returns:
        The metadata field of the response.

    Raises:
        IllegalOperationError: If the user lacks permission to access this
            entity represented by this response.
    """
    if self.permission_denied:
        raise IllegalOperationError(
            f"Missing permissions to access {type(self).__name__} with "
            f"ID {self.id}."
        )

    return super().get_metadata()
BasePluginFlavorResponse

Bases: BaseResponse[AnyPluginBody, AnyPluginMetadata, AnyPluginResources], Generic[AnyPluginBody, AnyPluginMetadata, AnyPluginResources]

Base response for all Plugin Flavors.

Functions
get_hydrated_version() -> BasePluginFlavorResponse[AnyPluginBody, AnyPluginMetadata, AnyPluginResources]

Abstract method to fetch the hydrated version of the model.

Returns:

Type Description
BasePluginFlavorResponse[AnyPluginBody, AnyPluginMetadata, AnyPluginResources]

Hydrated version of the PluginFlavorResponse

Source code in src/zenml/models/v2/base/base_plugin_flavor.py
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
def get_hydrated_version(
    self,
) -> "BasePluginFlavorResponse[AnyPluginBody, AnyPluginMetadata, AnyPluginResources]":
    """Abstract method to fetch the hydrated version of the model.

    Returns:
        Hydrated version of the PluginFlavorResponse
    """
    # TODO: shouldn't this call the Zen store ? The client should not have
    #  to know about the plugin flavor registry
    from zenml.zen_server.utils import plugin_flavor_registry

    plugin_flavor = plugin_flavor_registry().get_flavor_class(
        name=self.name, _type=self.type, subtype=self.subtype
    )
    return plugin_flavor.get_flavor_response_model(hydrate=True)
BaseRequest

Bases: BaseZenModel

Base request model.

Used as a base class for all request models.

BaseResponse

Bases: BaseZenModel, Generic[AnyBody, AnyMetadata, AnyResources]

Base domain model for all responses.

Functions
get_body() -> AnyBody

Fetch the body of the entity.

Returns:

Type Description
AnyBody

The body field of the response.

Raises:

Type Description
RuntimeError

If the body was not included in the response.

Source code in src/zenml/models/v2/base/base.py
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
def get_body(self) -> "AnyBody":
    """Fetch the body of the entity.

    Returns:
        The body field of the response.

    Raises:
        RuntimeError: If the body was not included in the response.
    """
    if not self.body:
        raise RuntimeError(
            f"Missing response body for {type(self).__name__}."
        )

    return self.body
get_hydrated_version() -> BaseResponse[AnyBody, AnyMetadata, AnyResources]

Abstract method to fetch the hydrated version of the model.

Raises:

Type Description
NotImplementedError

in case the method is not implemented.

Source code in src/zenml/models/v2/base/base.py
221
222
223
224
225
226
227
228
229
230
231
232
def get_hydrated_version(
    self,
) -> "BaseResponse[AnyBody, AnyMetadata, AnyResources]":
    """Abstract method to fetch the hydrated version of the model.

    Raises:
        NotImplementedError: in case the method is not implemented.
    """
    raise NotImplementedError(
        "Please implement a `get_hydrated_version` method before "
        "using/hydrating the model."
    )
get_metadata() -> AnyMetadata

Fetch the metadata of the entity.

Returns:

Type Description
AnyMetadata

The metadata field of the response.

Source code in src/zenml/models/v2/base/base.py
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
def get_metadata(self) -> "AnyMetadata":
    """Fetch the metadata of the entity.

    Returns:
        The metadata field of the response.
    """
    if self.metadata is None:
        # If the metadata is not there, check the class first.
        metadata_annotation = (
            type(self).model_fields["metadata"].annotation
        )
        assert metadata_annotation is not None, (
            "For each response model, an annotated metadata"
            "field should exist."
        )

        # metadata is defined as:
        #   metadata: Optional[....ResponseMetadata] = Field(default=None)
        # We need to find the actual class inside the Optional annotation.
        from zenml.utils.typing_utils import get_args

        metadata_type = get_args(metadata_annotation)[0]
        assert issubclass(metadata_type, BaseResponseMetadata)

        if len(metadata_type.model_fields):
            # If the metadata class defines any fields, fetch the metadata
            # through the hydrated version.
            self.hydrate()
        else:
            # Otherwise, use the metadata class to create an empty metadata
            # object.
            self.metadata = metadata_type()

    assert self.metadata is not None

    return self.metadata
get_resources() -> AnyResources

Fetch the resources related to this entity.

Returns:

Type Description
AnyResources

The resources field of the response.

Raises:

Type Description
RuntimeError

If the resources field was not included in the response.

Source code in src/zenml/models/v2/base/base.py
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
def get_resources(self) -> "AnyResources":
    """Fetch the resources related to this entity.

    Returns:
        The resources field of the response.

    Raises:
        RuntimeError: If the resources field was not included in the response.
    """
    if self.resources is None:
        # If the resources are not there, check the class first.
        resources_annotation = (
            type(self).model_fields["resources"].annotation
        )
        assert resources_annotation is not None, (
            "For each response model, an annotated resources"
            "field should exist."
        )

        # resources is defined as:
        #   resources: Optional[....ResponseResources] = Field(default=None)
        # We need to find the actual class inside the Optional annotation.
        from zenml.utils.typing_utils import get_args

        resources_type = get_args(resources_annotation)[0]
        assert issubclass(resources_type, BaseResponseResources)

        if len(resources_type.model_fields):
            # If the resources class defines any fields, fetch the resources
            # through the hydrated version.
            self.hydrate()
        else:
            # Otherwise, use the resources class to create an empty
            # resources object.
            self.resources = resources_type()

    if self.resources is None:
        raise RuntimeError(
            f"Missing response resources for {type(self).__name__}."
        )

    return self.resources
hydrate() -> None

Hydrate the response.

Source code in src/zenml/models/v2/base/base.py
213
214
215
216
217
218
219
def hydrate(self) -> None:
    """Hydrate the response."""
    hydrated_version = self.get_hydrated_version()
    self._validate_hydrated_version(hydrated_version)

    self.resources = hydrated_version.resources
    self.metadata = hydrated_version.metadata
BaseResponseBody

Bases: BaseZenModel

Base body model.

BaseResponseMetadata

Bases: BaseZenModel

Base metadata model.

Used as a base class for all metadata models associated with responses.

BaseResponseResources

Bases: BaseZenModel

Base resources model.

Used as a base class for all resource models associated with responses.

BaseUpdate

Bases: BaseZenModel

Base update model.

Used as a base class for all update models.

BaseZenModel

Bases: YAMLSerializationMixin, AnalyticsTrackedModelMixin

Base model class for all ZenML models.

This class is used as a base class for all ZenML models. It provides functionality for tracking analytics events.

BoolFilter

Bases: Filter

Filter for all Boolean fields.

Functions
generate_query_conditions_from_column(column: Any) -> Any

Generate query conditions for a boolean column.

Parameters:

Name Type Description Default
column Any

The boolean column of an SQLModel table on which to filter.

required

Returns:

Type Description
Any

A list of query conditions.

Source code in src/zenml/models/v2/base/filter.py
156
157
158
159
160
161
162
163
164
165
166
167
168
def generate_query_conditions_from_column(self, column: Any) -> Any:
    """Generate query conditions for a boolean column.

    Args:
        column: The boolean column of an SQLModel table on which to filter.

    Returns:
        A list of query conditions.
    """
    if self.operation == GenericFilterOps.NOT_EQUALS:
        return column != self.value

    return column == self.value
BuildItem

Bases: BaseModel

Pipeline build item.

Attributes:

Name Type Description
image str

The image name or digest.

dockerfile Optional[str]

The contents of the Dockerfile used to build the image.

requirements Optional[str]

The pip requirements installed in the image. This is a string consisting of multiple concatenated requirements.txt files.

settings_checksum Optional[str]

Checksum of the settings used for the build.

contains_code bool

Whether the image contains user files.

requires_code_download bool

Whether the image needs to download files.

CodeReferenceRequest

Bases: BaseRequest

Request model for code references.

CodeReferenceResponse

Bases: BaseIdentifiedResponse[CodeReferenceResponseBody, CodeReferenceResponseMetadata, CodeReferenceResponseResources]

Response model for code references.

Attributes
code_repository: CodeRepositoryResponse property

The code_repository property.

Returns:

Type Description
CodeRepositoryResponse

the value of the property.

commit: str property

The commit property.

Returns:

Type Description
str

the value of the property.

subdirectory: str property

The subdirectory property.

Returns:

Type Description
str

the value of the property.

Functions
get_hydrated_version() -> CodeReferenceResponse

Get the hydrated version of this code reference.

Returns:

Type Description
CodeReferenceResponse

an instance of the same entity with the metadata field attached.

Source code in src/zenml/models/v2/core/code_reference.py
85
86
87
88
89
90
91
92
93
def get_hydrated_version(self) -> "CodeReferenceResponse":
    """Get the hydrated version of this code reference.

    Returns:
        an instance of the same entity with the metadata field attached.
    """
    from zenml.client import Client

    return Client().zen_store.get_code_reference(self.id)
CodeReferenceResponseBody

Bases: BaseDatedResponseBody

Response body for code references.

CodeReferenceResponseMetadata

Bases: BaseResponseMetadata

Response metadata for code references.

CodeRepositoryFilter

Bases: ProjectScopedFilter

Model to enable advanced filtering of all code repositories.

CodeRepositoryRequest

Bases: ProjectScopedRequest

Request model for code repositories.

CodeRepositoryResponse

Bases: ProjectScopedResponse[CodeRepositoryResponseBody, CodeRepositoryResponseMetadata, CodeRepositoryResponseResources]

Response model for code repositories.

Attributes
config: Dict[str, Any] property

The config property.

Returns:

Type Description
Dict[str, Any]

the value of the property.

description: Optional[str] property

The description property.

Returns:

Type Description
Optional[str]

the value of the property.

logo_url: Optional[str] property

The logo_url property.

Returns:

Type Description
Optional[str]

the value of the property.

source: Source property

The source property.

Returns:

Type Description
Source

the value of the property.

Functions
get_hydrated_version() -> CodeRepositoryResponse

Get the hydrated version of this code repository.

Returns:

Type Description
CodeRepositoryResponse

an instance of the same entity with the metadata field attached.

Source code in src/zenml/models/v2/core/code_repository.py
133
134
135
136
137
138
139
140
141
def get_hydrated_version(self) -> "CodeRepositoryResponse":
    """Get the hydrated version of this code repository.

    Returns:
        an instance of the same entity with the metadata field attached.
    """
    from zenml.client import Client

    return Client().zen_store.get_code_repository(self.id)
CodeRepositoryResponseBody

Bases: ProjectScopedResponseBody

Response body for code repositories.

CodeRepositoryResponseMetadata

Bases: ProjectScopedResponseMetadata

Response metadata for code repositories.

CodeRepositoryUpdate

Bases: BaseUpdate

Update model for code repositories.

ComponentBase

Bases: BaseModel

Base model for components.

ComponentFilter

Bases: UserScopedFilter

Model to enable advanced stack component filtering.

Functions
generate_filter(table: Type[AnySchema]) -> Union[ColumnElement[bool]]

Generate the filter for the query.

Stack components can be scoped by type to narrow the search.

Parameters:

Name Type Description Default
table Type[AnySchema]

The Table that is being queried from.

required

Returns:

Type Description
Union[ColumnElement[bool]]

The filter expression for the query.

Source code in src/zenml/models/v2/core/component.py
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
def generate_filter(
    self, table: Type["AnySchema"]
) -> Union["ColumnElement[bool]"]:
    """Generate the filter for the query.

    Stack components can be scoped by type to narrow the search.

    Args:
        table: The Table that is being queried from.

    Returns:
        The filter expression for the query.
    """
    from sqlmodel import and_, or_

    from zenml.zen_stores.schemas import (
        StackComponentSchema,
        StackCompositionSchema,
    )

    base_filter = super().generate_filter(table)
    if self.scope_type:
        type_filter = getattr(table, "type") == self.scope_type
        return and_(base_filter, type_filter)

    if self.stack_id:
        operator = (
            or_ if self.logical_operator == LogicalOperators.OR else and_
        )

        stack_filter = and_(
            StackCompositionSchema.stack_id == self.stack_id,
            StackCompositionSchema.component_id == StackComponentSchema.id,
        )
        base_filter = operator(base_filter, stack_filter)

    return base_filter
set_scope_type(component_type: str) -> None

Set the type of component on which to perform the filtering to scope the response.

Parameters:

Name Type Description Default
component_type str

The type of component to scope the query to.

required
Source code in src/zenml/models/v2/core/component.py
383
384
385
386
387
388
389
def set_scope_type(self, component_type: str) -> None:
    """Set the type of component on which to perform the filtering to scope the response.

    Args:
        component_type: The type of component to scope the query to.
    """
    self.scope_type = component_type
ComponentInfo

Bases: BaseModel

Information about each stack components when creating a full stack.

ComponentRequest

Bases: ComponentBase, UserScopedRequest

Request model for stack components.

Functions
name_cant_be_a_secret_reference(name: str) -> str classmethod

Validator to ensure that the given name is not a secret reference.

Parameters:

Name Type Description Default
name str

The name to validate.

required

Returns:

Type Description
str

The name if it is not a secret reference.

Raises:

Type Description
ValueError

If the name is a secret reference.

Source code in src/zenml/models/v2/core/component.py
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
@field_validator("name")
@classmethod
def name_cant_be_a_secret_reference(cls, name: str) -> str:
    """Validator to ensure that the given name is not a secret reference.

    Args:
        name: The name to validate.

    Returns:
        The name if it is not a secret reference.

    Raises:
        ValueError: If the name is a secret reference.
    """
    if secret_utils.is_secret_reference(name):
        raise ValueError(
            "Passing the `name` attribute of a stack component as a "
            "secret reference is not allowed."
        )
    return name
ComponentResponse

Bases: UserScopedResponse[ComponentResponseBody, ComponentResponseMetadata, ComponentResponseResources]

Response model for stack components.

Attributes
configuration: Dict[str, Any] property

The configuration property.

Returns:

Type Description
Dict[str, Any]

the value of the property.

connector: Optional[ServiceConnectorResponse] property

The connector property.

Returns:

Type Description
Optional[ServiceConnectorResponse]

the value of the property.

connector_resource_id: Optional[str] property

The connector_resource_id property.

Returns:

Type Description
Optional[str]

the value of the property.

flavor: FlavorResponse property

The flavor property.

Returns:

Type Description
FlavorResponse

the value of the property.

flavor_name: str property

The flavor_name property.

Returns:

Type Description
str

the value of the property.

integration: Optional[str] property

The integration property.

Returns:

Type Description
Optional[str]

the value of the property.

labels: Optional[Dict[str, Any]] property

The labels property.

Returns:

Type Description
Optional[Dict[str, Any]]

the value of the property.

logo_url: Optional[str] property

The logo_url property.

Returns:

Type Description
Optional[str]

the value of the property.

type: StackComponentType property

The type property.

Returns:

Type Description
StackComponentType

the value of the property.

Functions
get_analytics_metadata() -> Dict[str, Any]

Add the component labels to analytics metadata.

Returns:

Type Description
Dict[str, Any]

Dict of analytics metadata.

Source code in src/zenml/models/v2/core/component.py
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
def get_analytics_metadata(self) -> Dict[str, Any]:
    """Add the component labels to analytics metadata.

    Returns:
        Dict of analytics metadata.
    """
    metadata = super().get_analytics_metadata()

    if self.labels is not None:
        metadata.update(
            {
                label[6:]: value
                for label, value in self.labels.items()
                if label.startswith("zenml:")
            }
        )
    metadata["flavor"] = self.flavor_name

    return metadata
get_hydrated_version() -> ComponentResponse

Get the hydrated version of this component.

Returns:

Type Description
ComponentResponse

an instance of the same entity with the metadata field attached.

Source code in src/zenml/models/v2/core/component.py
248
249
250
251
252
253
254
255
256
def get_hydrated_version(self) -> "ComponentResponse":
    """Get the hydrated version of this component.

    Returns:
        an instance of the same entity with the metadata field attached.
    """
    from zenml.client import Client

    return Client().zen_store.get_stack_component(self.id)
ComponentResponseBody

Bases: UserScopedResponseBody

Response body for stack components.

ComponentResponseMetadata

Bases: UserScopedResponseMetadata

Response metadata for stack components.

ComponentResponseResources

Bases: UserScopedResponseResources

Response resources for stack components.

ComponentUpdate

Bases: BaseUpdate

Update model for stack components.

DefaultComponentRequest

Bases: ComponentRequest

Internal component request model used only for default stack components.

DefaultStackRequest

Bases: StackRequest

Internal stack request model used only for default stacks.

DeployedStack

Bases: BaseModel

Information about a deployed stack.

EventSourceFilter

Bases: ProjectScopedFilter

Model to enable advanced filtering of all EventSourceModels.

EventSourceFlavorResponse

Bases: BasePluginFlavorResponse[EventSourceFlavorResponseBody, EventSourceFlavorResponseMetadata, EventSourceFlavorResponseResources]

Response model for Event Source Flavors.

Attributes
filter_config_schema: Dict[str, Any] property

The filter_config_schema property.

Returns:

Type Description
Dict[str, Any]

the value of the property.

source_config_schema: Dict[str, Any] property

The source_config_schema property.

Returns:

Type Description
Dict[str, Any]

the value of the property.

EventSourceFlavorResponseBody

Bases: BasePluginResponseBody

Response body for event flavors.

EventSourceFlavorResponseMetadata

Bases: BasePluginResponseMetadata

Response metadata for event flavors.

EventSourceFlavorResponseResources

Bases: BasePluginResponseResources

Response resources for event source flavors.

EventSourceRequest

Bases: ProjectScopedRequest

BaseModel for all event sources.

EventSourceResponse

Bases: ProjectScopedResponse[EventSourceResponseBody, EventSourceResponseMetadata, EventSourceResponseResources]

Response model for event sources.

Attributes
configuration: Dict[str, Any] property

The configuration property.

Returns:

Type Description
Dict[str, Any]

the value of the property.

description: str property

The description property.

Returns:

Type Description
str

the value of the property.

flavor: str property

The flavor property.

Returns:

Type Description
str

the value of the property.

is_active: bool property

The is_active property.

Returns:

Type Description
bool

the value of the property.

plugin_subtype: PluginSubType property

The plugin_subtype property.

Returns:

Type Description
PluginSubType

the value of the property.

Functions
get_hydrated_version() -> EventSourceResponse

Get the hydrated version of this event source.

Returns:

Type Description
EventSourceResponse

An instance of the same entity with the metadata field attached.

Source code in src/zenml/models/v2/core/event_source.py
161
162
163
164
165
166
167
168
169
def get_hydrated_version(self) -> "EventSourceResponse":
    """Get the hydrated version of this event source.

    Returns:
        An instance of the same entity with the metadata field attached.
    """
    from zenml.client import Client

    return Client().zen_store.get_event_source(self.id)
set_configuration(configuration: Dict[str, Any]) -> None

Set the configuration property.

Parameters:

Name Type Description Default
configuration Dict[str, Any]

The value to set.

required
Source code in src/zenml/models/v2/core/event_source.py
217
218
219
220
221
222
223
def set_configuration(self, configuration: Dict[str, Any]) -> None:
    """Set the `configuration` property.

    Args:
        configuration: The value to set.
    """
    self.get_metadata().configuration = configuration
EventSourceResponseBody

Bases: ProjectScopedResponseBody

ResponseBody for event sources.

EventSourceResponseMetadata

Bases: ProjectScopedResponseMetadata

Response metadata for event sources.

EventSourceResponseResources

Bases: ProjectScopedResponseResources

Class for all resource models associated with the code repository entity.

EventSourceUpdate

Bases: BaseUpdate

Update model for event sources.

Functions
from_response(response: EventSourceResponse) -> EventSourceUpdate classmethod

Create an update model from a response model.

Parameters:

Name Type Description Default
response EventSourceResponse

The response model to create the update model from.

required

Returns:

Type Description
EventSourceUpdate

The update model.

Source code in src/zenml/models/v2/core/event_source.py
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
@classmethod
def from_response(
    cls, response: "EventSourceResponse"
) -> "EventSourceUpdate":
    """Create an update model from a response model.

    Args:
        response: The response model to create the update model from.

    Returns:
        The update model.
    """
    return EventSourceUpdate(
        name=response.name,
        description=response.description,
        configuration=copy.deepcopy(response.configuration),
        is_active=response.is_active,
    )
ExternalArtifact

Bases: ExternalArtifactConfiguration

External artifacts can be used to provide values as input to ZenML steps.

ZenML steps accept either artifacts (=outputs of other steps), parameters (raw, JSON serializable values) or external artifacts. External artifacts can be used to provide any value as input to a step without needing to write an additional step that returns this value.

The external artifact needs to have a value associated with it that will be uploaded to the artifact store.

Parameters:

Name Type Description Default
value

The artifact value.

required
materializer

The materializer to use for saving the artifact value to the artifact store. Only used when value is provided.

required
store_artifact_metadata

Whether metadata for the artifact should be stored. Only used when value is provided.

required
store_artifact_visualizations

Whether visualizations for the artifact should be stored. Only used when value is provided.

required

Example:

from zenml import step, pipeline
from zenml.artifacts.external_artifact import ExternalArtifact
import numpy as np

@step
def my_step(value: np.ndarray) -> None:
  print(value)

my_array = np.array([1, 2, 3])

@pipeline
def my_pipeline():
  my_step(value=ExternalArtifact(my_array))
Attributes
config: ExternalArtifactConfiguration property

Returns the lightweight config without hard for JSON properties.

Returns:

Type Description
ExternalArtifactConfiguration

The config object to be evaluated in runtime by step interface.

Functions
external_artifact_validator() -> ExternalArtifact

Model validator for the external artifact.

Raises:

Type Description
ValueError

If an ID was set.

Returns:

Type Description
ExternalArtifact

The validated instance.

Source code in src/zenml/artifacts/external_artifact.py
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
@model_validator(mode="after")
def external_artifact_validator(self) -> "ExternalArtifact":
    """Model validator for the external artifact.

    Raises:
        ValueError: If an ID was set.

    Returns:
        The validated instance.
    """
    if self.id:
        raise ValueError(
            "External artifacts can only be initialized with a value."
        )

    return self
upload_by_value() -> UUID

Uploads the artifact by value.

Returns:

Type Description
UUID

The uploaded artifact ID.

Source code in src/zenml/artifacts/external_artifact.py
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
def upload_by_value(self) -> UUID:
    """Uploads the artifact by value.

    Returns:
        The uploaded artifact ID.
    """
    from zenml.artifacts.utils import save_artifact

    artifact_name = f"external_{uuid4()}"
    uri = os.path.join("external_artifacts", artifact_name)
    logger.info("Uploading external artifact to '%s'.", uri)

    artifact = save_artifact(
        name=artifact_name,
        data=self.value,
        extract_metadata=self.store_artifact_metadata,
        include_visualizations=self.store_artifact_visualizations,
        materializer=self.materializer,
        uri=uri,
        has_custom_name=False,
        save_type=ArtifactSaveType.EXTERNAL,
    )

    # To avoid duplicate uploads, switch to referencing the uploaded
    # artifact by ID
    self.id = artifact.id
    self.value = None

    logger.info("Finished uploading external artifact %s.", self.id)
    return self.id
ExternalUserModel

Bases: BaseModel

External user model.

FlavorFilter

Bases: UserScopedFilter

Model to enable advanced stack component flavor filtering.

FlavorRequest

Bases: UserScopedRequest

Request model for stack component flavors.

FlavorResponse

Bases: UserScopedResponse[FlavorResponseBody, FlavorResponseMetadata, FlavorResponseResources]

Response model for stack component flavors.

Attributes
config_schema: Dict[str, Any] property

The config_schema property.

Returns:

Type Description
Dict[str, Any]

the value of the property.

connector_requirements: Optional[ServiceConnectorRequirements] property

Returns the connector requirements for the flavor.

Returns:

Type Description
Optional[ServiceConnectorRequirements]

The connector requirements for the flavor.

connector_resource_id_attr: Optional[str] property

The connector_resource_id_attr property.

Returns:

Type Description
Optional[str]

the value of the property.

connector_resource_type: Optional[str] property

The connector_resource_type property.

Returns:

Type Description
Optional[str]

the value of the property.

connector_type: Optional[str] property

The connector_type property.

Returns:

Type Description
Optional[str]

the value of the property.

docs_url: Optional[str] property

The docs_url property.

Returns:

Type Description
Optional[str]

the value of the property.

integration: Optional[str] property

The integration property.

Returns:

Type Description
Optional[str]

the value of the property.

is_custom: bool property

The is_custom property.

Returns:

Type Description
bool

the value of the property.

logo_url: Optional[str] property

The logo_url property.

Returns:

Type Description
Optional[str]

the value of the property.

sdk_docs_url: Optional[str] property

The sdk_docs_url property.

Returns:

Type Description
Optional[str]

the value of the property.

source: str property

The source property.

Returns:

Type Description
str

the value of the property.

type: StackComponentType property

The type property.

Returns:

Type Description
StackComponentType

the value of the property.

Functions
get_hydrated_version() -> FlavorResponse

Get the hydrated version of the flavor.

Returns:

Type Description
FlavorResponse

an instance of the same entity with the metadata field attached.

Source code in src/zenml/models/v2/core/flavor.py
251
252
253
254
255
256
257
258
259
def get_hydrated_version(self) -> "FlavorResponse":
    """Get the hydrated version of the flavor.

    Returns:
        an instance of the same entity with the metadata field attached.
    """
    from zenml.client import Client

    return Client().zen_store.get_flavor(self.id)
FlavorResponseBody

Bases: UserScopedResponseBody

Response body for stack component flavors.

FlavorResponseMetadata

Bases: UserScopedResponseMetadata

Response metadata for stack component flavors.

FlavorUpdate

Bases: BaseUpdate

Update model for stack component flavors.

LoadedVisualization

Bases: BaseModel

Model for loaded visualizations.

LogsRequest

Bases: BaseRequest

Request model for logs.

Functions
str_field_max_length_check(value: Any) -> Any classmethod

Checks if the length of the value exceeds the maximum text length.

Parameters:

Name Type Description Default
value Any

the value set in the field

required

Returns:

Type Description
Any

the value itself.

Raises:

Type Description
AssertionError

if the length of the field is longer than the maximum threshold.

Source code in src/zenml/models/v2/core/logs.py
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
@field_validator("artifact_store_id")
@classmethod
def str_field_max_length_check(cls, value: Any) -> Any:
    """Checks if the length of the value exceeds the maximum text length.

    Args:
        value: the value set in the field

    Returns:
        the value itself.

    Raises:
        AssertionError: if the length of the field is longer than the
            maximum threshold.
    """
    assert len(str(value)) < STR_FIELD_MAX_LENGTH, (
        "The length of the value for this field can not "
        f"exceed {STR_FIELD_MAX_LENGTH}"
    )
    return value
text_field_max_length_check(value: Any) -> Any classmethod

Checks if the length of the value exceeds the maximum text length.

Parameters:

Name Type Description Default
value Any

the value set in the field

required

Returns:

Type Description
Any

the value itself.

Raises:

Type Description
AssertionError

if the length of the field is longer than the maximum threshold.

Source code in src/zenml/models/v2/core/logs.py
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
@field_validator("uri")
@classmethod
def text_field_max_length_check(cls, value: Any) -> Any:
    """Checks if the length of the value exceeds the maximum text length.

    Args:
        value: the value set in the field

    Returns:
        the value itself.

    Raises:
        AssertionError: if the length of the field is longer than the
            maximum threshold.
    """
    assert len(str(value)) < TEXT_FIELD_MAX_LENGTH, (
        "The length of the value for this field can not "
        f"exceed {TEXT_FIELD_MAX_LENGTH}"
    )
    return value
LogsResponse

Bases: BaseIdentifiedResponse[LogsResponseBody, LogsResponseMetadata, LogsResponseResources]

Response model for logs.

Attributes
artifact_store_id: Union[str, UUID] property

The artifact_store_id property.

Returns:

Type Description
Union[str, UUID]

the value of the property.

pipeline_run_id: Optional[Union[str, UUID]] property

The pipeline_run_id property.

Returns:

Type Description
Optional[Union[str, UUID]]

the value of the property.

step_run_id: Optional[Union[str, UUID]] property

The step_run_id property.

Returns:

Type Description
Optional[Union[str, UUID]]

the value of the property.

uri: str property

The uri property.

Returns:

Type Description
str

the value of the property.

Functions
get_hydrated_version() -> LogsResponse

Get the hydrated version of these logs.

Returns:

Type Description
LogsResponse

an instance of the same entity with the metadata field attached.

Source code in src/zenml/models/v2/core/logs.py
151
152
153
154
155
156
157
158
159
def get_hydrated_version(self) -> "LogsResponse":
    """Get the hydrated version of these logs.

    Returns:
        an instance of the same entity with the metadata field attached.
    """
    from zenml.client import Client

    return Client().zen_store.get_logs(self.id)
LogsResponseBody

Bases: BaseDatedResponseBody

Response body for logs.

LogsResponseMetadata

Bases: BaseResponseMetadata

Response metadata for logs.

Functions
str_field_max_length_check(value: Any) -> Any classmethod

Checks if the length of the value exceeds the maximum text length.

Parameters:

Name Type Description Default
value Any

the value set in the field

required

Returns:

Type Description
Any

the value itself.

Raises:

Type Description
AssertionError

if the length of the field is longer than the maximum threshold.

Source code in src/zenml/models/v2/core/logs.py
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
@field_validator("artifact_store_id")
@classmethod
def str_field_max_length_check(cls, value: Any) -> Any:
    """Checks if the length of the value exceeds the maximum text length.

    Args:
        value: the value set in the field

    Returns:
        the value itself.

    Raises:
        AssertionError: if the length of the field is longer than the
            maximum threshold.
    """
    assert len(str(value)) < STR_FIELD_MAX_LENGTH
    return value
Model

Bases: BaseModel

Model class to pass into pipeline or step to set it into a model context.

name: The name of the model. license: The license under which the model is created. description: The description of the model. audience: The target audience of the model. use_cases: The use cases of the model. limitations: The known limitations of the model. trade_offs: The tradeoffs of the model. ethics: The ethical implications of the model. tags: Tags associated with the model. version: The version name, version number or stage is optional and points model context to a specific version/stage. If skipped new version will be created. version also supports placeholders: standard {date} and {time} and any custom placeholders that are passed as substitutions in the pipeline or step decorators. save_models_to_registry: Whether to save all ModelArtifacts to Model Registry, if available in active stack.

Attributes
id: UUID property

Get version id from the Model Control Plane.

Returns:

Type Description
UUID

ID of the model version or None, if model version doesn't exist and can only be read given current config (you used stage name or number as a version name).

Raises:

Type Description
RuntimeError

if model version doesn't exist and cannot be fetched from the Model Control Plane.

model_id: UUID property

Get model id from the Model Control Plane.

Returns:

Type Description
UUID

The UUID of the model containing this model version.

number: int property

Get version number from the Model Control Plane.

Returns:

Type Description
int

Number of the model version or None, if model version doesn't exist and can only be read given current config (you used stage name or number as a version name).

Raises:

Type Description
KeyError

if model version doesn't exist and cannot be fetched from the Model Control Plane.

run_metadata: Dict[str, MetadataType] property

Get model version run metadata.

Returns:

Type Description
Dict[str, MetadataType]

The model version run metadata.

Raises:

Type Description
RuntimeError

If the model version run metadata cannot be fetched.

stage: Optional[ModelStages] property

Get version stage from the Model Control Plane.

Returns:

Type Description
Optional[ModelStages]

Stage of the model version or None, if model version doesn't exist and can only be read given current config (you used stage name or number as a version name).

Functions
delete_all_artifacts(only_link: bool = True, delete_from_artifact_store: bool = False) -> None

Delete all artifacts linked to this model version.

Parameters:

Name Type Description Default
only_link bool

Whether to only delete the link to the artifact.

True
delete_from_artifact_store bool

Whether to delete the artifact from the artifact store.

False
Source code in src/zenml/model/model.py
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
def delete_all_artifacts(
    self,
    only_link: bool = True,
    delete_from_artifact_store: bool = False,
) -> None:
    """Delete all artifacts linked to this model version.

    Args:
        only_link: Whether to only delete the link to the artifact.
        delete_from_artifact_store: Whether to delete the artifact from
            the artifact store.
    """
    from zenml.client import Client

    client = Client()

    if not only_link and delete_from_artifact_store:
        mv = self._get_model_version()
        artifact_responses = mv.data_artifacts
        artifact_responses.update(mv.model_artifacts)
        artifact_responses.update(mv.deployment_artifacts)

        for artifact_ in artifact_responses.values():
            for artifact_response_ in artifact_.values():
                client._delete_artifact_from_artifact_store(
                    artifact_version=artifact_response_
                )

    client.delete_all_model_version_artifact_links(self.id, only_link)
delete_artifact(name: str, version: Optional[str] = None, only_link: bool = True, delete_metadata: bool = True, delete_from_artifact_store: bool = False) -> None

Delete the artifact linked to this model version.

Parameters:

Name Type Description Default
name str

The name of the artifact to delete.

required
version Optional[str]

The version of the artifact to delete (None for latest/non-versioned)

None
only_link bool

Whether to only delete the link to the artifact.

True
delete_metadata bool

Whether to delete the metadata of the artifact.

True
delete_from_artifact_store bool

Whether to delete the artifact from the artifact store.

False
Source code in src/zenml/model/model.py
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
def delete_artifact(
    self,
    name: str,
    version: Optional[str] = None,
    only_link: bool = True,
    delete_metadata: bool = True,
    delete_from_artifact_store: bool = False,
) -> None:
    """Delete the artifact linked to this model version.

    Args:
        name: The name of the artifact to delete.
        version: The version of the artifact to delete (None for
            latest/non-versioned)
        only_link: Whether to only delete the link to the artifact.
        delete_metadata: Whether to delete the metadata of the artifact.
        delete_from_artifact_store: Whether to delete the artifact from the
            artifact store.
    """
    from zenml.client import Client
    from zenml.models import ArtifactVersionResponse

    artifact_version = self.get_artifact(name, version)
    if isinstance(artifact_version, ArtifactVersionResponse):
        client = Client()
        client.delete_model_version_artifact_link(
            model_version_id=self.id,
            artifact_version_id=artifact_version.id,
        )
        if not only_link:
            client.delete_artifact_version(
                name_id_or_prefix=artifact_version.id,
                delete_metadata=delete_metadata,
                delete_from_artifact_store=delete_from_artifact_store,
            )
get_artifact(name: str, version: Optional[str] = None) -> Optional[ArtifactVersionResponse]

Get the artifact linked to this model version.

Parameters:

Name Type Description Default
name str

The name of the artifact to retrieve.

required
version Optional[str]

The version of the artifact to retrieve (None for latest/non-versioned)

None

Returns:

Type Description
Optional[ArtifactVersionResponse]

Specific version of the artifact or placeholder in the design time of the pipeline.

Source code in src/zenml/model/model.py
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
def get_artifact(
    self,
    name: str,
    version: Optional[str] = None,
) -> Optional["ArtifactVersionResponse"]:
    """Get the artifact linked to this model version.

    Args:
        name: The name of the artifact to retrieve.
        version: The version of the artifact to retrieve (None for
            latest/non-versioned)

    Returns:
        Specific version of the artifact or placeholder in the design time
            of the pipeline.
    """
    if lazy := self._lazy_artifact_get(name, version):
        return lazy

    return self._get_or_create_model_version().get_artifact(
        name=name,
        version=version,
    )
get_data_artifact(name: str, version: Optional[str] = None) -> Optional[ArtifactVersionResponse]

Get the data artifact linked to this model version.

Parameters:

Name Type Description Default
name str

The name of the data artifact to retrieve.

required
version Optional[str]

The version of the data artifact to retrieve (None for latest/non-versioned)

None

Returns:

Type Description
Optional[ArtifactVersionResponse]

Specific version of the data artifact or placeholder in the design

Optional[ArtifactVersionResponse]

time of the pipeline.

Source code in src/zenml/model/model.py
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
def get_data_artifact(
    self,
    name: str,
    version: Optional[str] = None,
) -> Optional["ArtifactVersionResponse"]:
    """Get the data artifact linked to this model version.

    Args:
        name: The name of the data artifact to retrieve.
        version: The version of the data artifact to retrieve (None for
            latest/non-versioned)

    Returns:
        Specific version of the data artifact or placeholder in the design
        time of the pipeline.
    """
    if lazy := self._lazy_artifact_get(name, version):
        return lazy

    return self._get_or_create_model_version().get_data_artifact(
        name=name,
        version=version,
    )
get_deployment_artifact(name: str, version: Optional[str] = None) -> Optional[ArtifactVersionResponse]

Get the deployment artifact linked to this model version.

Parameters:

Name Type Description Default
name str

The name of the deployment artifact to retrieve.

required
version Optional[str]

The version of the deployment artifact to retrieve (None for latest/non-versioned)

None

Returns:

Type Description
Optional[ArtifactVersionResponse]

Specific version of the deployment artifact or placeholder in the

Optional[ArtifactVersionResponse]

design time of the pipeline.

Source code in src/zenml/model/model.py
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
def get_deployment_artifact(
    self,
    name: str,
    version: Optional[str] = None,
) -> Optional["ArtifactVersionResponse"]:
    """Get the deployment artifact linked to this model version.

    Args:
        name: The name of the deployment artifact to retrieve.
        version: The version of the deployment artifact to retrieve (None
            for latest/non-versioned)

    Returns:
        Specific version of the deployment artifact or placeholder in the
        design time of the pipeline.
    """
    if lazy := self._lazy_artifact_get(name, version):
        return lazy

    return self._get_or_create_model_version().get_deployment_artifact(
        name=name,
        version=version,
    )
get_model_artifact(name: str, version: Optional[str] = None) -> Optional[ArtifactVersionResponse]

Get the model artifact linked to this model version.

Parameters:

Name Type Description Default
name str

The name of the model artifact to retrieve.

required
version Optional[str]

The version of the model artifact to retrieve (None for latest/non-versioned)

None

Returns:

Type Description
Optional[ArtifactVersionResponse]

Specific version of the model artifact or placeholder in the design time of the pipeline.

Source code in src/zenml/model/model.py
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
def get_model_artifact(
    self,
    name: str,
    version: Optional[str] = None,
) -> Optional["ArtifactVersionResponse"]:
    """Get the model artifact linked to this model version.

    Args:
        name: The name of the model artifact to retrieve.
        version: The version of the model artifact to retrieve (None for
            latest/non-versioned)

    Returns:
        Specific version of the model artifact or placeholder in the design
            time of the pipeline.
    """
    if lazy := self._lazy_artifact_get(name, version):
        return lazy

    return self._get_or_create_model_version().get_model_artifact(
        name=name,
        version=version,
    )
get_pipeline_run(name: str) -> PipelineRunResponse

Get pipeline run linked to this version.

Parameters:

Name Type Description Default
name str

The name of the pipeline run to retrieve.

required

Returns:

Type Description
PipelineRunResponse

PipelineRun as PipelineRunResponse

Source code in src/zenml/model/model.py
306
307
308
309
310
311
312
313
314
315
def get_pipeline_run(self, name: str) -> "PipelineRunResponse":
    """Get pipeline run linked to this version.

    Args:
        name: The name of the pipeline run to retrieve.

    Returns:
        PipelineRun as PipelineRunResponse
    """
    return self._get_or_create_model_version().get_pipeline_run(name=name)
load_artifact(name: str, version: Optional[str] = None) -> Any

Load artifact from the Model Control Plane.

Parameters:

Name Type Description Default
name str

Name of the artifact to load.

required
version Optional[str]

Version of the artifact to load.

None

Returns:

Type Description
Any

The loaded artifact.

Raises:

Type Description
ValueError

if the model version is not linked to any artifact with the given name and version.

Source code in src/zenml/model/model.py
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
def load_artifact(self, name: str, version: Optional[str] = None) -> Any:
    """Load artifact from the Model Control Plane.

    Args:
        name: Name of the artifact to load.
        version: Version of the artifact to load.

    Returns:
        The loaded artifact.

    Raises:
        ValueError: if the model version is not linked to any artifact with
            the given name and version.
    """
    from zenml.artifacts.utils import load_artifact
    from zenml.models import ArtifactVersionResponse

    artifact = self.get_artifact(name=name, version=version)

    if not isinstance(artifact, ArtifactVersionResponse):
        raise ValueError(
            f"Version {self.version} of model {self.name} does not have "
            f"an artifact with name {name} and version {version}."
        )

    return load_artifact(artifact.id, str(artifact.version))
log_metadata(metadata: Dict[str, MetadataType]) -> None

Log model version metadata.

This function can be used to log metadata for current model version.

Parameters:

Name Type Description Default
metadata Dict[str, MetadataType]

The metadata to log.

required
Source code in src/zenml/model/model.py
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
def log_metadata(
    self,
    metadata: Dict[str, "MetadataType"],
) -> None:
    """Log model version metadata.

    This function can be used to log metadata for current model version.

    Args:
        metadata: The metadata to log.
    """
    from zenml.client import Client
    from zenml.models import RunMetadataResource

    response = self._get_or_create_model_version()
    Client().create_run_metadata(
        metadata=metadata,
        resources=[
            RunMetadataResource(
                id=response.id, type=MetadataResourceTypes.MODEL_VERSION
            )
        ],
    )
set_stage(stage: Union[str, ModelStages], force: bool = False) -> None

Sets this Model to a desired stage.

Parameters:

Name Type Description Default
stage Union[str, ModelStages]

the target stage for model version.

required
force bool

whether to force archiving of current model version in target stage or raise.

False
Source code in src/zenml/model/model.py
317
318
319
320
321
322
323
324
325
326
327
def set_stage(
    self, stage: Union[str, ModelStages], force: bool = False
) -> None:
    """Sets this Model to a desired stage.

    Args:
        stage: the target stage for model version.
        force: whether to force archiving of current model version in
            target stage or raise.
    """
    self._get_or_create_model_version().set_stage(stage=stage, force=force)
ModelFilter

Bases: ProjectScopedFilter, TaggableFilter

Model to enable advanced filtering of all models.

Functions
apply_sorting(query: AnyQuery, table: Type[AnySchema]) -> AnyQuery

Apply sorting to the query for Models.

Parameters:

Name Type Description Default
query AnyQuery

The query to which to apply the sorting.

required
table Type[AnySchema]

The query table.

required

Returns:

Type Description
AnyQuery

The query with sorting applied.

Source code in src/zenml/models/v2/core/model.py
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
def apply_sorting(
    self,
    query: AnyQuery,
    table: Type["AnySchema"],
) -> AnyQuery:
    """Apply sorting to the query for Models.

    Args:
        query: The query to which to apply the sorting.
        table: The query table.

    Returns:
        The query with sorting applied.
    """
    from sqlmodel import asc, case, col, desc, func, select

    from zenml.enums import SorterOps
    from zenml.zen_stores.schemas import (
        ModelSchema,
        ModelVersionSchema,
    )

    sort_by, operand = self.sorting_params

    if sort_by == SORT_BY_LATEST_VERSION_KEY:
        # Subquery to find the latest version per model
        latest_version_subquery = (
            select(
                ModelSchema.id,
                case(
                    (
                        func.max(ModelVersionSchema.created).is_(None),
                        ModelSchema.created,
                    ),
                    else_=func.max(ModelVersionSchema.created),
                ).label("latest_version_created"),
            )
            .outerjoin(
                ModelVersionSchema,
                ModelSchema.id == ModelVersionSchema.model_id,  # type: ignore[arg-type]
            )
            .group_by(col(ModelSchema.id))
            .subquery()
        )

        query = query.add_columns(
            latest_version_subquery.c.latest_version_created,
        ).where(ModelSchema.id == latest_version_subquery.c.id)

        # Apply sorting based on the operand
        if operand == SorterOps.ASCENDING:
            query = query.order_by(
                asc(latest_version_subquery.c.latest_version_created),
                asc(ModelSchema.id),
            )
        else:
            query = query.order_by(
                desc(latest_version_subquery.c.latest_version_created),
                desc(ModelSchema.id),
            )
        return query

    # For other sorting cases, delegate to the parent class
    return super().apply_sorting(query=query, table=table)
ModelRequest

Bases: ProjectScopedRequest

Request model for models.

ModelResponse

Bases: ProjectScopedResponse[ModelResponseBody, ModelResponseMetadata, ModelResponseResources]

Response model for models.

Attributes
audience: Optional[str] property

The audience property.

Returns:

Type Description
Optional[str]

the value of the property.

description: Optional[str] property

The description property.

Returns:

Type Description
Optional[str]

the value of the property.

ethics: Optional[str] property

The ethics property.

Returns:

Type Description
Optional[str]

the value of the property.

latest_version_id: Optional[UUID] property

The latest_version_id property.

Returns:

Type Description
Optional[UUID]

the value of the property.

latest_version_name: Optional[str] property

The latest_version_name property.

Returns:

Type Description
Optional[str]

the value of the property.

license: Optional[str] property

The license property.

Returns:

Type Description
Optional[str]

the value of the property.

limitations: Optional[str] property

The limitations property.

Returns:

Type Description
Optional[str]

the value of the property.

save_models_to_registry: bool property

The save_models_to_registry property.

Returns:

Type Description
bool

the value of the property.

tags: List[TagResponse] property

The tags property.

Returns:

Type Description
List[TagResponse]

the value of the property.

trade_offs: Optional[str] property

The trade_offs property.

Returns:

Type Description
Optional[str]

the value of the property.

use_cases: Optional[str] property

The use_cases property.

Returns:

Type Description
Optional[str]

the value of the property.

versions: List[Model] property

List all versions of the model.

Returns:

Type Description
List[Model]

The list of all model version.

Functions
get_hydrated_version() -> ModelResponse

Get the hydrated version of this model.

Returns:

Type Description
ModelResponse

an instance of the same entity with the metadata field attached.

Source code in src/zenml/models/v2/core/model.py
202
203
204
205
206
207
208
209
210
def get_hydrated_version(self) -> "ModelResponse":
    """Get the hydrated version of this model.

    Returns:
        an instance of the same entity with the metadata field attached.
    """
    from zenml.client import Client

    return Client().zen_store.get_model(self.id)
ModelResponseBody

Bases: ProjectScopedResponseBody

Response body for models.

ModelResponseMetadata

Bases: ProjectScopedResponseMetadata

Response metadata for models.

ModelUpdate

Bases: BaseUpdate

Update model for models.

ModelVersionArtifactFilter

Bases: BaseFilter

Model version pipeline run links filter model.

Functions
get_custom_filters(table: Type[AnySchema]) -> List[Union[ColumnElement[bool]]]

Get custom filters.

Parameters:

Name Type Description Default
table Type[AnySchema]

The query table.

required

Returns:

Type Description
List[Union[ColumnElement[bool]]]

A list of custom filters.

Source code in src/zenml/models/v2/core/model_version_artifact.py
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
def get_custom_filters(
    self, table: Type["AnySchema"]
) -> List[Union["ColumnElement[bool]"]]:
    """Get custom filters.

    Args:
        table: The query table.

    Returns:
        A list of custom filters.
    """
    custom_filters = super().get_custom_filters(table)

    from sqlmodel import and_, col

    from zenml.zen_stores.schemas import (
        ArtifactSchema,
        ArtifactVersionSchema,
        ModelVersionArtifactSchema,
        UserSchema,
    )

    if self.artifact_name:
        value, filter_operator = self._resolve_operator(self.artifact_name)
        filter_ = StrFilter(
            operation=GenericFilterOps(filter_operator),
            column="name",
            value=value,
        )
        artifact_name_filter = and_(
            ModelVersionArtifactSchema.artifact_version_id
            == ArtifactVersionSchema.id,
            ArtifactVersionSchema.artifact_id == ArtifactSchema.id,
            filter_.generate_query_conditions(ArtifactSchema),
        )
        custom_filters.append(artifact_name_filter)

    if self.only_data_artifacts:
        data_artifact_filter = and_(
            ModelVersionArtifactSchema.artifact_version_id
            == ArtifactVersionSchema.id,
            col(ArtifactVersionSchema.type).not_in(
                ["ServiceArtifact", "ModelArtifact"]
            ),
        )
        custom_filters.append(data_artifact_filter)

    if self.only_model_artifacts:
        model_artifact_filter = and_(
            ModelVersionArtifactSchema.artifact_version_id
            == ArtifactVersionSchema.id,
            ArtifactVersionSchema.type == "ModelArtifact",
        )
        custom_filters.append(model_artifact_filter)

    if self.only_deployment_artifacts:
        deployment_artifact_filter = and_(
            ModelVersionArtifactSchema.artifact_version_id
            == ArtifactVersionSchema.id,
            ArtifactVersionSchema.type == "ServiceArtifact",
        )
        custom_filters.append(deployment_artifact_filter)

    if self.has_custom_name is not None:
        custom_name_filter = and_(
            ModelVersionArtifactSchema.artifact_version_id
            == ArtifactVersionSchema.id,
            ArtifactVersionSchema.artifact_id == ArtifactSchema.id,
            ArtifactSchema.has_custom_name == self.has_custom_name,
        )
        custom_filters.append(custom_name_filter)

    if self.user:
        user_filter = and_(
            ModelVersionArtifactSchema.artifact_version_id
            == ArtifactVersionSchema.id,
            ArtifactVersionSchema.user_id == UserSchema.id,
            self.generate_name_or_id_query_conditions(
                value=self.user,
                table=UserSchema,
                additional_columns=["full_name"],
            ),
        )
        custom_filters.append(user_filter)

    return custom_filters
ModelVersionArtifactRequest

Bases: BaseRequest

Request model for links between model versions and artifacts.

ModelVersionArtifactResponse

Bases: BaseIdentifiedResponse[ModelVersionArtifactResponseBody, BaseResponseMetadata, ModelVersionArtifactResponseResources]

Response model for links between model versions and artifacts.

Attributes
artifact_version: ArtifactVersionResponse property

The artifact_version property.

Returns:

Type Description
ArtifactVersionResponse

the value of the property.

model_version: UUID property

The model_version property.

Returns:

Type Description
UUID

the value of the property.

ModelVersionArtifactResponseBody

Bases: BaseDatedResponseBody

Response body for links between model versions and artifacts.

ModelVersionFilter

Bases: ProjectScopedFilter, TaggableFilter, RunMetadataFilterMixin

Filter model for model versions.

Functions
get_custom_filters(table: Type[AnySchema]) -> List[Union[ColumnElement[bool]]]

Get custom filters.

Parameters:

Name Type Description Default
table Type[AnySchema]

The query table.

required

Returns:

Type Description
List[Union[ColumnElement[bool]]]

A list of custom filters.

Source code in src/zenml/models/v2/core/model_version.py
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
def get_custom_filters(
    self, table: Type["AnySchema"]
) -> List[Union["ColumnElement[bool]"]]:
    """Get custom filters.

    Args:
        table: The query table.

    Returns:
        A list of custom filters.
    """
    from sqlalchemy import and_

    from zenml.zen_stores.schemas import (
        ModelSchema,
        ModelVersionSchema,
    )

    custom_filters = super().get_custom_filters(table)

    if self.model:
        value, operator = self._resolve_operator(self.model)
        model_filter = and_(
            ModelVersionSchema.model_id == ModelSchema.id,  # type: ignore[arg-type]
            self.generate_name_or_id_query_conditions(
                value=self.model, table=ModelSchema
            ),
        )
        custom_filters.append(model_filter)

    return custom_filters
ModelVersionPipelineRunFilter

Bases: BaseFilter

Model version pipeline run links filter model.

Functions
get_custom_filters(table: Type[AnySchema]) -> List[ColumnElement[bool]]

Get custom filters.

Parameters:

Name Type Description Default
table Type[AnySchema]

The query table.

required

Returns:

Type Description
List[ColumnElement[bool]]

A list of custom filters.

Source code in src/zenml/models/v2/core/model_version_pipeline_run.py
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
def get_custom_filters(
    self, table: Type["AnySchema"]
) -> List["ColumnElement[bool]"]:
    """Get custom filters.

    Args:
        table: The query table.

    Returns:
        A list of custom filters.
    """
    custom_filters = super().get_custom_filters(table)

    from sqlmodel import and_

    from zenml.zen_stores.schemas import (
        ModelVersionPipelineRunSchema,
        PipelineRunSchema,
        UserSchema,
    )

    if self.pipeline_run_name:
        value, filter_operator = self._resolve_operator(
            self.pipeline_run_name
        )
        filter_ = StrFilter(
            operation=GenericFilterOps(filter_operator),
            column="name",
            value=value,
        )
        pipeline_run_name_filter = and_(
            ModelVersionPipelineRunSchema.pipeline_run_id
            == PipelineRunSchema.id,
            filter_.generate_query_conditions(PipelineRunSchema),
        )
        custom_filters.append(pipeline_run_name_filter)

    if self.user:
        user_filter = and_(
            ModelVersionPipelineRunSchema.pipeline_run_id
            == PipelineRunSchema.id,
            PipelineRunSchema.user_id == UserSchema.id,
            self.generate_name_or_id_query_conditions(
                value=self.user,
                table=UserSchema,
                additional_columns=["full_name"],
            ),
        )
        custom_filters.append(user_filter)

    return custom_filters
ModelVersionPipelineRunRequest

Bases: BaseRequest

Request model for links between model versions and pipeline runs.

ModelVersionPipelineRunResponse

Bases: BaseIdentifiedResponse[ModelVersionPipelineRunResponseBody, BaseResponseMetadata, ModelVersionPipelineRunResponseResources]

Response model for links between model versions and pipeline runs.

Attributes
model_version: UUID property

The model_version property.

Returns:

Type Description
UUID

the value of the property.

pipeline_run: PipelineRunResponse property

The pipeline_run property.

Returns:

Type Description
PipelineRunResponse

the value of the property.

ModelVersionPipelineRunResponseBody

Bases: BaseDatedResponseBody

Response body for links between model versions and pipeline runs.

ModelVersionRequest

Bases: ProjectScopedRequest

Request model for model versions.

ModelVersionResponse

Bases: ProjectScopedResponse[ModelVersionResponseBody, ModelVersionResponseMetadata, ModelVersionResponseResources]

Response model for model versions.

Attributes
data_artifact_ids: Dict[str, Dict[str, UUID]] property

The data_artifact_ids property.

Returns:

Type Description
Dict[str, Dict[str, UUID]]

the value of the property.

data_artifacts: Dict[str, Dict[str, ArtifactVersionResponse]] property

Get all data artifacts linked to this model version.

Returns:

Type Description
Dict[str, Dict[str, ArtifactVersionResponse]]

Dictionary of data artifacts with versions as

Dict[str, Dict[str, ArtifactVersionResponse]]

Dict[str, Dict[str, ArtifactResponse]]

deployment_artifact_ids: Dict[str, Dict[str, UUID]] property

The deployment_artifact_ids property.

Returns:

Type Description
Dict[str, Dict[str, UUID]]

the value of the property.

deployment_artifacts: Dict[str, Dict[str, ArtifactVersionResponse]] property

Get all deployment artifacts linked to this model version.

Returns:

Type Description
Dict[str, Dict[str, ArtifactVersionResponse]]

Dictionary of deployment artifacts with versions as

Dict[str, Dict[str, ArtifactVersionResponse]]

Dict[str, Dict[str, ArtifactResponse]]

description: Optional[str] property

The description property.

Returns:

Type Description
Optional[str]

the value of the property.

model: ModelResponse property

The model property.

Returns:

Type Description
ModelResponse

the value of the property.

model_artifact_ids: Dict[str, Dict[str, UUID]] property

The model_artifact_ids property.

Returns:

Type Description
Dict[str, Dict[str, UUID]]

the value of the property.

model_artifacts: Dict[str, Dict[str, ArtifactVersionResponse]] property

Get all model artifacts linked to this model version.

Returns:

Type Description
Dict[str, Dict[str, ArtifactVersionResponse]]

Dictionary of model artifacts with versions as

Dict[str, Dict[str, ArtifactVersionResponse]]

Dict[str, Dict[str, ArtifactResponse]]

number: int property

The number property.

Returns:

Type Description
int

the value of the property.

pipeline_run_ids: Dict[str, UUID] property

The pipeline_run_ids property.

Returns:

Type Description
Dict[str, UUID]

the value of the property.

pipeline_runs: Dict[str, PipelineRunResponse] property

Get all pipeline runs linked to this version.

Returns:

Type Description
Dict[str, PipelineRunResponse]

Dictionary of Pipeline Runs as PipelineRunResponseModel

run_metadata: Dict[str, MetadataType] property

The run_metadata property.

Returns:

Type Description
Dict[str, MetadataType]

the value of the property.

stage: Optional[str] property

The stage property.

Returns:

Type Description
Optional[str]

the value of the property.

tags: List[TagResponse] property

The tags property.

Returns:

Type Description
List[TagResponse]

the value of the property.

Functions
get_artifact(name: str, version: Optional[str] = None) -> Optional[ArtifactVersionResponse]

Get the artifact linked to this model version.

Parameters:

Name Type Description Default
name str

The name of the artifact to retrieve.

required
version Optional[str]

The version of the artifact to retrieve (None for latest/non-versioned)

None

Returns:

Type Description
Optional[ArtifactVersionResponse]

Specific version of an artifact or None

Source code in src/zenml/models/v2/core/model_version.py
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
def get_artifact(
    self,
    name: str,
    version: Optional[str] = None,
) -> Optional["ArtifactVersionResponse"]:
    """Get the artifact linked to this model version.

    Args:
        name: The name of the artifact to retrieve.
        version: The version of the artifact to retrieve (None for
            latest/non-versioned)

    Returns:
        Specific version of an artifact or None
    """
    return self._get_linked_object(name, version)
get_data_artifact(name: str, version: Optional[str] = None) -> Optional[ArtifactVersionResponse]

Get the data artifact linked to this model version.

Parameters:

Name Type Description Default
name str

The name of the data artifact to retrieve.

required
version Optional[str]

The version of the data artifact to retrieve (None for latest/non-versioned)

None

Returns:

Type Description
Optional[ArtifactVersionResponse]

Specific version of the data artifact or None

Source code in src/zenml/models/v2/core/model_version.py
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
def get_data_artifact(
    self,
    name: str,
    version: Optional[str] = None,
) -> Optional["ArtifactVersionResponse"]:
    """Get the data artifact linked to this model version.

    Args:
        name: The name of the data artifact to retrieve.
        version: The version of the data artifact to retrieve (None for
            latest/non-versioned)

    Returns:
        Specific version of the data artifact or None
    """
    return self._get_linked_object(name, version, ArtifactType.DATA)
get_deployment_artifact(name: str, version: Optional[str] = None) -> Optional[ArtifactVersionResponse]

Get the deployment artifact linked to this model version.

Parameters:

Name Type Description Default
name str

The name of the deployment artifact to retrieve.

required
version Optional[str]

The version of the deployment artifact to retrieve (None for latest/non-versioned)

None

Returns:

Type Description
Optional[ArtifactVersionResponse]

Specific version of the deployment artifact or None

Source code in src/zenml/models/v2/core/model_version.py
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
def get_deployment_artifact(
    self,
    name: str,
    version: Optional[str] = None,
) -> Optional["ArtifactVersionResponse"]:
    """Get the deployment artifact linked to this model version.

    Args:
        name: The name of the deployment artifact to retrieve.
        version: The version of the deployment artifact to retrieve (None for
            latest/non-versioned)

    Returns:
        Specific version of the deployment artifact or None
    """
    return self._get_linked_object(name, version, ArtifactType.SERVICE)
get_hydrated_version() -> ModelVersionResponse

Get the hydrated version of this model version.

Returns:

Type Description
ModelVersionResponse

an instance of the same entity with the metadata field attached.

Source code in src/zenml/models/v2/core/model_version.py
310
311
312
313
314
315
316
317
318
def get_hydrated_version(self) -> "ModelVersionResponse":
    """Get the hydrated version of this model version.

    Returns:
        an instance of the same entity with the metadata field attached.
    """
    from zenml.client import Client

    return Client().zen_store.get_model_version(self.id)
get_model_artifact(name: str, version: Optional[str] = None) -> Optional[ArtifactVersionResponse]

Get the model artifact linked to this model version.

Parameters:

Name Type Description Default
name str

The name of the model artifact to retrieve.

required
version Optional[str]

The version of the model artifact to retrieve (None for latest/non-versioned)

None

Returns:

Type Description
Optional[ArtifactVersionResponse]

Specific version of the model artifact or None

Source code in src/zenml/models/v2/core/model_version.py
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
def get_model_artifact(
    self,
    name: str,
    version: Optional[str] = None,
) -> Optional["ArtifactVersionResponse"]:
    """Get the model artifact linked to this model version.

    Args:
        name: The name of the model artifact to retrieve.
        version: The version of the model artifact to retrieve (None for
            latest/non-versioned)

    Returns:
        Specific version of the model artifact or None
    """
    return self._get_linked_object(name, version, ArtifactType.MODEL)
get_pipeline_run(name: str) -> PipelineRunResponse

Get pipeline run linked to this version.

Parameters:

Name Type Description Default
name str

The name of the pipeline run to retrieve.

required

Returns:

Type Description
PipelineRunResponse

PipelineRun as PipelineRunResponseModel

Source code in src/zenml/models/v2/core/model_version.py
528
529
530
531
532
533
534
535
536
537
538
539
def get_pipeline_run(self, name: str) -> "PipelineRunResponse":
    """Get pipeline run linked to this version.

    Args:
        name: The name of the pipeline run to retrieve.

    Returns:
        PipelineRun as PipelineRunResponseModel
    """
    from zenml.client import Client

    return Client().get_pipeline_run(self.pipeline_run_ids[name])
set_stage(stage: Union[str, ModelStages], force: bool = False) -> None

Sets this Model Version to a desired stage.

Parameters:

Name Type Description Default
stage Union[str, ModelStages]

the target stage for model version.

required
force bool

whether to force archiving of current model version in target stage or raise.

False

Raises:

Type Description
ValueError

if model_stage is not valid.

Source code in src/zenml/models/v2/core/model_version.py
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
def set_stage(
    self, stage: Union[str, ModelStages], force: bool = False
) -> None:
    """Sets this Model Version to a desired stage.

    Args:
        stage: the target stage for model version.
        force: whether to force archiving of current model version in
            target stage or raise.

    Raises:
        ValueError: if model_stage is not valid.
    """
    from zenml.client import Client

    stage = getattr(stage, "value", stage)
    if stage not in [stage.value for stage in ModelStages]:
        raise ValueError(f"`{stage}` is not a valid model stage.")

    Client().update_model_version(
        model_name_or_id=self.model.id,
        version_name_or_id=self.id,
        stage=stage,
        force=force,
    )
to_model_class(suppress_class_validation_warnings: bool = True) -> Model

Convert response model to Model object.

Parameters:

Name Type Description Default
suppress_class_validation_warnings bool

internally used to suppress repeated warnings.

True

Returns:

Type Description
Model

Model object

Source code in src/zenml/models/v2/core/model_version.py
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
def to_model_class(
    self,
    suppress_class_validation_warnings: bool = True,
) -> "Model":
    """Convert response model to Model object.

    Args:
        suppress_class_validation_warnings: internally used to suppress
            repeated warnings.

    Returns:
        Model object
    """
    from zenml.model.model import Model

    mv = Model(
        name=self.model.name,
        license=self.model.license,
        description=self.description,
        audience=self.model.audience,
        use_cases=self.model.use_cases,
        limitations=self.model.limitations,
        trade_offs=self.model.trade_offs,
        ethics=self.model.ethics,
        tags=[t.name for t in self.tags],
        version=self.name,
        suppress_class_validation_warnings=suppress_class_validation_warnings,
        model_version_id=self.id,
    )

    return mv
ModelVersionResponseBody

Bases: ProjectScopedResponseBody

Response body for model versions.

ModelVersionResponseMetadata

Bases: ProjectScopedResponseMetadata

Response metadata for model versions.

ModelVersionResponseResources

Bases: ProjectScopedResponseResources

Class for all resource models associated with the model version entity.

ModelVersionUpdate

Bases: BaseUpdate

Update model for model versions.

NumericFilter

Bases: Filter

Filter for all numeric fields.

Functions
generate_query_conditions_from_column(column: Any) -> Any

Generate query conditions for a numeric column.

Parameters:

Name Type Description Default
column Any

The numeric column of an SQLModel table on which to filter.

required

Returns:

Type Description
Any

A list of query conditions.

Source code in src/zenml/models/v2/base/filter.py
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
def generate_query_conditions_from_column(self, column: Any) -> Any:
    """Generate query conditions for a numeric column.

    Args:
        column: The numeric column of an SQLModel table on which to filter.

    Returns:
        A list of query conditions.
    """
    if self.operation == GenericFilterOps.GTE:
        return column >= self.value
    if self.operation == GenericFilterOps.GT:
        return column > self.value
    if self.operation == GenericFilterOps.LTE:
        return column <= self.value
    if self.operation == GenericFilterOps.LT:
        return column < self.value
    if self.operation == GenericFilterOps.NOT_EQUALS:
        return column != self.value
    return column == self.value
OAuthDeviceAuthorizationRequest

Bases: BaseModel

OAuth2 device authorization grant request.

OAuthDeviceAuthorizationResponse

Bases: BaseModel

OAuth2 device authorization grant response.

OAuthDeviceFilter

Bases: UserScopedFilter

Model to enable advanced filtering of OAuth2 devices.

OAuthDeviceInternalRequest

Bases: BaseRequest

Internal request model for OAuth2 devices.

OAuthDeviceInternalResponse

Bases: OAuthDeviceResponse

OAuth2 device response model used internally for authentication.

Functions
verify_device_code(device_code: str) -> bool

Verifies a given device code against the stored (hashed) device code.

Parameters:

Name Type Description Default
device_code str

The device code to verify.

required

Returns:

Type Description
bool

True if the device code is valid, False otherwise.

Source code in src/zenml/models/v2/core/device.py
422
423
424
425
426
427
428
429
430
431
432
433
434
def verify_device_code(
    self,
    device_code: str,
) -> bool:
    """Verifies a given device code against the stored (hashed) device code.

    Args:
        device_code: The device code to verify.

    Returns:
        True if the device code is valid, False otherwise.
    """
    return self._verify_code(device_code, self.device_code)
verify_user_code(user_code: str) -> bool

Verifies a given user code against the stored (hashed) user code.

Parameters:

Name Type Description Default
user_code str

The user code to verify.

required

Returns:

Type Description
bool

True if the user code is valid, False otherwise.

Source code in src/zenml/models/v2/core/device.py
408
409
410
411
412
413
414
415
416
417
418
419
420
def verify_user_code(
    self,
    user_code: str,
) -> bool:
    """Verifies a given user code against the stored (hashed) user code.

    Args:
        user_code: The user code to verify.

    Returns:
        True if the user code is valid, False otherwise.
    """
    return self._verify_code(user_code, self.user_code)
OAuthDeviceInternalUpdate

Bases: OAuthDeviceUpdate

OAuth2 device update model used internally for authentication.

OAuthDeviceResponse

Bases: UserScopedResponse[OAuthDeviceResponseBody, OAuthDeviceResponseMetadata, OAuthDeviceResponseResources]

Response model for OAuth2 devices.

Attributes
city: Optional[str] property

The city property.

Returns:

Type Description
Optional[str]

the value of the property.

client_id: UUID property

The client_id property.

Returns:

Type Description
UUID

the value of the property.

country: Optional[str] property

The country property.

Returns:

Type Description
Optional[str]

the value of the property.

expires: Optional[datetime] property

The expires property.

Returns:

Type Description
Optional[datetime]

the value of the property.

failed_auth_attempts: int property

The failed_auth_attempts property.

Returns:

Type Description
int

the value of the property.

hostname: Optional[str] property

The hostname property.

Returns:

Type Description
Optional[str]

the value of the property.

ip_address: Optional[str] property

The ip_address property.

Returns:

Type Description
Optional[str]

the value of the property.

last_login: Optional[datetime] property

The last_login property.

Returns:

Type Description
Optional[datetime]

the value of the property.

os: Optional[str] property

The os property.

Returns:

Type Description
Optional[str]

the value of the property.

python_version: Optional[str] property

The python_version property.

Returns:

Type Description
Optional[str]

the value of the property.

region: Optional[str] property

The region property.

Returns:

Type Description
Optional[str]

the value of the property.

status: OAuthDeviceStatus property

The status property.

Returns:

Type Description
OAuthDeviceStatus

the value of the property.

trusted_device: bool property

The trusted_device property.

Returns:

Type Description
bool

the value of the property.

zenml_version: Optional[str] property

The zenml_version property.

Returns:

Type Description
Optional[str]

the value of the property.

Functions
get_hydrated_version() -> OAuthDeviceResponse

Get the hydrated version of this OAuth2 device.

Returns:

Type Description
OAuthDeviceResponse

an instance of the same entity with the metadata field attached.

Source code in src/zenml/models/v2/core/device.py
241
242
243
244
245
246
247
248
249
def get_hydrated_version(self) -> "OAuthDeviceResponse":
    """Get the hydrated version of this OAuth2 device.

    Returns:
        an instance of the same entity with the metadata field attached.
    """
    from zenml.client import Client

    return Client().zen_store.get_authorized_device(self.id)
OAuthDeviceResponseBody

Bases: UserScopedResponseBody

Response body for OAuth2 devices.

OAuthDeviceResponseMetadata

Bases: UserScopedResponseMetadata

Response metadata for OAuth2 devices.

OAuthDeviceTokenRequest

Bases: BaseModel

OAuth2 device authorization grant request.

OAuthDeviceUpdate

Bases: BaseUpdate

OAuth2 device update model.

OAuthDeviceUserAgentHeader

Bases: BaseModel

OAuth2 device user agent header.

Functions
decode(header_str: str) -> OAuthDeviceUserAgentHeader classmethod

Decode the user agent header.

Parameters:

Name Type Description Default
header_str str

The user agent header string value.

required

Returns:

Type Description
OAuthDeviceUserAgentHeader

The decoded user agent header.

Source code in src/zenml/models/v2/misc/auth_models.py
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
@classmethod
def decode(cls, header_str: str) -> "OAuthDeviceUserAgentHeader":
    """Decode the user agent header.

    Args:
        header_str: The user agent header string value.

    Returns:
        The decoded user agent header.
    """
    header = cls()
    properties = header_str.strip().split(" ")
    for property in properties:
        try:
            key, value = property.split("/", maxsplit=1)
        except ValueError:
            continue
        if key == "Host":
            header.hostname = value
        elif key == "ZenML":
            header.zenml_version = value
        elif key == "Python":
            header.python_version = value
        elif key == "OS":
            header.os = value
    return header
encode() -> str

Encode the user agent header.

Returns:

Type Description
str

The encoded user agent header.

Source code in src/zenml/models/v2/misc/auth_models.py
85
86
87
88
89
90
91
92
93
94
95
96
def encode(self) -> str:
    """Encode the user agent header.

    Returns:
        The encoded user agent header.
    """
    return (
        f"Host/{self.hostname} "
        f"ZenML/{self.zenml_version} "
        f"Python/{self.python_version} "
        f"OS/{self.os}"
    )
OAuthDeviceVerificationRequest

Bases: BaseModel

OAuth2 device authorization verification request.

OAuthRedirectResponse

Bases: BaseModel

Redirect response.

OAuthTokenResponse

Bases: BaseModel

OAuth2 device authorization token response.

Page

Bases: BaseModel, Generic[B]

Return Model for List Models to accommodate pagination.

Attributes
size: int property

Return the item count of the page.

Returns:

Type Description
int

The amount of items in the page.

PipelineBuildBase

Bases: BaseZenModel

Base model for pipeline builds.

Attributes
requires_code_download: bool property

Whether the build requires code download.

Returns:

Type Description
bool

Whether the build requires code download.

Functions
get_image(component_key: str, step: Optional[str] = None) -> str

Get the image built for a specific key.

Parameters:

Name Type Description Default
component_key str

The key for which to get the image.

required
step Optional[str]

The pipeline step for which to get the image. If no image exists for this step, will fall back to the pipeline image for the same key.

None

Returns:

Type Description
str

The image name or digest.

Source code in src/zenml/models/v2/core/pipeline_build.py
107
108
109
110
111
112
113
114
115
116
117
118
119
def get_image(self, component_key: str, step: Optional[str] = None) -> str:
    """Get the image built for a specific key.

    Args:
        component_key: The key for which to get the image.
        step: The pipeline step for which to get the image. If no image
            exists for this step, will fall back to the pipeline image for
            the same key.

    Returns:
        The image name or digest.
    """
    return self._get_item(component_key=component_key, step=step).image
get_image_key(component_key: str, step: Optional[str] = None) -> str staticmethod

Get the image key.

Parameters:

Name Type Description Default
component_key str

The component key.

required
step Optional[str]

The pipeline step for which the image was built.

None

Returns:

Type Description
str

The image key.

Source code in src/zenml/models/v2/core/pipeline_build.py
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
@staticmethod
def get_image_key(component_key: str, step: Optional[str] = None) -> str:
    """Get the image key.

    Args:
        component_key: The component key.
        step: The pipeline step for which the image was built.

    Returns:
        The image key.
    """
    if step:
        return f"{step}.{component_key}"
    else:
        return component_key
get_settings_checksum(component_key: str, step: Optional[str] = None) -> Optional[str]

Get the settings checksum for a specific key.

Parameters:

Name Type Description Default
component_key str

The key for which to get the checksum.

required
step Optional[str]

The pipeline step for which to get the checksum. If no image exists for this step, will fall back to the pipeline image for the same key.

None

Returns:

Type Description
Optional[str]

The settings checksum.

Source code in src/zenml/models/v2/core/pipeline_build.py
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
def get_settings_checksum(
    self, component_key: str, step: Optional[str] = None
) -> Optional[str]:
    """Get the settings checksum for a specific key.

    Args:
        component_key: The key for which to get the checksum.
        step: The pipeline step for which to get the checksum. If no
            image exists for this step, will fall back to the pipeline image
            for the same key.

    Returns:
        The settings checksum.
    """
    return self._get_item(
        component_key=component_key, step=step
    ).settings_checksum
PipelineBuildFilter

Bases: ProjectScopedFilter

Model to enable advanced filtering of all pipeline builds.

Functions
get_custom_filters(table: Type[AnySchema]) -> List[ColumnElement[bool]]

Get custom filters.

Parameters:

Name Type Description Default
table Type[AnySchema]

The query table.

required

Returns:

Type Description
List[ColumnElement[bool]]

A list of custom filters.

Source code in src/zenml/models/v2/core/pipeline_build.py
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
def get_custom_filters(
    self,
    table: Type["AnySchema"],
) -> List["ColumnElement[bool]"]:
    """Get custom filters.

    Args:
        table: The query table.

    Returns:
        A list of custom filters.
    """
    custom_filters = super().get_custom_filters(table)

    from sqlmodel import and_

    from zenml.enums import StackComponentType
    from zenml.zen_stores.schemas import (
        PipelineBuildSchema,
        StackComponentSchema,
        StackCompositionSchema,
        StackSchema,
    )

    if self.container_registry_id:
        container_registry_filter = and_(
            PipelineBuildSchema.stack_id == StackSchema.id,
            StackSchema.id == StackCompositionSchema.stack_id,
            StackCompositionSchema.component_id == StackComponentSchema.id,
            StackComponentSchema.type
            == StackComponentType.CONTAINER_REGISTRY.value,
            StackComponentSchema.id == self.container_registry_id,
        )
        custom_filters.append(container_registry_filter)

    return custom_filters
PipelineBuildRequest

Bases: PipelineBuildBase, ProjectScopedRequest

Request model for pipelines builds.

PipelineBuildResponse

Bases: ProjectScopedResponse[PipelineBuildResponseBody, PipelineBuildResponseMetadata, PipelineBuildResponseResources]

Response model for pipeline builds.

Attributes
checksum: Optional[str] property

The checksum property.

Returns:

Type Description
Optional[str]

the value of the property.

contains_code: bool property

The contains_code property.

Returns:

Type Description
bool

the value of the property.

duration: Optional[int] property

The duration property.

Returns:

Type Description
Optional[int]

the value of the property.

images: Dict[str, BuildItem] property

The images property.

Returns:

Type Description
Dict[str, BuildItem]

the value of the property.

is_local: bool property

The is_local property.

Returns:

Type Description
bool

the value of the property.

pipeline: Optional[PipelineResponse] property

The pipeline property.

Returns:

Type Description
Optional[PipelineResponse]

the value of the property.

python_version: Optional[str] property

The python_version property.

Returns:

Type Description
Optional[str]

the value of the property.

requires_code_download: bool property

Whether the build requires code download.

Returns:

Type Description
bool

Whether the build requires code download.

stack: Optional[StackResponse] property

The stack property.

Returns:

Type Description
Optional[StackResponse]

the value of the property.

stack_checksum: Optional[str] property

The stack_checksum property.

Returns:

Type Description
Optional[str]

the value of the property.

zenml_version: Optional[str] property

The zenml_version property.

Returns:

Type Description
Optional[str]

the value of the property.

Functions
get_hydrated_version() -> PipelineBuildResponse

Return the hydrated version of this pipeline build.

Returns:

Type Description
PipelineBuildResponse

an instance of the same entity with the metadata field attached.

Source code in src/zenml/models/v2/core/pipeline_build.py
247
248
249
250
251
252
253
254
255
def get_hydrated_version(self) -> "PipelineBuildResponse":
    """Return the hydrated version of this pipeline build.

    Returns:
        an instance of the same entity with the metadata field attached.
    """
    from zenml.client import Client

    return Client().zen_store.get_build(self.id)
get_image(component_key: str, step: Optional[str] = None) -> str

Get the image built for a specific key.

Parameters:

Name Type Description Default
component_key str

The key for which to get the image.

required
step Optional[str]

The pipeline step for which to get the image. If no image exists for this step, will fall back to the pipeline image for the same key.

None

Returns:

Type Description
str

The image name or digest.

Source code in src/zenml/models/v2/core/pipeline_build.py
315
316
317
318
319
320
321
322
323
324
325
326
327
def get_image(self, component_key: str, step: Optional[str] = None) -> str:
    """Get the image built for a specific key.

    Args:
        component_key: The key for which to get the image.
        step: The pipeline step for which to get the image. If no image
            exists for this step, will fall back to the pipeline image for
            the same key.

    Returns:
        The image name or digest.
    """
    return self._get_item(component_key=component_key, step=step).image
get_image_key(component_key: str, step: Optional[str] = None) -> str staticmethod

Get the image key.

Parameters:

Name Type Description Default
component_key str

The component key.

required
step Optional[str]

The pipeline step for which the image was built.

None

Returns:

Type Description
str

The image key.

Source code in src/zenml/models/v2/core/pipeline_build.py
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
@staticmethod
def get_image_key(component_key: str, step: Optional[str] = None) -> str:
    """Get the image key.

    Args:
        component_key: The component key.
        step: The pipeline step for which the image was built.

    Returns:
        The image key.
    """
    if step:
        return f"{step}.{component_key}"
    else:
        return component_key
get_settings_checksum(component_key: str, step: Optional[str] = None) -> Optional[str]

Get the settings checksum for a specific key.

Parameters:

Name Type Description Default
component_key str

The key for which to get the checksum.

required
step Optional[str]

The pipeline step for which to get the checksum. If no image exists for this step, will fall back to the pipeline image for the same key.

None

Returns:

Type Description
Optional[str]

The settings checksum.

Source code in src/zenml/models/v2/core/pipeline_build.py
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
def get_settings_checksum(
    self, component_key: str, step: Optional[str] = None
) -> Optional[str]:
    """Get the settings checksum for a specific key.

    Args:
        component_key: The key for which to get the checksum.
        step: The pipeline step for which to get the checksum. If no
            image exists for this step, will fall back to the pipeline image
            for the same key.

    Returns:
        The settings checksum.
    """
    return self._get_item(
        component_key=component_key, step=step
    ).settings_checksum
to_yaml() -> Dict[str, Any]

Create a yaml representation of the pipeline build.

Create a yaml representation of the pipeline build that can be used to create a PipelineBuildBase instance.

Returns:

Type Description
Dict[str, Any]

The yaml representation of the pipeline build.

Source code in src/zenml/models/v2/core/pipeline_build.py
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
def to_yaml(self) -> Dict[str, Any]:
    """Create a yaml representation of the pipeline build.

    Create a yaml representation of the pipeline build that can be used
    to create a PipelineBuildBase instance.

    Returns:
        The yaml representation of the pipeline build.
    """
    # Get the base attributes
    yaml_dict: Dict[str, Any] = json.loads(
        self.model_dump_json(
            exclude={
                "body",
                "metadata",
            }
        )
    )
    images = json.loads(
        self.get_metadata().model_dump_json(
            exclude={
                "pipeline",
                "stack",
                "project",
            }
        )
    )
    yaml_dict.update(images)
    return yaml_dict
PipelineBuildResponseBody

Bases: ProjectScopedResponseBody

Response body for pipeline builds.

PipelineBuildResponseMetadata

Bases: ProjectScopedResponseMetadata

Response metadata for pipeline builds.

PipelineDeploymentBase

Bases: BaseZenModel

Base model for pipeline deployments.

Attributes
should_prevent_build_reuse: bool property

Whether the deployment prevents a build reuse.

Returns:

Type Description
bool

Whether the deployment prevents a build reuse.

PipelineDeploymentFilter

Bases: ProjectScopedFilter

Model to enable advanced filtering of all pipeline deployments.

PipelineDeploymentRequest

Bases: PipelineDeploymentBase, ProjectScopedRequest

Request model for pipeline deployments.

PipelineDeploymentResponse

Bases: ProjectScopedResponse[PipelineDeploymentResponseBody, PipelineDeploymentResponseMetadata, PipelineDeploymentResponseResources]

Response model for pipeline deployments.

Attributes
build: Optional[PipelineBuildResponse] property

The build property.

Returns:

Type Description
Optional[PipelineBuildResponse]

the value of the property.

client_environment: Dict[str, Any] property

The client_environment property.

Returns:

Type Description
Dict[str, Any]

the value of the property.

client_version: Optional[str] property

The client_version property.

Returns:

Type Description
Optional[str]

the value of the property.

code_path: Optional[str] property

The code_path property.

Returns:

Type Description
Optional[str]

the value of the property.

code_reference: Optional[CodeReferenceResponse] property

The code_reference property.

Returns:

Type Description
Optional[CodeReferenceResponse]

the value of the property.

pipeline: Optional[PipelineResponse] property

The pipeline property.

Returns:

Type Description
Optional[PipelineResponse]

the value of the property.

pipeline_configuration: PipelineConfiguration property

The pipeline_configuration property.

Returns:

Type Description
PipelineConfiguration

the value of the property.

pipeline_spec: Optional[PipelineSpec] property

The pipeline_spec property.

Returns:

Type Description
Optional[PipelineSpec]

the value of the property.

pipeline_version_hash: Optional[str] property

The pipeline_version_hash property.

Returns:

Type Description
Optional[str]

the value of the property.

run_name_template: str property

The run_name_template property.

Returns:

Type Description
str

the value of the property.

schedule: Optional[ScheduleResponse] property

The schedule property.

Returns:

Type Description
Optional[ScheduleResponse]

the value of the property.

server_version: Optional[str] property

The server_version property.

Returns:

Type Description
Optional[str]

the value of the property.

stack: Optional[StackResponse] property

The stack property.

Returns:

Type Description
Optional[StackResponse]

the value of the property.

step_configurations: Dict[str, Step] property

The step_configurations property.

Returns:

Type Description
Dict[str, Step]

the value of the property.

template_id: Optional[UUID] property

The template_id property.

Returns:

Type Description
Optional[UUID]

the value of the property.

Functions
get_hydrated_version() -> PipelineDeploymentResponse

Return the hydrated version of this pipeline deployment.

Returns:

Type Description
PipelineDeploymentResponse

an instance of the same entity with the metadata field attached.

Source code in src/zenml/models/v2/core/pipeline_deployment.py
206
207
208
209
210
211
212
213
214
def get_hydrated_version(self) -> "PipelineDeploymentResponse":
    """Return the hydrated version of this pipeline deployment.

    Returns:
        an instance of the same entity with the metadata field attached.
    """
    from zenml.client import Client

    return Client().zen_store.get_deployment(self.id)
PipelineDeploymentResponseBody

Bases: ProjectScopedResponseBody

Response body for pipeline deployments.

PipelineDeploymentResponseMetadata

Bases: ProjectScopedResponseMetadata

Response metadata for pipeline deployments.

PipelineFilter

Bases: ProjectScopedFilter, TaggableFilter

Pipeline filter model.

Functions
apply_filter(query: AnyQuery, table: Type[AnySchema]) -> AnyQuery

Applies the filter to a query.

Parameters:

Name Type Description Default
query AnyQuery

The query to which to apply the filter.

required
table Type[AnySchema]

The query table.

required

Returns:

Type Description
AnyQuery

The query with filter applied.

Source code in src/zenml/models/v2/core/pipeline.py
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
def apply_filter(
    self, query: AnyQuery, table: Type["AnySchema"]
) -> AnyQuery:
    """Applies the filter to a query.

    Args:
        query: The query to which to apply the filter.
        table: The query table.

    Returns:
        The query with filter applied.
    """
    query = super().apply_filter(query, table)

    from sqlmodel import and_, col, func, select

    from zenml.zen_stores.schemas import PipelineRunSchema, PipelineSchema

    if self.latest_run_status:
        latest_pipeline_run_subquery = (
            select(
                PipelineRunSchema.pipeline_id,
                func.max(PipelineRunSchema.created).label("created"),
            )
            .where(col(PipelineRunSchema.pipeline_id).is_not(None))
            .group_by(col(PipelineRunSchema.pipeline_id))
            .subquery()
        )

        query = (
            query.join(
                PipelineRunSchema,
                PipelineSchema.id == PipelineRunSchema.pipeline_id,
            )
            .join(
                latest_pipeline_run_subquery,
                and_(
                    PipelineRunSchema.pipeline_id
                    == latest_pipeline_run_subquery.c.pipeline_id,
                    PipelineRunSchema.created
                    == latest_pipeline_run_subquery.c.created,
                ),
            )
            .where(
                self.generate_custom_query_conditions_for_column(
                    value=self.latest_run_status,
                    table=PipelineRunSchema,
                    column="status",
                )
            )
        )

    return query
apply_sorting(query: AnyQuery, table: Type[AnySchema]) -> AnyQuery

Apply sorting to the query.

Parameters:

Name Type Description Default
query AnyQuery

The query to which to apply the sorting.

required
table Type[AnySchema]

The query table.

required

Returns:

Type Description
AnyQuery

The query with sorting applied.

Source code in src/zenml/models/v2/core/pipeline.py
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
def apply_sorting(
    self,
    query: AnyQuery,
    table: Type["AnySchema"],
) -> AnyQuery:
    """Apply sorting to the query.

    Args:
        query: The query to which to apply the sorting.
        table: The query table.

    Returns:
        The query with sorting applied.
    """
    from sqlmodel import asc, case, col, desc, func, select

    from zenml.enums import SorterOps
    from zenml.zen_stores.schemas import PipelineRunSchema, PipelineSchema

    sort_by, operand = self.sorting_params

    if sort_by == SORT_PIPELINES_BY_LATEST_RUN_KEY:
        # Subquery to find the latest run per pipeline
        latest_run_subquery = (
            select(
                PipelineSchema.id,
                case(
                    (
                        func.max(PipelineRunSchema.created).is_(None),
                        PipelineSchema.created,
                    ),
                    else_=func.max(PipelineRunSchema.created),
                ).label("latest_run"),
            )
            .outerjoin(
                PipelineRunSchema,
                PipelineSchema.id == PipelineRunSchema.pipeline_id,  # type: ignore[arg-type]
            )
            .group_by(col(PipelineSchema.id))
            .subquery()
        )

        query = query.add_columns(
            latest_run_subquery.c.latest_run,
        ).where(PipelineSchema.id == latest_run_subquery.c.id)

        if operand == SorterOps.ASCENDING:
            query = query.order_by(
                asc(latest_run_subquery.c.latest_run),
                asc(PipelineSchema.id),
            )
        else:
            query = query.order_by(
                desc(latest_run_subquery.c.latest_run),
                desc(PipelineSchema.id),
            )
        return query
    else:
        return super().apply_sorting(query=query, table=table)
PipelineRequest

Bases: ProjectScopedRequest

Request model for pipelines.

PipelineResponse

Bases: ProjectScopedResponse[PipelineResponseBody, PipelineResponseMetadata, PipelineResponseResources]

Response model for pipelines.

Attributes
last_run: PipelineRunResponse property

Returns the last run of this pipeline.

Returns:

Type Description
PipelineRunResponse

The last run of this pipeline.

Raises:

Type Description
RuntimeError

If no runs were found for this pipeline.

last_successful_run: PipelineRunResponse property

Returns the last successful run of this pipeline.

Returns:

Type Description
PipelineRunResponse

The last successful run of this pipeline.

Raises:

Type Description
RuntimeError

If no successful runs were found for this pipeline.

latest_run_id: Optional[UUID] property

The latest_run_id property.

Returns:

Type Description
Optional[UUID]

the value of the property.

latest_run_status: Optional[ExecutionStatus] property

The latest_run_status property.

Returns:

Type Description
Optional[ExecutionStatus]

the value of the property.

num_runs: int property

Returns the number of runs of this pipeline.

Returns:

Type Description
int

The number of runs of this pipeline.

runs: List[PipelineRunResponse] property

Returns the 20 most recent runs of this pipeline in descending order.

Returns:

Type Description
List[PipelineRunResponse]

The 20 most recent runs of this pipeline in descending order.

tags: List[TagResponse] property

The tags property.

Returns:

Type Description
List[TagResponse]

the value of the property.

Functions
get_hydrated_version() -> PipelineResponse

Get the hydrated version of this pipeline.

Returns:

Type Description
PipelineResponse

an instance of the same entity with the metadata field attached.

Source code in src/zenml/models/v2/core/pipeline.py
146
147
148
149
150
151
152
153
154
def get_hydrated_version(self) -> "PipelineResponse":
    """Get the hydrated version of this pipeline.

    Returns:
        an instance of the same entity with the metadata field attached.
    """
    from zenml.client import Client

    return Client().zen_store.get_pipeline(self.id)
get_runs(**kwargs: Any) -> List[PipelineRunResponse]

Get runs of this pipeline.

Can be used to fetch runs other than self.runs and supports fine-grained filtering and pagination.

Parameters:

Name Type Description Default
**kwargs Any

Further arguments for filtering or pagination that are passed to client.list_pipeline_runs().

{}

Returns:

Type Description
List[PipelineRunResponse]

List of runs of this pipeline.

Source code in src/zenml/models/v2/core/pipeline.py
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
def get_runs(self, **kwargs: Any) -> List["PipelineRunResponse"]:
    """Get runs of this pipeline.

    Can be used to fetch runs other than `self.runs` and supports
    fine-grained filtering and pagination.

    Args:
        **kwargs: Further arguments for filtering or pagination that are
            passed to `client.list_pipeline_runs()`.

    Returns:
        List of runs of this pipeline.
    """
    from zenml.client import Client

    return Client().list_pipeline_runs(pipeline_id=self.id, **kwargs).items
PipelineResponseBody

Bases: ProjectScopedResponseBody

Response body for pipelines.

PipelineResponseMetadata

Bases: ProjectScopedResponseMetadata

Response metadata for pipelines.

PipelineResponseResources

Bases: ProjectScopedResponseResources

Class for all resource models associated with the pipeline entity.

PipelineRunFilter

Bases: ProjectScopedFilter, TaggableFilter, RunMetadataFilterMixin

Model to enable advanced filtering of all pipeline runs.

Functions
apply_sorting(query: AnyQuery, table: Type[AnySchema]) -> AnyQuery

Apply sorting to the query.

Parameters:

Name Type Description Default
query AnyQuery

The query to which to apply the sorting.

required
table Type[AnySchema]

The query table.

required

Returns:

Type Description
AnyQuery

The query with sorting applied.

Source code in src/zenml/models/v2/core/pipeline_run.py
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
def apply_sorting(
    self,
    query: AnyQuery,
    table: Type["AnySchema"],
) -> AnyQuery:
    """Apply sorting to the query.

    Args:
        query: The query to which to apply the sorting.
        table: The query table.

    Returns:
        The query with sorting applied.
    """
    from sqlmodel import asc, desc

    from zenml.enums import SorterOps
    from zenml.zen_stores.schemas import (
        ModelSchema,
        ModelVersionSchema,
        PipelineDeploymentSchema,
        PipelineRunSchema,
        PipelineSchema,
        StackSchema,
    )

    sort_by, operand = self.sorting_params

    if sort_by == "pipeline":
        query = query.outerjoin(
            PipelineSchema,
            PipelineRunSchema.pipeline_id == PipelineSchema.id,
        )
        column = PipelineSchema.name
    elif sort_by == "stack":
        query = query.outerjoin(
            PipelineDeploymentSchema,
            PipelineRunSchema.deployment_id == PipelineDeploymentSchema.id,
        ).outerjoin(
            StackSchema,
            PipelineDeploymentSchema.stack_id == StackSchema.id,
        )
        column = StackSchema.name
    elif sort_by == "model":
        query = query.outerjoin(
            ModelVersionSchema,
            PipelineRunSchema.model_version_id == ModelVersionSchema.id,
        ).outerjoin(
            ModelSchema,
            ModelVersionSchema.model_id == ModelSchema.id,
        )
        column = ModelSchema.name
    elif sort_by == "model_version":
        query = query.outerjoin(
            ModelVersionSchema,
            PipelineRunSchema.model_version_id == ModelVersionSchema.id,
        )
        column = ModelVersionSchema.name
    else:
        return super().apply_sorting(query=query, table=table)

    query = query.add_columns(column)

    if operand == SorterOps.ASCENDING:
        query = query.order_by(asc(column))
    else:
        query = query.order_by(desc(column))

    return query
get_custom_filters(table: Type[AnySchema]) -> List[ColumnElement[bool]]

Get custom filters.

Parameters:

Name Type Description Default
table Type[AnySchema]

The query table.

required

Returns:

Type Description
List[ColumnElement[bool]]

A list of custom filters.

Source code in src/zenml/models/v2/core/pipeline_run.py
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
def get_custom_filters(
    self,
    table: Type["AnySchema"],
) -> List["ColumnElement[bool]"]:
    """Get custom filters.

    Args:
        table: The query table.

    Returns:
        A list of custom filters.
    """
    custom_filters = super().get_custom_filters(table)

    from sqlmodel import and_, col, or_

    from zenml.zen_stores.schemas import (
        CodeReferenceSchema,
        CodeRepositorySchema,
        ModelSchema,
        ModelVersionSchema,
        PipelineBuildSchema,
        PipelineDeploymentSchema,
        PipelineRunSchema,
        PipelineSchema,
        ScheduleSchema,
        StackComponentSchema,
        StackCompositionSchema,
        StackSchema,
    )

    if self.unlisted is not None:
        if self.unlisted is True:
            unlisted_filter = PipelineRunSchema.pipeline_id.is_(None)  # type: ignore[union-attr]
        else:
            unlisted_filter = PipelineRunSchema.pipeline_id.is_not(None)  # type: ignore[union-attr]
        custom_filters.append(unlisted_filter)

    if self.code_repository_id:
        code_repo_filter = and_(
            PipelineRunSchema.deployment_id == PipelineDeploymentSchema.id,
            PipelineDeploymentSchema.code_reference_id
            == CodeReferenceSchema.id,
            CodeReferenceSchema.code_repository_id
            == self.code_repository_id,
        )
        custom_filters.append(code_repo_filter)

    if self.stack_id:
        stack_filter = and_(
            PipelineRunSchema.deployment_id == PipelineDeploymentSchema.id,
            PipelineDeploymentSchema.stack_id == StackSchema.id,
            StackSchema.id == self.stack_id,
        )
        custom_filters.append(stack_filter)

    if self.schedule_id:
        schedule_filter = and_(
            PipelineRunSchema.deployment_id == PipelineDeploymentSchema.id,
            PipelineDeploymentSchema.schedule_id == ScheduleSchema.id,
            ScheduleSchema.id == self.schedule_id,
        )
        custom_filters.append(schedule_filter)

    if self.build_id:
        pipeline_build_filter = and_(
            PipelineRunSchema.deployment_id == PipelineDeploymentSchema.id,
            PipelineDeploymentSchema.build_id == PipelineBuildSchema.id,
            PipelineBuildSchema.id == self.build_id,
        )
        custom_filters.append(pipeline_build_filter)

    if self.template_id:
        run_template_filter = and_(
            PipelineRunSchema.deployment_id == PipelineDeploymentSchema.id,
            PipelineDeploymentSchema.template_id == self.template_id,
        )
        custom_filters.append(run_template_filter)

    if self.pipeline:
        pipeline_filter = and_(
            PipelineRunSchema.pipeline_id == PipelineSchema.id,
            self.generate_name_or_id_query_conditions(
                value=self.pipeline, table=PipelineSchema
            ),
        )
        custom_filters.append(pipeline_filter)

    if self.stack:
        stack_filter = and_(
            PipelineRunSchema.deployment_id == PipelineDeploymentSchema.id,
            PipelineDeploymentSchema.stack_id == StackSchema.id,
            self.generate_name_or_id_query_conditions(
                value=self.stack,
                table=StackSchema,
            ),
        )
        custom_filters.append(stack_filter)

    if self.code_repository:
        code_repo_filter = and_(
            PipelineRunSchema.deployment_id == PipelineDeploymentSchema.id,
            PipelineDeploymentSchema.code_reference_id
            == CodeReferenceSchema.id,
            CodeReferenceSchema.code_repository_id
            == CodeRepositorySchema.id,
            self.generate_name_or_id_query_conditions(
                value=self.code_repository,
                table=CodeRepositorySchema,
            ),
        )
        custom_filters.append(code_repo_filter)

    if self.model:
        model_filter = and_(
            PipelineRunSchema.model_version_id == ModelVersionSchema.id,
            ModelVersionSchema.model_id == ModelSchema.id,
            self.generate_name_or_id_query_conditions(
                value=self.model, table=ModelSchema
            ),
        )
        custom_filters.append(model_filter)

    if self.stack_component:
        component_filter = and_(
            PipelineRunSchema.deployment_id == PipelineDeploymentSchema.id,
            PipelineDeploymentSchema.stack_id == StackSchema.id,
            StackSchema.id == StackCompositionSchema.stack_id,
            StackCompositionSchema.component_id == StackComponentSchema.id,
            self.generate_name_or_id_query_conditions(
                value=self.stack_component,
                table=StackComponentSchema,
            ),
        )
        custom_filters.append(component_filter)

    if self.pipeline_name:
        pipeline_name_filter = and_(
            PipelineRunSchema.pipeline_id == PipelineSchema.id,
            self.generate_custom_query_conditions_for_column(
                value=self.pipeline_name,
                table=PipelineSchema,
                column="name",
            ),
        )
        custom_filters.append(pipeline_name_filter)

    if self.templatable is not None:
        if self.templatable is True:
            templatable_filter = and_(
                # The following condition is not perfect as it does not
                # consider stacks with custom flavor components or local
                # components, but the best we can do currently with our
                # table columns.
                PipelineRunSchema.deployment_id
                == PipelineDeploymentSchema.id,
                PipelineDeploymentSchema.build_id
                == PipelineBuildSchema.id,
                col(PipelineBuildSchema.is_local).is_(False),
                col(PipelineBuildSchema.stack_id).is_not(None),
            )
        else:
            templatable_filter = or_(
                col(PipelineRunSchema.deployment_id).is_(None),
                and_(
                    PipelineRunSchema.deployment_id
                    == PipelineDeploymentSchema.id,
                    col(PipelineDeploymentSchema.build_id).is_(None),
                ),
                and_(
                    PipelineRunSchema.deployment_id
                    == PipelineDeploymentSchema.id,
                    PipelineDeploymentSchema.build_id
                    == PipelineBuildSchema.id,
                    or_(
                        col(PipelineBuildSchema.is_local).is_(True),
                        col(PipelineBuildSchema.stack_id).is_(None),
                    ),
                ),
            )

        custom_filters.append(templatable_filter)

    return custom_filters
PipelineRunRequest

Bases: ProjectScopedRequest

Request model for pipeline runs.

PipelineRunResponse

Bases: ProjectScopedResponse[PipelineRunResponseBody, PipelineRunResponseMetadata, PipelineRunResponseResources]

Response model for pipeline runs.

Attributes
artifact_versions: List[ArtifactVersionResponse] property

Get all artifact versions that are outputs of steps of this run.

Returns:

Type Description
List[ArtifactVersionResponse]

All output artifact versions of this run (including cached ones).

build: Optional[PipelineBuildResponse] property

The build property.

Returns:

Type Description
Optional[PipelineBuildResponse]

the value of the property.

client_environment: Dict[str, Any] property

The client_environment property.

Returns:

Type Description
Dict[str, Any]

the value of the property.

code_path: Optional[str] property

The code_path property.

Returns:

Type Description
Optional[str]

the value of the property.

code_reference: Optional[CodeReferenceResponse] property

The schedule property.

Returns:

Type Description
Optional[CodeReferenceResponse]

the value of the property.

config: PipelineConfiguration property

The config property.

Returns:

Type Description
PipelineConfiguration

the value of the property.

deployment_id: Optional[UUID] property

The deployment_id property.

Returns:

Type Description
Optional[UUID]

the value of the property.

end_time: Optional[datetime] property

The end_time property.

Returns:

Type Description
Optional[datetime]

the value of the property.

is_templatable: bool property

The is_templatable property.

Returns:

Type Description
bool

the value of the property.

logs: Optional[LogsResponse] property

The logs property.

Returns:

Type Description
Optional[LogsResponse]

the value of the property.

model_version: Optional[ModelVersionResponse] property

The model_version property.

Returns:

Type Description
Optional[ModelVersionResponse]

the value of the property.

model_version_id: Optional[UUID] property

The model_version_id property.

Returns:

Type Description
Optional[UUID]

the value of the property.

orchestrator_environment: Dict[str, Any] property

The orchestrator_environment property.

Returns:

Type Description
Dict[str, Any]

the value of the property.

orchestrator_run_id: Optional[str] property

The orchestrator_run_id property.

Returns:

Type Description
Optional[str]

the value of the property.

pipeline: Optional[PipelineResponse] property

The pipeline property.

Returns:

Type Description
Optional[PipelineResponse]

the value of the property.

produced_artifact_versions: List[ArtifactVersionResponse] property

Get all artifact versions produced during this pipeline run.

Returns:

Type Description
List[ArtifactVersionResponse]

A list of all artifact versions produced during this pipeline run.

run_metadata: Dict[str, MetadataType] property

The run_metadata property.

Returns:

Type Description
Dict[str, MetadataType]

the value of the property.

schedule: Optional[ScheduleResponse] property

The schedule property.

Returns:

Type Description
Optional[ScheduleResponse]

the value of the property.

stack: Optional[StackResponse] property

The stack property.

Returns:

Type Description
Optional[StackResponse]

the value of the property.

start_time: Optional[datetime] property

The start_time property.

Returns:

Type Description
Optional[datetime]

the value of the property.

status: ExecutionStatus property

The status property.

Returns:

Type Description
ExecutionStatus

the value of the property.

step_substitutions: Dict[str, Dict[str, str]] property

The step_substitutions property.

Returns:

Type Description
Dict[str, Dict[str, str]]

the value of the property.

steps: Dict[str, StepRunResponse] property

The steps property.

Returns:

Type Description
Dict[str, StepRunResponse]

the value of the property.

tags: List[TagResponse] property

The tags property.

Returns:

Type Description
List[TagResponse]

the value of the property.

template_id: Optional[UUID] property

The template_id property.

Returns:

Type Description
Optional[UUID]

the value of the property.

trigger_execution: Optional[TriggerExecutionResponse] property

The trigger_execution property.

Returns:

Type Description
Optional[TriggerExecutionResponse]

the value of the property.

Functions
get_hydrated_version() -> PipelineRunResponse

Get the hydrated version of this pipeline run.

Returns:

Type Description
PipelineRunResponse

an instance of the same entity with the metadata field attached.

Source code in src/zenml/models/v2/core/pipeline_run.py
282
283
284
285
286
287
288
289
290
def get_hydrated_version(self) -> "PipelineRunResponse":
    """Get the hydrated version of this pipeline run.

    Returns:
        an instance of the same entity with the metadata field attached.
    """
    from zenml.client import Client

    return Client().zen_store.get_run(self.id)
refresh_run_status() -> PipelineRunResponse

Method to refresh the status of a run if it is initializing/running.

Returns:

Type Description
PipelineRunResponse

The updated pipeline.

Raises:

Type Description
ValueError

If the stack of the run response is None.

Source code in src/zenml/models/v2/core/pipeline_run.py
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
def refresh_run_status(self) -> "PipelineRunResponse":
    """Method to refresh the status of a run if it is initializing/running.

    Returns:
        The updated pipeline.

    Raises:
        ValueError: If the stack of the run response is None.
    """
    if self.status in [
        ExecutionStatus.INITIALIZING,
        ExecutionStatus.RUNNING,
    ]:
        # Check if the stack still accessible
        if self.stack is None:
            raise ValueError(
                "The stack that this pipeline run response was executed on"
                "has been deleted."
            )

        # Create the orchestrator instance
        from zenml.enums import StackComponentType
        from zenml.orchestrators.base_orchestrator import BaseOrchestrator
        from zenml.stack.stack_component import StackComponent

        # Check if the stack still accessible
        orchestrator_list = self.stack.components.get(
            StackComponentType.ORCHESTRATOR, []
        )
        if len(orchestrator_list) == 0:
            raise ValueError(
                "The orchestrator that this pipeline run response was "
                "executed with has been deleted."
            )

        orchestrator = cast(
            BaseOrchestrator,
            StackComponent.from_model(
                component_model=orchestrator_list[0]
            ),
        )

        # Fetch the status
        status = orchestrator.fetch_status(run=self)

        # If it is different from the current status, update it
        if status != self.status:
            from zenml.client import Client
            from zenml.models import PipelineRunUpdate

            client = Client()
            return client.zen_store.update_run(
                run_id=self.id,
                run_update=PipelineRunUpdate(status=status),
            )

    return self
PipelineRunResponseBody

Bases: ProjectScopedResponseBody

Response body for pipeline runs.

PipelineRunResponseMetadata

Bases: ProjectScopedResponseMetadata

Response metadata for pipeline runs.

PipelineRunResponseResources

Bases: ProjectScopedResponseResources

Class for all resource models associated with the pipeline run entity.

PipelineRunUpdate

Bases: BaseUpdate

Pipeline run update model.

PipelineUpdate

Bases: BaseUpdate

Update model for pipelines.

ProjectFilter

Bases: BaseFilter

Model to enable advanced filtering of all projects.

ProjectRequest

Bases: BaseRequest

Request model for projects.

ProjectResponse

Bases: BaseIdentifiedResponse[ProjectResponseBody, ProjectResponseMetadata, ProjectResponseResources]

Response model for projects.

Attributes
description: str property

The description property.

Returns:

Type Description
str

the value of the property.

display_name: str property

The display_name property.

Returns:

Type Description
str

the value of the property.

Functions
get_hydrated_version() -> ProjectResponse

Get the hydrated version of this project.

Returns:

Type Description
ProjectResponse

an instance of the same entity with the metadata field attached.

Source code in src/zenml/models/v2/core/project.py
158
159
160
161
162
163
164
165
166
def get_hydrated_version(self) -> "ProjectResponse":
    """Get the hydrated version of this project.

    Returns:
        an instance of the same entity with the metadata field attached.
    """
    from zenml.client import Client

    return Client().zen_store.get_project(self.id)
ProjectResponseBody

Bases: BaseDatedResponseBody

Response body for projects.

ProjectResponseMetadata

Bases: BaseResponseMetadata

Response metadata for projects.

ProjectScopedFilter

Bases: UserScopedFilter

Model to enable advanced scoping with project.

Functions
apply_filter(query: AnyQuery, table: Type[AnySchema]) -> AnyQuery

Applies the filter to a query.

Parameters:

Name Type Description Default
query AnyQuery

The query to which to apply the filter.

required
table Type[AnySchema]

The query table.

required

Returns:

Type Description
AnyQuery

The query with filter applied.

Raises:

Type Description
ValueError

If the project scope is missing from the filter.

Source code in src/zenml/models/v2/base/scoped.py
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
def apply_filter(
    self,
    query: AnyQuery,
    table: Type["AnySchema"],
) -> AnyQuery:
    """Applies the filter to a query.

    Args:
        query: The query to which to apply the filter.
        table: The query table.

    Returns:
        The query with filter applied.

    Raises:
        ValueError: If the project scope is missing from the filter.
    """
    query = super().apply_filter(query=query, table=table)

    # The project scope must always be set and must be a UUID. If the
    # client sets this to a string, the server will try to resolve it to a
    # project ID.
    #
    # If not set by the client, the server will fall back to using the
    # user's default project or even the server's default project, if
    # they are configured. If this also fails to yield a project, this
    # method will raise a ValueError.
    #
    # See: SqlZenStore._set_filter_project_id

    if not self.project:
        raise ValueError("Project scope missing from the filter.")

    if not isinstance(self.project, UUID):
        raise ValueError(
            f"Project scope must be a UUID, got {type(self.project)}."
        )

    scope_filter = getattr(table, "project_id") == self.project
    query = query.where(scope_filter)

    return query
ProjectScopedRequest

Bases: UserScopedRequest

Base project-scoped request domain model.

Used as a base class for all domain models that are project-scoped.

Functions
get_analytics_metadata() -> Dict[str, Any]

Fetches the analytics metadata for project scoped models.

Returns:

Type Description
Dict[str, Any]

The analytics metadata.

Source code in src/zenml/models/v2/base/scoped.py
91
92
93
94
95
96
97
98
99
def get_analytics_metadata(self) -> Dict[str, Any]:
    """Fetches the analytics metadata for project scoped models.

    Returns:
        The analytics metadata.
    """
    metadata = super().get_analytics_metadata()
    metadata["project_id"] = self.project
    return metadata
ProjectScopedResponse

Bases: UserScopedResponse[ProjectBody, ProjectMetadata, ProjectResources], Generic[ProjectBody, ProjectMetadata, ProjectResources]

Base project-scoped domain model.

Used as a base class for all domain models that are project-scoped.

Attributes
project: ProjectResponse property

The project property.

Returns:

Type Description
ProjectResponse

the value of the property.

Functions
get_analytics_metadata() -> Dict[str, Any]

Fetches the analytics metadata for project scoped models.

Returns:

Type Description
Dict[str, Any]

The analytics metadata.

Source code in src/zenml/models/v2/base/scoped.py
322
323
324
325
326
327
328
329
330
331
def get_analytics_metadata(self) -> Dict[str, Any]:
    """Fetches the analytics metadata for project scoped models.

    Returns:
        The analytics metadata.
    """
    metadata = super().get_analytics_metadata()
    if self.project is not None:
        metadata["project_id"] = self.project.id
    return metadata
ProjectScopedResponseBody

Bases: UserScopedResponseBody

Base project-scoped body.

ProjectScopedResponseMetadata

Bases: UserScopedResponseMetadata

Base project-scoped metadata.

ProjectScopedResponseResources

Bases: UserScopedResponseResources

Base project-scoped resources.

ProjectStatistics

Bases: BaseZenModel

Project statistics.

ProjectUpdate

Bases: BaseUpdate

Update model for projects.

ResourceTypeModel

Bases: BaseModel

Resource type specification.

Describes the authentication methods and resource instantiation model for one or more resource types.

Attributes
emojified_resource_type: str property

Get the emojified resource type.

Returns:

Type Description
str

The emojified resource type.

ResourcesInfo

Bases: BaseModel

Information about the resources needed for CLI and UI.

RunMetadataEntry

Bases: BaseModel

Utility class to sort/list run metadata entries.

RunMetadataFilterMixin

Bases: BaseFilter

Model to enable filtering and sorting by run metadata.

Functions
get_custom_filters(table: Type[AnySchema]) -> List[ColumnElement[bool]]

Get custom run metadata filters.

Parameters:

Name Type Description Default
table Type[AnySchema]

The query table.

required

Returns:

Type Description
List[ColumnElement[bool]]

A list of custom filters.

Source code in src/zenml/models/v2/base/scoped.py
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
def get_custom_filters(
    self, table: Type["AnySchema"]
) -> List["ColumnElement[bool]"]:
    """Get custom run metadata filters.

    Args:
        table: The query table.

    Returns:
        A list of custom filters.
    """
    custom_filters = super().get_custom_filters(table)

    if self.run_metadata is not None:
        from sqlmodel import exists, select

        from zenml.enums import MetadataResourceTypes
        from zenml.zen_stores.schemas import (
            ArtifactVersionSchema,
            ModelVersionSchema,
            PipelineRunSchema,
            RunMetadataResourceSchema,
            RunMetadataSchema,
            ScheduleSchema,
            StepRunSchema,
        )

        resource_type_mapping = {
            ArtifactVersionSchema: MetadataResourceTypes.ARTIFACT_VERSION,
            ModelVersionSchema: MetadataResourceTypes.MODEL_VERSION,
            PipelineRunSchema: MetadataResourceTypes.PIPELINE_RUN,
            StepRunSchema: MetadataResourceTypes.STEP_RUN,
            ScheduleSchema: MetadataResourceTypes.SCHEDULE,
        }

        # Create an EXISTS subquery for each run_metadata filter
        for entry in self.run_metadata:
            # Split at the first colon to get the key
            key, value = entry.split(":", 1)

            # Create an exists subquery
            exists_subquery = exists(
                select(RunMetadataResourceSchema.id)
                .join(
                    RunMetadataSchema,
                    RunMetadataSchema.id  # type: ignore[arg-type]
                    == RunMetadataResourceSchema.run_metadata_id,
                )
                .where(
                    RunMetadataResourceSchema.resource_id == table.id,
                    RunMetadataResourceSchema.resource_type
                    == resource_type_mapping[table].value,
                    self.generate_custom_query_conditions_for_column(
                        value=key,
                        table=RunMetadataSchema,
                        column="key",
                    ),
                    self.generate_custom_query_conditions_for_column(
                        value=value,
                        table=RunMetadataSchema,
                        column="value",
                    ),
                )
            )
            custom_filters.append(exists_subquery)

    return custom_filters
validate_run_metadata_format() -> RunMetadataFilterMixin

Validates that run_metadata entries are in the correct format.

Each run_metadata entry must be in one of the following formats: 1. "key:value" - Direct equality comparison (key equals value) 2. "key:filterop:value" - Where filterop is one of the GenericFilterOps: - equals: Exact match - notequals: Not equal to - contains: String contains value - startswith: String starts with value - endswith: String ends with value - oneof: Value is one of the specified options - gte: Greater than or equal to - gt: Greater than - lte: Less than or equal to - lt: Less than - in: Value is in a list

Examples: - "status:completed" - Find entries where status equals "completed" - "name:contains:test" - Find entries where name contains "test" - "duration:gt:10" - Find entries where duration is greater than 10

Returns:

Type Description
RunMetadataFilterMixin

self

Raises:

Type Description
ValueError

If any entry in run_metadata does not contain a colon.

Source code in src/zenml/models/v2/base/scoped.py
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
@model_validator(mode="after")
def validate_run_metadata_format(self) -> "RunMetadataFilterMixin":
    """Validates that run_metadata entries are in the correct format.

    Each run_metadata entry must be in one of the following formats:
    1. "key:value" - Direct equality comparison (key equals value)
    2. "key:filterop:value" - Where filterop is one of the GenericFilterOps:
       - equals: Exact match
       - notequals: Not equal to
       - contains: String contains value
       - startswith: String starts with value
       - endswith: String ends with value
       - oneof: Value is one of the specified options
       - gte: Greater than or equal to
       - gt: Greater than
       - lte: Less than or equal to
       - lt: Less than
       - in: Value is in a list

    Examples:
    - "status:completed" - Find entries where status equals "completed"
    - "name:contains:test" - Find entries where name contains "test"
    - "duration:gt:10" - Find entries where duration is greater than 10

    Returns:
        self

    Raises:
        ValueError: If any entry in run_metadata does not contain a colon.
    """
    if self.run_metadata:
        for entry in self.run_metadata:
            if ":" not in entry:
                raise ValueError(
                    f"Invalid run_metadata entry format: '{entry}'. "
                    "Entry must be in format 'key:value' for direct "
                    "equality comparison or 'key:filterop:value' where "
                    "filterop is one of: equals, notequals, "
                    f"contains, startswith, endswith, oneof, gte, gt, "
                    f"lte, lt, in."
                )
    return self
RunMetadataRequest

Bases: ProjectScopedRequest

Request model for run metadata.

Functions
validate_values_keys() -> RunMetadataRequest

Validates if the keys in the metadata are properly defined.

Returns:

Type Description
RunMetadataRequest

self

Raises:

Type Description
ValueError

if one of the key in the metadata contains :

Source code in src/zenml/models/v2/core/run_metadata.py
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
@model_validator(mode="after")
def validate_values_keys(self) -> "RunMetadataRequest":
    """Validates if the keys in the metadata are properly defined.

    Returns:
        self

    Raises:
        ValueError: if one of the key in the metadata contains `:`
    """
    invalid_keys = [key for key in self.values.keys() if ":" in key]
    if invalid_keys:
        raise ValueError(
            "You can not use colons (`:`) in the key names when you "
            "are creating metadata for your ZenML objects. Please change "
            f"the following keys: {invalid_keys}"
        )
    return self
RunMetadataResource

Bases: BaseModel

Utility class to help identify resources to tag metadata to.

RunTemplateFilter

Bases: ProjectScopedFilter, TaggableFilter

Model for filtering of run templates.

Functions
get_custom_filters(table: Type[AnySchema]) -> List[ColumnElement[bool]]

Get custom filters.

Parameters:

Name Type Description Default
table Type[AnySchema]

The query table.

required

Returns:

Type Description
List[ColumnElement[bool]]

A list of custom filters.

Source code in src/zenml/models/v2/core/run_template.py
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
def get_custom_filters(
    self, table: Type["AnySchema"]
) -> List["ColumnElement[bool]"]:
    """Get custom filters.

    Args:
        table: The query table.

    Returns:
        A list of custom filters.
    """
    custom_filters = super().get_custom_filters(table)

    from sqlmodel import and_, col

    from zenml.zen_stores.schemas import (
        CodeReferenceSchema,
        PipelineDeploymentSchema,
        PipelineSchema,
        RunTemplateSchema,
        StackSchema,
    )

    if self.hidden is not None:
        custom_filters.append(
            col(RunTemplateSchema.hidden).is_(self.hidden)
        )

    if self.code_repository_id:
        code_repo_filter = and_(
            RunTemplateSchema.source_deployment_id
            == PipelineDeploymentSchema.id,
            PipelineDeploymentSchema.code_reference_id
            == CodeReferenceSchema.id,
            CodeReferenceSchema.code_repository_id
            == self.code_repository_id,
        )
        custom_filters.append(code_repo_filter)

    if self.stack_id:
        stack_filter = and_(
            RunTemplateSchema.source_deployment_id
            == PipelineDeploymentSchema.id,
            PipelineDeploymentSchema.stack_id == self.stack_id,
        )
        custom_filters.append(stack_filter)

    if self.build_id:
        build_filter = and_(
            RunTemplateSchema.source_deployment_id
            == PipelineDeploymentSchema.id,
            PipelineDeploymentSchema.build_id == self.build_id,
        )
        custom_filters.append(build_filter)

    if self.pipeline_id:
        pipeline_filter = and_(
            RunTemplateSchema.source_deployment_id
            == PipelineDeploymentSchema.id,
            PipelineDeploymentSchema.pipeline_id == self.pipeline_id,
        )
        custom_filters.append(pipeline_filter)

    if self.pipeline:
        pipeline_filter = and_(
            RunTemplateSchema.source_deployment_id
            == PipelineDeploymentSchema.id,
            PipelineDeploymentSchema.pipeline_id == PipelineSchema.id,
            self.generate_name_or_id_query_conditions(
                value=self.pipeline,
                table=PipelineSchema,
            ),
        )
        custom_filters.append(pipeline_filter)

    if self.stack:
        stack_filter = and_(
            RunTemplateSchema.source_deployment_id
            == PipelineDeploymentSchema.id,
            PipelineDeploymentSchema.stack_id == StackSchema.id,
            self.generate_name_or_id_query_conditions(
                value=self.stack,
                table=StackSchema,
            ),
        )
        custom_filters.append(stack_filter)

    return custom_filters
RunTemplateRequest

Bases: ProjectScopedRequest

Request model for run templates.

RunTemplateResponse

Bases: ProjectScopedResponse[RunTemplateResponseBody, RunTemplateResponseMetadata, RunTemplateResponseResources]

Response model for run templates.

Attributes
build: Optional[PipelineBuildResponse] property

The build property.

Returns:

Type Description
Optional[PipelineBuildResponse]

the value of the property.

code_reference: Optional[CodeReferenceResponse] property

The code_reference property.

Returns:

Type Description
Optional[CodeReferenceResponse]

the value of the property.

config_schema: Optional[Dict[str, Any]] property

The config_schema property.

Returns:

Type Description
Optional[Dict[str, Any]]

the value of the property.

config_template: Optional[Dict[str, Any]] property

The config_template property.

Returns:

Type Description
Optional[Dict[str, Any]]

the value of the property.

description: Optional[str] property

The description property.

Returns:

Type Description
Optional[str]

the value of the property.

hidden: bool property

The hidden property.

Returns:

Type Description
bool

the value of the property.

latest_run_id: Optional[UUID] property

The latest_run_id property.

Returns:

Type Description
Optional[UUID]

the value of the property.

latest_run_status: Optional[ExecutionStatus] property

The latest_run_status property.

Returns:

Type Description
Optional[ExecutionStatus]

the value of the property.

pipeline: Optional[PipelineResponse] property

The pipeline property.

Returns:

Type Description
Optional[PipelineResponse]

the value of the property.

pipeline_spec: Optional[PipelineSpec] property

The pipeline_spec property.

Returns:

Type Description
Optional[PipelineSpec]

the value of the property.

runnable: bool property

The runnable property.

Returns:

Type Description
bool

the value of the property.

source_deployment: Optional[PipelineDeploymentResponse] property

The source_deployment property.

Returns:

Type Description
Optional[PipelineDeploymentResponse]

the value of the property.

tags: List[TagResponse] property

The tags property.

Returns:

Type Description
List[TagResponse]

the value of the property.

Functions
get_hydrated_version() -> RunTemplateResponse

Return the hydrated version of this run template.

Returns:

Type Description
RunTemplateResponse

The hydrated run template.

Source code in src/zenml/models/v2/core/run_template.py
198
199
200
201
202
203
204
205
206
207
208
def get_hydrated_version(self) -> "RunTemplateResponse":
    """Return the hydrated version of this run template.

    Returns:
        The hydrated run template.
    """
    from zenml.client import Client

    return Client().zen_store.get_run_template(
        template_id=self.id, hydrate=True
    )
RunTemplateResponseBody

Bases: ProjectScopedResponseBody

Response body for run templates.

RunTemplateResponseMetadata

Bases: ProjectScopedResponseMetadata

Response metadata for run templates.

RunTemplateResponseResources

Bases: ProjectScopedResponseResources

All resource models associated with the run template.

RunTemplateUpdate

Bases: BaseUpdate

Run template update model.

ScheduleFilter

Bases: ProjectScopedFilter

Model to enable advanced filtering of all Users.

ScheduleRequest

Bases: ProjectScopedRequest

Request model for schedules.

ScheduleResponse

Bases: ProjectScopedResponse[ScheduleResponseBody, ScheduleResponseMetadata, ScheduleResponseResources]

Response model for schedules.

Attributes
active: bool property

The active property.

Returns:

Type Description
bool

the value of the property.

catchup: bool property

The catchup property.

Returns:

Type Description
bool

the value of the property.

cron_expression: Optional[str] property

The cron_expression property.

Returns:

Type Description
Optional[str]

the value of the property.

end_time: Optional[datetime] property

The end_time property.

Returns:

Type Description
Optional[datetime]

the value of the property.

interval_second: Optional[timedelta] property

The interval_second property.

Returns:

Type Description
Optional[timedelta]

the value of the property.

orchestrator_id: Optional[UUID] property

The orchestrator_id property.

Returns:

Type Description
Optional[UUID]

the value of the property.

pipeline_id: Optional[UUID] property

The pipeline_id property.

Returns:

Type Description
Optional[UUID]

the value of the property.

run_metadata: Dict[str, MetadataType] property

The run_metadata property.

Returns:

Type Description
Dict[str, MetadataType]

the value of the property.

run_once_start_time: Optional[datetime] property

The run_once_start_time property.

Returns:

Type Description
Optional[datetime]

the value of the property.

start_time: Optional[datetime] property

The start_time property.

Returns:

Type Description
Optional[datetime]

the value of the property.

utc_end_time: Optional[str] property

Optional ISO-formatted string of the UTC end time.

Returns:

Type Description
Optional[str]

Optional ISO-formatted string of the UTC end time.

utc_start_time: Optional[str] property

Optional ISO-formatted string of the UTC start time.

Returns:

Type Description
Optional[str]

Optional ISO-formatted string of the UTC start time.

Functions
get_hydrated_version() -> ScheduleResponse

Get the hydrated version of this schedule.

Returns:

Type Description
ScheduleResponse

an instance of the same entity with the metadata field attached.

Source code in src/zenml/models/v2/core/schedule.py
177
178
179
180
181
182
183
184
185
def get_hydrated_version(self) -> "ScheduleResponse":
    """Get the hydrated version of this schedule.

    Returns:
        an instance of the same entity with the metadata field attached.
    """
    from zenml.client import Client

    return Client().zen_store.get_schedule(self.id)
ScheduleResponseBody

Bases: ProjectScopedResponseBody

Response body for schedules.

ScheduleResponseMetadata

Bases: ProjectScopedResponseMetadata

Response metadata for schedules.

ScheduleUpdate

Bases: BaseUpdate

Update model for schedules.

SecretFilter

Bases: UserScopedFilter

Model to enable advanced secret filtering.

Functions
apply_filter(query: AnyQuery, table: Type[AnySchema]) -> AnyQuery

Applies the filter to a query.

Parameters:

Name Type Description Default
query AnyQuery

The query to which to apply the filter.

required
table Type[AnySchema]

The query table.

required

Returns:

Type Description
AnyQuery

The query with filter applied.

Source code in src/zenml/models/v2/core/secret.py
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
def apply_filter(
    self,
    query: AnyQuery,
    table: Type["AnySchema"],
) -> AnyQuery:
    """Applies the filter to a query.

    Args:
        query: The query to which to apply the filter.
        table: The query table.

    Returns:
        The query with filter applied.
    """
    # The secret user scoping works a bit differently than the other
    # scoped filters. We have to filter out all private secrets that are
    # not owned by the current user.
    if not self.scope_user:
        return super().apply_filter(query=query, table=table)

    scope_user = self.scope_user

    # First we apply the inherited filters without the user scoping
    # applied.
    self.scope_user = None
    query = super().apply_filter(query=query, table=table)
    self.scope_user = scope_user

    # Then we apply the user scoping filter.
    if self.scope_user:
        from sqlmodel import and_, or_

        query = query.where(
            or_(
                and_(
                    getattr(table, "user_id") == self.scope_user,
                    getattr(table, "private") == True,  # noqa: E712
                ),
                getattr(table, "private") == False,  # noqa: E712
            )
        )

    else:
        query = query.where(getattr(table, "private") == False)  # noqa: E712

    return query
SecretRequest

Bases: UserScopedRequest

Request model for secrets.

Attributes
secret_values: Dict[str, str] property

A dictionary with all un-obfuscated values stored in this secret.

The values are returned as strings, not SecretStr. If a value is None, it is not included in the returned dictionary. This is to enable the use of None values in the update model to indicate that a secret value should be deleted.

Returns:

Type Description
Dict[str, str]

A dictionary containing the secret's values.

SecretResponse

Bases: UserScopedResponse[SecretResponseBody, SecretResponseMetadata, SecretResponseResources]

Response model for secrets.

Attributes
has_missing_values: bool property

Returns True if the secret has missing values (i.e. None).

Values can be missing from a secret for example if the user retrieves a secret but does not have the permission to view the secret values.

Returns:

Type Description
bool

True if the secret has any values set to None.

private: bool property

The private property.

Returns:

Type Description
bool

the value of the property.

secret_values: Dict[str, str] property

A dictionary with all un-obfuscated values stored in this secret.

The values are returned as strings, not SecretStr. If a value is None, it is not included in the returned dictionary. This is to enable the use of None values in the update model to indicate that a secret value should be deleted.

Returns:

Type Description
Dict[str, str]

A dictionary containing the secret's values.

values: Dict[str, Optional[SecretStr]] property

The values property.

Returns:

Type Description
Dict[str, Optional[SecretStr]]

the value of the property.

Functions
add_secret(key: str, value: str) -> None

Adds a secret value to the secret.

Parameters:

Name Type Description Default
key str

The key of the secret value.

required
value str

The secret value.

required
Source code in src/zenml/models/v2/core/secret.py
225
226
227
228
229
230
231
232
def add_secret(self, key: str, value: str) -> None:
    """Adds a secret value to the secret.

    Args:
        key: The key of the secret value.
        value: The secret value.
    """
    self.get_body().values[key] = SecretStr(value)
get_hydrated_version() -> SecretResponse

Get the hydrated version of this secret.

Returns:

Type Description
SecretResponse

an instance of the same entity with the metadata field attached.

Source code in src/zenml/models/v2/core/secret.py
164
165
166
167
168
169
170
171
172
def get_hydrated_version(self) -> "SecretResponse":
    """Get the hydrated version of this secret.

    Returns:
        an instance of the same entity with the metadata field attached.
    """
    from zenml.client import Client

    return Client().zen_store.get_secret(self.id)
remove_secret(key: str) -> None

Removes a secret value from the secret.

Parameters:

Name Type Description Default
key str

The key of the secret value.

required
Source code in src/zenml/models/v2/core/secret.py
234
235
236
237
238
239
240
def remove_secret(self, key: str) -> None:
    """Removes a secret value from the secret.

    Args:
        key: The key of the secret value.
    """
    del self.get_body().values[key]
remove_secrets() -> None

Removes all secret values from the secret but keep the keys.

Source code in src/zenml/models/v2/core/secret.py
242
243
244
def remove_secrets(self) -> None:
    """Removes all secret values from the secret but keep the keys."""
    self.get_body().values = {k: None for k in self.values.keys()}
set_secrets(values: Dict[str, str]) -> None

Sets the secret values of the secret.

Parameters:

Name Type Description Default
values Dict[str, str]

The secret values to set.

required
Source code in src/zenml/models/v2/core/secret.py
246
247
248
249
250
251
252
def set_secrets(self, values: Dict[str, str]) -> None:
    """Sets the secret values of the secret.

    Args:
        values: The secret values to set.
    """
    self.get_body().values = {k: SecretStr(v) for k, v in values.items()}
SecretResponseBody

Bases: UserScopedResponseBody

Response body for secrets.

SecretResponseMetadata

Bases: UserScopedResponseMetadata

Response metadata for secrets.

SecretUpdate

Bases: BaseUpdate

Update model for secrets.

Functions
get_secret_values_update() -> Dict[str, Optional[str]]

Returns a dictionary with the secret values to update.

Returns:

Type Description
Dict[str, Optional[str]]

A dictionary with the secret values to update.

Source code in src/zenml/models/v2/core/secret.py
109
110
111
112
113
114
115
116
117
118
119
120
121
def get_secret_values_update(self) -> Dict[str, Optional[str]]:
    """Returns a dictionary with the secret values to update.

    Returns:
        A dictionary with the secret values to update.
    """
    if self.values is not None:
        return {
            k: v.get_secret_value() if v is not None else None
            for k, v in self.values.items()
        }

    return {}
ServerActivationRequest

Bases: ServerSettingsUpdate

Model for activating the server.

ServerDatabaseType

Bases: StrEnum

Enum for server database types.

ServerDeploymentType

Bases: StrEnum

Enum for server deployment types.

ServerLoadInfo

Bases: BaseModel

Domain model for ZenML server load information.

ServerModel

Bases: BaseModel

Domain model for ZenML servers.

Functions
is_local() -> bool

Return whether the server is running locally.

Returns:

Type Description
bool

True if the server is running locally, False otherwise.

Source code in src/zenml/models/v2/misc/server_models.py
146
147
148
149
150
151
152
153
154
155
156
def is_local(self) -> bool:
    """Return whether the server is running locally.

    Returns:
        True if the server is running locally, False otherwise.
    """
    from zenml.config.global_config import GlobalConfiguration

    # Local ZenML servers are identifiable by the fact that their
    # server ID is the same as the local client (user) ID.
    return self.id == GlobalConfiguration().user_id
is_pro_server() -> bool

Return whether the server is a ZenML Pro server.

Returns:

Type Description
bool

True if the server is a ZenML Pro server, False otherwise.

Source code in src/zenml/models/v2/misc/server_models.py
158
159
160
161
162
163
164
def is_pro_server(self) -> bool:
    """Return whether the server is a ZenML Pro server.

    Returns:
        True if the server is a ZenML Pro server, False otherwise.
    """
    return self.deployment_type == ServerDeploymentType.CLOUD
ServerSettingsResponse

Bases: BaseResponse[ServerSettingsResponseBody, ServerSettingsResponseMetadata, ServerSettingsResponseResources]

Response model for server settings.

Attributes
active: bool property

The active property.

Returns:

Type Description
bool

the value of the property.

display_announcements: Optional[bool] property

The display_announcements property.

Returns:

Type Description
Optional[bool]

the value of the property.

display_updates: Optional[bool] property

The display_updates property.

Returns:

Type Description
Optional[bool]

the value of the property.

enable_analytics: bool property

The enable_analytics property.

Returns:

Type Description
bool

the value of the property.

last_user_activity: datetime property

The last_user_activity property.

Returns:

Type Description
datetime

the value of the property.

logo_url: Optional[str] property

The logo_url property.

Returns:

Type Description
Optional[str]

the value of the property.

server_id: UUID property

The server_id property.

Returns:

Type Description
UUID

the value of the property.

server_name: str property

The server_name property.

Returns:

Type Description
str

the value of the property.

updated: datetime property

The updated property.

Returns:

Type Description
datetime

the value of the property.

Functions
get_hydrated_version() -> ServerSettingsResponse

Get the hydrated version of the server settings.

Returns:

Type Description
ServerSettingsResponse

An instance of the same entity with the metadata field attached.

Source code in src/zenml/models/v2/core/server_settings.py
110
111
112
113
114
115
116
117
118
def get_hydrated_version(self) -> "ServerSettingsResponse":
    """Get the hydrated version of the server settings.

    Returns:
        An instance of the same entity with the metadata field attached.
    """
    from zenml.client import Client

    return Client().zen_store.get_server_settings(hydrate=True)
ServerSettingsResponseBody

Bases: BaseResponseBody

Response body for server settings.

ServerSettingsResponseMetadata

Bases: BaseResponseMetadata

Response metadata for server settings.

ServerSettingsResponseResources

Bases: BaseResponseResources

Response resources for server settings.

ServerSettingsUpdate

Bases: BaseUpdate

Model for updating server settings.

ServerStatistics

Bases: BaseZenModel

Server statistics.

ServiceAccountFilter

Bases: BaseFilter

Model to enable advanced filtering of service accounts.

Functions
apply_filter(query: AnyQuery, table: Type[AnySchema]) -> AnyQuery

Override to filter out user accounts from the query.

Parameters:

Name Type Description Default
query AnyQuery

The query to which to apply the filter.

required
table Type[AnySchema]

The query table.

required

Returns:

Type Description
AnyQuery

The query with filter applied.

Source code in src/zenml/models/v2/core/service_account.py
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
def apply_filter(
    self,
    query: AnyQuery,
    table: Type["AnySchema"],
) -> AnyQuery:
    """Override to filter out user accounts from the query.

    Args:
        query: The query to which to apply the filter.
        table: The query table.

    Returns:
        The query with filter applied.
    """
    query = super().apply_filter(query=query, table=table)
    query = query.where(
        getattr(table, "is_service_account") == True  # noqa: E712
    )

    return query
ServiceAccountRequest

Bases: BaseRequest

Request model for service accounts.

ServiceAccountResponse

Bases: BaseIdentifiedResponse[ServiceAccountResponseBody, ServiceAccountResponseMetadata, ServiceAccountResponseResources]

Response model for service accounts.

Attributes
active: bool property

The active property.

Returns:

Type Description
bool

the value of the property.

description: str property

The description property.

Returns:

Type Description
str

the value of the property.

Functions
get_hydrated_version() -> ServiceAccountResponse

Get the hydrated version of this service account.

Returns:

Type Description
ServiceAccountResponse

an instance of the same entity with the metadata field attached.

Source code in src/zenml/models/v2/core/service_account.py
126
127
128
129
130
131
132
133
134
def get_hydrated_version(self) -> "ServiceAccountResponse":
    """Get the hydrated version of this service account.

    Returns:
        an instance of the same entity with the metadata field attached.
    """
    from zenml.client import Client

    return Client().zen_store.get_service_account(self.id)
to_user_model() -> UserResponse

Converts the service account to a user model.

For now, a lot of code still relies on the active user and resource owners being a UserResponse object, which is a superset of the ServiceAccountResponse object. We need this method to convert the service account to a user.

Returns:

Type Description
UserResponse

The user model.

Source code in src/zenml/models/v2/core/service_account.py
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
def to_user_model(self) -> "UserResponse":
    """Converts the service account to a user model.

    For now, a lot of code still relies on the active user and resource
    owners being a UserResponse object, which is a superset of the
    ServiceAccountResponse object. We need this method to convert the
    service account to a user.

    Returns:
        The user model.
    """
    from zenml.models.v2.core.user import (
        UserResponse,
        UserResponseBody,
        UserResponseMetadata,
    )

    return UserResponse(
        id=self.id,
        name=self.name,
        body=UserResponseBody(
            active=self.active,
            is_service_account=True,
            email_opted_in=False,
            created=self.created,
            updated=self.updated,
            is_admin=False,
        ),
        metadata=UserResponseMetadata(
            description=self.description,
        ),
    )
ServiceAccountResponseBody

Bases: BaseDatedResponseBody

Response body for service accounts.

ServiceAccountResponseMetadata

Bases: BaseResponseMetadata

Response metadata for service accounts.

ServiceAccountUpdate

Bases: BaseUpdate

Update model for service accounts.

ServiceConnectorFilter

Bases: UserScopedFilter

Model to enable advanced filtering of service connectors.

Functions
validate_labels() -> ServiceConnectorFilter

Parse the labels string into a label dictionary and vice-versa.

Returns:

Type Description
ServiceConnectorFilter

The validated values.

Source code in src/zenml/models/v2/core/service_connector.py
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
@model_validator(mode="after")
def validate_labels(self) -> "ServiceConnectorFilter":
    """Parse the labels string into a label dictionary and vice-versa.

    Returns:
        The validated values.
    """
    if self.labels_str is not None:
        try:
            self.labels = json.loads(self.labels_str)
        except json.JSONDecodeError:
            # Interpret as comma-separated values instead
            self.labels = {
                label.split("=", 1)[0]: label.split("=", 1)[1]
                if "=" in label
                else None
                for label in self.labels_str.split(",")
            }
    elif self.labels is not None:
        self.labels_str = json.dumps(self.labels)

    return self
ServiceConnectorInfo

Bases: BaseModel

Information about the service connector when creating a full stack.

ServiceConnectorRequest

Bases: UserScopedRequest

Request model for service connectors.

Attributes
emojified_connector_type: str property

Get the emojified connector type.

Returns:

Type Description
str

The emojified connector type.

emojified_resource_types: List[str] property

Get the emojified connector type.

Returns:

Type Description
List[str]

The emojified connector type.

type: str property

Get the connector type.

Returns:

Type Description
str

The connector type.

Functions
get_analytics_metadata() -> Dict[str, Any]

Format the resource types in the analytics metadata.

Returns:

Type Description
Dict[str, Any]

Dict of analytics metadata.

Source code in src/zenml/models/v2/core/service_connector.py
120
121
122
123
124
125
126
127
128
129
130
131
132
def get_analytics_metadata(self) -> Dict[str, Any]:
    """Format the resource types in the analytics metadata.

    Returns:
        Dict of analytics metadata.
    """
    metadata = super().get_analytics_metadata()
    if len(self.resource_types) == 1:
        metadata["resource_types"] = self.resource_types[0]
    else:
        metadata["resource_types"] = ", ".join(self.resource_types)
    metadata["connector_type"] = self.type
    return metadata
validate_and_configure_resources(connector_type: ServiceConnectorTypeModel, resource_types: Optional[Union[str, List[str]]] = None, resource_id: Optional[str] = None, configuration: Optional[Dict[str, Any]] = None, secrets: Optional[Dict[str, Optional[SecretStr]]] = None) -> None

Validate and configure the resources that the connector can be used to access.

Parameters:

Name Type Description Default
connector_type ServiceConnectorTypeModel

The connector type specification used to validate the connector configuration.

required
resource_types Optional[Union[str, List[str]]]

The type(s) of resource that the connector instance can be used to access. If omitted, a multi-type connector is configured.

None
resource_id Optional[str]

Uniquely identifies a specific resource instance that the connector instance can be used to access.

None
configuration Optional[Dict[str, Any]]

The connector configuration.

None
secrets Optional[Dict[str, Optional[SecretStr]]]

The connector secrets.

None
Source code in src/zenml/models/v2/core/service_connector.py
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
def validate_and_configure_resources(
    self,
    connector_type: "ServiceConnectorTypeModel",
    resource_types: Optional[Union[str, List[str]]] = None,
    resource_id: Optional[str] = None,
    configuration: Optional[Dict[str, Any]] = None,
    secrets: Optional[Dict[str, Optional[SecretStr]]] = None,
) -> None:
    """Validate and configure the resources that the connector can be used to access.

    Args:
        connector_type: The connector type specification used to validate
            the connector configuration.
        resource_types: The type(s) of resource that the connector instance
            can be used to access. If omitted, a multi-type connector is
            configured.
        resource_id: Uniquely identifies a specific resource instance that
            the connector instance can be used to access.
        configuration: The connector configuration.
        secrets: The connector secrets.
    """
    _validate_and_configure_resources(
        connector=self,
        connector_type=connector_type,
        resource_types=resource_types,
        resource_id=resource_id,
        configuration=configuration,
        secrets=secrets,
    )
ServiceConnectorRequirements

Bases: BaseModel

Service connector requirements.

Describes requirements that a service connector consumer has for a service connector instance that it needs in order to access a resource.

Attributes:

Name Type Description
connector_type Optional[str]

The type of service connector that is required. If omitted, any service connector type can be used.

resource_type str

The type of resource that the service connector instance must be able to access.

resource_id_attr Optional[str]

The name of an attribute in the stack component configuration that contains the resource ID of the resource that the service connector instance must be able to access.

Functions
is_satisfied_by(connector: Union[ServiceConnectorResponse, ServiceConnectorRequest], component: Union[ComponentResponse, ComponentBase]) -> Tuple[bool, str]

Check if the requirements are satisfied by a connector.

Parameters:

Name Type Description Default
connector Union[ServiceConnectorResponse, ServiceConnectorRequest]

The connector to check.

required
component Union[ComponentResponse, ComponentBase]

The stack component that the connector is associated with.

required

Returns:

Type Description
bool

True if the requirements are satisfied, False otherwise, and a

str

message describing the reason for the failure.

Source code in src/zenml/models/v2/misc/service_connector_type.py
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
def is_satisfied_by(
    self,
    connector: Union[
        "ServiceConnectorResponse", "ServiceConnectorRequest"
    ],
    component: Union["ComponentResponse", "ComponentBase"],
) -> Tuple[bool, str]:
    """Check if the requirements are satisfied by a connector.

    Args:
        connector: The connector to check.
        component: The stack component that the connector is associated
            with.

    Returns:
        True if the requirements are satisfied, False otherwise, and a
        message describing the reason for the failure.
    """
    if self.connector_type and self.connector_type != connector.type:
        return (
            False,
            f"connector type '{connector.type}' does not match the "
            f"'{self.connector_type}' connector type specified in the "
            "stack component requirements",
        )
    if self.resource_type not in connector.resource_types:
        return False, (
            f"connector does not provide the '{self.resource_type}' "
            "resource type specified in the stack component requirements. "
            "Only the following resource types are supported: "
            f"{', '.join(connector.resource_types)}"
        )
    if self.resource_id_attr:
        resource_id = component.configuration.get(self.resource_id_attr)
        if not resource_id:
            return (
                False,
                f"the '{self.resource_id_attr}' stack component "
                f"configuration attribute plays the role of resource "
                f"identifier, but the stack component does not contain a "
                f"'{self.resource_id_attr}' attribute. Please add the "
                f"'{self.resource_id_attr}' attribute to the stack "
                "component configuration and try again.",
            )

    return True, ""
ServiceConnectorResourcesInfo

Bases: BaseModel

Information about the service connector resources needed for CLI and UI.

ServiceConnectorResourcesModel

Bases: BaseModel

Service connector resources list.

Lists the resource types and resource instances that a service connector can provide access to.

Attributes
emojified_connector_type: str property

Get the emojified connector type.

Returns:

Type Description
str

The emojified connector type.

resource_types: List[str] property

Get the resource types.

Returns:

Type Description
List[str]

The resource types.

resources_dict: Dict[str, ServiceConnectorTypedResourcesModel] property

Get the resources as a dictionary indexed by resource type.

Returns:

Type Description
Dict[str, ServiceConnectorTypedResourcesModel]

The resources as a dictionary indexed by resource type.

type: str property

Get the connector type.

Returns:

Type Description
str

The connector type.

Functions
from_connector_model(connector_model: ServiceConnectorResponse, resource_type: Optional[str] = None) -> ServiceConnectorResourcesModel classmethod

Initialize a resource model from a connector model.

Parameters:

Name Type Description Default
connector_model ServiceConnectorResponse

The connector model.

required
resource_type Optional[str]

The resource type to set on the resource model. If omitted, the resource type is set according to the connector model.

None

Returns:

Type Description
ServiceConnectorResourcesModel

A resource list model instance.

Source code in src/zenml/models/v2/misc/service_connector_type.py
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
@classmethod
def from_connector_model(
    cls,
    connector_model: "ServiceConnectorResponse",
    resource_type: Optional[str] = None,
) -> "ServiceConnectorResourcesModel":
    """Initialize a resource model from a connector model.

    Args:
        connector_model: The connector model.
        resource_type: The resource type to set on the resource model. If
            omitted, the resource type is set according to the connector
            model.

    Returns:
        A resource list model instance.
    """
    resources = cls(
        id=connector_model.id,
        name=connector_model.name,
        connector_type=connector_model.type,
    )

    resource_types = resource_type or connector_model.resource_types
    for resource_type in resource_types:
        resources.resources.append(
            ServiceConnectorTypedResourcesModel(
                resource_type=resource_type,
                resource_ids=[connector_model.resource_id]
                if connector_model.resource_id
                else None,
            )
        )

    return resources
get_default_resource_id() -> Optional[str]

Get the default resource ID, if included in the resource list.

The default resource ID is a resource ID supplied by the connector implementation only for resource types that do not support multiple instances.

Returns:

Type Description
Optional[str]

The default resource ID, or None if no resource ID is set.

Source code in src/zenml/models/v2/misc/service_connector_type.py
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
def get_default_resource_id(self) -> Optional[str]:
    """Get the default resource ID, if included in the resource list.

    The default resource ID is a resource ID supplied by the connector
    implementation only for resource types that do not support multiple
    instances.

    Returns:
        The default resource ID, or None if no resource ID is set.
    """
    if len(self.resources) != 1:
        # multi-type connectors do not have a default resource ID
        return None

    if isinstance(self.connector_type, str):
        # can't determine default resource ID for unknown connector types
        return None

    resource_type_spec = self.connector_type.resource_type_dict[
        self.resources[0].resource_type
    ]
    if resource_type_spec.supports_instances:
        # resource types that support multiple instances do not have a
        # default resource ID
        return None

    resource_ids = self.resources[0].resource_ids

    if not resource_ids or len(resource_ids) != 1:
        return None

    return resource_ids[0]
get_emojified_resource_types(resource_type: Optional[str] = None) -> List[str]

Get the emojified resource type.

Parameters:

Name Type Description Default
resource_type Optional[str]

The resource type to get the emojified resource type for. If omitted, the emojified resource type for all resource types is returned.

None

Returns:

Type Description
List[str]

The list of emojified resource types.

Source code in src/zenml/models/v2/misc/service_connector_type.py
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
def get_emojified_resource_types(
    self, resource_type: Optional[str] = None
) -> List[str]:
    """Get the emojified resource type.

    Args:
        resource_type: The resource type to get the emojified resource type
            for. If omitted, the emojified resource type for all resource
            types is returned.


    Returns:
        The list of emojified resource types.
    """
    if not isinstance(self.connector_type, str):
        if resource_type:
            return [
                self.connector_type.resource_type_dict[
                    resource_type
                ].emojified_resource_type
            ]
        return [
            self.connector_type.resource_type_dict[
                resource_type
            ].emojified_resource_type
            for resource_type in self.resources_dict.keys()
        ]
    if resource_type:
        return [resource_type]
    return list(self.resources_dict.keys())
set_error(error: str, resource_type: Optional[str] = None) -> None

Set a global error message or an error for a single resource type.

Parameters:

Name Type Description Default
error str

The error message.

required
resource_type Optional[str]

The resource type to set the error message for. If omitted, or if there is only one resource type involved, the error message is (also) set globally.

None

Raises:

Type Description
KeyError

If the resource type is not found in the resources list.

Source code in src/zenml/models/v2/misc/service_connector_type.py
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
def set_error(
    self, error: str, resource_type: Optional[str] = None
) -> None:
    """Set a global error message or an error for a single resource type.

    Args:
        error: The error message.
        resource_type: The resource type to set the error message for. If
            omitted, or if there is only one resource type involved, the
            error message is (also) set globally.

    Raises:
        KeyError: If the resource type is not found in the resources list.
    """
    if resource_type:
        resource = self.resources_dict.get(resource_type)
        if not resource:
            raise KeyError(
                f"resource type '{resource_type}' not found in "
                "service connector resources list"
            )
        resource.error = error
        resource.resource_ids = None
        if len(self.resources) == 1:
            # If there is only one resource type involved, set the global
            # error message as well.
            self.error = error
    else:
        self.error = error
        for resource in self.resources:
            resource.error = error
            resource.resource_ids = None
set_resource_ids(resource_type: str, resource_ids: List[str]) -> None

Set the resource IDs for a resource type.

Parameters:

Name Type Description Default
resource_type str

The resource type to set the resource IDs for.

required
resource_ids List[str]

The resource IDs to set.

required

Raises:

Type Description
KeyError

If the resource type is not found in the resources list.

Source code in src/zenml/models/v2/misc/service_connector_type.py
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
def set_resource_ids(
    self, resource_type: str, resource_ids: List[str]
) -> None:
    """Set the resource IDs for a resource type.

    Args:
        resource_type: The resource type to set the resource IDs for.
        resource_ids: The resource IDs to set.

    Raises:
        KeyError: If the resource type is not found in the resources list.
    """
    resource = self.resources_dict.get(resource_type)
    if not resource:
        raise KeyError(
            f"resource type '{resource_type}' not found in "
            "service connector resources list"
        )
    resource.resource_ids = resource_ids
    resource.error = None
ServiceConnectorResponse

Bases: UserScopedResponse[ServiceConnectorResponseBody, ServiceConnectorResponseMetadata, ServiceConnectorResponseResources]

Response model for service connectors.

Attributes
auth_method: str property

The auth_method property.

Returns:

Type Description
str

the value of the property.

configuration: Dict[str, Any] property

The configuration property.

Returns:

Type Description
Dict[str, Any]

the value of the property.

connector_type: Union[str, ServiceConnectorTypeModel] property

The connector_type property.

Returns:

Type Description
Union[str, ServiceConnectorTypeModel]

the value of the property.

description: str property

The description property.

Returns:

Type Description
str

the value of the property.

emojified_connector_type: str property

Get the emojified connector type.

Returns:

Type Description
str

The emojified connector type.

emojified_resource_types: List[str] property

Get the emojified connector type.

Returns:

Type Description
List[str]

The emojified connector type.

expiration_seconds: Optional[int] property

The expiration_seconds property.

Returns:

Type Description
Optional[int]

the value of the property.

expires_at: Optional[datetime] property

The expires_at property.

Returns:

Type Description
Optional[datetime]

the value of the property.

expires_skew_tolerance: Optional[int] property

The expires_skew_tolerance property.

Returns:

Type Description
Optional[int]

the value of the property.

full_configuration: Dict[str, str] property

Get the full connector configuration, including secrets.

Returns:

Type Description
Dict[str, str]

The full connector configuration, including secrets.

is_multi_instance: bool property

Checks if the connector is multi-instance.

A multi-instance connector is configured to access multiple instances of the configured resource type.

Returns:

Type Description
bool

True if the connector is multi-instance, False otherwise.

is_multi_type: bool property

Checks if the connector is multi-type.

A multi-type connector can be used to access multiple types of resources.

Returns:

Type Description
bool

True if the connector is multi-type, False otherwise.

is_single_instance: bool property

Checks if the connector is single-instance.

A single-instance connector is configured to access only a single instance of the configured resource type or does not support multiple resource instances.

Returns:

Type Description
bool

True if the connector is single-instance, False otherwise.

labels: Dict[str, str] property

The labels property.

Returns:

Type Description
Dict[str, str]

the value of the property.

resource_id: Optional[str] property

The resource_id property.

Returns:

Type Description
Optional[str]

the value of the property.

resource_types: List[str] property

The resource_types property.

Returns:

Type Description
List[str]

the value of the property.

secret_id: Optional[UUID] property

The secret_id property.

Returns:

Type Description
Optional[UUID]

the value of the property.

secrets: Dict[str, Optional[SecretStr]] property

The secrets property.

Returns:

Type Description
Dict[str, Optional[SecretStr]]

the value of the property.

supports_instances: bool property

The supports_instances property.

Returns:

Type Description
bool

the value of the property.

type: str property

Get the connector type.

Returns:

Type Description
str

The connector type.

Functions
get_analytics_metadata() -> Dict[str, Any]

Add the service connector labels to analytics metadata.

Returns:

Type Description
Dict[str, Any]

Dict of analytics metadata.

Source code in src/zenml/models/v2/core/service_connector.py
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
def get_analytics_metadata(self) -> Dict[str, Any]:
    """Add the service connector labels to analytics metadata.

    Returns:
        Dict of analytics metadata.
    """
    metadata = super().get_analytics_metadata()

    metadata.update(
        {
            label[6:]: value
            for label, value in self.labels.items()
            if label.startswith("zenml:")
        }
    )
    return metadata
get_hydrated_version() -> ServiceConnectorResponse

Get the hydrated version of this service connector.

Returns:

Type Description
ServiceConnectorResponse

an instance of the same entity with the metadata field attached.

Source code in src/zenml/models/v2/core/service_connector.py
515
516
517
518
519
520
521
522
523
def get_hydrated_version(self) -> "ServiceConnectorResponse":
    """Get the hydrated version of this service connector.

    Returns:
        an instance of the same entity with the metadata field attached.
    """
    from zenml.client import Client

    return Client().zen_store.get_service_connector(self.id)
set_connector_type(value: Union[str, ServiceConnectorTypeModel]) -> None

Auxiliary method to set the connector type.

Parameters:

Name Type Description Default
value Union[str, ServiceConnectorTypeModel]

the new value for the connector type.

required
Source code in src/zenml/models/v2/core/service_connector.py
620
621
622
623
624
625
626
627
628
def set_connector_type(
    self, value: Union[str, "ServiceConnectorTypeModel"]
) -> None:
    """Auxiliary method to set the connector type.

    Args:
        value: the new value for the connector type.
    """
    self.get_body().connector_type = value
validate_and_configure_resources(connector_type: ServiceConnectorTypeModel, resource_types: Optional[Union[str, List[str]]] = None, resource_id: Optional[str] = None, configuration: Optional[Dict[str, Any]] = None, secrets: Optional[Dict[str, Optional[SecretStr]]] = None) -> None

Validate and configure the resources that the connector can be used to access.

Parameters:

Name Type Description Default
connector_type ServiceConnectorTypeModel

The connector type specification used to validate the connector configuration.

required
resource_types Optional[Union[str, List[str]]]

The type(s) of resource that the connector instance can be used to access. If omitted, a multi-type connector is configured.

None
resource_id Optional[str]

Uniquely identifies a specific resource instance that the connector instance can be used to access.

None
configuration Optional[Dict[str, Any]]

The connector configuration.

None
secrets Optional[Dict[str, Optional[SecretStr]]]

The connector secrets.

None
Source code in src/zenml/models/v2/core/service_connector.py
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
def validate_and_configure_resources(
    self,
    connector_type: "ServiceConnectorTypeModel",
    resource_types: Optional[Union[str, List[str]]] = None,
    resource_id: Optional[str] = None,
    configuration: Optional[Dict[str, Any]] = None,
    secrets: Optional[Dict[str, Optional[SecretStr]]] = None,
) -> None:
    """Validate and configure the resources that the connector can be used to access.

    Args:
        connector_type: The connector type specification used to validate
            the connector configuration.
        resource_types: The type(s) of resource that the connector instance
            can be used to access. If omitted, a multi-type connector is
            configured.
        resource_id: Uniquely identifies a specific resource instance that
            the connector instance can be used to access.
        configuration: The connector configuration.
        secrets: The connector secrets.
    """
    _validate_and_configure_resources(
        connector=self,
        connector_type=connector_type,
        resource_types=resource_types,
        resource_id=resource_id,
        configuration=configuration,
        secrets=secrets,
    )
ServiceConnectorResponseBody

Bases: UserScopedResponseBody

Response body for service connectors.

ServiceConnectorResponseMetadata

Bases: UserScopedResponseMetadata

Response metadata for service connectors.

ServiceConnectorTypeModel

Bases: BaseModel

Service connector type specification.

Describes the types of resources to which the service connector can be used to gain access and the authentication methods that are supported by the service connector.

The connector type, resource types, resource IDs and authentication methods can all be used as search criteria to lookup and filter service connector instances that are compatible with the requirements of a consumer (e.g. a stack component).

Attributes
auth_method_dict: Dict[str, AuthenticationMethodModel] property

Returns a map of authentication methods to authentication method specifications.

Returns:

Type Description
Dict[str, AuthenticationMethodModel]

A map of authentication methods to authentication method

Dict[str, AuthenticationMethodModel]

specifications.

connector_class: Optional[Type[ServiceConnector]] property

Get the service connector class.

Returns:

Type Description
Optional[Type[ServiceConnector]]

The service connector class.

emojified_connector_type: str property

Get the emojified connector type.

Returns:

Type Description
str

The emojified connector type.

emojified_resource_types: List[str] property

Get the emojified connector types.

Returns:

Type Description
List[str]

The emojified connector types.

resource_type_dict: Dict[str, ResourceTypeModel] property

Returns a map of resource types to resource type specifications.

Returns:

Type Description
Dict[str, ResourceTypeModel]

A map of resource types to resource type specifications.

Functions
find_resource_specifications(auth_method: str, resource_type: Optional[str] = None) -> Tuple[AuthenticationMethodModel, Optional[ResourceTypeModel]]

Find the specifications for a configurable resource.

Validate the supplied connector configuration parameters against the connector specification and return the matching authentication method specification and resource specification.

Parameters:

Name Type Description Default
auth_method str

The name of the authentication method.

required
resource_type Optional[str]

The type of resource being configured.

None

Returns:

Type Description
AuthenticationMethodModel

The authentication method specification and resource specification

Optional[ResourceTypeModel]

for the specified authentication method and resource type.

Raises:

Type Description
KeyError

If the authentication method is not supported by the connector for the specified resource type and ID.

Source code in src/zenml/models/v2/misc/service_connector_type.py
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
def find_resource_specifications(
    self,
    auth_method: str,
    resource_type: Optional[str] = None,
) -> Tuple[AuthenticationMethodModel, Optional[ResourceTypeModel]]:
    """Find the specifications for a configurable resource.

    Validate the supplied connector configuration parameters against the
    connector specification and return the matching authentication method
    specification and resource specification.

    Args:
        auth_method: The name of the authentication method.
        resource_type: The type of resource being configured.

    Returns:
        The authentication method specification and resource specification
        for the specified authentication method and resource type.

    Raises:
        KeyError: If the authentication method is not supported by the
            connector for the specified resource type and ID.
    """
    # Verify the authentication method
    auth_method_dict = self.auth_method_dict
    if auth_method in auth_method_dict:
        # A match was found for the authentication method
        auth_method_spec = auth_method_dict[auth_method]
    else:
        # No match was found for the authentication method
        raise KeyError(
            f"connector type '{self.connector_type}' does not support the "
            f"'{auth_method}' authentication method. Supported "
            f"authentication methods are: {list(auth_method_dict.keys())}."
        )

    if resource_type is None:
        # No resource type was specified, so no resource type
        # specification can be returned.
        return auth_method_spec, None

    # Verify the resource type
    resource_type_dict = self.resource_type_dict
    if resource_type in resource_type_dict:
        resource_type_spec = resource_type_dict[resource_type]
    else:
        raise KeyError(
            f"connector type '{self.connector_type}' does not support "
            f"resource type '{resource_type}'. Supported resource types "
            f"are: {list(resource_type_dict.keys())}."
        )

    if auth_method not in resource_type_spec.auth_methods:
        raise KeyError(
            f"the '{self.connector_type}' connector type does not support "
            f"the '{auth_method}' authentication method for the "
            f"'{resource_type}' resource type. Supported authentication "
            f"methods are: {resource_type_spec.auth_methods}."
        )

    return auth_method_spec, resource_type_spec
set_connector_class(connector_class: Type[ServiceConnector]) -> None

Set the service connector class.

Parameters:

Name Type Description Default
connector_class Type[ServiceConnector]

The service connector class.

required
Source code in src/zenml/models/v2/misc/service_connector_type.py
321
322
323
324
325
326
327
328
329
def set_connector_class(
    self, connector_class: Type["ServiceConnector"]
) -> None:
    """Set the service connector class.

    Args:
        connector_class: The service connector class.
    """
    self._connector_class = connector_class
validate_auth_methods(values: List[AuthenticationMethodModel]) -> List[AuthenticationMethodModel] classmethod

Validate that the authentication methods are unique.

Parameters:

Name Type Description Default
values List[AuthenticationMethodModel]

The list of authentication methods.

required

Returns:

Type Description
List[AuthenticationMethodModel]

The list of authentication methods.

Raises:

Type Description
ValueError

If two or more authentication method specifications share the same authentication method value.

Source code in src/zenml/models/v2/misc/service_connector_type.py
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
@field_validator("auth_methods")
@classmethod
def validate_auth_methods(
    cls, values: List[AuthenticationMethodModel]
) -> List[AuthenticationMethodModel]:
    """Validate that the authentication methods are unique.

    Args:
        values: The list of authentication methods.

    Returns:
        The list of authentication methods.

    Raises:
        ValueError: If two or more authentication method specifications
            share the same authentication method value.
    """
    # Gather all auth methods from the list of auth method
    # specifications.
    auth_methods = [a.auth_method for a in values]
    if len(auth_methods) != len(set(auth_methods)):
        raise ValueError(
            "Two or more authentication method specifications must not "
            "share the same authentication method value."
        )

    return values
validate_resource_types(values: List[ResourceTypeModel]) -> List[ResourceTypeModel] classmethod

Validate that the resource types are unique.

Parameters:

Name Type Description Default
values List[ResourceTypeModel]

The list of resource types.

required

Returns:

Type Description
List[ResourceTypeModel]

The list of resource types.

Raises:

Type Description
ValueError

If two or more resource type specifications list the same resource type.

Source code in src/zenml/models/v2/misc/service_connector_type.py
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
@field_validator("resource_types")
@classmethod
def validate_resource_types(
    cls, values: List[ResourceTypeModel]
) -> List[ResourceTypeModel]:
    """Validate that the resource types are unique.

    Args:
        values: The list of resource types.

    Returns:
        The list of resource types.

    Raises:
        ValueError: If two or more resource type specifications list the
            same resource type.
    """
    # Gather all resource types from the list of resource type
    # specifications.
    resource_types = [r.resource_type for r in values]
    if len(resource_types) != len(set(resource_types)):
        raise ValueError(
            "Two or more resource type specifications must not list "
            "the same resource type."
        )

    return values
ServiceConnectorTypedResourcesModel

Bases: BaseModel

Service connector typed resources list.

Lists the resource instances that a service connector can provide access to.

ServiceConnectorUpdate

Bases: BaseUpdate

Model used for service connector updates.

Most fields in the update model are optional and will not be updated if omitted. However, the following fields are "special" and leaving them out will also cause the corresponding value to be removed from the service connector in the database:

  • the resource_id field
  • the expiration_seconds field

In addition to the above exceptions, the following rules apply:

  • the configuration and secrets fields together represent a full valid configuration update, not just a partial update. If either is set (i.e. not None) in the update, their values are merged together and will replace the existing configuration and secrets values.
  • the labels field is also a full labels update: if set (i.e. not None), all existing labels are removed and replaced by the new labels in the update.

NOTE: the attributes here override the ones in the base class, so they have a None default value.

Attributes
type: Optional[str] property

Get the connector type.

Returns:

Type Description
Optional[str]

The connector type.

Functions
convert_to_request() -> ServiceConnectorRequest

Method to generate a service connector request object from self.

For certain operations, the service connector update model need to adhere to the limitations set by the request model. In order to use update models in such situations, we need to be able to convert an update model into a request model.

Returns:

Type Description
ServiceConnectorRequest

The equivalent request model

Raises:

Type Description
RuntimeError

if the model can not be converted to a request model.

Source code in src/zenml/models/v2/core/service_connector.py
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
def convert_to_request(self) -> "ServiceConnectorRequest":
    """Method to generate a service connector request object from self.

    For certain operations, the service connector update model need to
    adhere to the limitations set by the request model. In order to use
    update models in such situations, we need to be able to convert an
    update model into a request model.

    Returns:
        The equivalent request model

    Raises:
        RuntimeError: if the model can not be converted to a request model.
    """
    try:
        return ServiceConnectorRequest.model_validate(self.model_dump())
    except ValidationError as e:
        raise RuntimeError(
            "The service connector update model can not be converted into "
            f"an equivalent request model: {e}"
        )
get_analytics_metadata() -> Dict[str, Any]

Format the resource types in the analytics metadata.

Returns:

Type Description
Dict[str, Any]

Dict of analytics metadata.

Source code in src/zenml/models/v2/core/service_connector.py
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
def get_analytics_metadata(self) -> Dict[str, Any]:
    """Format the resource types in the analytics metadata.

    Returns:
        Dict of analytics metadata.
    """
    metadata = super().get_analytics_metadata()

    if self.resource_types is not None:
        if len(self.resource_types) == 1:
            metadata["resource_types"] = self.resource_types[0]
        else:
            metadata["resource_types"] = ", ".join(self.resource_types)

    if self.connector_type is not None:
        metadata["connector_type"] = self.type

    return metadata
validate_and_configure_resources(connector_type: ServiceConnectorTypeModel, resource_types: Optional[Union[str, List[str]]] = None, resource_id: Optional[str] = None, configuration: Optional[Dict[str, Any]] = None, secrets: Optional[Dict[str, Optional[SecretStr]]] = None) -> None

Validate and configure the resources that the connector can be used to access.

Parameters:

Name Type Description Default
connector_type ServiceConnectorTypeModel

The connector type specification used to validate the connector configuration.

required
resource_types Optional[Union[str, List[str]]]

The type(s) of resource that the connector instance can be used to access. If omitted, a multi-type connector is configured.

None
resource_id Optional[str]

Uniquely identifies a specific resource instance that the connector instance can be used to access.

None
configuration Optional[Dict[str, Any]]

The connector configuration.

None
secrets Optional[Dict[str, Optional[SecretStr]]]

The connector secrets.

None
Source code in src/zenml/models/v2/core/service_connector.py
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
def validate_and_configure_resources(
    self,
    connector_type: "ServiceConnectorTypeModel",
    resource_types: Optional[Union[str, List[str]]] = None,
    resource_id: Optional[str] = None,
    configuration: Optional[Dict[str, Any]] = None,
    secrets: Optional[Dict[str, Optional[SecretStr]]] = None,
) -> None:
    """Validate and configure the resources that the connector can be used to access.

    Args:
        connector_type: The connector type specification used to validate
            the connector configuration.
        resource_types: The type(s) of resource that the connector instance
            can be used to access. If omitted, a multi-type connector is
            configured.
        resource_id: Uniquely identifies a specific resource instance that
            the connector instance can be used to access.
        configuration: The connector configuration.
        secrets: The connector secrets.
    """
    _validate_and_configure_resources(
        connector=self,
        connector_type=connector_type,
        resource_types=resource_types,
        resource_id=resource_id,
        configuration=configuration,
        secrets=secrets,
    )
ServiceFilter

Bases: ProjectScopedFilter

Model to enable advanced filtering of services.

Functions
generate_filter(table: Type[AnySchema]) -> Union[ColumnElement[bool]]

Generate the filter for the query.

Services can be scoped by type to narrow the search.

Parameters:

Name Type Description Default
table Type[AnySchema]

The Table that is being queried from.

required

Returns:

Type Description
Union[ColumnElement[bool]]

The filter expression for the query.

Source code in src/zenml/models/v2/core/service.py
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
def generate_filter(
    self, table: Type["AnySchema"]
) -> Union["ColumnElement[bool]"]:
    """Generate the filter for the query.

    Services can be scoped by type to narrow the search.

    Args:
        table: The Table that is being queried from.

    Returns:
        The filter expression for the query.
    """
    from sqlmodel import and_

    base_filter = super().generate_filter(table)

    if self.type:
        type_filter = getattr(table, "type") == self.type
        base_filter = and_(base_filter, type_filter)

    if self.flavor:
        flavor_filter = getattr(table, "flavor") == self.flavor
        base_filter = and_(base_filter, flavor_filter)

    if self.pipeline_name:
        pipeline_name_filter = (
            getattr(table, "pipeline_name") == self.pipeline_name
        )
        base_filter = and_(base_filter, pipeline_name_filter)

    if self.pipeline_step_name:
        pipeline_step_name_filter = (
            getattr(table, "pipeline_step_name") == self.pipeline_step_name
        )
        base_filter = and_(base_filter, pipeline_step_name_filter)

    return base_filter
set_flavor(flavor: str) -> None

Set the flavor of the service.

Parameters:

Name Type Description Default
flavor str

The flavor of the service.

required
Source code in src/zenml/models/v2/core/service.py
467
468
469
470
471
472
473
def set_flavor(self, flavor: str) -> None:
    """Set the flavor of the service.

    Args:
        flavor: The flavor of the service.
    """
    self.flavor = flavor
set_type(type: str) -> None

Set the type of the service.

Parameters:

Name Type Description Default
type str

The type of the service.

required
Source code in src/zenml/models/v2/core/service.py
459
460
461
462
463
464
465
def set_type(self, type: str) -> None:
    """Set the type of the service.

    Args:
        type: The type of the service.
    """
    self.type = type
ServiceRequest

Bases: ProjectScopedRequest

Request model for services.

ServiceResponse

Bases: ProjectScopedResponse[ServiceResponseBody, ServiceResponseMetadata, ServiceResponseResources]

Response model for services.

Attributes
admin_state: Optional[ServiceState] property

The admin_state property.

Returns:

Type Description
Optional[ServiceState]

the value of the property.

config: Dict[str, Any] property

The config property.

Returns:

Type Description
Dict[str, Any]

the value of the property.

created: datetime property

The created property.

Returns:

Type Description
datetime

the value of the property.

endpoint: Optional[Dict[str, Any]] property

The endpoint property.

Returns:

Type Description
Optional[Dict[str, Any]]

the value of the property.

health_check_url: Optional[str] property

The health_check_url property.

Returns:

Type Description
Optional[str]

the value of the property.

labels: Optional[Dict[str, str]] property

The labels property.

Returns:

Type Description
Optional[Dict[str, str]]

the value of the property.

model_version: Optional[ModelVersionResponse] property

The model_version property.

Returns:

Type Description
Optional[ModelVersionResponse]

the value of the property.

pipeline_run: Optional[PipelineRunResponse] property

The pipeline_run property.

Returns:

Type Description
Optional[PipelineRunResponse]

the value of the property.

prediction_url: Optional[str] property

The prediction_url property.

Returns:

Type Description
Optional[str]

the value of the property.

service_source: Optional[str] property

The service_source property.

Returns:

Type Description
Optional[str]

the value of the property.

service_type: ServiceType property

The service_type property.

Returns:

Type Description
ServiceType

the value of the property.

state: Optional[ServiceState] property

The state property.

Returns:

Type Description
Optional[ServiceState]

the value of the property.

status: Optional[Dict[str, Any]] property

The status property.

Returns:

Type Description
Optional[Dict[str, Any]]

the value of the property.

updated: datetime property

The updated property.

Returns:

Type Description
datetime

the value of the property.

Functions
get_hydrated_version() -> ServiceResponse

Get the hydrated version of this artifact.

Returns:

Type Description
ServiceResponse

an instance of the same entity with the metadata field attached.

Source code in src/zenml/models/v2/core/service.py
265
266
267
268
269
270
271
272
273
def get_hydrated_version(self) -> "ServiceResponse":
    """Get the hydrated version of this artifact.

    Returns:
        an instance of the same entity with the metadata field attached.
    """
    from zenml.client import Client

    return Client().zen_store.get_service(self.id)
ServiceResponseBody

Bases: ProjectScopedResponseBody

Response body for services.

ServiceResponseMetadata

Bases: ProjectScopedResponseMetadata

Response metadata for services.

ServiceResponseResources

Bases: ProjectScopedResponseResources

Class for all resource models associated with the service entity.

ServiceType

Bases: BaseModel

Service type descriptor.

Attributes:

Name Type Description
type str

service type

flavor str

service flavor

name str

name of the service type

description str

description of the service type

logo_url str

logo of the service type

ServiceUpdate

Bases: BaseUpdate

Update model for stack components.

StackDeploymentConfig

Bases: BaseModel

Configuration about a stack deployment.

StackDeploymentInfo

Bases: BaseModel

Information about a stack deployment.

StackFilter

Bases: UserScopedFilter

Model to enable advanced stack filtering.

Functions
get_custom_filters(table: Type[AnySchema]) -> List[ColumnElement[bool]]

Get custom filters.

Parameters:

Name Type Description Default
table Type[AnySchema]

The query table.

required

Returns:

Type Description
List[ColumnElement[bool]]

A list of custom filters.

Source code in src/zenml/models/v2/core/stack.py
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
def get_custom_filters(
    self, table: Type["AnySchema"]
) -> List["ColumnElement[bool]"]:
    """Get custom filters.

    Args:
        table: The query table.

    Returns:
        A list of custom filters.
    """
    custom_filters = super().get_custom_filters(table)

    from zenml.zen_stores.schemas import (
        StackComponentSchema,
        StackCompositionSchema,
        StackSchema,
    )

    if self.component_id:
        component_id_filter = and_(
            StackCompositionSchema.stack_id == StackSchema.id,
            StackCompositionSchema.component_id == self.component_id,
        )
        custom_filters.append(component_id_filter)

    if self.component:
        component_filter = and_(
            StackCompositionSchema.stack_id == StackSchema.id,
            StackCompositionSchema.component_id == StackComponentSchema.id,
            self.generate_name_or_id_query_conditions(
                value=self.component,
                table=StackComponentSchema,
            ),
        )
        custom_filters.append(component_filter)

    return custom_filters
StackRequest

Bases: UserScopedRequest

Request model for stack creation.

Attributes
is_valid: bool property

Check if the stack is valid.

Returns:

Type Description
bool

True if the stack is valid, False otherwise.

StackResponse

Bases: UserScopedResponse[StackResponseBody, StackResponseMetadata, StackResponseResources]

Response model for stacks.

Attributes
components: Dict[StackComponentType, List[ComponentResponse]] property

The components property.

Returns:

Type Description
Dict[StackComponentType, List[ComponentResponse]]

the value of the property.

description: Optional[str] property

The description property.

Returns:

Type Description
Optional[str]

the value of the property.

is_valid: bool property

Check if the stack is valid.

Returns:

Type Description
bool

True if the stack is valid, False otherwise.

labels: Optional[Dict[str, Any]] property

The labels property.

Returns:

Type Description
Optional[Dict[str, Any]]

the value of the property.

stack_spec_path: Optional[str] property

The stack_spec_path property.

Returns:

Type Description
Optional[str]

the value of the property.

Functions
get_analytics_metadata() -> Dict[str, Any]

Add the stack components to the stack analytics metadata.

Returns:

Type Description
Dict[str, Any]

Dict of analytics metadata.

Source code in src/zenml/models/v2/core/stack.py
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
def get_analytics_metadata(self) -> Dict[str, Any]:
    """Add the stack components to the stack analytics metadata.

    Returns:
        Dict of analytics metadata.
    """
    metadata = super().get_analytics_metadata()
    metadata.update(
        {ct: c[0].flavor_name for ct, c in self.components.items()}
    )

    if self.labels is not None:
        metadata.update(
            {
                label[6:]: value
                for label, value in self.labels.items()
                if label.startswith("zenml:")
            }
        )
    return metadata
get_hydrated_version() -> StackResponse

Get the hydrated version of this stack.

Returns:

Type Description
StackResponse

an instance of the same entity with the metadata field attached.

Source code in src/zenml/models/v2/core/stack.py
213
214
215
216
217
218
219
220
221
def get_hydrated_version(self) -> "StackResponse":
    """Get the hydrated version of this stack.

    Returns:
        an instance of the same entity with the metadata field attached.
    """
    from zenml.client import Client

    return Client().zen_store.get_stack(self.id)
to_yaml() -> Dict[str, Any]

Create yaml representation of the Stack Model.

Returns:

Type Description
Dict[str, Any]

The yaml representation of the Stack Model.

Source code in src/zenml/models/v2/core/stack.py
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
def to_yaml(self) -> Dict[str, Any]:
    """Create yaml representation of the Stack Model.

    Returns:
        The yaml representation of the Stack Model.
    """
    component_data = {}
    for component_type, components_list in self.components.items():
        component = components_list[0]
        component_dict = dict(
            name=component.name,
            type=str(component.type),
            flavor=component.flavor_name,
        )
        configuration = json.loads(
            component.get_metadata().model_dump_json(
                include={"configuration"}
            )
        )
        component_dict.update(configuration)

        component_data[component_type.value] = component_dict

    # write zenml version and stack dict to YAML
    yaml_data = {
        "stack_name": self.name,
        "components": component_data,
    }

    return yaml_data
StackResponseBody

Bases: UserScopedResponseBody

Response body for stacks.

StackResponseMetadata

Bases: UserScopedResponseMetadata

Response metadata for stacks.

StackUpdate

Bases: BaseUpdate

Update model for stacks.

StepRunFilter

Bases: ProjectScopedFilter, RunMetadataFilterMixin

Model to enable advanced filtering of step runs.

Functions
get_custom_filters(table: Type[AnySchema]) -> List[ColumnElement[bool]]

Get custom filters.

Parameters:

Name Type Description Default
table Type[AnySchema]

The query table.

required

Returns:

Type Description
List[ColumnElement[bool]]

A list of custom filters.

Source code in src/zenml/models/v2/core/step_run.py
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
def get_custom_filters(
    self, table: Type["AnySchema"]
) -> List["ColumnElement[bool]"]:
    """Get custom filters.

    Args:
        table: The query table.

    Returns:
        A list of custom filters.
    """
    custom_filters = super().get_custom_filters(table)

    from sqlmodel import and_

    from zenml.zen_stores.schemas import (
        ModelSchema,
        ModelVersionSchema,
        StepRunSchema,
    )

    if self.model:
        model_filter = and_(
            StepRunSchema.model_version_id == ModelVersionSchema.id,
            ModelVersionSchema.model_id == ModelSchema.id,
            self.generate_name_or_id_query_conditions(
                value=self.model, table=ModelSchema
            ),
        )
        custom_filters.append(model_filter)

    return custom_filters
StepRunRequest

Bases: ProjectScopedRequest

Request model for step runs.

StepRunResponse

Bases: ProjectScopedResponse[StepRunResponseBody, StepRunResponseMetadata, StepRunResponseResources]

Response model for step runs.

Attributes
cache_key: Optional[str] property

The cache_key property.

Returns:

Type Description
Optional[str]

the value of the property.

code_hash: Optional[str] property

The code_hash property.

Returns:

Type Description
Optional[str]

the value of the property.

config: StepConfiguration property

The config property.

Returns:

Type Description
StepConfiguration

the value of the property.

deployment_id: UUID property

The deployment_id property.

Returns:

Type Description
UUID

the value of the property.

docstring: Optional[str] property

The docstring property.

Returns:

Type Description
Optional[str]

the value of the property.

end_time: Optional[datetime] property

The end_time property.

Returns:

Type Description
Optional[datetime]

the value of the property.

input: ArtifactVersionResponse property

Returns the input artifact that was used to run this step.

Returns:

Type Description
ArtifactVersionResponse

The input artifact.

Raises:

Type Description
ValueError

If there were zero or multiple inputs to this step.

inputs: Dict[str, StepRunInputResponse] property

The inputs property.

Returns:

Type Description
Dict[str, StepRunInputResponse]

the value of the property.

logs: Optional[LogsResponse] property

The logs property.

Returns:

Type Description
Optional[LogsResponse]

the value of the property.

model_version: Optional[ModelVersionResponse] property

The model_version property.

Returns:

Type Description
Optional[ModelVersionResponse]

the value of the property.

model_version_id: Optional[UUID] property

The model_version_id property.

Returns:

Type Description
Optional[UUID]

the value of the property.

original_step_run_id: Optional[UUID] property

The original_step_run_id property.

Returns:

Type Description
Optional[UUID]

the value of the property.

output: ArtifactVersionResponse property

Returns the output artifact that was written by this step.

Returns:

Type Description
ArtifactVersionResponse

The output artifact.

Raises:

Type Description
ValueError

If there were zero or multiple step outputs.

outputs: Dict[str, List[ArtifactVersionResponse]] property

The outputs property.

Returns:

Type Description
Dict[str, List[ArtifactVersionResponse]]

the value of the property.

parent_step_ids: List[UUID] property

The parent_step_ids property.

Returns:

Type Description
List[UUID]

the value of the property.

pipeline_run_id: UUID property

The pipeline_run_id property.

Returns:

Type Description
UUID

the value of the property.

run_metadata: Dict[str, MetadataType] property

The run_metadata property.

Returns:

Type Description
Dict[str, MetadataType]

the value of the property.

source_code: Optional[str] property

The source_code property.

Returns:

Type Description
Optional[str]

the value of the property.

spec: StepSpec property

The spec property.

Returns:

Type Description
StepSpec

the value of the property.

start_time: Optional[datetime] property

The start_time property.

Returns:

Type Description
Optional[datetime]

the value of the property.

status: ExecutionStatus property

The status property.

Returns:

Type Description
ExecutionStatus

the value of the property.

Functions
get_hydrated_version() -> StepRunResponse

Get the hydrated version of this step run.

Returns:

Type Description
StepRunResponse

an instance of the same entity with the metadata field attached.

Source code in src/zenml/models/v2/core/step_run.py
279
280
281
282
283
284
285
286
287
def get_hydrated_version(self) -> "StepRunResponse":
    """Get the hydrated version of this step run.

    Returns:
        an instance of the same entity with the metadata field attached.
    """
    from zenml.client import Client

    return Client().zen_store.get_run_step(self.id)
StepRunResponseBody

Bases: ProjectScopedResponseBody

Response body for step runs.

StepRunResponseMetadata

Bases: ProjectScopedResponseMetadata

Response metadata for step runs.

StepRunResponseResources

Bases: ProjectScopedResponseResources

Class for all resource models associated with the step run entity.

StepRunUpdate

Bases: BaseUpdate

Update model for step runs.

StrFilter

Bases: Filter

Filter for all string fields.

Functions
check_value_if_operation_oneof() -> StrFilter

Validator to check if value is a list if oneof operation is used.

Raises:

Type Description
ValueError

If the value is not a list

Returns:

Type Description
StrFilter

self

Source code in src/zenml/models/v2/base/filter.py
187
188
189
190
191
192
193
194
195
196
197
198
199
200
@model_validator(mode="after")
def check_value_if_operation_oneof(self) -> "StrFilter":
    """Validator to check if value is a list if oneof operation is used.

    Raises:
        ValueError: If the value is not a list

    Returns:
        self
    """
    if self.operation == GenericFilterOps.ONEOF:
        if not isinstance(self.value, list):
            raise ValueError(ONEOF_ERROR)
    return self
generate_query_conditions_from_column(column: Any) -> Any

Generate query conditions for a string column.

Parameters:

Name Type Description Default
column Any

The string column of an SQLModel table on which to filter.

required

Returns:

Type Description
Any

A list of query conditions.

Source code in src/zenml/models/v2/base/filter.py
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
def generate_query_conditions_from_column(self, column: Any) -> Any:
    """Generate query conditions for a string column.

    Args:
        column: The string column of an SQLModel table on which to filter.

    Returns:
        A list of query conditions.
    """
    # Handle numeric comparisons (GT, LT, GTE, LTE)
    if self.operation in {
        GenericFilterOps.GT,
        GenericFilterOps.LT,
        GenericFilterOps.GTE,
        GenericFilterOps.LTE,
    }:
        return self._handle_numeric_comparison(column)

    # Handle operations that need special treatment for JSON-encoded columns
    is_json_encoded = self._check_if_column_is_json_encoded(column)

    # Handle list operations
    if self.operation == GenericFilterOps.ONEOF:
        assert isinstance(self.value, list)
        return self._handle_oneof(column, is_json_encoded)

    # Handle pattern matching operations
    if self.operation == GenericFilterOps.CONTAINS:
        return column.like(f"%{self.value}%")

    if self.operation == GenericFilterOps.STARTSWITH:
        return self._handle_startswith(column, is_json_encoded)

    if self.operation == GenericFilterOps.ENDSWITH:
        return self._handle_endswith(column, is_json_encoded)

    if self.operation == GenericFilterOps.NOT_EQUALS:
        return self._handle_not_equals(column, is_json_encoded)

    # Default case (EQUALS)
    return self._handle_equals(column, is_json_encoded)
Tag

Bases: BaseModel

A model representing a tag.

Functions
to_request() -> TagRequest

Convert the tag to a TagRequest.

Returns:

Type Description
TagRequest

The tag as a TagRequest.

Source code in src/zenml/utils/tag_utils.py
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
def to_request(self) -> "TagRequest":
    """Convert the tag to a TagRequest.

    Returns:
        The tag as a TagRequest.
    """
    from zenml.models import TagRequest

    request = TagRequest(name=self.name)
    if self.color is not None:
        request.color = self.color

    if self.exclusive is not None:
        request.exclusive = self.exclusive
    return request
TagFilter

Bases: UserScopedFilter

Model to enable advanced filtering of all tags.

Functions
get_custom_filters(table: Type[AnySchema]) -> List[ColumnElement[bool]]

Get custom filters.

Parameters:

Name Type Description Default
table Type[AnySchema]

The query table.

required

Returns:

Type Description
List[ColumnElement[bool]]

A list of custom filters.

Source code in src/zenml/models/v2/core/tag.py
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
def get_custom_filters(
    self, table: Type["AnySchema"]
) -> List["ColumnElement[bool]"]:
    """Get custom filters.

    Args:
        table: The query table.

    Returns:
        A list of custom filters.
    """
    custom_filters = super().get_custom_filters(table)

    from sqlmodel import exists, select

    from zenml.zen_stores.schemas import (
        TagResourceSchema,
        TagSchema,
    )

    if self.resource_type:
        # Filter for tags that have at least one association with the specified resource type
        resource_type_filter = exists(
            select(TagResourceSchema).where(
                TagResourceSchema.tag_id == TagSchema.id,
                TagResourceSchema.resource_type
                == self.resource_type.value,
            )
        )
        custom_filters.append(resource_type_filter)

    return custom_filters
TagRequest

Bases: UserScopedRequest

Request model for tags.

Functions
validate_name_not_uuid(value: str) -> str classmethod

Validates that the tag name is not a UUID.

Parameters:

Name Type Description Default
value str

The tag name to validate.

required

Returns:

Type Description
str

The validated tag name.

Raises:

Type Description
ValueError

If the tag name can be converted to a UUID.

Source code in src/zenml/models/v2/core/tag.py
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
@field_validator("name")
@classmethod
def validate_name_not_uuid(cls, value: str) -> str:
    """Validates that the tag name is not a UUID.

    Args:
        value: The tag name to validate.

    Returns:
        The validated tag name.

    Raises:
        ValueError: If the tag name can be converted
            to a UUID.
    """
    if is_valid_uuid(value):
        raise ValueError(
            "Tag names cannot be UUIDs or strings that "
            "can be converted to UUIDs."
        )
    return value
TagResource

Bases: BaseModel

Utility class to help identify resources to tag.

TagResourceRequest

Bases: BaseRequest

Request model for links between tags and resources.

TagResourceResponse

Bases: BaseIdentifiedResponse[TagResourceResponseBody, BaseResponseMetadata, TagResourceResponseResources]

Response model for the links between tags and resources.

Attributes
resource_id: UUID property

The resource_id property.

Returns:

Type Description
UUID

the value of the property.

resource_type: TaggableResourceTypes property

The resource_type property.

Returns:

Type Description
TaggableResourceTypes

the value of the property.

tag_id: UUID property

The tag_id property.

Returns:

Type Description
UUID

the value of the property.

TagResourceResponseBody

Bases: BaseDatedResponseBody

Response body for the links between tags and resources.

TagResponse

Bases: UserScopedResponse[TagResponseBody, TagResponseMetadata, TagResponseResources]

Response model for tags.

Attributes
color: ColorVariants property

The color property.

Returns:

Type Description
ColorVariants

the value of the property.

exclusive: bool property

The exclusive property.

Returns:

Type Description
bool

the value of the property.

tagged_count: int property

The tagged_count property.

Returns:

Type Description
int

the value of the property.

Functions
get_hydrated_version() -> TagResponse

Get the hydrated version of this tag.

Returns:

Type Description
TagResponse

an instance of the same entity with the metadata field attached.

Source code in src/zenml/models/v2/core/tag.py
153
154
155
156
157
158
159
160
161
def get_hydrated_version(self) -> "TagResponse":
    """Get the hydrated version of this tag.

    Returns:
        an instance of the same entity with the metadata field attached.
    """
    from zenml.client import Client

    return Client().zen_store.get_tag(self.id)
TagResponseBody

Bases: UserScopedResponseBody

Response body for tags.

TagResponseMetadata

Bases: UserScopedResponseMetadata

Response metadata for tags.

TagUpdate

Bases: BaseUpdate

Update model for tags.

Functions
validate_name_not_uuid(value: Optional[str]) -> Optional[str] classmethod

Validates that the tag name is not a UUID.

Parameters:

Name Type Description Default
value Optional[str]

The tag name to validate.

required

Returns:

Type Description
Optional[str]

The validated tag name.

Raises:

Type Description
ValueError

If the tag name can be converted to a UUID.

Source code in src/zenml/models/v2/core/tag.py
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
@field_validator("name")
@classmethod
def validate_name_not_uuid(cls, value: Optional[str]) -> Optional[str]:
    """Validates that the tag name is not a UUID.

    Args:
        value: The tag name to validate.

    Returns:
        The validated tag name.

    Raises:
        ValueError: If the tag name can be converted to a UUID.
    """
    if value is not None and is_valid_uuid(value):
        raise ValueError(
            "Tag names cannot be UUIDs or strings that "
            "can be converted to UUIDs."
        )
    return value
TaggableFilter

Bases: BaseFilter

Model to enable filtering and sorting by tags.

Functions
add_tag_to_tags() -> TaggableFilter

Deprecated the tag attribute in favor of the tags attribute.

Returns:

Type Description
TaggableFilter

self

Source code in src/zenml/models/v2/base/scoped.py
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
@model_validator(mode="after")
def add_tag_to_tags(self) -> "TaggableFilter":
    """Deprecated the tag attribute in favor of the tags attribute.

    Returns:
        self
    """
    if self.tag is not None:
        logger.warning(
            "The `tag` attribute is deprecated in favor of the `tags` attribute. "
            "Please update your code to use the `tags` attribute instead."
        )
        if self.tags is not None:
            self.tags.append(self.tag)
        else:
            self.tags = [self.tag]

        self.tag = None

    return self
apply_filter(query: AnyQuery, table: Type[AnySchema]) -> AnyQuery

Applies the filter to a query.

Parameters:

Name Type Description Default
query AnyQuery

The query to which to apply the filter.

required
table Type[AnySchema]

The query table.

required

Returns:

Type Description
AnyQuery

The query with filter applied.

Source code in src/zenml/models/v2/base/scoped.py
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
def apply_filter(
    self,
    query: AnyQuery,
    table: Type["AnySchema"],
) -> AnyQuery:
    """Applies the filter to a query.

    Args:
        query: The query to which to apply the filter.
        table: The query table.

    Returns:
        The query with filter applied.
    """
    from zenml.zen_stores.schemas import TagResourceSchema, TagSchema

    query = super().apply_filter(query=query, table=table)

    if self.tags:
        query = query.join(
            TagResourceSchema,
            TagResourceSchema.resource_id == getattr(table, "id"),
        ).join(TagSchema, TagSchema.id == TagResourceSchema.tag_id)

    return query
apply_sorting(query: AnyQuery, table: Type[AnySchema]) -> AnyQuery

Apply sorting to the query.

Parameters:

Name Type Description Default
query AnyQuery

The query to which to apply the sorting.

required
table Type[AnySchema]

The query table.

required

Returns:

Type Description
AnyQuery

The query with sorting applied.

Source code in src/zenml/models/v2/base/scoped.py
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
def apply_sorting(
    self,
    query: AnyQuery,
    table: Type["AnySchema"],
) -> AnyQuery:
    """Apply sorting to the query.

    Args:
        query: The query to which to apply the sorting.
        table: The query table.

    Returns:
        The query with sorting applied.
    """
    sort_by, operand = self.sorting_params

    if sort_by == "tags":
        from sqlmodel import asc, desc, func, select

        from zenml.enums import SorterOps, TaggableResourceTypes
        from zenml.zen_stores.schemas import (
            ArtifactSchema,
            ArtifactVersionSchema,
            ModelSchema,
            ModelVersionSchema,
            PipelineRunSchema,
            PipelineSchema,
            RunTemplateSchema,
            TagResourceSchema,
            TagSchema,
        )

        resource_type_mapping = {
            ArtifactSchema: TaggableResourceTypes.ARTIFACT,
            ArtifactVersionSchema: TaggableResourceTypes.ARTIFACT_VERSION,
            ModelSchema: TaggableResourceTypes.MODEL,
            ModelVersionSchema: TaggableResourceTypes.MODEL_VERSION,
            PipelineSchema: TaggableResourceTypes.PIPELINE,
            PipelineRunSchema: TaggableResourceTypes.PIPELINE_RUN,
            RunTemplateSchema: TaggableResourceTypes.RUN_TEMPLATE,
        }

        sorted_tags = (
            select(TagResourceSchema.resource_id, TagSchema.name)
            .join(TagSchema, TagResourceSchema.tag_id == TagSchema.id)  # type: ignore[arg-type]
            .filter(
                TagResourceSchema.resource_type  # type: ignore[arg-type]
                == resource_type_mapping[table]
            )
            .order_by(
                asc(TagResourceSchema.resource_id), asc(TagSchema.name)
            )
        ).alias("sorted_tags")

        tags_subquery = (
            select(
                sorted_tags.c.resource_id,
                func.group_concat(sorted_tags.c.name, ", ").label(
                    "tags_list"
                ),
            ).group_by(sorted_tags.c.resource_id)
        ).alias("tags_subquery")

        query = query.add_columns(tags_subquery.c.tags_list).outerjoin(
            tags_subquery, table.id == tags_subquery.c.resource_id
        )

        # Apply ordering based on the tags list
        if operand == SorterOps.ASCENDING:
            query = query.order_by(asc("tags_list"))
        else:
            query = query.order_by(desc("tags_list"))

        return query

    return super().apply_sorting(query=query, table=table)
get_custom_filters(table: Type[AnySchema]) -> List[ColumnElement[bool]]

Get custom tag filters.

Parameters:

Name Type Description Default
table Type[AnySchema]

The query table.

required

Returns:

Type Description
List[ColumnElement[bool]]

A list of custom filters.

Source code in src/zenml/models/v2/base/scoped.py
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
def get_custom_filters(
    self, table: Type["AnySchema"]
) -> List["ColumnElement[bool]"]:
    """Get custom tag filters.

    Args:
        table: The query table.

    Returns:
        A list of custom filters.
    """
    custom_filters = super().get_custom_filters(table)

    if self.tags:
        from sqlmodel import exists, select

        from zenml.zen_stores.schemas import TagResourceSchema, TagSchema

        for tag in self.tags:
            condition = self.generate_custom_query_conditions_for_column(
                value=tag, table=TagSchema, column="name"
            )
            exists_subquery = exists(
                select(TagResourceSchema)
                .join(TagSchema, TagSchema.id == TagResourceSchema.tag_id)  # type: ignore[arg-type]
                .where(
                    TagResourceSchema.resource_id == table.id, condition
                )
            )
            custom_filters.append(exists_subquery)

    return custom_filters
TriggerExecutionFilter

Bases: ProjectScopedFilter

Model to enable advanced filtering of all trigger executions.

TriggerExecutionRequest

Bases: BaseRequest

Model for creating a new Trigger execution.

TriggerExecutionResponse

Bases: BaseIdentifiedResponse[TriggerExecutionResponseBody, TriggerExecutionResponseMetadata, TriggerExecutionResponseResources]

Response model for trigger executions.

Attributes
event_metadata: Dict[str, Any] property

The event_metadata property.

Returns:

Type Description
Dict[str, Any]

the value of the property.

trigger: TriggerResponse property

The trigger property.

Returns:

Type Description
TriggerResponse

the value of the property.

Functions
get_hydrated_version() -> TriggerExecutionResponse

Get the hydrated version of this trigger execution.

Returns:

Type Description
TriggerExecutionResponse

an instance of the same entity with the metadata field attached.

Source code in src/zenml/models/v2/core/trigger_execution.py
78
79
80
81
82
83
84
85
86
def get_hydrated_version(self) -> "TriggerExecutionResponse":
    """Get the hydrated version of this trigger execution.

    Returns:
        an instance of the same entity with the metadata field attached.
    """
    from zenml.client import Client

    return Client().zen_store.get_trigger_execution(self.id)
TriggerExecutionResponseBody

Bases: BaseDatedResponseBody

Response body for trigger executions.

TriggerExecutionResponseMetadata

Bases: BaseResponseMetadata

Response metadata for trigger executions.

TriggerExecutionResponseResources

Bases: BaseResponseResources

Class for all resource models associated with the trigger entity.

TriggerFilter

Bases: ProjectScopedFilter

Model to enable advanced filtering of all triggers.

Functions
get_custom_filters(table: Type[AnySchema]) -> List[ColumnElement[bool]]

Get custom filters.

Parameters:

Name Type Description Default
table Type[AnySchema]

The query table.

required

Returns:

Type Description
List[ColumnElement[bool]]

A list of custom filters.

Source code in src/zenml/models/v2/core/trigger.py
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
def get_custom_filters(
    self, table: Type["AnySchema"]
) -> List["ColumnElement[bool]"]:
    """Get custom filters.

    Args:
        table: The query table.

    Returns:
        A list of custom filters.
    """
    from sqlmodel import and_

    from zenml.zen_stores.schemas import (
        ActionSchema,
        EventSourceSchema,
        TriggerSchema,
    )

    custom_filters = super().get_custom_filters(table)

    if self.event_source_flavor:
        event_source_flavor_filter = and_(
            EventSourceSchema.id == TriggerSchema.event_source_id,
            EventSourceSchema.flavor == self.event_source_flavor,
        )
        custom_filters.append(event_source_flavor_filter)

    if self.event_source_subtype:
        event_source_subtype_filter = and_(
            EventSourceSchema.id == TriggerSchema.event_source_id,
            EventSourceSchema.plugin_subtype == self.event_source_subtype,
        )
        custom_filters.append(event_source_subtype_filter)

    if self.action_flavor:
        action_flavor_filter = and_(
            ActionSchema.id == TriggerSchema.action_id,
            ActionSchema.flavor == self.action_flavor,
        )
        custom_filters.append(action_flavor_filter)

    if self.action_subtype:
        action_subtype_filter = and_(
            ActionSchema.id == TriggerSchema.action_id,
            ActionSchema.plugin_subtype == self.action_subtype,
        )
        custom_filters.append(action_subtype_filter)

    return custom_filters
TriggerRequest

Bases: ProjectScopedRequest

Model for creating a new trigger.

TriggerResponse

Bases: ProjectScopedResponse[TriggerResponseBody, TriggerResponseMetadata, TriggerResponseResources]

Response model for models.

Attributes
action: ActionResponse property

The action property.

Returns:

Type Description
ActionResponse

the value of the property.

action_flavor: str property

The action_flavor property.

Returns:

Type Description
str

the value of the property.

action_subtype: str property

The action_subtype property.

Returns:

Type Description
str

the value of the property.

description: str property

The description property.

Returns:

Type Description
str

the value of the property.

event_filter: Optional[Dict[str, Any]] property

The event_filter property.

Returns:

Type Description
Optional[Dict[str, Any]]

the value of the property.

event_source: Optional[EventSourceResponse] property

The event_source property.

Returns:

Type Description
Optional[EventSourceResponse]

the value of the property.

event_source_flavor: Optional[str] property

The event_source_flavor property.

Returns:

Type Description
Optional[str]

the value of the property.

event_source_subtype: Optional[str] property

The event_source_subtype property.

Returns:

Type Description
Optional[str]

the value of the property.

executions: Page[TriggerExecutionResponse] property

The event_source property.

Returns:

Type Description
Page[TriggerExecutionResponse]

the value of the property.

is_active: bool property

The is_active property.

Returns:

Type Description
bool

the value of the property.

Functions
get_hydrated_version() -> TriggerResponse

Get the hydrated version of this trigger.

Returns:

Type Description
TriggerResponse

An instance of the same entity with the metadata field attached.

Source code in src/zenml/models/v2/core/trigger.py
223
224
225
226
227
228
229
230
231
def get_hydrated_version(self) -> "TriggerResponse":
    """Get the hydrated version of this trigger.

    Returns:
        An instance of the same entity with the metadata field attached.
    """
    from zenml.client import Client

    return Client().zen_store.get_trigger(self.id)
TriggerResponseBody

Bases: ProjectScopedResponseBody

Response body for triggers.

TriggerResponseMetadata

Bases: ProjectScopedResponseMetadata

Response metadata for triggers.

TriggerResponseResources

Bases: ProjectScopedResponseResources

Class for all resource models associated with the trigger entity.

TriggerUpdate

Bases: BaseUpdate

Update model for triggers.

UUIDFilter

Bases: StrFilter

Filter for all uuid fields which are mostly treated like strings.

Functions
generate_query_conditions_from_column(column: Any) -> Any

Generate query conditions for a UUID column.

Parameters:

Name Type Description Default
column Any

The UUID column of an SQLModel table on which to filter.

required

Returns:

Type Description
Any

A list of query conditions.

Source code in src/zenml/models/v2/base/filter.py
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
def generate_query_conditions_from_column(self, column: Any) -> Any:
    """Generate query conditions for a UUID column.

    Args:
        column: The UUID column of an SQLModel table on which to filter.

    Returns:
        A list of query conditions.
    """
    import sqlalchemy
    from sqlalchemy_utils.functions import cast_if

    from zenml.utils import uuid_utils

    # For equality checks, compare the UUID directly
    if self.operation == GenericFilterOps.EQUALS:
        if not uuid_utils.is_valid_uuid(self.value):
            return False

        return column == self.value

    if self.operation == GenericFilterOps.NOT_EQUALS:
        if not uuid_utils.is_valid_uuid(self.value):
            return True

        return column != self.value

    # For all other operations, cast and handle the column as string
    return super().generate_query_conditions_from_column(
        column=cast_if(column, sqlalchemy.String)
    )
UserAuthModel

Bases: BaseZenModel

Authentication Model for the User.

This model is only used server-side. The server endpoints can use this model to authenticate the user credentials (Token, Password).

Functions
get_hashed_activation_token() -> Optional[str]

Returns the hashed activation token, if configured.

Returns:

Type Description
Optional[str]

The hashed activation token.

Source code in src/zenml/models/v2/misc/user_auth.py
139
140
141
142
143
144
145
def get_hashed_activation_token(self) -> Optional[str]:
    """Returns the hashed activation token, if configured.

    Returns:
        The hashed activation token.
    """
    return self._get_hashed_secret(self.activation_token)
get_hashed_password() -> Optional[str]

Returns the hashed password, if configured.

Returns:

Type Description
Optional[str]

The hashed password.

Source code in src/zenml/models/v2/misc/user_auth.py
131
132
133
134
135
136
137
def get_hashed_password(self) -> Optional[str]:
    """Returns the hashed password, if configured.

    Returns:
        The hashed password.
    """
    return self._get_hashed_secret(self.password)
get_password() -> Optional[str]

Get the password.

Returns:

Type Description
Optional[str]

The password as a plain string, if it exists.

Source code in src/zenml/models/v2/misc/user_auth.py
121
122
123
124
125
126
127
128
129
def get_password(self) -> Optional[str]:
    """Get the password.

    Returns:
        The password as a plain string, if it exists.
    """
    if self.password is None:
        return None
    return self.password.get_secret_value()
verify_activation_token(activation_token: str, user: Optional[UserAuthModel] = None) -> bool classmethod

Verifies a given activation token against the stored token.

Parameters:

Name Type Description Default
activation_token str

Input activation token to be verified.

required
user Optional[UserAuthModel]

User for which the activation token is to be verified.

None

Returns:

Type Description
bool

True if the token is valid.

Source code in src/zenml/models/v2/misc/user_auth.py
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
@classmethod
def verify_activation_token(
    cls, activation_token: str, user: Optional["UserAuthModel"] = None
) -> bool:
    """Verifies a given activation token against the stored token.

    Args:
        activation_token: Input activation token to be verified.
        user: User for which the activation token is to be verified.

    Returns:
        True if the token is valid.
    """
    # even when the user or token is not set, we still want to execute the
    # token hash verification to protect against response discrepancy
    # attacks (https://cwe.mitre.org/data/definitions/204.html)
    token_hash: str = ""
    if (
        user is not None
        # Disable activation tokens for service accounts as an extra
        # security measure. Service accounts should only be used with API
        # keys.
        and not user.is_service_account
        and user.activation_token is not None
        and not user.active
    ):
        token_hash = user.get_hashed_activation_token() or ""
    pwd_context = cls._get_crypt_context()
    return pwd_context.verify(activation_token, token_hash)
verify_password(plain_password: str, user: Optional[UserAuthModel] = None) -> bool classmethod

Verifies a given plain password against the stored password.

Parameters:

Name Type Description Default
plain_password str

Input password to be verified.

required
user Optional[UserAuthModel]

User for which the password is to be verified.

None

Returns:

Type Description
bool

True if the passwords match.

Source code in src/zenml/models/v2/misc/user_auth.py
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
@classmethod
def verify_password(
    cls, plain_password: str, user: Optional["UserAuthModel"] = None
) -> bool:
    """Verifies a given plain password against the stored password.

    Args:
        plain_password: Input password to be verified.
        user: User for which the password is to be verified.

    Returns:
        True if the passwords match.
    """
    # even when the user or password is not set, we still want to execute
    # the password hash verification to protect against response discrepancy
    # attacks (https://cwe.mitre.org/data/definitions/204.html)
    password_hash: Optional[str] = None
    if (
        user is not None
        # Disable password verification for service accounts as an extra
        # security measure. Service accounts should only be used with API
        # keys.
        and not user.is_service_account
        and user.password is not None
    ):  # and user.active:
        password_hash = user.get_hashed_password()
    pwd_context = cls._get_crypt_context()
    return pwd_context.verify(plain_password, password_hash)
UserFilter

Bases: BaseFilter

Model to enable advanced filtering of all Users.

Functions
apply_filter(query: AnyQuery, table: Type[AnySchema]) -> AnyQuery

Override to filter out service accounts from the query.

Parameters:

Name Type Description Default
query AnyQuery

The query to which to apply the filter.

required
table Type[AnySchema]

The query table.

required

Returns:

Type Description
AnyQuery

The query with filter applied.

Source code in src/zenml/models/v2/core/user.py
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
def apply_filter(
    self,
    query: AnyQuery,
    table: Type["AnySchema"],
) -> AnyQuery:
    """Override to filter out service accounts from the query.

    Args:
        query: The query to which to apply the filter.
        table: The query table.

    Returns:
        The query with filter applied.
    """
    query = super().apply_filter(query=query, table=table)
    query = query.where(
        getattr(table, "is_service_account") != True  # noqa: E712
    )

    return query
UserRequest

Bases: UserBase, BaseRequest

Request model for users.

UserResponse

Bases: BaseIdentifiedResponse[UserResponseBody, UserResponseMetadata, UserResponseResources]

Response model for user and service accounts.

This returns the activation_token that is required for the user-invitation-flow of the frontend. The email is returned optionally as well for use by the analytics on the client-side.

Attributes
activation_token: Optional[str] property

The activation_token property.

Returns:

Type Description
Optional[str]

the value of the property.

active: bool property

The active property.

Returns:

Type Description
bool

the value of the property.

default_project_id: Optional[UUID] property

The default_project_id property.

Returns:

Type Description
Optional[UUID]

the value of the property.

email: Optional[str] property

The email property.

Returns:

Type Description
Optional[str]

the value of the property.

email_opted_in: Optional[bool] property

The email_opted_in property.

Returns:

Type Description
Optional[bool]

the value of the property.

external_user_id: Optional[UUID] property

The external_user_id property.

Returns:

Type Description
Optional[UUID]

the value of the property.

full_name: str property

The full_name property.

Returns:

Type Description
str

the value of the property.

is_admin: bool property

The is_admin property.

Returns:

Type Description
bool

Whether the user is an admin.

is_service_account: bool property

The is_service_account property.

Returns:

Type Description
bool

the value of the property.

user_metadata: Dict[str, Any] property

The user_metadata property.

Returns:

Type Description
Dict[str, Any]

the value of the property.

Functions
get_hydrated_version() -> UserResponse

Get the hydrated version of this user.

Returns:

Type Description
UserResponse

an instance of the same entity with the metadata field attached.

Source code in src/zenml/models/v2/core/user.py
341
342
343
344
345
346
347
348
349
def get_hydrated_version(self) -> "UserResponse":
    """Get the hydrated version of this user.

    Returns:
        an instance of the same entity with the metadata field attached.
    """
    from zenml.client import Client

    return Client().zen_store.get_user(self.id)
UserResponseBody

Bases: BaseDatedResponseBody

Response body for users.

UserResponseMetadata

Bases: BaseResponseMetadata

Response metadata for users.

UserScopedFilter

Bases: BaseFilter

Model to enable advanced user-based scoping.

Functions
apply_filter(query: AnyQuery, table: Type[AnySchema]) -> AnyQuery

Applies the filter to a query.

Parameters:

Name Type Description Default
query AnyQuery

The query to which to apply the filter.

required
table Type[AnySchema]

The query table.

required

Returns:

Type Description
AnyQuery

The query with filter applied.

Source code in src/zenml/models/v2/base/scoped.py
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
def apply_filter(
    self,
    query: AnyQuery,
    table: Type["AnySchema"],
) -> AnyQuery:
    """Applies the filter to a query.

    Args:
        query: The query to which to apply the filter.
        table: The query table.

    Returns:
        The query with filter applied.
    """
    query = super().apply_filter(query=query, table=table)

    if self.scope_user:
        query = query.where(getattr(table, "user_id") == self.scope_user)

    return query
apply_sorting(query: AnyQuery, table: Type[AnySchema]) -> AnyQuery

Apply sorting to the query.

Parameters:

Name Type Description Default
query AnyQuery

The query to which to apply the sorting.

required
table Type[AnySchema]

The query table.

required

Returns:

Type Description
AnyQuery

The query with sorting applied.

Source code in src/zenml/models/v2/base/scoped.py
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
def apply_sorting(
    self,
    query: AnyQuery,
    table: Type["AnySchema"],
) -> AnyQuery:
    """Apply sorting to the query.

    Args:
        query: The query to which to apply the sorting.
        table: The query table.

    Returns:
        The query with sorting applied.
    """
    from sqlmodel import asc, desc

    from zenml.enums import SorterOps
    from zenml.zen_stores.schemas import UserSchema

    sort_by, operand = self.sorting_params

    if sort_by == "user":
        column = UserSchema.name

        query = query.outerjoin(
            UserSchema,
            getattr(table, "user_id") == UserSchema.id,
        )

        query = query.add_columns(UserSchema.name)

        if operand == SorterOps.ASCENDING:
            query = query.order_by(asc(column))
        else:
            query = query.order_by(desc(column))

        return query

    return super().apply_sorting(query=query, table=table)
get_custom_filters(table: Type[AnySchema]) -> List[ColumnElement[bool]]

Get custom filters.

Parameters:

Name Type Description Default
table Type[AnySchema]

The query table.

required

Returns:

Type Description
List[ColumnElement[bool]]

A list of custom filters.

Source code in src/zenml/models/v2/base/scoped.py
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
def get_custom_filters(
    self, table: Type["AnySchema"]
) -> List["ColumnElement[bool]"]:
    """Get custom filters.

    Args:
        table: The query table.

    Returns:
        A list of custom filters.
    """
    custom_filters = super().get_custom_filters(table)

    from sqlmodel import and_

    from zenml.zen_stores.schemas import UserSchema

    if self.user:
        user_filter = and_(
            getattr(table, "user_id") == UserSchema.id,
            self.generate_name_or_id_query_conditions(
                value=self.user,
                table=UserSchema,
                additional_columns=["full_name"],
            ),
        )
        custom_filters.append(user_filter)

    return custom_filters
set_scope_user(user_id: UUID) -> None

Set the user that is performing the filtering to scope the response.

Parameters:

Name Type Description Default
user_id UUID

The user ID to scope the response to.

required
Source code in src/zenml/models/v2/base/scoped.py
186
187
188
189
190
191
192
def set_scope_user(self, user_id: UUID) -> None:
    """Set the user that is performing the filtering to scope the response.

    Args:
        user_id: The user ID to scope the response to.
    """
    self.scope_user = user_id
UserScopedRequest

Bases: BaseRequest

Base user-owned request model.

Used as a base class for all domain models that are "owned" by a user.

Functions
get_analytics_metadata() -> Dict[str, Any]

Fetches the analytics metadata for user scoped models.

Returns:

Type Description
Dict[str, Any]

The analytics metadata.

Source code in src/zenml/models/v2/base/scoped.py
72
73
74
75
76
77
78
79
80
def get_analytics_metadata(self) -> Dict[str, Any]:
    """Fetches the analytics metadata for user scoped models.

    Returns:
        The analytics metadata.
    """
    metadata = super().get_analytics_metadata()
    metadata["user_id"] = self.user
    return metadata
UserScopedResponse

Bases: BaseIdentifiedResponse[UserBody, UserMetadata, UserResources], Generic[UserBody, UserMetadata, UserResources]

Base user-owned model.

Used as a base class for all domain models that are "owned" by a user.

Attributes
user: Optional[UserResponse] property

The user property.

Returns:

Type Description
Optional[UserResponse]

the value of the property.

Functions
get_analytics_metadata() -> Dict[str, Any]

Fetches the analytics metadata for user scoped models.

Returns:

Type Description
Dict[str, Any]

The analytics metadata.

Source code in src/zenml/models/v2/base/scoped.py
137
138
139
140
141
142
143
144
145
146
def get_analytics_metadata(self) -> Dict[str, Any]:
    """Fetches the analytics metadata for user scoped models.

    Returns:
        The analytics metadata.
    """
    metadata = super().get_analytics_metadata()
    if self.user is not None:
        metadata["user_id"] = self.user.id
    return metadata
UserScopedResponseBody

Bases: BaseDatedResponseBody

Base user-owned body.

UserScopedResponseMetadata

Bases: BaseResponseMetadata

Base user-owned metadata.

UserUpdate

Bases: UserBase, BaseUpdate

Update model for users.

Functions
create_copy(exclude: AbstractSet[str]) -> UserUpdate

Create a copy of the current instance.

Parameters:

Name Type Description Default
exclude AbstractSet[str]

Fields to exclude from the copy.

required

Returns:

Type Description
UserUpdate

A copy of the current instance.

Source code in src/zenml/models/v2/core/user.py
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
def create_copy(self, exclude: AbstractSet[str]) -> "UserUpdate":
    """Create a copy of the current instance.

    Args:
        exclude: Fields to exclude from the copy.

    Returns:
        A copy of the current instance.
    """
    return UserUpdate(
        **self.model_dump(
            exclude=set(exclude),
            exclude_unset=True,
        )
    )
user_email_updates() -> UserUpdate

Validate that the UserUpdateModel conforms to the email-opt-in-flow.

Returns:

Type Description
UserUpdate

The validated values.

Raises:

Type Description
ValueError

If the email was not provided when the email_opted_in field was set to True.

Source code in src/zenml/models/v2/core/user.py
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
@model_validator(mode="after")
def user_email_updates(self) -> "UserUpdate":
    """Validate that the UserUpdateModel conforms to the email-opt-in-flow.

    Returns:
        The validated values.

    Raises:
        ValueError: If the email was not provided when the email_opted_in
            field was set to True.
    """
    # When someone sets the email, or updates the email and hasn't
    #  before explicitly opted out, they are opted in
    if self.email is not None:
        if self.email_opted_in is None:
            self.email_opted_in = True

    # It should not be possible to do opt in without an email
    if self.email_opted_in is True:
        if self.email is None:
            raise ValueError(
                "Please provide an email, when you are opting-in with "
                "your email."
            )
    return self
Functions
add_tags(tags: List[Union[str, Tag]], pipeline: Optional[Union[UUID, str]] = None, run: Optional[Union[UUID, str]] = None, run_template: Optional[Union[UUID, str]] = None, artifact: Optional[Union[UUID, str]] = None, artifact_version_id: Optional[UUID] = None, artifact_name: Optional[str] = None, artifact_version: Optional[str] = None, infer_artifact: bool = False) -> None
add_tags(tags: List[Union[str, Tag]]) -> None
add_tags(
    *, tags: List[Union[str, Tag]], run: Union[UUID, str]
) -> None
add_tags(
    *,
    tags: List[Union[str, Tag]],
    artifact: Union[UUID, str],
) -> None
add_tags(
    *,
    tags: List[Union[str, Tag]],
    artifact_version_id: UUID,
) -> None
add_tags(
    *,
    tags: List[Union[str, Tag]],
    artifact_name: str,
    artifact_version: Optional[str] = None,
) -> None
add_tags(
    *,
    tags: List[Union[str, Tag]],
    infer_artifact: bool = False,
    artifact_name: Optional[str] = None,
) -> None
add_tags(
    *,
    tags: List[Union[str, Tag]],
    pipeline: Union[UUID, str],
) -> None
add_tags(
    *,
    tags: List[Union[str, Tag]],
    run_template: Union[UUID, str],
) -> None

Add tags to various resource types in a generalized way.

Parameters:

Name Type Description Default
tags List[Union[str, Tag]]

The tags to add.

required
pipeline Optional[Union[UUID, str]]

The ID or the name of the pipeline.

None
run Optional[Union[UUID, str]]

The id, name or prefix of the run.

None
run_template Optional[Union[UUID, str]]

The ID or the name of the run template.

None
artifact Optional[Union[UUID, str]]

The ID or the name of the artifact.

None
artifact_version_id Optional[UUID]

The ID of the artifact version.

None
artifact_name Optional[str]

The name of the artifact.

None
artifact_version Optional[str]

The version of the artifact.

None
infer_artifact bool

Flag deciding whether the artifact version should be inferred from the step context.

False

Raises:

Type Description
ValueError

If no identifiers are provided and the function is not called from within a step, or if exclusive is provided for a resource type that doesn't support it.

Source code in src/zenml/utils/tag_utils.py
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
def add_tags(
    tags: List[Union[str, Tag]],
    # Pipelines
    pipeline: Optional[Union[UUID, str]] = None,
    # Runs
    run: Optional[Union[UUID, str]] = None,
    # Run Templates
    run_template: Optional[Union[UUID, str]] = None,
    # Artifacts
    artifact: Optional[Union[UUID, str]] = None,
    # Artifact Versions
    artifact_version_id: Optional[UUID] = None,
    artifact_name: Optional[str] = None,
    artifact_version: Optional[str] = None,
    infer_artifact: bool = False,
) -> None:
    """Add tags to various resource types in a generalized way.

    Args:
        tags: The tags to add.
        pipeline: The ID or the name of the pipeline.
        run: The id, name or prefix of the run.
        run_template: The ID or the name of the run template.
        artifact: The ID or the name of the artifact.
        artifact_version_id: The ID of the artifact version.
        artifact_name: The name of the artifact.
        artifact_version: The version of the artifact.
        infer_artifact: Flag deciding whether the artifact version should be
            inferred from the step context.

    Raises:
        ValueError: If no identifiers are provided and the function is not
            called from within a step, or if exclusive is provided for a
            resource type that doesn't support it.
    """
    from zenml.client import Client
    from zenml.models.v2.misc.tag import TagResource

    client = Client()
    resource_id = None
    resource_type = None

    # Tag a pipeline
    if pipeline is not None:
        pipeline_model = client.get_pipeline(name_id_or_prefix=pipeline)
        resource_id = pipeline_model.id
        resource_type = TaggableResourceTypes.PIPELINE

    # Tag a run by ID
    elif run is not None:
        run_model = client.get_pipeline_run(name_id_or_prefix=run)
        resource_id = run_model.id
        resource_type = TaggableResourceTypes.PIPELINE_RUN

    # Tag a run template
    elif run_template is not None:
        run_template_model = client.get_run_template(
            name_id_or_prefix=run_template
        )
        resource_id = run_template_model.id
        resource_type = TaggableResourceTypes.RUN_TEMPLATE

    # Tag an artifact
    elif artifact is not None:
        artifact_model = client.get_artifact(name_id_or_prefix=artifact)
        resource_id = artifact_model.id
        resource_type = TaggableResourceTypes.ARTIFACT

    # Tag an artifact version by its name and version
    elif artifact_name is not None and artifact_version is not None:
        artifact_version_model = client.get_artifact_version(
            name_id_or_prefix=artifact_name, version=artifact_version
        )
        resource_id = artifact_version_model.id
        resource_type = TaggableResourceTypes.ARTIFACT_VERSION

    # Tag an artifact version by its ID
    elif artifact_version_id is not None:
        resource_id = artifact_version_id
        resource_type = TaggableResourceTypes.ARTIFACT_VERSION

    # Tag an artifact version through the step context
    elif infer_artifact is True:
        resource_type = TaggableResourceTypes.ARTIFACT_VERSION

        try:
            from zenml.steps.step_context import get_step_context

            step_context = get_step_context()
        except RuntimeError:
            raise ValueError(
                "When you are using the `infer_artifact` option when you call "
                "`add_tags`, it must be called inside a step with outputs."
                "Otherwise, you can provide a `artifact_version_id` or a "
                "combination of `artifact_name` and `artifact_version`."
            )

        step_output_names = list(step_context._outputs.keys())

        if artifact_name is not None:
            # If a name provided, ensure it is in the outputs
            if artifact_name not in step_output_names:
                raise ValueError(
                    f"The provided artifact name`{artifact_name}` does not "
                    f"exist in the step outputs: {step_output_names}."
                )
        else:
            # If no name provided, ensure there is only one output
            if len(step_output_names) > 1:
                raise ValueError(
                    "There is more than one output. If you would like to use "
                    "the `infer_artifact` option, you need to define an "
                    "`artifact_name`."
                )

            if len(step_output_names) == 0:
                raise ValueError("The step does not have any outputs.")

            artifact_name = step_output_names[0]

        step_context.add_output_tags(
            tags=[t.name if isinstance(t, Tag) else t for t in tags],
            output_name=artifact_name,
        )

    # If every additional value is None, that means we are calling it bare bones
    # and this call needs to happen during a step execution. We will use the
    # step context to fetch the run and attach the tags accordingly.
    elif all(
        v is None
        for v in [
            run,
            artifact_version_id,
            artifact_name,
            artifact_version,
            pipeline,
            run_template,
        ]
    ):
        try:
            from zenml.steps.step_context import get_step_context

            step_context = get_step_context()
        except RuntimeError:
            raise ValueError(
                f"""
                You are calling 'add_tags()' outside of a step execution. 
                If you would like to add tags to a ZenML entity outside 
                of the step execution, please provide the required 
                identifiers.\n{add_tags_warning}
                """
            )

        # Tag the pipeline run, not the step
        resource_id = step_context.pipeline_run.id
        resource_type = TaggableResourceTypes.PIPELINE_RUN

    else:
        raise ValueError(
            f"""
            Unsupported way to call the `add_tags`. Possible combinations "
            include: \n{add_tags_warning}
            """
        )

    # Create tag resources and add tags
    for tag in tags:
        try:
            if isinstance(tag, Tag):
                tag_model = client.get_tag(tag.name)

                if tag.exclusive != tag_model.exclusive:
                    raise ValueError(
                        f"The tag `{tag.name}` is an "
                        f"{'exclusive' if tag_model.exclusive else 'non-exclusive'} "
                        "tag. Please update it before attaching it to a resource."
                    )
                if tag.cascade is not None:
                    raise ValueError(
                        "Cascading tags can only be used with the "
                        "pipeline decorator."
                    )
            else:
                tag_model = client.get_tag(tag)

        except KeyError:
            if isinstance(tag, Tag):
                tag_model = client.create_tag(
                    name=tag.name,
                    exclusive=tag.exclusive
                    if tag.exclusive is not None
                    else False,
                )

                if tag.cascade is not None:
                    raise ValueError(
                        "Cascading tags can only be used with the "
                        "pipeline decorator."
                    )
            else:
                tag_model = client.create_tag(name=tag)

        if resource_id:
            client.attach_tag(
                tag_name_or_id=tag_model.name,
                resources=[TagResource(id=resource_id, type=resource_type)],
            )
get_pipeline_context() -> PipelineContext

Get the context of the current pipeline.

Returns:

Type Description
PipelineContext

The context of the current pipeline.

Raises:

Type Description
RuntimeError

If no active pipeline is found.

RuntimeError

If inside a running step.

Source code in src/zenml/pipelines/pipeline_context.py
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
def get_pipeline_context() -> "PipelineContext":
    """Get the context of the current pipeline.

    Returns:
        The context of the current pipeline.

    Raises:
        RuntimeError: If no active pipeline is found.
        RuntimeError: If inside a running step.
    """
    from zenml.pipelines.pipeline_definition import Pipeline

    if Pipeline.ACTIVE_PIPELINE is None:
        try:
            from zenml.steps.step_context import get_step_context

            get_step_context()
        except RuntimeError:
            raise RuntimeError("No active pipeline found.")
        else:
            raise RuntimeError(
                "Inside a step use `from zenml import get_step_context` "
                "instead."
            )

    return PipelineContext(
        pipeline_configuration=Pipeline.ACTIVE_PIPELINE.configuration
    )
get_step_context() -> StepContext

Get the context of the currently running step.

Returns:

Type Description
StepContext

The context of the currently running step.

Raises:

Type Description
RuntimeError

If no step is currently running.

Source code in src/zenml/steps/step_context.py
48
49
50
51
52
53
54
55
56
57
58
59
60
61
def get_step_context() -> "StepContext":
    """Get the context of the currently running step.

    Returns:
        The context of the currently running step.

    Raises:
        RuntimeError: If no step is currently running.
    """
    if StepContext._exists():
        return StepContext()  # type: ignore
    raise RuntimeError(
        "The step context is only available inside a step function."
    )

Link the artifact to the model.

Parameters:

Name Type Description Default
artifact_version ArtifactVersionResponse

The artifact version to link.

required
model Optional[Model]

The model to link to.

None

Raises:

Type Description
RuntimeError

If called outside a step.

Source code in src/zenml/model/utils.py
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
def link_artifact_to_model(
    artifact_version: ArtifactVersionResponse,
    model: Optional["Model"] = None,
) -> None:
    """Link the artifact to the model.

    Args:
        artifact_version: The artifact version to link.
        model: The model to link to.

    Raises:
        RuntimeError: If called outside a step.
    """
    if not model:
        is_issue = False
        try:
            step_context = get_step_context()
            model = step_context.model
        except StepContextError:
            is_issue = True

        if model is None or is_issue:
            raise RuntimeError(
                "`link_artifact_to_model` called without `model` parameter "
                "and configured model context cannot be identified. Consider "
                "passing the `model` explicitly or configuring it in "
                "@step or @pipeline decorator."
            )

    model_version = model._get_or_create_model_version()
    link_artifact_version_to_model_version(
        artifact_version=artifact_version,
        model_version=model_version,
    )
load_artifact(name_or_id: Union[str, UUID], version: Optional[str] = None) -> Any

Load an artifact.

Parameters:

Name Type Description Default
name_or_id Union[str, UUID]

The name or ID of the artifact to load.

required
version Optional[str]

The version of the artifact to load, if name_or_id is a name. If not provided, the latest version will be loaded.

None

Returns:

Type Description
Any

The loaded artifact.

Source code in src/zenml/artifacts/utils.py
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
def load_artifact(
    name_or_id: Union[str, UUID],
    version: Optional[str] = None,
) -> Any:
    """Load an artifact.

    Args:
        name_or_id: The name or ID of the artifact to load.
        version: The version of the artifact to load, if `name_or_id` is a
            name. If not provided, the latest version will be loaded.

    Returns:
        The loaded artifact.
    """
    artifact = Client().get_artifact_version(name_or_id, version)
    return load_artifact_from_response(artifact)
log_artifact_metadata(metadata: Dict[str, MetadataType], artifact_name: Optional[str] = None, artifact_version: Optional[str] = None) -> None

Log artifact metadata.

This function can be used to log metadata for either existing artifact versions or artifact versions that are newly created in the same step.

Parameters:

Name Type Description Default
metadata Dict[str, MetadataType]

The metadata to log.

required
artifact_name Optional[str]

The name of the artifact to log metadata for. Can be omitted when being called inside a step with only one output.

None
artifact_version Optional[str]

The version of the artifact to log metadata for. If not provided, when being called inside a step that produces an artifact named artifact_name, the metadata will be associated to the corresponding newly created artifact.

None

Raises:

Type Description
ValueError

If no artifact name is provided and the function is not called inside a step with a single output, or, if neither an artifact nor an output with the given name exists.

Source code in src/zenml/artifacts/utils.py
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
def log_artifact_metadata(
    metadata: Dict[str, "MetadataType"],
    artifact_name: Optional[str] = None,
    artifact_version: Optional[str] = None,
) -> None:
    """Log artifact metadata.

    This function can be used to log metadata for either existing artifact
    versions or artifact versions that are newly created in the same step.

    Args:
        metadata: The metadata to log.
        artifact_name: The name of the artifact to log metadata for. Can
            be omitted when being called inside a step with only one output.
        artifact_version: The version of the artifact to log metadata for. If
            not provided, when being called inside a step that produces an
            artifact named `artifact_name`, the metadata will be associated to
            the corresponding newly created artifact.

    Raises:
        ValueError: If no artifact name is provided and the function is not
            called inside a step with a single output, or, if neither an
            artifact nor an output with the given name exists.

    """
    logger.warning(
        "The `log_artifact_metadata` function is deprecated and will soon be "
        "removed. Instead, you can consider using: "
        "`log_metadata(metadata={...}, infer_artifact=True, ...)` instead. For more "
        "info: https://docs.zenml.io/how-to/model-management-metrics/track-metrics-metadata/attach-metadata-to-an-artifact"
    )

    from zenml import log_metadata

    if artifact_name and artifact_version:
        assert artifact_name is not None

        log_metadata(
            metadata=metadata,
            artifact_name=artifact_name,
            artifact_version=artifact_version,
        )

    step_context = None
    with contextlib.suppress(RuntimeError):
        step_context = get_step_context()

    if step_context and artifact_name in step_context._outputs.keys():
        log_metadata(
            metadata=metadata,
            artifact_name=artifact_name,
            infer_artifact=True,
        )
    elif step_context and len(step_context._outputs) == 1:
        single_output_name = list(step_context._outputs.keys())[0]

        log_metadata(
            metadata=metadata,
            artifact_name=single_output_name,
            infer_artifact=True,
        )
    elif artifact_name:
        client = Client()
        logger.warning(
            "Deprecation warning! Currently, you are calling "
            "`log_artifact_metadata` from a context, where we use the "
            "`artifact_name` to fetch it and link the metadata to its "
            "latest version. This behavior is deprecated and will be "
            "removed in the future. To circumvent this, please check"
            "the `log_metadata` function."
        )
        artifact_version_model = client.get_artifact_version(
            name_id_or_prefix=artifact_name
        )
        log_metadata(
            metadata=metadata,
            artifact_version_id=artifact_version_model.id,
        )
    else:
        raise ValueError(
            "You need to call `log_artifact_metadata` either within a step "
            "(potentially with an artifact name) or outside of a step with an "
            "artifact name (and/or version)."
        )
log_metadata(metadata: Dict[str, MetadataType], step_id: Optional[UUID] = None, step_name: Optional[str] = None, run_id_name_or_prefix: Optional[Union[UUID, str]] = None, artifact_version_id: Optional[UUID] = None, artifact_name: Optional[str] = None, artifact_version: Optional[str] = None, infer_artifact: bool = False, model_version_id: Optional[UUID] = None, model_name: Optional[str] = None, model_version: Optional[Union[ModelStages, int, str]] = None, infer_model: bool = False) -> None
log_metadata(metadata: Dict[str, MetadataType]) -> None
log_metadata(
    *, metadata: Dict[str, MetadataType], step_id: UUID
) -> None
log_metadata(
    *,
    metadata: Dict[str, MetadataType],
    step_name: str,
    run_id_name_or_prefix: Union[UUID, str],
) -> None
log_metadata(
    *,
    metadata: Dict[str, MetadataType],
    run_id_name_or_prefix: Union[UUID, str],
) -> None
log_metadata(
    *,
    metadata: Dict[str, MetadataType],
    artifact_version_id: UUID,
) -> None
log_metadata(
    *,
    metadata: Dict[str, MetadataType],
    artifact_name: str,
    artifact_version: Optional[str] = None,
) -> None
log_metadata(
    *,
    metadata: Dict[str, MetadataType],
    infer_artifact: bool = False,
    artifact_name: Optional[str] = None,
) -> None
log_metadata(
    *,
    metadata: Dict[str, MetadataType],
    model_version_id: UUID,
) -> None
log_metadata(
    *,
    metadata: Dict[str, MetadataType],
    model_name: str,
    model_version: Union[ModelStages, int, str],
) -> None
log_metadata(
    *,
    metadata: Dict[str, MetadataType],
    infer_model: bool = False,
) -> None

Logs metadata for various resource types in a generalized way.

Parameters:

Name Type Description Default
metadata Dict[str, MetadataType]

The metadata to log.

required
step_id Optional[UUID]

The ID of the step.

None
step_name Optional[str]

The name of the step.

None
run_id_name_or_prefix Optional[Union[UUID, str]]

The id, name or prefix of the run

None
artifact_version_id Optional[UUID]

The ID of the artifact version

None
artifact_name Optional[str]

The name of the artifact.

None
artifact_version Optional[str]

The version of the artifact.

None
infer_artifact bool

Flag deciding whether the artifact version should be inferred from the step context.

False
model_version_id Optional[UUID]

The ID of the model version.

None
model_name Optional[str]

The name of the model.

None
model_version Optional[Union[ModelStages, int, str]]

The version of the model.

None
infer_model bool

Flag deciding whether the model version should be inferred from the step context.

False

Raises:

Type Description
ValueError

If no identifiers are provided and the function is not called from within a step.

Source code in src/zenml/utils/metadata_utils.py
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
def log_metadata(
    metadata: Dict[str, MetadataType],
    # Steps and runs
    step_id: Optional[UUID] = None,
    step_name: Optional[str] = None,
    run_id_name_or_prefix: Optional[Union[UUID, str]] = None,
    # Artifacts
    artifact_version_id: Optional[UUID] = None,
    artifact_name: Optional[str] = None,
    artifact_version: Optional[str] = None,
    infer_artifact: bool = False,
    # Models
    model_version_id: Optional[UUID] = None,
    model_name: Optional[str] = None,
    model_version: Optional[Union[ModelStages, int, str]] = None,
    infer_model: bool = False,
) -> None:
    """Logs metadata for various resource types in a generalized way.

    Args:
        metadata: The metadata to log.
        step_id: The ID of the step.
        step_name: The name of the step.
        run_id_name_or_prefix: The id, name or prefix of the run
        artifact_version_id: The ID of the artifact version
        artifact_name: The name of the artifact.
        artifact_version: The version of the artifact.
        infer_artifact: Flag deciding whether the artifact version should be
            inferred from the step context.
        model_version_id: The ID of the model version.
        model_name: The name of the model.
        model_version: The version of the model.
        infer_model: Flag deciding whether the model version should be
            inferred from the step context.

    Raises:
        ValueError: If no identifiers are provided and the function is not
            called from within a step.
    """
    client = Client()

    resources: List[RunMetadataResource] = []
    publisher_step_id = None

    # Log metadata to a step by ID
    if step_id is not None:
        resources = [
            RunMetadataResource(
                id=step_id, type=MetadataResourceTypes.STEP_RUN
            )
        ]

    # Log metadata to a step by name and run ID
    elif step_name is not None and run_id_name_or_prefix is not None:
        step_model_id = (
            client.get_pipeline_run(name_id_or_prefix=run_id_name_or_prefix)
            .steps[step_name]
            .id
        )
        resources = [
            RunMetadataResource(
                id=step_model_id, type=MetadataResourceTypes.STEP_RUN
            )
        ]

    # Log metadata to a run by ID
    elif run_id_name_or_prefix is not None:
        run_model = client.get_pipeline_run(
            name_id_or_prefix=run_id_name_or_prefix
        )
        resources = [
            RunMetadataResource(
                id=run_model.id, type=MetadataResourceTypes.PIPELINE_RUN
            )
        ]

    # Log metadata to a model version by name and version
    elif model_name is not None and model_version is not None:
        model_version_model = client.get_model_version(
            model_name_or_id=model_name,
            model_version_name_or_number_or_id=model_version,
        )
        resources = [
            RunMetadataResource(
                id=model_version_model.id,
                type=MetadataResourceTypes.MODEL_VERSION,
            )
        ]

    # Log metadata to a model version by id
    elif model_version_id is not None:
        resources = [
            RunMetadataResource(
                id=model_version_id,
                type=MetadataResourceTypes.MODEL_VERSION,
            )
        ]

    # Log metadata to a model through the step context
    elif infer_model is True:
        try:
            step_context = get_step_context()
        except RuntimeError:
            raise ValueError(
                "If you are using the `infer_model` option, the function must "
                "be called inside a step with configured `model` in decorator."
                "Otherwise, you can provide a `model_version_id` or a "
                "combination of `model_name` and `model_version`."
            )

        if step_context.model_version is None:
            raise ValueError(
                "The step context does not feature any model versions."
            )

        resources = [
            RunMetadataResource(
                id=step_context.model_version.id,
                type=MetadataResourceTypes.MODEL_VERSION,
            )
        ]

    # Log metadata to an artifact version by its name and version
    elif artifact_name is not None and artifact_version is not None:
        artifact_version_model = client.get_artifact_version(
            name_id_or_prefix=artifact_name, version=artifact_version
        )
        resources = [
            RunMetadataResource(
                id=artifact_version_model.id,
                type=MetadataResourceTypes.ARTIFACT_VERSION,
            )
        ]

    # Log metadata to an artifact version by its ID
    elif artifact_version_id is not None:
        resources = [
            RunMetadataResource(
                id=artifact_version_id,
                type=MetadataResourceTypes.ARTIFACT_VERSION,
            )
        ]

    # Log metadata to an artifact version through the step context
    elif infer_artifact is True:
        try:
            step_context = get_step_context()
        except RuntimeError:
            raise ValueError(
                "When you are using the `infer_artifact` option when you call "
                "`log_metadata`, it must be called inside a step with outputs."
                "Otherwise, you can provide a `artifact_version_id` or a "
                "combination of `artifact_name` and `artifact_version`."
            )

        step_output_names = list(step_context._outputs.keys())

        if artifact_name is not None:
            # If a name provided, ensure it is in the outputs
            if artifact_name not in step_output_names:
                raise ValueError(
                    f"The provided artifact name`{artifact_name}` does not "
                    f"exist in the step outputs: {step_output_names}."
                )
        else:
            # If no name provided, ensure there is only one output
            if len(step_output_names) > 1:
                raise ValueError(
                    "There is more than one output. If you would like to use "
                    "the `infer_artifact` option, you need to define an "
                    "`artifact_name`."
                )

            if len(step_output_names) == 0:
                raise ValueError("The step does not have any outputs.")

            artifact_name = step_output_names[0]

        step_context.add_output_metadata(
            metadata=metadata, output_name=artifact_name
        )
        return

    # If every additional value is None, that means we are calling it bare bones
    # and this call needs to happen during a step execution. We will use the
    # step context to fetch the step, run and possibly the model version and
    # attach the metadata accordingly.
    elif all(
        v is None
        for v in [
            step_id,
            step_name,
            run_id_name_or_prefix,
            artifact_version_id,
            artifact_name,
            artifact_version,
            model_version_id,
            model_name,
            model_version,
        ]
    ):
        try:
            step_context = get_step_context()
        except RuntimeError:
            raise ValueError(
                "You are calling 'log_metadata()' outside of a step execution. "
                "If you would like to add metadata to a ZenML entity outside "
                "of the step execution, please provide the required "
                "identifiers."
            )

        resources = [
            RunMetadataResource(
                id=step_context.step_run.id,
                type=MetadataResourceTypes.STEP_RUN,
            )
        ]
        publisher_step_id = step_context.step_run.id

    else:
        raise ValueError(
            """
            Unsupported way to call the `log_metadata`. Possible combinations "
            include:

            # Automatic logging to a step (within a step)
            log_metadata(metadata={})

            # Manual logging to a step
            log_metadata(metadata={}, step_name=..., run_id_name_or_prefix=...)
            log_metadata(metadata={}, step_id=...)

            # Manual logging to a run
            log_metadata(metadata={}, run_id_name_or_prefix=...)

            # Automatic logging to a model (within a step)
            log_metadata(metadata={}, infer_model=True)

            # Manual logging to a model
            log_metadata(metadata={}, model_name=..., model_version=...)
            log_metadata(metadata={}, model_version_id=...)

            # Automatic logging to an artifact (within a step)
            log_metadata(metadata={}, infer_artifact=True)  # step with single output
            log_metadata(metadata={}, artifact_name=..., infer_artifact=True)  # specific output of a step

            # Manual logging to an artifact
            log_metadata(metadata={}, artifact_name=..., artifact_version=...)
            log_metadata(metadata={}, artifact_version_id=...)
            """
        )

    client.create_run_metadata(
        metadata=metadata,
        resources=resources,
        publisher_step_id=publisher_step_id,
    )
log_model_metadata(metadata: Dict[str, MetadataType], model_name: Optional[str] = None, model_version: Optional[Union[ModelStages, int, str]] = None) -> None

Log model version metadata.

This function can be used to log metadata for existing model versions.

Parameters:

Name Type Description Default
metadata Dict[str, MetadataType]

The metadata to log.

required
model_name Optional[str]

The name of the model to log metadata for. Can be omitted when being called inside a step with configured model in decorator.

None
model_version Optional[Union[ModelStages, int, str]]

The version of the model to log metadata for. Can be omitted when being called inside a step with configured model in decorator.

None

Raises:

Type Description
ValueError

If the function is not called with proper input.

Source code in src/zenml/model/utils.py
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
def log_model_metadata(
    metadata: Dict[str, "MetadataType"],
    model_name: Optional[str] = None,
    model_version: Optional[Union[ModelStages, int, str]] = None,
) -> None:
    """Log model version metadata.

    This function can be used to log metadata for existing model versions.

    Args:
        metadata: The metadata to log.
        model_name: The name of the model to log metadata for. Can
            be omitted when being called inside a step with configured
            `model` in decorator.
        model_version: The version of the model to log metadata for. Can
            be omitted when being called inside a step with configured
            `model` in decorator.

    Raises:
        ValueError: If the function is not called with proper input.
    """
    logger.warning(
        "The `log_model_metadata` function is deprecated and will soon be "
        "removed. Instead, you can consider using: "
        "`log_metadata(metadata={...}, infer_model=True)` instead. For more "
        "info: https://docs.zenml.io/how-to/model-management-metrics/track-metrics-metadata/attach-metadata-to-a-model"
    )

    from zenml import log_metadata

    if model_name and model_version:
        log_metadata(
            metadata=metadata,
            model_version=model_version,
            model_name=model_name,
        )
    elif model_name is None and model_version is None:
        log_metadata(
            metadata=metadata,
            infer_model=True,
        )
    else:
        raise ValueError(
            "You can call `log_model_metadata` by either providing both "
            "`model_name` and `model_version` or keeping both of them None."
        )
log_step_metadata(metadata: Dict[str, MetadataType], step_name: Optional[str] = None, pipeline_name_id_or_prefix: Optional[Union[str, UUID]] = None, run_id: Optional[str] = None) -> None

Logs step metadata.

Parameters:

Name Type Description Default
metadata Dict[str, MetadataType]

The metadata to log.

required
step_name Optional[str]

The name of the step to log metadata for. Can be omitted when being called inside a step.

None
pipeline_name_id_or_prefix Optional[Union[str, UUID]]

The name of the pipeline to log metadata for. Can be omitted when being called inside a step.

None
run_id Optional[str]

The ID of the run to log metadata for. Can be omitted when being called inside a step.

None

Raises:

Type Description
ValueError

If no step name is provided and the function is not called from within a step or if no pipeline name or ID is provided and the function is not called from within a step.

Source code in src/zenml/steps/utils.py
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
def log_step_metadata(
    metadata: Dict[str, "MetadataType"],
    step_name: Optional[str] = None,
    pipeline_name_id_or_prefix: Optional[Union[str, UUID]] = None,
    run_id: Optional[str] = None,
) -> None:
    """Logs step metadata.

    Args:
        metadata: The metadata to log.
        step_name: The name of the step to log metadata for. Can be omitted
            when being called inside a step.
        pipeline_name_id_or_prefix: The name of the pipeline to log metadata
            for. Can be omitted when being called inside a step.
        run_id: The ID of the run to log metadata for. Can be omitted when
            being called inside a step.

    Raises:
        ValueError: If no step name is provided and the function is not called
            from within a step or if no pipeline name or ID is provided and
            the function is not called from within a step.
    """
    logger.warning(
        "The `log_step_metadata` function is deprecated and will soon be "
        "removed. Please use `log_metadata` instead."
    )

    step_context = None
    if not step_name:
        with contextlib.suppress(RuntimeError):
            step_context = get_step_context()
            step_name = step_context.step_name
    # not running within a step and no user-provided step name
    if not step_name:
        raise ValueError(
            "No step name provided and you are not running "
            "within a step. Please provide a step name."
        )

    client = Client()
    if step_context:
        step_run_id = step_context.step_run.id
    elif run_id:
        step_run_id = UUID(int=int(run_id))
    else:
        if not pipeline_name_id_or_prefix:
            raise ValueError(
                "No pipeline name or ID provided and you are not running "
                "within a step. Please provide a pipeline name or ID, or "
                "provide a run ID."
            )
        pipeline_run = client.get_pipeline(
            name_id_or_prefix=pipeline_name_id_or_prefix,
        ).last_run
        step_run_id = pipeline_run.steps[step_name].id
    client.create_run_metadata(
        metadata=metadata,
        resources=[
            RunMetadataResource(
                id=step_run_id, type=MetadataResourceTypes.STEP_RUN
            )
        ],
    )
pipeline(_func: Optional[F] = None, *, name: Optional[str] = None, enable_cache: Optional[bool] = None, enable_artifact_metadata: Optional[bool] = None, enable_step_logs: Optional[bool] = None, enable_pipeline_logs: Optional[bool] = None, settings: Optional[Dict[str, SettingsOrDict]] = None, tags: Optional[List[Union[str, Tag]]] = None, extra: Optional[Dict[str, Any]] = None, on_failure: Optional[HookSpecification] = None, on_success: Optional[HookSpecification] = None, model: Optional[Model] = None, substitutions: Optional[Dict[str, str]] = None) -> Union[Pipeline, Callable[[F], Pipeline]]
pipeline(_func: F) -> Pipeline
pipeline(
    *,
    name: Optional[str] = None,
    enable_cache: Optional[bool] = None,
    enable_artifact_metadata: Optional[bool] = None,
    enable_step_logs: Optional[bool] = None,
    enable_pipeline_logs: Optional[bool] = None,
    settings: Optional[Dict[str, SettingsOrDict]] = None,
    tags: Optional[List[Union[str, Tag]]] = None,
    extra: Optional[Dict[str, Any]] = None,
    on_failure: Optional[HookSpecification] = None,
    on_success: Optional[HookSpecification] = None,
    model: Optional[Model] = None,
    substitutions: Optional[Dict[str, str]] = None,
) -> Callable[[F], Pipeline]

Decorator to create a pipeline.

Parameters:

Name Type Description Default
_func Optional[F]

The decorated function.

None
name Optional[str]

The name of the pipeline. If left empty, the name of the decorated function will be used as a fallback.

None
enable_cache Optional[bool]

Whether to use caching or not.

None
enable_artifact_metadata Optional[bool]

Whether to enable artifact metadata or not.

None
enable_step_logs Optional[bool]

If step logs should be enabled for this pipeline.

None
enable_pipeline_logs Optional[bool]

If pipeline logs should be enabled for this pipeline.

None
settings Optional[Dict[str, SettingsOrDict]]

Settings for this pipeline.

None
tags Optional[List[Union[str, Tag]]]

Tags to apply to runs of the pipeline.

None
extra Optional[Dict[str, Any]]

Extra configurations for this pipeline.

None
on_failure Optional[HookSpecification]

Callback function in event of failure of the step. Can be a function with a single argument of type BaseException, or a source path to such a function (e.g. module.my_function).

None
on_success Optional[HookSpecification]

Callback function in event of success of the step. Can be a function with no arguments, or a source path to such a function (e.g. module.my_function).

None
model Optional[Model]

configuration of the model in the Model Control Plane.

None
substitutions Optional[Dict[str, str]]

Extra placeholders to use in the name templates.

None

Returns:

Type Description
Union[Pipeline, Callable[[F], Pipeline]]

A pipeline instance.

Source code in src/zenml/pipelines/pipeline_decorator.py
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
def pipeline(
    _func: Optional["F"] = None,
    *,
    name: Optional[str] = None,
    enable_cache: Optional[bool] = None,
    enable_artifact_metadata: Optional[bool] = None,
    enable_step_logs: Optional[bool] = None,
    enable_pipeline_logs: Optional[bool] = None,
    settings: Optional[Dict[str, "SettingsOrDict"]] = None,
    tags: Optional[List[Union[str, "Tag"]]] = None,
    extra: Optional[Dict[str, Any]] = None,
    on_failure: Optional["HookSpecification"] = None,
    on_success: Optional["HookSpecification"] = None,
    model: Optional["Model"] = None,
    substitutions: Optional[Dict[str, str]] = None,
) -> Union["Pipeline", Callable[["F"], "Pipeline"]]:
    """Decorator to create a pipeline.

    Args:
        _func: The decorated function.
        name: The name of the pipeline. If left empty, the name of the
            decorated function will be used as a fallback.
        enable_cache: Whether to use caching or not.
        enable_artifact_metadata: Whether to enable artifact metadata or not.
        enable_step_logs: If step logs should be enabled for this pipeline.
        enable_pipeline_logs: If pipeline logs should be enabled for this pipeline.
        settings: Settings for this pipeline.
        tags: Tags to apply to runs of the pipeline.
        extra: Extra configurations for this pipeline.
        on_failure: Callback function in event of failure of the step. Can be a
            function with a single argument of type `BaseException`, or a source
            path to such a function (e.g. `module.my_function`).
        on_success: Callback function in event of success of the step. Can be a
            function with no arguments, or a source path to such a function
            (e.g. `module.my_function`).
        model: configuration of the model in the Model Control Plane.
        substitutions: Extra placeholders to use in the name templates.

    Returns:
        A pipeline instance.
    """

    def inner_decorator(func: "F") -> "Pipeline":
        from zenml.pipelines.pipeline_definition import Pipeline

        p = Pipeline(
            name=name or func.__name__,
            enable_cache=enable_cache,
            enable_artifact_metadata=enable_artifact_metadata,
            enable_step_logs=enable_step_logs,
            enable_pipeline_logs=enable_pipeline_logs,
            settings=settings,
            tags=tags,
            extra=extra,
            on_failure=on_failure,
            on_success=on_success,
            model=model,
            entrypoint=func,
            substitutions=substitutions,
        )

        p.__doc__ = func.__doc__
        return p

    return inner_decorator if _func is None else inner_decorator(_func)
register_artifact(folder_or_file_uri: str, name: str, version: Optional[Union[int, str]] = None, artifact_type: Optional[ArtifactType] = None, tags: Optional[List[str]] = None, has_custom_name: bool = True, artifact_metadata: Dict[str, MetadataType] = {}) -> ArtifactVersionResponse

Register existing data stored in the artifact store as a ZenML Artifact.

Parameters:

Name Type Description Default
folder_or_file_uri str

The full URI within the artifact store to the folder or to the file.

required
name str

The name of the artifact.

required
version Optional[Union[int, str]]

The version of the artifact. If not provided, a new auto-incremented version will be used.

None
artifact_type Optional[ArtifactType]

The artifact type. If not given, the type will default to data.

None
tags Optional[List[str]]

Tags to associate with the artifact.

None
has_custom_name bool

If the artifact name is custom and should be listed in the dashboard "Artifacts" tab.

True
artifact_metadata Dict[str, MetadataType]

Metadata dictionary to attach to the artifact version.

{}

Returns:

Type Description
ArtifactVersionResponse

The saved artifact response.

Raises:

Type Description
FileNotFoundError

If the folder URI is outside the artifact store bounds.

Source code in src/zenml/artifacts/utils.py
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
def register_artifact(
    folder_or_file_uri: str,
    name: str,
    version: Optional[Union[int, str]] = None,
    artifact_type: Optional[ArtifactType] = None,
    tags: Optional[List[str]] = None,
    has_custom_name: bool = True,
    artifact_metadata: Dict[str, "MetadataType"] = {},
) -> "ArtifactVersionResponse":
    """Register existing data stored in the artifact store as a ZenML Artifact.

    Args:
        folder_or_file_uri: The full URI within the artifact store to the folder
            or to the file.
        name: The name of the artifact.
        version: The version of the artifact. If not provided, a new
            auto-incremented version will be used.
        artifact_type: The artifact type. If not given, the type will default
            to `data`.
        tags: Tags to associate with the artifact.
        has_custom_name: If the artifact name is custom and should be listed in
            the dashboard "Artifacts" tab.
        artifact_metadata: Metadata dictionary to attach to the artifact version.

    Returns:
        The saved artifact response.

    Raises:
        FileNotFoundError: If the folder URI is outside the artifact store
            bounds.
    """
    client = Client()

    # Get the current artifact store
    artifact_store = client.active_stack.artifact_store

    if not folder_or_file_uri.startswith(artifact_store.path):
        raise FileNotFoundError(
            f"Folder `{folder_or_file_uri}` is outside of "
            f"artifact store bounds `{artifact_store.path}`"
        )

    _check_if_artifact_with_given_uri_already_registered(
        artifact_store=artifact_store,
        uri=folder_or_file_uri,
        name=name,
    )

    artifact_version_request = ArtifactVersionRequest(
        artifact_name=name,
        version=version,
        tags=tags,
        type=artifact_type or ArtifactType.DATA,
        save_type=ArtifactSaveType.PREEXISTING,
        uri=folder_or_file_uri,
        materializer=source_utils.resolve(PreexistingDataMaterializer),
        data_type=source_utils.resolve(Path),
        project=Client().active_project.id,
        artifact_store_id=artifact_store.id,
        has_custom_name=has_custom_name,
        metadata=validate_metadata(artifact_metadata)
        if artifact_metadata
        else None,
    )
    artifact_version = client.zen_store.create_artifact_version(
        artifact_version=artifact_version_request
    )

    _link_artifact_version_to_the_step_and_model(
        artifact_version=artifact_version,
    )

    return artifact_version
remove_tags(tags: List[str], pipeline: Optional[Union[UUID, str]] = None, run: Optional[Union[UUID, str]] = None, run_template: Optional[Union[UUID, str]] = None, artifact: Optional[Union[UUID, str]] = None, artifact_version_id: Optional[UUID] = None, artifact_name: Optional[str] = None, artifact_version: Optional[str] = None, infer_artifact: bool = False) -> None
remove_tags(tags: List[str]) -> None
remove_tags(
    *, tags: List[str], pipeline: Union[UUID, str]
) -> None
remove_tags(
    *, tags: List[str], run: Union[UUID, str]
) -> None
remove_tags(
    *, tags: List[str], run_template: Union[UUID, str]
) -> None
remove_tags(
    *, tags: List[str], artifact: Union[UUID, str]
) -> None
remove_tags(
    *, tags: List[str], artifact_version_id: UUID
) -> None
remove_tags(
    *,
    tags: List[str],
    artifact_name: str,
    artifact_version: Optional[str] = None,
) -> None
remove_tags(
    *,
    tags: List[str],
    infer_artifact: bool = False,
    artifact_name: Optional[str] = None,
) -> None

Remove tags from various resource types in a generalized way.

Parameters:

Name Type Description Default
tags List[str]

The tags to remove.

required
pipeline Optional[Union[UUID, str]]

The ID or the name of the pipeline.

None
run Optional[Union[UUID, str]]

The id, name or prefix of the run.

None
run_template Optional[Union[UUID, str]]

The ID or the name of the run template.

None
artifact Optional[Union[UUID, str]]

The ID or the name of the artifact.

None
artifact_version_id Optional[UUID]

The ID of the artifact version.

None
artifact_name Optional[str]

The name of the artifact.

None
artifact_version Optional[str]

The version of the artifact.

None
infer_artifact bool

Flag deciding whether the artifact version should be inferred from the step context.

False

Raises:

Type Description
ValueError

If no identifiers are provided and the function is not called from within a step.

Source code in src/zenml/utils/tag_utils.py
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
def remove_tags(
    tags: List[str],
    # Pipelines
    pipeline: Optional[Union[UUID, str]] = None,
    # Runs
    run: Optional[Union[UUID, str]] = None,
    # Run Templates
    run_template: Optional[Union[UUID, str]] = None,
    # Artifacts
    artifact: Optional[Union[UUID, str]] = None,
    # Artifact Versions
    artifact_version_id: Optional[UUID] = None,
    artifact_name: Optional[str] = None,
    artifact_version: Optional[str] = None,
    infer_artifact: bool = False,
) -> None:
    """Remove tags from various resource types in a generalized way.

    Args:
        tags: The tags to remove.
        pipeline: The ID or the name of the pipeline.
        run: The id, name or prefix of the run.
        run_template: The ID or the name of the run template.
        artifact: The ID or the name of the artifact.
        artifact_version_id: The ID of the artifact version.
        artifact_name: The name of the artifact.
        artifact_version: The version of the artifact.
        infer_artifact: Flag deciding whether the artifact version should be
            inferred from the step context.

    Raises:
        ValueError: If no identifiers are provided and the function is not
            called from within a step.
    """
    from zenml.client import Client
    from zenml.models.v2.misc.tag import TagResource

    client = Client()
    resource_id = None
    resource_type = None

    # Remove tags from a pipeline
    if pipeline is not None:
        pipeline_model = client.get_pipeline(name_id_or_prefix=pipeline)
        resource_id = pipeline_model.id
        resource_type = TaggableResourceTypes.PIPELINE

    # Remove tags from a run template
    elif run_template is not None:
        run_template_model = client.get_run_template(
            name_id_or_prefix=run_template
        )
        resource_id = run_template_model.id
        resource_type = TaggableResourceTypes.RUN_TEMPLATE

    # Remove tags from a run
    elif run is not None:
        run_model = client.get_pipeline_run(name_id_or_prefix=run)
        resource_id = run_model.id
        resource_type = TaggableResourceTypes.PIPELINE_RUN

    # Remove tags from an artifact
    elif artifact is not None:
        artifact_model = client.get_artifact(name_id_or_prefix=artifact)
        resource_id = artifact_model.id
        resource_type = TaggableResourceTypes.ARTIFACT

    # Remove tags from an artifact version by its name and version
    elif artifact_name is not None and artifact_version is not None:
        artifact_version_model = client.get_artifact_version(
            name_id_or_prefix=artifact_name, version=artifact_version
        )
        resource_id = artifact_version_model.id
        resource_type = TaggableResourceTypes.ARTIFACT_VERSION

    # Remove tags from an artifact version by its ID
    elif artifact_version_id is not None:
        resource_id = artifact_version_id
        resource_type = TaggableResourceTypes.ARTIFACT_VERSION

    # Remove tags from an artifact version through the step context
    elif infer_artifact is True:
        try:
            from zenml.steps.step_context import get_step_context

            step_context = get_step_context()
        except RuntimeError:
            raise ValueError(
                "When you are using the `infer_artifact` option when you call "
                "`remove_tags`, it must be called inside a step with outputs."
                "Otherwise, you can provide a `artifact_version_id` or a "
                "combination of `artifact_name` and `artifact_version`."
            )

        step_output_names = list(step_context._outputs.keys())

        if artifact_name is not None:
            # If a name provided, ensure it is in the outputs
            if artifact_name not in step_output_names:
                raise ValueError(
                    f"The provided artifact name`{artifact_name}` does not "
                    f"exist in the step outputs: {step_output_names}."
                )
        else:
            # If no name provided, ensure there is only one output
            if len(step_output_names) > 1:
                raise ValueError(
                    "There is more than one output. If you would like to use "
                    "the `infer_artifact` option, you need to define an "
                    "`artifact_name`."
                )

            if len(step_output_names) == 0:
                raise ValueError("The step does not have any outputs.")

            artifact_name = step_output_names[0]

        step_context.remove_output_tags(
            tags=tags,
            output_name=artifact_name,
        )
        return

    # If every additional value is None, that means we are calling it bare bones
    # and this call needs to happen during a step execution. We will use the
    # step context to fetch the run and detach the tags accordingly.
    elif all(
        v is None
        for v in [
            run,
            artifact_version_id,
            artifact_name,
            artifact_version,
            pipeline,
            run_template,
        ]
    ):
        try:
            from zenml.steps.step_context import get_step_context

            step_context = get_step_context()
        except RuntimeError:
            raise ValueError(
                f"""
                You are calling 'remove_tags()' outside of a step execution. 
                If you would like to remove tags from a ZenML entity outside 
                of the step execution, please provide the required 
                identifiers. \n{remove_tags_warning}
                """
            )

        # Tag the pipeline run, not the step
        resource_id = step_context.pipeline_run.id
        resource_type = TaggableResourceTypes.PIPELINE_RUN

    else:
        raise ValueError(
            f"""
            Unsupported way to call the `remove_tags`. Possible combinations "
            include: \n{remove_tags_warning}
            """
        )

    # Remove tags from resource
    for tag_name in tags:
        try:
            # Get the tag
            tag = client.get_tag(tag_name)

            # Detach tag from resources
            client.detach_tag(
                tag_name_or_id=tag.id,
                resources=[TagResource(id=resource_id, type=resource_type)],
            )

        except KeyError:
            # Tag doesn't exist, nothing to remove
            pass
save_artifact(data: Any, name: str, version: Optional[Union[int, str]] = None, artifact_type: Optional[ArtifactType] = None, tags: Optional[List[str]] = None, extract_metadata: bool = True, include_visualizations: bool = True, user_metadata: Optional[Dict[str, MetadataType]] = None, materializer: Optional[MaterializerClassOrSource] = None, uri: Optional[str] = None, save_type: ArtifactSaveType = ArtifactSaveType.MANUAL, has_custom_name: bool = True) -> ArtifactVersionResponse

Upload and publish an artifact.

Parameters:

Name Type Description Default
name str

The name of the artifact.

required
data Any

The artifact data.

required
version Optional[Union[int, str]]

The version of the artifact. If not provided, a new auto-incremented version will be used.

None
tags Optional[List[str]]

Tags to associate with the artifact.

None
artifact_type Optional[ArtifactType]

The artifact type. If not given, the type will be defined by the materializer that is used to save the artifact.

None
extract_metadata bool

If artifact metadata should be extracted and returned.

True
include_visualizations bool

If artifact visualizations should be generated.

True
user_metadata Optional[Dict[str, MetadataType]]

User-provided metadata to store with the artifact.

None
materializer Optional[MaterializerClassOrSource]

The materializer to use for saving the artifact to the artifact store.

None
uri Optional[str]

The URI within the artifact store to upload the artifact to. If not provided, the artifact will be uploaded to custom_artifacts/{name}/{version}.

None
save_type ArtifactSaveType

The type of save operation that created the artifact version.

MANUAL
has_custom_name bool

If the artifact name is custom and should be listed in the dashboard "Artifacts" tab.

True

Returns:

Type Description
ArtifactVersionResponse

The saved artifact response.

Source code in src/zenml/artifacts/utils.py
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
def save_artifact(
    data: Any,
    name: str,
    version: Optional[Union[int, str]] = None,
    artifact_type: Optional[ArtifactType] = None,
    tags: Optional[List[str]] = None,
    extract_metadata: bool = True,
    include_visualizations: bool = True,
    user_metadata: Optional[Dict[str, "MetadataType"]] = None,
    materializer: Optional["MaterializerClassOrSource"] = None,
    uri: Optional[str] = None,
    # TODO: remove these once external artifact does not use this function anymore
    save_type: ArtifactSaveType = ArtifactSaveType.MANUAL,
    has_custom_name: bool = True,
) -> "ArtifactVersionResponse":
    """Upload and publish an artifact.

    Args:
        name: The name of the artifact.
        data: The artifact data.
        version: The version of the artifact. If not provided, a new
            auto-incremented version will be used.
        tags: Tags to associate with the artifact.
        artifact_type: The artifact type. If not given, the type will be defined
            by the materializer that is used to save the artifact.
        extract_metadata: If artifact metadata should be extracted and returned.
        include_visualizations: If artifact visualizations should be generated.
        user_metadata: User-provided metadata to store with the artifact.
        materializer: The materializer to use for saving the artifact to the
            artifact store.
        uri: The URI within the artifact store to upload the artifact
            to. If not provided, the artifact will be uploaded to
            `custom_artifacts/{name}/{version}`.
        save_type: The type of save operation that created the artifact version.
        has_custom_name: If the artifact name is custom and should be listed in
            the dashboard "Artifacts" tab.

    Returns:
        The saved artifact response.
    """
    from zenml.materializers.materializer_registry import (
        materializer_registry,
    )
    from zenml.utils import source_utils

    client = Client()
    artifact_store = client.active_stack.artifact_store

    if not uri:
        uri = os.path.join("custom_artifacts", name, str(uuid4()))
    if not uri.startswith(artifact_store.path):
        uri = os.path.join(artifact_store.path, uri)

    if save_type == ArtifactSaveType.MANUAL:
        # This check is only necessary for manual saves as we already check
        # it when creating the directory for step output artifacts
        _check_if_artifact_with_given_uri_already_registered(
            artifact_store=artifact_store,
            uri=uri,
            name=name,
        )

    if isinstance(materializer, type):
        materializer_class = materializer
    elif materializer:
        materializer_class = source_utils.load_and_validate_class(
            materializer, expected_class=BaseMaterializer
        )
    else:
        materializer_class = materializer_registry[type(data)]

    artifact_version_request = _store_artifact_data_and_prepare_request(
        data=data,
        name=name,
        uri=uri,
        materializer_class=materializer_class,
        save_type=save_type,
        version=version,
        artifact_type=artifact_type,
        tags=tags,
        store_metadata=extract_metadata,
        store_visualizations=include_visualizations,
        has_custom_name=has_custom_name,
        metadata=user_metadata,
    )
    artifact_version = client.zen_store.create_artifact_version(
        artifact_version=artifact_version_request
    )

    if save_type == ArtifactSaveType.MANUAL:
        _link_artifact_version_to_the_step_and_model(
            artifact_version=artifact_version,
        )

    return artifact_version
show(local: bool = False, ngrok_token: Optional[str] = None) -> None

Show the ZenML dashboard.

Parameters:

Name Type Description Default
local bool

Whether to show the dashboard for the local server or the one for the active server.

False
ngrok_token Optional[str]

An ngrok auth token to use for exposing the ZenML dashboard on a public domain. Primarily used for accessing the dashboard in Colab.

None

Raises:

Type Description
RuntimeError

If no server is connected.

Source code in src/zenml/utils/dashboard_utils.py
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
def show_dashboard(
    local: bool = False,
    ngrok_token: Optional[str] = None,
) -> None:
    """Show the ZenML dashboard.

    Args:
        local: Whether to show the dashboard for the local server or the
            one for the active server.
        ngrok_token: An ngrok auth token to use for exposing the ZenML
            dashboard on a public domain. Primarily used for accessing the
            dashboard in Colab.

    Raises:
        RuntimeError: If no server is connected.
    """
    from zenml.utils.networking_utils import get_or_create_ngrok_tunnel

    url: Optional[str] = None
    if not local:
        gc = GlobalConfiguration()
        if gc.store_configuration.type == StoreType.REST:
            url = gc.store_configuration.url

    if not url:
        # Else, check for local servers
        server = get_local_server()
        if server and server.status and server.status.url:
            url = server.status.url

    if not url:
        raise RuntimeError(
            "ZenML is not connected to any server right now. Please use "
            "`zenml login` to connect to a server or spin up a new local server "
            "via `zenml login --local`."
        )

    if ngrok_token:
        parsed_url = urlparse(url)

        ngrok_url = get_or_create_ngrok_tunnel(
            ngrok_token=ngrok_token, port=parsed_url.port or 80
        )
        logger.debug(f"Tunneling dashboard from {url} to {ngrok_url}.")
        url = ngrok_url

    show_dashboard_with_url(url)
step(_func: Optional[F] = None, *, name: Optional[str] = None, enable_cache: Optional[bool] = None, enable_artifact_metadata: Optional[bool] = None, enable_artifact_visualization: Optional[bool] = None, enable_step_logs: Optional[bool] = None, experiment_tracker: Optional[str] = None, step_operator: Optional[str] = None, output_materializers: Optional[OutputMaterializersSpecification] = None, settings: Optional[Dict[str, SettingsOrDict]] = None, extra: Optional[Dict[str, Any]] = None, on_failure: Optional[HookSpecification] = None, on_success: Optional[HookSpecification] = None, model: Optional[Model] = None, retry: Optional[StepRetryConfig] = None, substitutions: Optional[Dict[str, str]] = None) -> Union[BaseStep, Callable[[F], BaseStep]]
step(_func: F) -> BaseStep
step(
    *,
    name: Optional[str] = None,
    enable_cache: Optional[bool] = None,
    enable_artifact_metadata: Optional[bool] = None,
    enable_artifact_visualization: Optional[bool] = None,
    enable_step_logs: Optional[bool] = None,
    experiment_tracker: Optional[str] = None,
    step_operator: Optional[str] = None,
    output_materializers: Optional[
        OutputMaterializersSpecification
    ] = None,
    settings: Optional[Dict[str, SettingsOrDict]] = None,
    extra: Optional[Dict[str, Any]] = None,
    on_failure: Optional[HookSpecification] = None,
    on_success: Optional[HookSpecification] = None,
    model: Optional[Model] = None,
    retry: Optional[StepRetryConfig] = None,
    substitutions: Optional[Dict[str, str]] = None,
) -> Callable[[F], BaseStep]

Decorator to create a ZenML step.

Parameters:

Name Type Description Default
_func Optional[F]

The decorated function.

None
name Optional[str]

The name of the step. If left empty, the name of the decorated function will be used as a fallback.

None
enable_cache Optional[bool]

Specify whether caching is enabled for this step. If no value is passed, caching is enabled by default.

None
enable_artifact_metadata Optional[bool]

Specify whether metadata is enabled for this step. If no value is passed, metadata is enabled by default.

None
enable_artifact_visualization Optional[bool]

Specify whether visualization is enabled for this step. If no value is passed, visualization is enabled by default.

None
enable_step_logs Optional[bool]

Specify whether step logs are enabled for this step.

None
experiment_tracker Optional[str]

The experiment tracker to use for this step.

None
step_operator Optional[str]

The step operator to use for this step.

None
output_materializers Optional[OutputMaterializersSpecification]

Output materializers for this step. If given as a dict, the keys must be a subset of the output names of this step. If a single value (type or string) is given, the materializer will be used for all outputs.

None
settings Optional[Dict[str, SettingsOrDict]]

Settings for this step.

None
extra Optional[Dict[str, Any]]

Extra configurations for this step.

None
on_failure Optional[HookSpecification]

Callback function in event of failure of the step. Can be a function with a single argument of type BaseException, or a source path to such a function (e.g. module.my_function).

None
on_success Optional[HookSpecification]

Callback function in event of success of the step. Can be a function with no arguments, or a source path to such a function (e.g. module.my_function).

None
model Optional[Model]

configuration of the model in the Model Control Plane.

None
retry Optional[StepRetryConfig]

configuration of step retry in case of step failure.

None
substitutions Optional[Dict[str, str]]

Extra placeholders for the step name.

None

Returns:

Type Description
Union[BaseStep, Callable[[F], BaseStep]]

The step instance.

Source code in src/zenml/steps/step_decorator.py
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
def step(
    _func: Optional["F"] = None,
    *,
    name: Optional[str] = None,
    enable_cache: Optional[bool] = None,
    enable_artifact_metadata: Optional[bool] = None,
    enable_artifact_visualization: Optional[bool] = None,
    enable_step_logs: Optional[bool] = None,
    experiment_tracker: Optional[str] = None,
    step_operator: Optional[str] = None,
    output_materializers: Optional["OutputMaterializersSpecification"] = None,
    settings: Optional[Dict[str, "SettingsOrDict"]] = None,
    extra: Optional[Dict[str, Any]] = None,
    on_failure: Optional["HookSpecification"] = None,
    on_success: Optional["HookSpecification"] = None,
    model: Optional["Model"] = None,
    retry: Optional["StepRetryConfig"] = None,
    substitutions: Optional[Dict[str, str]] = None,
) -> Union["BaseStep", Callable[["F"], "BaseStep"]]:
    """Decorator to create a ZenML step.

    Args:
        _func: The decorated function.
        name: The name of the step. If left empty, the name of the decorated
            function will be used as a fallback.
        enable_cache: Specify whether caching is enabled for this step. If no
            value is passed, caching is enabled by default.
        enable_artifact_metadata: Specify whether metadata is enabled for this
            step. If no value is passed, metadata is enabled by default.
        enable_artifact_visualization: Specify whether visualization is enabled
            for this step. If no value is passed, visualization is enabled by
            default.
        enable_step_logs: Specify whether step logs are enabled for this step.
        experiment_tracker: The experiment tracker to use for this step.
        step_operator: The step operator to use for this step.
        output_materializers: Output materializers for this step. If
            given as a dict, the keys must be a subset of the output names
            of this step. If a single value (type or string) is given, the
            materializer will be used for all outputs.
        settings: Settings for this step.
        extra: Extra configurations for this step.
        on_failure: Callback function in event of failure of the step. Can be a
            function with a single argument of type `BaseException`, or a source
            path to such a function (e.g. `module.my_function`).
        on_success: Callback function in event of success of the step. Can be a
            function with no arguments, or a source path to such a function
            (e.g. `module.my_function`).
        model: configuration of the model in the Model Control Plane.
        retry: configuration of step retry in case of step failure.
        substitutions: Extra placeholders for the step name.

    Returns:
        The step instance.
    """

    def inner_decorator(func: "F") -> "BaseStep":
        from zenml.steps.decorated_step import _DecoratedStep

        class_: Type["BaseStep"] = type(
            func.__name__,
            (_DecoratedStep,),
            {
                "entrypoint": staticmethod(func),
                "__module__": func.__module__,
                "__doc__": func.__doc__,
            },
        )

        step_instance = class_(
            name=name or func.__name__,
            enable_cache=enable_cache,
            enable_artifact_metadata=enable_artifact_metadata,
            enable_artifact_visualization=enable_artifact_visualization,
            enable_step_logs=enable_step_logs,
            experiment_tracker=experiment_tracker,
            step_operator=step_operator,
            output_materializers=output_materializers,
            settings=settings,
            extra=extra,
            on_failure=on_failure,
            on_success=on_success,
            model=model,
            retry=retry,
            substitutions=substitutions,
        )

        return step_instance

    if _func is None:
        return inner_decorator
    else:
        return inner_decorator(_func)
Modules
entrypoint

Functionality to run ZenML steps or pipelines.

Classes Functions
main() -> None

Runs the entrypoint configuration given by the command line arguments.

Source code in src/zenml/entrypoints/entrypoint.py
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
def main() -> None:
    """Runs the entrypoint configuration given by the command line arguments."""
    _setup_logging()

    # Make sure this entrypoint does not run an entire pipeline when
    # importing user modules. This could happen if the `pipeline.run()` call
    # is not wrapped in a function or an `if __name__== "__main__":` check)
    constants.SHOULD_PREVENT_PIPELINE_EXECUTION = True

    # Read the source for the entrypoint configuration class from the command
    # line arguments
    parser = argparse.ArgumentParser()
    parser.add_argument(f"--{ENTRYPOINT_CONFIG_SOURCE_OPTION}", required=True)
    args, remaining_args = parser.parse_known_args()

    entrypoint_config_class = source_utils.load_and_validate_class(
        args.entrypoint_config_source,
        expected_class=BaseEntrypointConfiguration,
    )
    entrypoint_config = entrypoint_config_class(arguments=remaining_args)

    entrypoint_config.run()
Modules