PotionUI Docs v0.3.0

Write a pipe

A pipe is one step of a generation pipeline: load a model, encode a prompt, sample, upscale, save. This guide writes a small pipe in a plugin, wires it into a preset and tests it.

GuideWritten for v0.3.0
On this page

What a pipe is#

Every mode of a native preset runs a list of pipes, top to bottom, as written in its pipeline.yml. Each pipe declares three things: the inputs it takes from earlier pipes, the outputs it hands to later ones, and the configuration it accepts from the preset. When its turn comes, PotionUI builds the pipe with its configuration and calls its process method with its inputs.

The core pipes live in src/pipelines/pipes/; the Pipes reference lists all of them. A plugin adds its own with the manifest's pipes: section, and presets then use it like any built-in pipe. You need a pipe when a preset needs a step no existing pipe does; to change only which values a pipe gets, edit the preset instead (Author a preset).

The contract#

A pipe is a class that extends BasePipe. Import it and everything around it from src.plugin_api.pipes, never from src.pipelines.

MemberWhat it is
nameClass attribute. The pipe's key, written as name: in a pipeline.yml step. A plain string, not a property.
descriptionClass attribute. Developer-facing text shown in the pipes reference.
display_titleOptional class attribute. The phase shown on the run's status line, such as Upscaling. Without it the title comes from the name.
inputs()Class method returning a list of PipeInputSpec(name, io_type, required, description, is_array=False).
outputs()Class method returning a list of PipeOutputSpec(name, io_type, description, is_array=False).
configuration()Class method returning a list of PipeConfigSpec(name, param_type, default, description, required, choices, min_value, max_value).
process(pipe_input, generation_outputs, is_cancelled=None)Does the work. Reads inputs from pipe_input.input (a dictionary by input name) and configuration from self.config, emits progress through generation_outputs, and returns PipeOutput(output={...}) keyed by output name.
validate_config(config)Optional. Raise ValueError to refuse a combination of values that are each valid alone.
get_requirements(), manual_install_instructions()Optional. Declare the pip packages, git repositories and models the pipe needs; return install instructions as text when PotionUI cannot install them itself.

Inputs and outputs are typed with IOType, the vocabulary of things that travel between pipes: IMAGE, MASK, LATENT, VIDEO, AUDIO, MESH, MODEL, TEXT_ENCODER, VAE, CONTROLNET, CONDITIONING, SEED, TEXT, DICT, INT, BOOL and others, plus SERVICE for the services described below. Images travel as Pillow images, videos as file paths.

Before process runs, PotionUI fills self.config from your PipeConfigSpec defaults, applies the preset's values, converts them to param_type and checks choices, min_value and max_value. A required key with no value and no default stops the run with an error. Keys you did not declare are passed through unchanged.

Accept is_cancelled in process and check it between units of work: PotionUI passes it only to pipes whose process has that parameter, and a user's Cancel then stops your pipe at the next check.

A complete pipe#

