Write a Python node¶
Use a Python node to add a transform, DSP step, model wrapper, or application-specific processing stage. The host owns its lifecycle; the node implements the behavior.
Choose the node contract¶
| Surface | Use it for |
|---|---|
Node |
Lightweight Python composition and direct instance execution |
MultiprocessNode |
Host-managed workers processing RuntimeData |
Generator mixins and GeneratorNode |
Generation that must declare modality and cancellation behavior |
| Python source plugin | Packaging and loading worker node types with dependencies |
The example below is a worker transform. It is not a generator or a demonstration of every buffer backend.
Implement a transform¶
The complete example registers DocsUppercase, reads a prefix from NodeConfig.params, uppercases text, and exposes an RPC description method:
"""Direct worker-node contract check; does not launch a host or worker process."""
import asyncio
import os
from remotemedia.core.multiprocessing import MultiprocessNode, NodeConfig, register_node
from remotemedia.core.multiprocessing.data import RuntimeData
from remotemedia.rpc import rpc
@register_node("DocsUppercase")
class DocsUppercase(MultiprocessNode):
def __init__(self, config: NodeConfig):
if not isinstance(config, NodeConfig):
raise TypeError("DocsUppercase requires NodeConfig with manifest parameters")
super().__init__(config)
self.prefix = str(config.params.get("prefix", ""))
async def initialize(self):
# Load model or device resources here when your node needs them.
pass
async def process(self, data: RuntimeData) -> RuntimeData:
if not data.is_text():
raise TypeError("DocsUppercase expects text input")
return RuntimeData.text(self.prefix + data.as_text().upper())
@rpc(reply=True)
async def describe(self) -> dict:
return {"operation": "uppercase", "prefix": self.prefix, "pid": os.getpid()}
async def cleanup(self):
# Release any resources allocated during initialize().
pass
async def main():
try:
DocsUppercase("formatter")
except TypeError:
pass
else:
raise AssertionError("A bare node ID must not discard manifest parameters")
node = DocsUppercase(NodeConfig("formatter", "DocsUppercase", {"prefix": "DOCS: "}))
try:
await node.initialize()
output = await node.process(RuntimeData.text("hello"))
print(output.as_text())
assert output.as_text() == "DOCS: HELLO"
assert await node.describe() == {"operation": "uppercase", "prefix": "DOCS: ", "pid": os.getpid()}
finally:
await node.cleanup()
if __name__ == "__main__":
asyncio.run(main())
The host constructs a node with NodeConfig(node_id, node_type, params, session_id, ...). Parameters must reach the constructor; the example explicitly raises TypeError on a bare node ID so a legacy construction fallback cannot silently discard manifest configuration. initialize() loads resources, process() handles each input, and cleanup() releases resources.
Run the direct contract check:
Expected output: DOCS: HELLO. This directly exercises configuration and node methods. It does not launch a worker or validate plugin discovery, IPC, or process teardown.
Execute in a worker¶
First install the worker environment. The worker harness registers the dotted class path with the native host and adds the module directory to the child's import path. Its manifest selects sys.prefix with python_env.explicit_venv, so the worker uses the environment containing the installed client and IPC dependencies.
The verified result is WORKER: HELLO, an RPC reply containing prefix: "WORKER: ", and a worker PID different from the host PID. The verifier requires the host and observed child processes to terminate normally. The Windows run passed all six checks with no forced cleanup or remaining children. This distinguishes host construction and IPC from the direct class test.
Use the matching client and native build
The passing profile uses the checkout client with the RPC reply-header fix, a matching Python extension, and writable Windows IPC paths. The published client alone does not provide this path. The source-plugin guide validates local loading and managed dependencies. Remote package publication remains a separate release task.
"""Execute DocsUppercase in a real worker using the current environment explicitly."""
import asyncio
import json
import os
import sys
from pathlib import Path
import remotemedia.runtime as rt
from remotemedia.control import attach_inproc
async def main():
# The worker imports this on-disk module; it does not inherit this process's registry.
module_dir = str(Path(__file__).resolve().parent)
os.environ["PYTHONPATH"] = os.pathsep.join(filter(None, [module_dir, os.environ.get("PYTHONPATH")]))
rt.register_python_node_type("DocsUppercase", python_class="node_transform.DocsUppercase")
manifest = {
"version": "v1",
"metadata": {"name": "docs-worker"},
"python_env": {"explicit_venv": sys.prefix},
"nodes": [{"id": "formatter", "node_type": "DocsUppercase", "params": {"prefix": "WORKER: "}}],
"connections": [],
}
session = await asyncio.wait_for(rt.create_streaming_session(json.dumps(manifest)), timeout=45)
try:
await session.send_input("hello")
kind, value = await asyncio.wait_for(session.recv_output(), timeout=10)
assert (kind, value) == ("data", "WORKER: HELLO"), (kind, value)
async with attach_inproc(session) as ctrl:
description = await asyncio.wait_for(ctrl.formatter.describe(), timeout=10)
assert description["prefix"] == "WORKER: "
assert description["pid"] != os.getpid(), "The node must execute in a separate process"
print(json.dumps({"output": value, "worker_pid": description["pid"], "host_pid": os.getpid()}))
finally:
await session.close()
if __name__ == "__main__":
asyncio.run(main())
Register and package¶
@register_node("DocsUppercase") registers the class when its module is imported. A host/worker must discover and import that module; decoration alone does not install it on another runner.
A source plugin adds a plugin.toml with the plugin identity, Python entry module, declared node types, module root, and dependencies. The host's source-plugin path also reads the node's __python_version__ parameter when selecting its managed environment. Follow the tested source-plugin guide for the complete manifest/environment/load sequence.
Preserve application context¶
The small transform creates new text output and does not demonstrate forwarding all input annotations. A production media node must preserve or intentionally transform participant attribution, timestamps, stream/segment context, and modality metadata according to the selected worker contract.
Generate and cancel¶
Text/audio/video generators use the generation contract in addition to worker lifecycle. They declare the generated modality and cancellation strategy and implement async cancel(self, call, cancellation). Interrupt and abort have different state/input semantics. Use the SDK's generator conformance helper and a real host test before documenting responsive barge-in or output-tail guarantees.
Continue with RPC and application tools for exposed methods, or the text and synthetic audio cancellation examples.
Source references: remotemedia-sdk/clients/python/remotemedia/core/multiprocessing/node.py · remotemedia-sdk/clients/python/remotemedia/core/multiprocessing/data.py · remotemedia-sdk/clients/python/remotemedia/core/multiprocessing/__init__.py · remotemedia-sdk/clients/python/remotemedia/core/multiprocessing/runner.py · remotemedia-sdk/crates/transports/ffi/src/api.rs · remotemedia-sdk/clients/python/remotemedia/rpc.py · remotemedia-sdk/clients/python/remotemedia/control/rpc_proxy.py (base revision; reviewed with local changes) · remotemedia-sdk/clients/python/remotemedia/core/cancel.py · remotemedia-sdk-base/src/loadable/source_python.rs