Skip to content

Write a node

The three kinds of node, process, function and shader, and everything each can declare and do, with working examples.

A node is one unit of a stream. You write it in Python, in a module of your project, and a graph document names it by its import path, module:Name. There are three kinds:

Kind Write it when Runs
Process node, @node.process It holds a model, a device, a file or a connection, or does anything a pure function can’t In a process of its own, with its own interpreter started from your .venv
Function node, @node.function It computes numbers or records from numbers or records Compiled, and evaluated where its result is read
Shader node, @node.shader It computes a picture, pixel by pixel, from pictures and numbers On the GPU, with no Python

Every kind can carry @node.meta(category=..., description=...): the group Studio’s node search files it under, such as "Effects" or "Effects/Stylize", and a description in CommonMark. Both are plain strings in the code, so a project’s node types are listed from source without running any of it.

Put each node in a module of the project, such as nodes/motion_detector.py. The graph document names it nodes.motion_detector:MotionDetector. A process node’s own process imports its class by that path, so the class must be at module level in an importable module, never inside a function.

A module’s import-time code runs each time a stream that uses it loads, because the runtime asks the project’s interpreter to describe each node type. Keep it cheap: load models in setup, not at import.

A new node file can start from the runtime’s template, with the create_node_file operation.

nodes/motion_detector.py
from dataclasses import dataclass
import numpy
from tatolab.stream import (
Image,
Input,
Output,
Records,
RuntimeContextFullAccess,
RuntimeContextLimitedAccess,
log,
node,
)
@dataclass
class MotionDetectorConfig:
threshold: float = 0.02
@node.meta(category="Analysis", description="Reports how much of the picture changed since the last frame.")
@node.process
class MotionDetector:
video = Input(Image, delivery="newest", description="The frames to watch.")
motion = Output(Records, names=("changed", "moving"), description="One report per frame.")
def __init__(self, config: MotionDetectorConfig) -> None:
self.threshold = config.threshold
self.previous: numpy.ndarray | None = None
def setup(self, ctx: RuntimeContextFullAccess) -> None:
log.info("watching for motion", threshold=self.threshold)
def process(self, ctx: RuntimeContextLimitedAccess) -> None:
frame = ctx.inputs.read(self.video)
if frame is None:
return
with frame.cpu() as pixels:
grey = pixels[::8, ::8, :3].mean(axis=2)
if self.previous is not None:
changed = float(numpy.mean(numpy.abs(grey - self.previous)) / 255.0)
ctx.outputs.write(
self.motion,
{"changed": changed, "moving": changed > self.threshold},
timestamp_ns=frame.timestamp_ns,
)
self.previous = grey

Ports are Input and Output class attributes. The attribute’s name is the port’s name, cast to lowercase URL-safe characters. Each port is of one family:

Family Carries A read returns A write takes
Image A picture, on the GPU ImageFrame An ImageFrame you read, or an ImageFrameToWrite
Array Named arrays or tensors ArrayFrame A mapping of name to array or tensor
Channels Audio and other sampled signals ChannelsBlock A [channel][sample] array, with start_sample
Packets Encoded media, one unit per message PacketsUnit The unit’s bytes
Records Small structured values dict A dict of at most 64 KiB

An Input’s delivery says how it reads. An input with a pin type reads by its type’s default when it names none, so an Image input reads the newest frame; any other input, such as a Records input, must name one:

  • "newest": each read drains to the most recent message. For displays, models and anything that should see the latest.
  • "ordered": messages in the order they were written, falling behind if it must. For loggers, recorders and audio.

Neither blocks the writer. Under sustained pressure, messages are dropped at the reader’s input and counted on the link.

Ports say more where it matters:

  • Output(Records, names=("changed", "moving")) lists the names every record carries; Input(Records, requires=("changed",)) lists the ones it needs. A link whose ends don’t fit is refused, naming both. A Records port checks names, not the types of values.
  • Input(Channels, window=AudioWindowContract(...)) states the audio shape the node wants, and the runtime converts what arrives. See Audio.
  • Input(Packets, requires_codec=("h264",)) and Output(Packets, codec="h264") name a codec.
  • from_config("key") reads an output’s names, codec or rate from the node’s settings.

A node’s settings are one class, the annotation on __init__’s config parameter: a dataclass, a TypedDict or a pydantic model. Its JSON Schema is derived from the annotations and defaults and published in the node catalog, which is how Studio draws the fields and an agent learns them. A class whose __init__ takes only self has no settings.

The values live in the graph document, in the node’s input_values, and Studio shows each as an input value on the node. A setting changed while the stream runs reaches the node only if it defines configure:

def configure(self, config: MotionDetectorConfig) -> None:
self.threshold = config.threshold

Without configure, the change is refused and the node keeps what it has. A setting can also be made an input of its own, so a link drives it.

