Cortex Python Reference

Cortex

class cortex.client.Cortex

Entry point to the Cortex API.

static client(api_endpoint: str = None, api_version: int = 3, verify_ssl_cert: bool = False, token: str = None, account: str = None, username: str = None, password: str = None)

Gets a client with the provided parameters. All parameters are optional and default to environment variable values if not specified.

Example

>>> from cortex import Cortex
>>> cortex = Cortex.client()
Parameters:
  • api_endpoint – The Cortex URL.
  • api_version – The version of the API to use with this client.
  • verify_ssl_cert – A boolean to indiciate if the SSL certificate needs to be validated.
  • token – An authentication token.
  • account – The Cortex account the client connects to.
  • username – The user name for the client.
  • password – The password for the client.
static from_message(msg)

Creates a Cortex client from a message that must incluide an API endpoint and a token.

Parameters:msg – A message for constructing a Cortex Client.
static login()

Login to Cortex5. The function prompts the caller for Cortex URI, account, user name, and password, retrieves the user’s JWT token and sets the information as environment variables for use by the SDK.

Example

>>> Cortex.login()
Cortex URI: [https://api.cortex.insights.ai]
Account: accountId
Username: userName
Password: ****

Cortex Client

class cortex.client.Client(url: str, token: cortex.client._Token, version: int = 3, verify_ssl_cert: bool = False)

API client used to access agents, skills, and datasets.

action(name: str) → cortex.action.Action

Gets an action with the specified name.

agent(name: str) → cortex.agent.Agent

Gets an agent with the specified name.

builder()

Gets a builder.

dataset(name: str) → cortex.dataset.Dataset

Gets a dataset with the specified name.

experiment(name: str, version: str = '2')

Gets an experiment with the specified name.

message(payload: dict) → cortex.message.Message

Constructs a Message from payload.

Parameters:payload – The payload to include in the Message.
Returns:A Message object.
session(session_id=None, ttl=None, instance_id=None) → cortex.session.Session

Gets a session with the specified identifier.

skill(name: str) → cortex.skill.Skill

Gets a skill with the specified name.

Cortex Action

class cortex.action.Action(action, connector: cortex_client.serviceconnector.ServiceConnector)

A Cortex Action. Actions are the computional part of a skill.

delete()

Delete an action.

static get_action(name: str, connector: cortex_client.serviceconnector.ServiceConnector)

Fetches an Action to work with.

Parameters:name – The name of the Action to retrieve.
Returns:An Action object.
get_deployment_status()

Get the deployment status of an action.

get_task_logs(task_id)

Get the logs for a task.

Parameters:task_id – The identifier for the task.
get_task_status(task_id)

Get the status for a job task (a task is a particular invocation of the action type: job).

Parameters:task_id – The identifier for the task.
invoke(message: cortex.message.Message, timeout=30)

Invoke an action.

Parameters:message – A Message to send as input to the action.
Returns:A response Message.

Cortex Agent

class cortex.agent.Agent(agent, connector: cortex_client.serviceconnector.ServiceConnector)

A Cortex5 agent, which represents the deployable applications that aggregate the skills, inputs and outputs, and data flows.

static get_agent(name: str, connector: cortex_client.serviceconnector.ServiceConnector)

Fetches an agent to work with.

Parameters:
  • name – The name of the agent to retrieve.
  • connector – A service connector.
Returns:

An agent object.

invoke_service(service_name: str, message: cortex.message.Message, timeout=30)

Invokes a service, polling for a result for the number of seconds specified when the service times out.

Parameters:
  • service_name – The name of the service to invoke.
  • message – The payload for the service invocation.
  • timeout – Number of seconds to poll for a result.
Returns:

Service activation result.

invoke_service_async(service_name: str, message: cortex.message.Message) → cortex.agent.ServiceActivation

Invokes a service.

Parameters:
  • service_name – The name of the service to invoke.
  • message – The payload for the service invocation.
Returns:

Service activation.

Cortex Dataset

class cortex.dataset.Dataset(ds, client: cortex_client.datasetsclient.DatasetsClient)

Defines the data and query parameters for accessing inputs to a managed content file or database connection.

as_pandas()

Gets a pandas dataframe for the dataset.

get_dataframe()

Gets the dataframe for the dataset.

static get_dataset(name, client: cortex_client.datasetsclient.DatasetsClient)

Gets a dataset.

Parameters:
  • name – The name of the dataset to retrieve.
  • client – The client instance to use.
Returns:

A dataset object.

get_stream()

Streams the data coming from the dataset.

pipeline(name, clear_cache=False, depends=None)

Gets a pipeline for the dataset.

Parameters:
  • name – name of the pipeline
  • clear_cache – a flag to indicate whether previous results for the pipeline should be cleared
  • depends – a list of pipeline names upon which this pipeline depends

Cortex Experiment

class cortex.experiment.Experiment(document: Dict, client: cortex_client.experimentclient.ExperimentClient)

Tracks runs, associated parameters, metrics, and artifacts of experiments.

static get_experiment(name, client: cortex_client.experimentclient.ExperimentClient, **kwargs)

Fetches or creates an experiment to work with.

Parameters:
  • name – The name of the experiment to retrieve.
  • client – The client instance to use.
Returns:

An experiment object.

Cortex Pipeline

class cortex.pipeline.Pipeline(name: str, depends=None, loader=<cortex.pipeline_loader.PipelineLoader object>)

Provides a pipeline abstraction used to transform or enrich data; steps either Python functions or classes with a transform method; a pipeline step accepts a dataframe as an argument and is expected to transform or enrich the dataframe in sequential order.

To create a pipeline to remove an unused column:

>>> from cortex import Cortex
>>> train_ds = cortex.dataset(' <path to your data set> ')
>>> pipeline = train_ds.pipeline(' <pipeline name> ', clear_cache=True)
>>> pipeline.reset()
>>> def drop_unused(pipeline, df):
...     df.drop(columns=['Id'], axis=1, inplace=True) # this pipeline will drop the field ID
...
>>> pipeline.add_step(drop_unused)
add_dependency(pipeline)

Adds a dependency on another pipeline.

Parameters:pipeline – the pipeline on which this pipeline depends.
add_step(step, name=None, serializer=<function dumps>)

Adds a transformation function to the pipeline.

Parameters:
  • fn – The function to add.
  • name – An optional name for the function to add.
dependencies

Gets a list of dependencies for the pipeline.

dumps(stream=None, notebook=False, camel='1.0.0', yaml_format=False)

Dumps the steps, dependencies, and context for the pipeline.

Parameters:
  • stream – Optional stream on which to dump the pipeline.
  • notebook – Optional notebook where the dump should be displayed.
from_pipeline(pipeline)

Copies a pipeline from the given pipeline.

Parameters:pipeline – The pipeline from which to copy this pipeline.
get_context(key: str, default_value=None, deserializer=<function loads>)

Gets the context for the pipeline.

Parameters:
  • key – The key for the context.
  • default_value – (Optional) A default value to return if the context for the given key is not found
Returns:

The context for the given key, if it exists. If it does not exist, the default value or none.

get_step(name, deserializer=<function loads>)

Gets a pipeline step by name.

Parameters:name – Name of the function to get.
Returns:The code for the step.
name

Gets the name of the pipeline.

remove_step(name)

Removes a step by name.

Parameters:name – Name of the function to remove.
reset(reset_deps=False, reset_context=False)

Removes all steps from the pipeline, but leaves context and dependencies in place. Context and dependencies can also be reset using the optional flags for each.

Parameters:
  • reset_deps – If True, removes all dependencies. Default: False.
  • reset_context – If True, resets context. Default: False
Returns:

The pipeline instance.

run(data, code_deserializer=<function loads>)

Runs the steps on the pipeline.

Parameters:data – Data to pass to dependencies.
Returns:The dataframe as transformed by the dependencies and steps.
set_context(key: str, obj, serializer=<function dumps>)

Sets the context for the pipeline.

Parameters:
  • key – The key for the context to set.
  • obj – The value for the context to set.
steps

Gets a list of steps in the pipeline.

Cortex Skill

class cortex.skill.Skill(skill, connector: cortex_client.serviceconnector.ServiceConnector)

Computational components of an agent; executes an atomic unit of work and can be triggered by one or more inputs to produce one or more outputs.

static get_skill(name: str, connector: cortex_client.serviceconnector.ServiceConnector)

Fetches a skill to work with.

Parameters:name – The name of the skill to retrieve.
Returns:A skill object.
invoke(input_name: str, message: cortex.message.Message, timeout=30)

Invokes the skill with a given message.

Parameters:
  • input_name – Identifier for an input to this skill.
  • message – The message used for the invocation.

Cortex Builders

Cortex Builder Factory

class cortex.builder.builder_factory.BuilderFactory(client)

Builds component builders.

action(name: str, camel_version='1.0.0')

Creates an ActionBuilder with the given name.

Parameters:name – name of the action builder. The name must provide at least one cortex namespace identifier and a resource name.
connection(name: str, camel_version='1.0.0') → cortex.builder.connection_builder.ConnectionBuilder

Creates a connection with the given name.

Parameters:name – name of the connection builder. The name must provide at least one cortex namespace identifier and a resource name.
dataset(name: str, camel_version='1.0.0') → cortex.builder.dataset_builder.DatasetBuilder

Creates a DatasetBuilder with the given name.

Example

>>> builder = cortex.builder()
>>> train_df = pd.read_csv(' <path to data as csv file>')
>>> train_ds = builder.dataset('<cortex name space>/<dataset name>').from_df(train_df).build()
Parameters:name – name of the dataset builder. The name must provide at least one cortex namespace identifier and a resource name.
pipeline(name: str)

Creates a pipeline with the given name.

Parameters:name – name of the pipeline
profile_schema(bareBoneSchema: cortex_common.types.schemas.ProfileSchema) → cortex.builder.profile_builder.ProfileSchemaBuilder

Builds a schema .. starting with barebone schema …

Parameters:bareBoneSchema
Returns:
profiles(schemaId: Optional[str]) → cortex.builder.profile_builder.ProfilesBuilder

Builds one or more profiles that adhere to a specific schema …

Parameters:schemaId – Can be optionally provided to enable verification on the profile building events …
Returns:
schema(name: str, camel_version='1.0.0')

Creates a SchemaBuilder with the given name.

Parameters:name – name of the schema builder
skill(name: str, camel_version='1.0.0') → cortex.builder.skill_builder.SkillBuilder

Creates a SkillBuilder with the given name.

Parameters:name – name of the skill builder. The name must provide at least one cortex namespace identifier and a resource name.

Cortex Action Builder

class cortex.builder.action_builder.ActionBuilder(name: str, client: cortex_client.actionclient.ActionClient, camel='1.0.0')

Builds an action, the computional part of a skill.

build(**kwargs) → Optional[cortex.action.Action]

Builds an action.

Returns:An action, or none, if the dry-run flag is set
daemon()

Sets the action to type: daemon.

from_image(image: str)

Sets the Docker image name.

Parameters:name – name of the docker image
from_model(model, model_type='sklearn', x_pipeline=None, y_pipeline=None, target='y')

Associates a model with this ActionBuilder.

from_setup(setup_script: str, action_module: str, function_name: str = 'main')

Builds an action from a source archive built using Python Setuptools; builds the source distribution using the Setuptools sandbox.

Parameters:
  • setup_script – path to setup.py script
  • action_module – full path to the Python module containing the action: function
  • function_name – name of the function to import and invoke, default is ‘main’
Returns:

the builder instance

from_source(source_str: str, function_name: str = 'main')

Builds an action from source code. NOTE: The Python source code must contain a function with the specified name.

Parameters:
  • source_str – Python source code string
  • function_name – name of the function to invoke, default is ‘main’
Returns:

the builder instance

from_source_file(file_path: str, function_name: str = 'main')

Builds an action from a source file. NOTE: The Python source code must contain a function with the specified name.

Parameters:
  • file_path – path to a file containing Python source code
  • function_name – name of the function to invoke, default is ‘main’
Returns:

the builder instance

image_prefix(prefix)

Adds a path definition prefix to the Docker image name; ignored when the ‘registry’ property is set.

Parameters:prefix – prefix to use with the Docker image
job()

Sets the action to type: job.

kind(kind: str)

Sets the kind of action, either “python:3” or “python:2”.

name

Gets the name for the ActionBuilder

registry(registry_uri: str)

Sets the Docker registry URI.

with_base_image(base_image)

Sets the base image to use for the Action container.

Parameters:base_image – a valid image name for an image that is accessible on the machine this builder is run.
with_conda_requirements(requirements: list)

Sets conda requirements for this ActionBuilder to the given list.

Parameters:requirements – a list of requirements
with_pip_freeze()

Sets the requirements for this ActionBuilder with pip freeze.

with_requirements(requirements: list)

Sets requirements for this ActionBuilder to the given list.

Parameters:requirements – a list of requirements

Cortex Dataset Builder

class cortex.builder.dataset_builder.DatasetBuilder(name: str, client: cortex_client.datasetsclient.DatasetsClient, camel='1.0.0')

A builder utility to aid in programmatic creation of Cortex datasets; not meant to be directly instantiated by clients.

build() → cortex.dataset.Dataset

Builds and saves a dataset using the properties configured on the builder.

Returns:the resulting dataset
create_schema(name: str, title: str = None, description: str = None)

Creates or replaces a schema (type) based on the message parameters set in the builder once the build is called. The Cortex dataset refers to this schema rather than embedding the parameters inline.

Parameters:
  • name – the resource name of the new schema
  • title – human-readable display name
  • description – human-readable long description
Returns:

the builder instance

description(description: str)

Sets the description property of the dataset.

Parameters:description – The human-readable long description of the dataset.
Returns:The builder instance.
from_csv(file_name, **kwargs)

Creates a dataset from a csv file.

Parameters:
  • file_name – name of the file
  • kwargs – optional key-value dictionary of parameters to pass to pandas on creation
from_dataset(ds: cortex.dataset.Dataset)

Creates a dataset builder from a given dataset.

Parameters:ds – dataset to use in creation of this builder
from_df(df, format='json')

Sets the content of the dataset to the provided pandas dataframe. The datarrame is serialized and uploaded to the Cortex Managed Content service in the specified path.

Parameters:
  • df – the pandas dataframe to use
  • format – ‘json’ or ‘csv’
Returns:

the builder instance

from_json(file_name, **kwargs)

Creates a dataset from a json file.

Parameters:
  • file_name – name of the file
  • kwargs – optional key-value dictionary of parameters to pass to pandas on creation
parameters(parameters: list)

Sets the parameters property of the dataset.

Parameters:parameters – The parameters to associate with the dataset.
Returns:The builder instance.
title(title: str)

Sets the title property of a dataset.

Parameters:title – the human-readable name of the dataset.
Returns:the builder instance.
to_camel()

Creates a dataset with the builder’s CAMEL definitions.

Cortex Schema Builder

class cortex.builder.schema_builder.SchemaBuilder(name: str, client: cortex_client.catalogclient.CatalogClient, camel='1.0.0')

Creates and replaces dataset schemas (types); not intended to be directly instantiated by clients.

description(description: str)

Sets the description property of the schema.

Parameters:description – the human-readable long description of the schema
Returns:the builder instance
title(title: str)

Sets the title property of the schema.

Parameters:title – the human-readable name of the schema
Returns:the builder instance

Cortex Skill Builder

class cortex.builder.skill_builder.SkillBuilder(name: str, client: cortex_client.catalogclient.CatalogClient, camel='1.0.0')

Creates a Cortex skill; not meant to be directly instantiated byclients.

build() → cortex.skill.Skill

Builds and replaces a skill using the properties configured on the builder.

Returns:the resulting skill
dataset(name: str)

Adds a skill dataset reference.

Parameters:name – the name of a dataset reference for a skill
Returns:the builder instance
description(description: str)

Sets the description property of the Skill.

Parameters:description – the human friendly long description of the Skill
Returns:the builder instance
input(name: str)

Adds a skill input.

Parameters:name – the name of a skill input parameter
Returns:the builder instance
output(name: str)

Adds a skill output.

Parameters:name – the name of a skill output parameter
Returns:the builder instance
property(name: str, data_type: str, title: str = None, description: str = None, required: bool = True, secure=False, default_val: str = None, valid_values=None)

Adds a skill property, which can be configured on a per instance basis and are passed down to actions for use.

Parameters:
  • name – the property name
  • data_type – the CAMEL schema data type of the skill property
  • title – the human-readable name of the skill property
  • description – the human-readable description of the skill property
  • required – boolean flag that identifies if the skill property is required
  • secure – boolean flag that identifies if the skill property requires a secure variable assignment
  • default_val – the default value of the propery
  • valid_values – additional valid values for the property that may be selected
Returns:

the builder instance

title(title: str)

Sets the title property of the Skill.

Parameters:title – the human friendly name of the Skill
Returns:the builder instance

CORTEX Python REST Clients

ML Models

ModelProcess

class cortex_client.ModelProcess

The abstract base class for model process classes that provides a signature for training and inquiring of the model.

static inquire(request: Dict[str, object], cortex_model: cortex_client.types.Model, model_client: cortex_client.modelclient.ModelClient) → Union[str, int, float, None, Dict[str, Any], List[Any]]

Performs ask against a trained_model.

Parameters:
  • request – The arguments of the inquiry.
  • cortex_model – The Cortex model object with which the trained_model is associated; used with the ModelClient to log model events.
  • model_client – The ModelClient with methods to log training events.
Returns:

The inquiry result.

static train(request: Dict[str, object], cortex_model: cortex_client.types.Model, datasets_client: cortex_client.datasetsclient.DatasetsClient, model_client: cortex_client.modelclient.ModelClient) → None

Performs training of the model.

Parameters:
  • request – The arguments needed to train the model.
  • cortex_model – The Cortex model object to train.
  • datasets_client – The DatasetsClient to download training data
  • model_client – The ModelClient with methods to report training events.

ModelRouter

class cortex_client.ModelRouter(modelrunner)

Implements a CLI for running the ML algorithm and defines the CLI commands:

  • –train executes a train request.
  • –inquire executes an inquiry request.
  • –inquire_init executes an inquiry initialization request,
  • –daemon starts the web server / service to serve inquiry requests via HTTP.
static main(modelprocess: cortex_client.modelprocess.ModelProcess) → None

The function called to execute a ModelProcess.

run()

Routing logic to run train or predict from the CLI.

run_service()

Starts Flask service to receive inquiry requests.

ModelRunner

class cortex_client.ModelRunner(modelprocess: cortex_client.modelprocess.ModelProcess)

Executes the ModelProcessor implementation and stores and retrieves execution artifacts.

run_inquire(context: cortex_client.types.InputMessage) → Union[str, int, float, None, Dict[str, Any], List[Any]]

Runs the ModelProcess.inquire function.

Parameters:context – A Cortex InputMessage
run_inquire_init(context: cortex_client.types.InputMessage) → Union[str, int, float, None, Dict[str, Any], List[Any]]

Downloads the trained model from Cortex and caches it to disk.

Parameters:context – A Cortex InputMessage.
Returns:Success or error result message.
run_train(context: cortex_client.types.InputMessage)

Runs the ModelProcess.train function.

Parameters:context – A Cortex InputMessage.

Clients

ActionClient

class cortex_client.actionclient.ActionClient(url, version, token, **kwargs)

A client for the Cortex Actions API.

delete_action(action_name, action_type=None)

Deletes an action.

Parameters:action_name – The name of the action to delete.
Returns:The status of the deletion.
delete_task(action_name, task_id)

Deletes a task associated with a job action.

Parameters:
  • action_name – The name of the job action.
  • task_id – The ID of the task to delete.
Returns:

Deletion status.

deploy_action(name, kind: str, docker: str, code='', action_type=None, **kwargs)

Deploys an action.

Parameters:
  • name – The resource name of the action.
  • kind – The action kind (only for functions) - python:2 or python:3
  • docker – The Docker image to use (optional for functions, required for jobs and daemons)
  • code – The action code to deploy; expects a file-like object and zip compressed contents.
  • action_type – The type of action workload: function, daemon, job (default: function).
Returns:

The action deployment result.

get_job_stats(action_name)

Gets execution stats for tasks associated with action action_name of type job.

Parameters:action_name – The name of the job action.
Returns:A dict with stats information.
get_logs(action_name) → Dict[str, object]

Gets the most recent logs for an action.

Parameters:action_name – The action name to retrieve logs from.
Returns:The most recent logs for the requested action.
get_task_logs(action_name, task_id)

Gets the logs for an action task (for job type actions only).

Parameters:
  • action_name – The name of the job action for the task.
  • task_id – The task id to get logs for.
Returns:

Task logs.

get_task_status(action_name, task_id)

Gets the status for an action task (for job type actions only).

Parameters:
  • action_name – The name of the job action for the task.
  • task_id – The task id to get status for.
Returns:

Task status.

get_tasks(action_name)

Gets list of tasks associated with the give job action_name.

Parameters:action_name – The name of the job action.
Returns:A dict with tasks.
invoke_action(action_name, params: Dict[str, object]) → Dict[str, object]

Invokes an action.

Parameters:
  • action_name – The name of the action to invoke.
  • params – The body params to send the action.
Returns:

The result of calling the action.

send_message(message)

Send Synapse Message

Parameters:message – Input message
Returns:status of message

AgentClient

class cortex_client.agentclient.AgentClient(url, version, token, **kwargs)

A client for the Cortex agent REST API.

create_instance(agent_id, snapshot_id, environment_id)

Creates an agent instance.

Parameters:
  • agent_id – The unique ID of the agent.
  • snapshot_id – The ID of the agent snapshot
  • environment_id – The ID of the environment in which to create the instance.
create_snapshot(agent_name, tags=None, version=None)

Creates an agent snapshot.

Parameters:
  • agent_name – The name of the agent to take a snapshot of.
  • tags – A list of tags associated with the agent.
  • version – The version of the agent from which the snapshot is created.
get_agent_service_response(instance_id, service_path, session_id)

Gets the response to a previously made request to an agent service.

Parameters:
  • instance_id – The agent instance ID.
  • service_path – The URI path of the service.
  • session_id – The ID of the session on which the service invocation was made.
get_deploy_targets()

Gets targets for the agent.

invoke_agent_service(instance_id, service_path, typeName, body: Dict[str, object])

Invokes an service defined for the agent.

Parameters:
  • instance_id – The agent instance ID.
  • service_path – The URI path of the service.
  • typeName – The name of the type of the request.
  • body – The payload of the request.

AuthenticationClient

class cortex_client.authenticationclient.AuthenticationClient(url, version)

Client authentication.

fetch_auth_token(tenant_id, username, password)

Retrieves the JWT token for a given user in a given tenant.

Parameters:
  • tenant_id – The ID of the tenant/account to authenticate to.
  • username – The name of the user.
  • password – The user’s password.
Returns:

A JWT string.

register(tenant_info, invitation_code)

Registers a client with an invitation code.

Parameters:
  • tenant_info – The tenant to register.
  • invitation_code – The invitation code for the registration requset.

CatalogClient

class cortex_client.catalogclient.CatalogClient(url, version, token, **kwargs)

A client for the catalog REST API.

save_agent(agent: Dict[str, object])

Saves an agent.

Parameters:agent – A Cortex agent as dict.
save_processor(processor: Dict[str, object])

Saves a processor / skill.

Parameters:processor – A Cortex processor as dict.
save_skill(skill: Dict[str, object])

Saves a skill.

Parameters:skill – A Cortex skill as dict.
save_type(type: Dict[str, object])

Saves a type.

Parameters:type – A Cortex type as dict.

ConnectionClient

class cortex_client.connectionclient.ConnectionClient(url, version, token)

A client used to manage connections.

download(key: str, retries: int = 1)

Download a file from managed content (S3).

Parameters:
  • key – The path of the file to retrieve.
  • retries – Number of times to retry a failed request from a response.
Returns:

A Generator.

exists(key: str) → bool

Check that a file from managed content (S3) exists.

Parameters:key – The path of the file to check.
Returns:A boolean indicating wether the file exists or not.
save_connection(connection: object)

Posts the connection client information.

upload(key: str, stream_name: str, stream: object, content_type: str, retries: int = 1)

Store stream file in S3.

Parameters:
  • key – The path where the file will be stored.
  • stream_name – The name under which to save the stream.
  • stream – The file object.
  • content_type – the type of the file to store (e.g., text/csv).
  • retries – Number of times to retry a failed request from a retryable response.
Returns:

a dict with the response to request upload.

uploadStreaming(key: str, stream: object, content_type: str, retries: int = 1)

Store stream file in S3.

Parameters:
  • key – The path where the file will be stored.
  • stream – The file object.
  • content_type – The type of the file to store (e.g., text/csv)
  • retries – Number of times to retry a failed request from a retryable response.
Returns:

A dict with the response to request upload.

upload_directory(source: str, destination: str, retries: int = 1)

Walk source directory and store in S3

Parameters:
  • source – The path to the local directory.
  • destination – Prefix to add to resulting saved directory.
  • retries – Number of times to retry a failed request from a retryable response.
Returns:

A dict with the response to request upload.

DatasetsClient

class cortex_client.datasetsclient.DatasetsClient(url, version, token)

A client used to manage datasets.

get_dataframe(dataset_name: str)

Gets data from a dataset as a dataframe.

Parameters:dataset_name – The name of the dataset to pull data.
Returns:A dataframe dictionary
get_stream(stream_name: str)

Gets a dataset as a stream.

list_datasets()

Get a list of all datasets.

save_dataset(dataset: Dict[str, object])

Saves a dataset.

Parameters:dataset – A Cortex dataset as dict.

JobsClient

class cortex_client.jobsclient.JobsClient

A client for the Cortex jobs REST API.

Deprecated since version 5.4.4: Use the ActionClient instead.

cancel_task(job_id, task_id)

Cancels a task that has been queued

Parameters:
  • job_id – The job identifier.
  • task_id – The identifier of the task to cancel.
Returns:

JSONType

get_job(job_id: str)

Gets job definition details.

Parameters:job_id – the identifier of the job.
Returns:JSONType
get_job_stats(job_id: str)

Gets stats for a given job.

Parameters:job_id – The identifier of the job.
Returns:JSONType
get_jobs() → Union[str, int, float, None, Dict[str, Any], List[Any]]

Lists jobs.

Returns:A list of jobs.
get_registries()

Returns a list of configured container registries.

Returns:JSONType
get_task(job_id, task_id)

Returns details for a single job task.

Parameters:
  • job_id – The identifier of the job.
  • task_id – The identifier of the task to return.
Returns:

JSONType

get_task_logs(job_id, task_id)

Returns logs for a job task.

Parameters:
  • job_id – The job identifier.
  • task_id – The identifier of the task to cancel.
Returns:

JSONType

get_tasks(job_id: str)

Lists tasks for a given job.

Parameters:job_id – The identifier of the job.
Returns:JSONType
post_job(job: Union[str, int, float, None, Dict[str, Any], List[Any]]) → Union[str, int, float, None, Dict[str, Any], List[Any]]

Deploys a job.

Parameters:job – A job definition
Returns:JSONType.
post_registry(registry_info: Union[str, int, float, None, Dict[str, Any], List[Any]])

Registers a private Docker registry account for job containers.

Parameters:registry_info – the Docker registry information
Returns:JSONType
post_task(job_id, task: Union[str, int, float, None, Dict[str, Any], List[Any]])

Submits a task for execution.

Parameters:
  • job_id – The identifier of the job.
  • task – The task definition.
Returns:

JSONType

ModelClient

class cortex_client.modelclient.ModelClient(url, version, token, cache_dir='/tmp/cortex-cache')

A client-side representation of a Cortex model.

create_model_version(agent_id, processor_id, name, description) → cortex_client.types.Model

Creates a new Mmdel version to link with a training execution.

Parameters:
  • agent_id – The unique id of the agent instance.
  • processor_id – The unique id of the processor.
  • name – The name of the new model.
  • description – A description of the model.
Returns:

A model object.

download_state(model: cortex_client.types.Model, key: str) → urllib3.response.HTTPResponse

Downloads the persisted model.

Parameters:
  • model – The model object from which to retrieve an artifact (e.g., serialized model).
  • key – The path / name of the object to retrieve.
Returns:

The upload state value.

get_model(agent_id, processor_id, name, version)

Gets the Cortex model object.

Parameters:
  • agent_id – The ID of the agent-instance to which the model belongs.
  • processor_id – The ID of the processor to which the model belongs.
  • name – The name of the model to retrieve.
  • version – The version of the model to retrieve.
Returns:

A model object.

get_model_id(agent_id, processor_id, name, version)

Returns the unique ID of a model.

load_state(model: cortex_client.types.Model, key: str)

Returns the persisted model.

Parameters:
  • model – The model object from which to retrieve an artifact (e.g., serialized model).
  • key – The path / name of the object to retrieve.
Returns:

The load state value.

load_state_cache(model: cortex_client.types.Model, key: str)

Reads the persisted model from disk cache.

Parameters:
  • model – The model object from which to retrieve an artifact (e.g., serialized model).
  • key – The path/name of the object to retrieve.
log_data_stats(model, value: object)

Before training, logs stats about the data itself. (sync)

Parameters:
  • model – The model object against which to log events.
  • value – A value to log.
log_event(model, key: str, value: object)

Logs a generic ModelEvent (sync/async).

Parameters:
  • model – A model object against which to log events.
  • key – A string specifying the event type (e.g., cortex.train.status).
  • value – The value to log.
Returns:

A response object.

log_hyperparams(model, value)

Logs hyperparameters (sync).

Parameters:
  • model – The model object against which to log events.
  • value – A value to log.
log_serving_datum(model, label: str, value: object)

Logs inquiry results (sync/async).

Parameters:
  • model – A model object against which to log events.
  • label – A label attached to the event key.
  • value – The value to log.
log_train_progress(model, value: object)

Logs training progress (sync).

Parameters:
  • model – The model object against which to log events.
  • value – The value that represents the progress.
save_state(model, key: str, stream)

Saves a trained model (sync).

Parameters:
  • model – The model object associated with the serialized trained model to store.
  • key – The path where the serialized model is stored.
  • value – The payload (serialized model) to store.
Returns:

The save state value.

save_state_cache(model: cortex_client.types.Model, key: str, stream: Union[bytes, _io.BufferedReader])

Saves a trained model to disk.

Parameters:
  • model – The model object associated with the serialized trained model to store.
  • key – The path where the serialized model is stored.
  • stream – The serialized model to store.
upload_state(model, key: str, stream: object) → object

Uploads a trained model (sync).

Parameters:
  • model – The model object associated with the serialized trained model to store.
  • key – The path where the serialized model is stored.
  • value – The payload (serialized model) to store.
Returns:

The upload state value.

SessionClient

class cortex_client.sessionclient.SessionClient(url, version, token, **kwargs)

A client for the Cortex Sessions API.

delete_session(session_id)

Deletes a session.

Parameters:session_id – The ID of the session to delete.
get_session_data(session_id, key=None) → Dict[str, object]

Gets data for a specific session.

Parameters:
  • session_id – The ID of the session to query.
  • key – An optional key in the session memory; the entire session memory is returned if a key is not specified.
Returns:

A dict containing the requested session data

put_session_data(session_id, data: Dict)

Adds data to an existing session.

Parameters:
  • session_id – The ID of the session to modify.
  • data – Dict containing the new session keys to set.
start_session(ttl=None, instance_id=None, description='No description given') → str

Starts a new session.

Parameters:
  • ttl – Resets sessions expiration; default is 15 minutes.
  • instance_id – An optional ID that scopes this session to a deployed agent-instance
  • description – An optional human readable description for this sessions instance
Returns:

The ID of the new Session.

Types

class cortex_client.types.InputMessage(instance_id, session_id, channel_id, payload, properties, api_endpoint, token)

The message structure that Cortex sends when making request across its APIs.

Parameters:
  • instance_id – The Agent instance ID.
  • session_id – Cortex’s session ID.
  • channel_id – The Skill/Processor ID.
  • payload – The payload of an HTTP request made to a Cortex service.
  • properties – The Skill properties associated with this message.
  • api_endpoint – The Cortex URL.
  • token – The JWT token necessary to make HTTP request to Cortex REST APIs.
class cortex_client.types.OutputMessage(payload, type_name)

The message structure to send back to Cortex as response to Cortex agent serivce calls.

Parameters:
  • payload – The payload to send to Cortex.
  • type_name – The name of the Cortex type for this message.
class cortex_client.types.Model(agent_id, processor_id, name, description, _id=None)

Holds information related to a train request.

Parameters:
  • agent_id – The agent-instance ID.
  • processor_id – The unique ID of the processor.
  • name – The name of the new model.
  • description – A description of the model.
class cortex_client.types.ModelEvent(trained_model_id, key, value, created_at=None)

An event associated with a specific model.

Parameters:
  • trainedModelId – The unique ID of the model to which this event belongs.
  • key – A string that labels the event (e.g., ‘train.status’).
  • value – The information this event carries.
  • createdAt – Creation datetime.