The example turns pictures grey, with an amount from 0 (unchanged) to 1 (fully grey). It ships in a plugin called grayscale-step.

  1. Lay out the folder

    A pipe is a folder with a main.py that defines one pipe class:

    content/plugins/local/grayscale-step/
    manifest.yml
    pipes/
      grayscale/
        main.py
    tests/
      test_grayscale.py
  2. Write the pipe

    PYpipes/grayscale/main.py
    from typing import List, Optional
    
    from PIL import Image
    
    from src.plugin_api.pipes import (
        BasePipe,
        GenerationExecutionError,
        Icon,
        IOType,
        PipeConfigSpec,
        PipeInput,
        PipeInputSpec,
        PipeOutput,
        PipeOutputSpec,
        Progress,
        ProgressGenerationOutput,
    )
    
    
    class GrayscalePipe(BasePipe):
        name = "grayscale"
        description = "Turn images grey, blended with the original by an amount"
        display_title = "Removing colour"
    
        @classmethod
        def inputs(cls) -> List[PipeInputSpec]:
            return [PipeInputSpec("image", IOType.IMAGE, True, "Images to convert", is_array=True)]
    
        @classmethod
        def outputs(cls) -> List[PipeOutputSpec]:
            return [PipeOutputSpec("image", IOType.IMAGE, "Converted images", is_array=True)]
    
        @classmethod
        def configuration(cls) -> List[PipeConfigSpec]:
            return [
                PipeConfigSpec(
                    name="amount", param_type=float, default=1.0,
                    description="0 leaves the image unchanged, 1 makes it fully grey",
                    min_value=0.0, max_value=1.0,
                ),
            ]
    
        def process(
            self,
            pipe_input: PipeInput,
            generation_outputs: callable,
            is_cancelled: Optional[callable] = None,
        ) -> PipeOutput:
            images = pipe_input.input.get("image") or []
            if not isinstance(images, list):
                images = [images]
            if not images:
                raise GenerationExecutionError("grayscale needs at least one image")
    
            amount = float(self.config.get("amount", 1.0))
            converted = []
            for index, image in enumerate(images):
                if is_cancelled and is_cancelled():
                    break
                generation_outputs(ProgressGenerationOutput(
                    state=f"Removing colour {index + 1}/{len(images)}",
                    icon=Icon(name="bolt"),
                    progress=Progress(index, len(images)),
                ))
                colour = image.convert("RGB")
                grey = colour.convert("L").convert("RGB")
                converted.append(Image.blend(colour, grey, amount))
    
            return PipeOutput(output={"image": converted})

    Keep heavy imports (a model library, a GPU extension) inside process, not at the top of the module. PotionUI imports pipe modules to discover them, and a module that fails to import is skipped, so the pipe would quietly disappear on a machine without that library.

  3. Declare it in the manifest

    YAMLmanifest.yml
    id: "grayscale-step"
    name: "Grayscale Step"
    version: "0.1.0"
    description: "A pipe that turns images grey"
    author: "Your name"
    type: "backend-only"
    category: "steps"
    
    pipes:
      - path: "pipes/grayscale"
        register_as: "grayscale"

    path is the folder holding main.py, relative to the plugin. register_as is the name presets use. Without it the pipe is registered as plugin:grayscale-step:grayscale. Pick a name no core pipe uses: a core pipe of the same name wins. A plugin with no pipes: section has every backend/pipes/<name>/main.py found automatically, under the prefixed name.

  4. Enable it

    In Administration, Plugins, choose Scan for plugins and switch Grayscale Step on.

    What you will see

    Administration, Documentation, Pipes lists grayscale with its input, output and the amount setting, read live from your install.

Use it from a preset#

Put the step between the generator and the gallery, and point the gallery at its output. This is the Z-Image preset from Author a preset, with a form field for the amount. With an amount of 0 the step returns the pictures unchanged, so it can stay on.

YAMLmodes/txt2img/pipeline.yml (end of the list)
  - name: "grayscale"
    enabled: true
    input:
      - ["image", "generator/z_image", "image"]
    configuration:
      amount: "{{ form.grey_amount }}"

  - name: "gallery"
    input:
      - ["image", "grayscale", "image"]
      - ["seed", "seed_generator", "seed"]
    enabled: true
YAMLmodes/txt2img/tabs/advanced.yml (added field)
  - name: "grey_amount"
    type: "slider"
    label: "Grey"
    default: 0.0
    configuration: { min: 0, max: 1, step: 0.05 }
  • An input: line is [your input name, source pipe, source output]. The source pipe is matched by its id, or by its name when it has no id.
  • When an array output feeds a single-value input, the pipe gets the first item; a single value feeding an array input arrives as a list of one.
  • A pipe switched off with enabled: does not run and its configuration is not rendered, so a later step that reads its outputs gets nothing while it is off.
  • Before the run, PotionUI checks that every required input is wired to an enabled step whose output has the same IOType; a mismatch, such as an IMAGE output feeding a VIDEO input, stops the run with an error naming the pipe and the input.

Render the mode to check the wiring before you generate: python scripts/preset_render.py content/presets/local/MyZImage/standard txt2img. To add the step to modes of presets you do not own, a plugin uses preset_extensions:; see Build a plugin.

Services: models, assets and the GPU#

A pipe asks for an application service by declaring an input of type SERVICE with the service's upper-case name. PotionUI fills it in; no earlier pipe has to provide it, and you do not wire it in pipeline.yml.