Never put a secret in a setting: the graph document is kept on the project’s history. Read secrets from the environment, as Python SDK explains.

All of these are optional; define the ones you need.

Method When it runs Context
__init__(self, config) Once, when the node’s process starts none
setup(self, ctx) Once, before any data flows. Load models, compile kernels, open files and devices here. full
start(self, ctx) When the node should begin; for a manual node, where it starts what drives it full
process(self, ctx) Whenever there’s work: new input, or the next tick of a continuous node limited
on_pause(self, ctx), on_resume(self, ctx) When the project pauses and resumes limited
stop(self, ctx) When the node stops. Stop what start started. full
teardown(self, ctx) Once, at the end. Release what setup acquired. full

The full context, RuntimeContextFullAccess, can create GPU resources through ctx.gpu_full_access. The limited one, RuntimeContextLimitedAccess, which process gets, can use them but not create them, which keeps allocations out of the per-frame path. Both carry:

  • ctx.inputs and ctx.outputs: the node’s ports.
  • ctx.time: stream time now, in nanoseconds.
  • ctx.gpu_limited_access: the GPU, for work that allocates nothing.
  • ctx.store(): values the node keeps by key, which outlive the run and a restart of the runtime.
  • ctx.node_id, ctx.node_name, ctx.stream_id and ctx.stream_project_directory.
  • ctx.asset_content_path(uuid): where an asset of the project sits on disk, for a setting that names one.
  • ctx.report_not_ready(reason) and ctx.report_ready(): say the node is running but can’t do its job yet, such as a file it names that is missing, without failing the stream. The graph shows the reason on the node.

A node whose process raises keeps running, and the graph shows what it raised, and where, until a call runs cleanly. A node whose process dies is restarted after a backoff, as a new instance of its class; one that dies five times in a row, each within a minute of starting, is left in error until the project reloads.

@node.process takes an execution mode:

  • reactive, the default for a node with inputs: process runs when a message arrives on any input.
  • continuous, with interval_ms: process runs on a fixed tick. For sources that poll something or produce on a schedule.
  • manual: the runtime calls start and never process; the node drives itself. The modules that move frames and samples on native threads, such as the camera and microphone, are manual, lending their ports to native code with ctx.open_module_host_table.

A node with no inputs is a source, and has to name continuous or manual: there’d be nothing to react to.

scheduling="high" or "realtime" asks for a raised scheduling priority, for a node that must keep a steady pace. paced_by_real_time=True declares a node that paces itself on real time, as a live device does, so it loads in a stream on a scaled or stepped clock and stands outside the step barrier.

A timed source that polls a sensor once a second:

nodes/http_sensor.py
import json
import urllib.request
from dataclasses import dataclass
from tatolab.stream import Output, Records, RuntimeContextLimitedAccess, log, node
@dataclass
class HttpSensorConfig:
url: str = "http://192.168.1.50/reading.json"
timeout_seconds: float = 0.5
@node.meta(category="Sources", description="Polls a JSON sensor over HTTP once a second.")
@node.process(execution="continuous", interval_ms=1000)
class HttpSensor:
reading = Output(Records, names=("celsius",))
def __init__(self, config: HttpSensorConfig) -> None:
self.url = config.url
self.timeout = config.timeout_seconds
def process(self, ctx: RuntimeContextLimitedAccess) -> None:
try:
with urllib.request.urlopen(self.url, timeout=self.timeout) as response:
body = json.load(response)
except (OSError, ValueError) as error:
log.warn("sensor unreachable", url=self.url, error=str(error))
return
ctx.outputs.write(self.reading, {"celsius": float(body["celsius"])})

ctx.inputs.read(self.video) returns the next message’s payload as its family’s type, or None when none is waiting. With delivery="ordered", drain what’s waiting in a loop:

while (record := ctx.inputs.read(self.events)) is not None:
handle(record)

read_with_timestamp also returns the message’s stamp. A read by port name, ctx.inputs.read("video"), returns the raw payload, and read("events", into=MyRecord) hands those bytes to MyRecord.from_bytes.

An ImageFrame stays on the GPU. frame.width, frame.height, frame.timestamp_ns and frame.colour describe it; torch.from_dlpack(frame) hands it to torch as device memory; with frame.cpu() as pixels: reads it on the CPU as a numpy array, H×W×4 uint8, which costs a copy back from the GPU. See GPU effects and Use your model.

ctx.outputs.write(self.motion, {...}) writes one message to every link on the port. Without timestamp_ns, it’s stamped with stream time now; pass the input’s stamp when the output describes an input, as the motion detector does, so a reader can pair them. A Channels write takes start_sample too, and write_channels_block writes a block by name. Encoded media passes starts_group=False for a unit a decoder can’t start at.

A write never blocks and never raises for a slow reader: the reader’s input drops what it can’t keep.

