Skip to main content

Python quick start

Everything the np command does is also available as a Python call. Both interfaces use the same thin client and backend and support the same use cases.

There is nothing extra to install. The wheel you already have contains both the np executable and the netspresso package.

from netspresso.api import NetsPresso

client = NetsPresso()
client.health.ready()

Use the command-line interface (CLI) for interactive work and the Python surface when the sequence is driven by code, for example, a parameter sweep, a nightly job, or a notebook. Neither wraps the other, so results and error codes are identical.

Prerequisites​

ItemRequirement
Python3.11 or later
NetworkHTTPS access to the Arm AI Model Optimizer backend API and auth server

Installation​

python3 -m venv .venv
source .venv/bin/activate # Windows: .venv\Scripts\activate

2. Install​

pip install arm-ai-model-optimizer

See Quick start: Installation for what the output looks like.

3. Verify the installation​

python3 -c "from netspresso.api import NetsPresso; print(NetsPresso())"

To check the version:

from importlib.metadata import version

print(version("arm_ai_model_optimizer")) # 2.1.5

Initial configuration and environment variables​

The Python surface reads the same 4 environment variables as the CLI, from the same place. The values for these are already baked into the tool. For more info, see Quick start: Initial configuration (environment variables).

The following table summarizes the variables required by each call:

VariableNeeded by
NP_CLIENT_API_URLevery call that reaches the backend
NP_CLIENT_AUTH_API_URLclient.auth.* and session refresh
NP_ENTERPRISE_FE_URLclient.visualize.create_link(). Without this variable the call raises InternalError: FE base URL not configured.
NP_MODEL_EXPLORER_URLclient.visualize.create_link(tool="model-explorer")

If you would rather not rely on the environment, you can pass the backend address and the access token to the constructor instead:

client = NetsPresso(endpoint="https://api.netspresso.devplatform.arm.com", token="<access-token>")

Both are keyword-only. The override applies only to calls made through that object. An injected token is never refreshed. See Python SDK reference: Creating a client for more details.

Check connectivity and log in​

Create and copy a token in the AI Portal as described in Manage access tokens. Use that complete value in place of <token> below.

from netspresso.api import NetsPresso

client = NetsPresso()

client.health.ready() # verify the Backend is reachable
client.auth.login("<token>") # log in with the token you copied
client.auth.status() # confirm you're authenticated

You must have a valid login before you make any call, including client.workspace.init(). After you log in, your session refreshes automatically. You do not need to log in again until the session is explicitly revoked.

auth.status() reads the local file, not the server

auth.status() reports what is stored on your local machine, not whether the backend will accept it. An access_status of EXPIRED here is normal and not a reason to log in again. The stored refresh token renews the access token when the next call needs it.

Initialize a workspace​

from pathlib import Path

result = client.workspace.init(Path("/home/user/my-workspace"))
print(result.model_dump())

This command is the equivalent of np workspace init. It creates a workspace/ directory under the path you specify, registers it as the workspace root with the backend, and generates a ready-to-run sample project. See Quick start: Initialize a workspace for what lands on disk.

The path is required, and it is not the current directory

The CLI initializes a workspace in whatever directory you ran it from. The Python call takes the path as a required argument and never looks at the current working directory.

This behavior is deliberate. A library that reads os.getcwd() puts the workspace wherever the interpreter started. Every later call then uses that location. As a result, the same script can behave differently depending on where you launch it.

The rule holds across the whole surface: nothing is inferred from the working directory, and nothing is prompted for. See 4 rules that differ from the shell.

The root is stored globally in ~/.config/np/config.json. There is only ever one active workspace on each machine. Calling workspace.init() again with any path reports the already-registered workspace rather than creating a second one.

Reset the local configuration​

Local state lives in the same files for both surfaces, so the reset procedure is identical. See Quick start: Reset the local configuration.

A first pipeline​

With the workspace in place, this is the shortest path from a model to a submitted run:

project = client.projects.create(
name="resnet50-rpi5",
model="resnet50_pt2_pytorch_static_fp32",
device="raspberry_pi_5_16gb",
runtime="executorch",
backend="xnnpack",
calibration_dataset="imagenet1k_calib_seed42_n1000",
evaluation_dataset="imagenet1k_eval_seed42_n5000",
)

experiment = client.experiments.create(project.project_id, steps=["graph_optimize"])

check = client.validate(experiment.experiment_id)
if not check.is_valid:
raise SystemExit("\n".join(str(v) for v in check.violations))

client.run(experiment.experiment_id, dry_run=True) # preview the plan
client.run(experiment.experiment_id) # submit

There are 2 differences here between Python and np:

  • name is required. The CLI prompts for options you leave out. A library must not read stdin, so a missing required option raises ValueError:
ValueError: Missing required options: name.
The Python surface never prompts — pass them explicitly.
  • validate() does not raise on a bad configuration. Check is_valid and read violations. Other errors raise NetsPressoError subclasses; see Errors.

Next steps​

  • Python SDK reference: All 31 interfaces, with parameter types, defaults, and return types
  • Concepts: The relationship between workspaces, projects, experiments, and jobs. This relationship is the same for both np and Python.
  • Tutorial 1: sample project: Validate, run, and inspect the sample project. This tutorial is written with np commands, but each one has a Python equivalent in the command reference.
  • Diagnosis and log reference: Error code lookup. The same error codes apply for both np and Python.