Package: rest-model-service
REST Model Servicerest-model-serviceis a package for building RESTful services for hosting machine learning models.This package helps you to quickly build RESTful services for your ML model by handling many low level details, like:Documentation, using pydantic and OpenAPILogging configurationStatus Check EndpointsMetricsThis package also allows you to extend the functionality of your deployed models by following theDecorator Pattern.InstallationThe package can be installed from pypi:pipinstallrest_model_serviceUsageTo use the service you must first have a working model class that uses the MLModel base class from theml_base package. The MLModel base class is designed to provide a consistent interface around model prediction
logic that allows the rest_model_service package to deploy any model that implements it. Some examples of how to create
MLModel classes for your model can be foundhere.You can then set up a configuration file that points at the model class of the model you want to host. The
configuration file should look like this:service_title:"RESTModelService"models:-class_path:tests.mocks.IrisModelcreate_endpoint:trueThe "class_path" should contain the full path to the class, including the package names, module name, and class name
separated by periods. The "create_endpoint" option is there for cases when you might want to load a model but not create
an endpoint for it, if it is set to "false" the model will be loaded and available for use within the service but
will not have an endpoint defined for it. A reference to the model object will be available from theModelManager
singleton.The config file should be YAML, be named "rest_config.yaml", and be in the current working directory. However,
we can point at configuration files that have different names and are in different locations if needed.The service can host many models, all that is needed is to add entries to the "models" array.Configuration options can also be passed to the models hosted by the service. To do this, add a configuration key to
the model entry in the "models" array:service_title:"RESTModelService"models:-class_path:tests.mocks.IrisModelcreate_endpoint:trueconfiguration:parameter1:trueparameter2:string_valueparameter3:123The key-value pairs are passed directly into the model class'__init__()method at instantiation time as keyword
arguments. The model can then use the parameters to configure itself.Adding Service InformationWe can add several details to the configuration file that are useful when building OpenAPI specifications.service_title:"RESTModelService"description:"Servicedescription"version:"1.1.0"models:-class_path:tests.mocks.IrisModelcreate_endpoint:trueThe service title, description, and version are passed into the application and used to build the OpenAPI specification.
Details for how to build the OpenAPI document for your model service are below.Adding a Decorator to a ModelThe rest_model_service package also supports thedecorator pattern.
Decorators are defined in theml_base packageand explainedhere. A decorator can be added to a model by adding the "decorators"
key to the model's configuration:service_title:REST Model Service With Decoratorsmodels:-class_path:tests.mocks.IrisModelcreate_endpoint:truedecorators:-class_path:tests.mocks.PredictionIDDecoratorThe PredictionIDDecorator will be instantiated and added to the IrisModel instance when the service starts up.
Keyword arguments can also be provided to the decorator's__init__()by adding a "configuration" key to the
decorator's entry like this:service_title:REST Model Service With Decoratorsmodels:-class_path:tests.mocks.IrisModelcreate_endpoint:truedecorators:-class_path:tests.mocks.PredictionIDDecoratorconfiguration:parameter1:"asdf"parameter2:"zxcv"The configuration dictionary will be passed to the decorator class as keyword arguments.Many decorators can be added to a single model, in which case each decorator will decorate the decorator that was
previously attached to the model. This will create a "stack" of decorators that will each handle the prediction request
before the model's prediction is created.Adding LoggingThe service also optionally accepts logging configuration through the YAML configuration file:service_title:REST Model Service With Loggingmodels:-class_path:tests.mocks.IrisModelcreate_endpoint:truelogging:version:1disable_existing_loggers:trueformatters:formatter:class:logging.Formatterformat:"%(asctime)s%(pathname)s%(lineno)s%(levelname)s%(message)s"handlers:stdout:level:INFOclass:logging.StreamHandlerstream:ext://sys.stdoutformatter:formatterloggers:root:level:INFOhandlers:-stdoutpropagate:falseThe YAML needs to be formatted so that it deserializes to a dictionary that matches the logging package'sconfiguration
dictionary schema.Adding MetricsThis package allows you to create an endpoint that exposes metrics to aPrometheus server.
The metrics endpoint is disabled by default and must be enabled in the configuration file.Using this aspect of the service requires installing the "metrics" optional dependencies:pipinstallrest_model_service[metrics]To enable the metrics collection, simply set the "enabled" attribute in the "metrics" attribute to "true" in the YAML
configuration file:service_title:"RESTModelService"description:"Servicedescription"version:"1.1.0"metrics:enabled:truemodels:-class_path:tests.mocks.IrisModelcreate_endpoint:trueThe default metrics are:http_requests_total: A counter that counts the number of requests to the service.http_request_size_bytes: A summary that counts the size of the requests to the service.http_response_size_bytes: A summary that counts the size of the responses from the service.http_request_duration_seconds: A histogram that counts the duration of the requests to the service. Only a few
buckets to keep cardinality low.http_request_duration_highr_seconds: A histogram that counts the duration of the requests to the service. Large
number of buckets (>20).The configuration allows more complex options to be passed to the Prometheus client library. To do this, add
keys to the metrics configuration:service_title:"RESTModelService"description:"Servicedescription"version:"1.1.0"metrics:enabled:trueshould_group_status_codes:trueshould_ignore_untemplated:falseshould_group_untemplated:trueshould_round_latency_decimals:falseshould_respect_env_var:falseshould_instrument_requests_inprogress:falseexcluded_handlers:[]body_handlers:[]round_latency_decimals:4env_var_name:"ENABLE_METRICS"inprogress_name:"http_requests_inprogress"inprogress_labels:falsemodels:-class_path:tests.mocks.IrisModelcreate_endpoint:trueThe options are passed directly into the Prometheus instrumentorlibrary, the options are explained in that library's documentation.Creating an OpenAPI ContractAn OpenAPI contract can be generated dynamically for your models as hosted within the REST model service. To create
the contract and save it execute this command:generate_openapiThe command looks for a "rest_config.yaml" in the current working directory and creates the application from it.
The command then saves the resulting OpenAPI document to a file named "openapi.yaml" in the current working directory.You can provide a path to the configuration file like this:generate_openapi--configuration_file=examples/rest_config.yamlYou can also provide the desired path for the OpenAPI document that will be created like this:generate_openapi--output_file=example.yamlBoth options together:generate_openapi--configuration_file=examples/rest_config.yaml--output_file=example.yamlAn example rest_config.yaml file is provided in the examples of the project. It points at a MLModel class in the tests
package.Using Status Check EndpointsThe service supports three status check endpoints:"/api/health", indicates whether the service process is running. This endpoint will return a 200 status once the
service has started."/api/health/ready", indicates whether the service is ready to respond to requests. This endpoint will return a 200
status only if all the models and decorators have finished being instantiated without errors. Once the models and
decorators are loaded, the readiness check will always return a ACCEPTING_TRAFFIC state."/api/health/startup", indicates whether the service is started. This endpoint will return a 200 status only if all
the models and decorators have finished being instantiated without errors.Running the ServiceTo start the service in development mode, execute this command:uvicornrest_model_service.main:app--reloadThe service should be able to find your configuration file, but if you did not place it in the current working
directory you can point the service to the right path like this:exportREST_CONFIG='examples/rest_config.yaml'uvicornrest_model_service.main:app--reloadCommon ErrorsIf you get an error that says something about not being able to find a module or a class, you might need to update your
PYTHONPATH environment variable:exportPYTHONPATH=./The service relies on being able to find the model classes and the decorator classes in the python environment to load
them and instantiate them. If your Python interpreter is not able to find the classes, then the service won't be able
to instantiate the model classes or create endpoints for the models or an OpenAPI document for them.DevelopmentDownload the source code with this command:gitclonehttps://github.com/schmidtbri/rest-model-servicecdrest-model-serviceThen create a virtual environment and activate it:makevenv# on Macssourcevenv/bin/activateInstall the dependencies:makedependenciesTestingTo run the unit test suite execute these commands:# first install the test dependenciesmaketest-dependencies# run the test suitemaketest# clean up the unit testsmakeclean-test