from tatolab.stream import log
log.info("motion started", changed=0.14, zone="door")

log.trace, log.debug, log.info, log.warn and log.error write to the project’s log, with the keyword fields as the record’s attrs. Anything a node prints is captured too, and marked as intercepted, so you can find it and make it a log call. See Logs.

A function node is a function whose signature is the node. It has no process of its own: the runtime compiles its body to native code and evaluates it where its result is read. A body that doesn’t compile, or takes or gives a dict, runs as Python inside the reader’s interpreter.

nodes/motion_math.py
from tatolab.stream import node
@node.meta(category="Math", description="1 when x is past the cutoff, 0 otherwise.")
@node.function
def Threshold(x: float, cutoff: float = 0.5) -> float:
return 1.0 if x > cutoff else 0.0
  • Each plain parameter is an input, and its default is the value it holds when nothing is wired. T | None = None is an optional input.
  • The return annotation is the output result. A returned dataclass makes one output per field, and T | None writes nothing on a call that returns None.
  • float, int and bool are one-channel Channels; dict is Records.
  • Annotated[float, Description("...")] describes a port.
  • A parameter typed Time is handed the stream time of the read, and is never an input.
  • config: SomeDataclass names the node’s settings.

A function node with memory takes the state its last call returned:

nodes/smoothing.py
from dataclasses import dataclass
from tatolab.stream import State, Stateful, Time, node
@dataclass(frozen=True)
class Followed:
value: float = 0.0
at_ns: int = 0
started: bool = False
@node.meta(category="Animation", description="Follow a jumpy number smoothly.")
@node.function
def Smooth(x: float, seconds: float = 0.2, *, now: Time, previous: State[Followed]) -> Stateful[float, Followed]:
if not previous.started or seconds <= 0.0:
return x, Followed(x, now, True)
keep = 0.5 ** ((now - previous.at_ns) * 1e-9 / seconds)
value = x + (previous.value - x) * keep
return value, Followed(value, now, True)

State[Record] is the record’s defaults on the first call; Stateful[Output, Record] returns the output, then the state for next time. Stopping the project resets every function node’s state.

A function node computes from its inputs alone. A body that reads the clock or a random source, opens a file or a socket, starts a thread, uses global, or reads a mutable module-level value is refused when it’s declared, naming the line; take now: Time for the time. It’s still an ordinary function, so a unit test calls it directly.

A loop of function nodes closes through Previous Value; see Streams and graph documents.

A shader node is a Slang function from pictures and numbers to a picture. The Python signature declares its ports, and its body is ...; the Slang source is the node.

nodes/duotone.py
from tatolab.stream import ImageFrame, node
@node.meta(category="Color", description="Map dark to one colour and light to another.")
@node.shader(
"""
float4 Duotone(ImageInput image, float shadow_hue, float mix_amount)
{
float luma = dot(image.pixel.rgb, float3(0.2126, 0.7152, 0.0722));
float3 shadow = float3(0.1, 0.05 + 0.3 * shadow_hue, 0.4);
float3 light = float3(1.0, 0.85, 0.6);
float3 toned = lerp(shadow, light, luma);
return float4(lerp(image.pixel.rgb, toned, mix_amount), image.pixel.a);
}
"""
)
def Duotone(image: ImageFrame, shadow_hue: float = 0.5, mix_amount: float = 1.0) -> ImageFrame: ...
  • The Slang function is named for the node and returns the float4 pixel it computes.
  • Each ImageFrame parameter arrives as an ImageInput: image.pixel is the input at this pixel, image.uv this pixel’s position from 0 to 1, and image.sample(uv) reads it anywhere, bilinear.
  • Each float arrives as a value. A number node, such as an LFO, can drive it.
  • The output is result, at the size of the first picture input. Shader nodes take RGBA pictures.

The runtime compiles the Slang and runs it on the GPU, with no Python process. A shader node runs once per picture it’s sent; a number changing doesn’t run it on its own, so the picture source sets the frame rate. It isn’t told the time: wire a Timer or Ramp into the input that moves it. For anything a single pixel function can’t do, such as reading a picture’s size or keeping state, write a process node with a compute kernel; see GPU effects.

A node in an installed package works the same as one in the project: name it by its import path. To have Studio and agents list a package’s nodes before any graph names one, declare them as tatolab.nodes entry points in the package’s pyproject.toml. Native code ships the same way, as a wheel with Rust or C inside and an ordinary @node.process class as its binding; it never links the runtime.

tatolab-stream imports without the runtime, so keep the logic of a process node in plain functions and test them with pytest. A function node is a plain function already:

tests/test_motion_math.py
from nodes.motion_math import Threshold
def test_threshold():
assert Threshold(0.7) == 1.0
assert Threshold(0.2, cutoff=0.1) == 1.0