NameWhat you get
MODELSThe model lifecycle: the shared cache that keeps loaded models between runs and frees memory when another model needs it.
ASSETSThe asset fetcher, for weights a pipe needs that are not user models.
GPU, MEMORY, SYSTEMGPU, memory and system monitors.
LLM, SETTINGS, MEDIA_TOOLSThe language model service, application settings and the media tools.
PYrequesting a service
@classmethod
def inputs(cls):
    return [
        PipeInputSpec("image", IOType.IMAGE, True, "Images to process", is_array=True),
        PipeInputSpec("MODELS", IOType.SERVICE, False, "Model lifecycle service"),
    ]

def process(self, pipe_input, generation_outputs, is_cancelled=None):
    models = pipe_input.input.get("MODELS")
    net = models.acquire(
        key="grayscale-step/net",
        fingerprint=weights_fingerprint,
        loader=load_net,
        estimated_vram_gb=1.0,
    )
    ...

Load models through MODELS.acquire(key, fingerprint, loader, estimated_vram_gb) rather than holding them yourself: it returns the cached model when the key and fingerprint match, calls loader otherwise, and lets PotionUI free the memory when another model needs it. A pipe that needs weights must not download them itself; request ASSETS and use ensure_asset_file(url, subdir=...) for one file or ensure_asset_repo(repo_id, subdir=...) for a Hugging Face repository, and catch AssetFetchError. Fetching directly skips the download history, the configured models folder and progress reporting.

Reporting progress and results#

A pipe returns its PipeOutput once, at the end. Everything the user should see during the run goes through generation_outputs:

  • ProgressGenerationOutput(state=..., icon=Icon(name=...), progress=Progress(current, max)) moves the progress line.
  • ImageGenerationOutput, VideoGenerationOutput and AudioGenerationOutput describe media; GalleryGenerationOutput(images=[...], videos=[...]) hands finished results to the gallery, as the core gallery pipe does. Set temporary=False on an item to save it.
  • Raise GenerationExecutionError("message") to fail the generation; the message is shown to the user.

Most pipelines end with the core gallery pipe, so a processing step like the example only returns its images. A pipe that makes something gallery does not take, such as a 3D mesh, emits its own GalleryGenerationOutput.

Test it#

A pipe is a class with a method: load main.py, build the pipe with its default configuration, call process with a list as the output collector, and check the result.

PYtests/test_grayscale.py
import importlib.util
from pathlib import Path

from PIL import Image

from src.plugin_api.pipes import PipeInput, ProgressGenerationOutput

MAIN = Path(__file__).resolve().parents[1] / "pipes" / "grayscale" / "main.py"


def load_pipe_class():
    spec = importlib.util.spec_from_file_location("grayscale_step_main", MAIN)
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    return module.GrayscalePipe


def test_full_amount_removes_colour():
    pipe_class = load_pipe_class()
    pipe = pipe_class(pipe_class.get_default_config())
    emitted = []

    result = pipe.process(PipeInput(input={"image": [Image.new("RGB", (8, 8), (255, 0, 0))]}), emitted.append)

    red, green, blue = result.output["image"][0].getpixel((0, 0))
    assert red == green == blue
    assert any(isinstance(item, ProgressGenerationOutput) for item in emitted)
SHrun the test
python -m pytest content/plugins/local/grayscale-step/tests -q --no-cov

Keep tests fast: use tiny images and no model weights. If the pipe imports a heavy library lazily, add a test that imports main.py with that library blocked and checks the class still loads; the shipped NVIDIA RTX Upscale plugin's tests do this.

Common mistakes#

  • The pipe does not appear. main.py failed to import (check the server log), the class is imported from another module instead of defined in main.py, or the plugin is not enabled.
  • A preset cannot find the pipe. Without register_as its name is plugin:<plugin id>:<name>.
  • A setting has no effect. The key in pipeline.yml does not match a PipeConfigSpec name; unknown keys are passed through silently.
  • A required input is missing. No earlier step produces it, or the input: line names the wrong pipe or output.
  • Remote workers. If you run Remote Native workers, install the same plugin there too: plugins that contribute pipes are part of the compatibility check between the server and its workers.

Pipe contract ↗Example plugin pipe ↗