Create Custom Python Reference

Estimated reading: 16 minutes 220 views

Custom components extend Robility flow’s functionality through Python classes that inherit from Component. This enables integration of new features, data manipulation, external services, and specialized tools.

In Robility flow’s  node-based environment, each node is a “component” that performs discrete functions. Custom components are Python classes which define:

1. Inputs — Data or parameters your component requires. 
2. Outputs — Data your component provides to downstream nodes. 
3. Logic — How you process inputs to produce outputs.

The benefits of creating custom components include unlimited extensibility, reusability, automatic field generation in the visual editor based on inputs, and type-safe connections between nodes.

Create custom components for performing specialized tasks, calling APIs, or adding advanced logic.

Custom components in Robility flow are built upon:

1. The Python class that inherits from Component.
2. Class-level attributes that identify and describe the component.
3. Input and output lists that determine data flow.
4. Internal variables for logging and advanced logic.

Class-level attributes

Define these attributes to control a custom component’s appearance and behavior: 

class MyCsvReader(Component):

    display_name = “CSV Reader”
    description = “Reads CSV files”
    icon = “file-text”
    name = “CSVReader”
    documentation = “http://docs.example.com/csv_reader”. 

1. display_name: A user-friendly label shown in the Components menu and on the component itself when you add it to a flow. 
2. description: A brief summary shown in tooltips and printed below the component name when added to a flow.
3. icon: A decorative icon from Robility flow’s icon library, printed next to the name.

Robility flow uses Lucide for icons. To assign an icon to your component, set the icon attribute to the name of a Lucide icon as a string, such as icon = “file-text”. Robility flow renders icons from the Lucide library automatically.

a. name: A unique internal identifier.

b. documentation: An optional link to external documentation, such as API or product documentation.

Structure of a custom component

A Robility flow custom component is more than a class with inputs and outputs. It includes an internal structure with optional lifecycle steps, output generation, front-end interaction, and logic organization.

A basic component:

a. Inherits from robilityflow.custom.Component.
b. Declares metadata like display_name, description, icon, and more.
c. Defines inputs and outputs lists.
d. Implement methods matching output specifications.

A minimal custom component skeleton contains the following: 

from robilityflow.custom import Component
from robilityflow.template import Output

class MyComponent(Component):

    display_name = “My Component”
    description = “A short summary.”
    icon = “sparkles”
    name = “MyComponent”

    inputs = []

    outputs = []

    def some_output_method(self):

        return …

Internal Lifecycle and Execution Flow

Robility flow’s engine manages:

a. Instantiation: A component is created and internal structures are initialized.
b. Assigning Inputs: Values from the visual editor or connections are assigned to component fields.
c. Validation and Setup: Optional hooks like _pre_run_setup. 
d. Outputs Generation: run() or build_results() triggers output methods.

Optional Hooks:

1. initialize_data or _pre_run_setup can run setup logic before the component’s main execution.
2. __call__, run(), or _run() can be overridden to customize how the component is called or to define custom execution logic.

Input and outputs

Custom component inputs are defined with properties like:

1. name, display_name
2. Optional: info, value, advanced, is_list, tool_mode, real_time_refresh

For example:

a. StrInput: simple text input.
b. DropdownInput: selectable options.
c. HandleInput: specialized connections.

Custom component Output properties define:

a. name, display_name, method
b. Optional: info

For more information, see Custom component inputs and outputs.

Associated Methods

Each output is linked to a method:

a. The output method name must match the method name.
b. The method typically returns objects like Message, Data, or DataFrame.
c. The method can use inputs with self.<input_name>.

For example:

Output(

    display_name=”File Contents”,

    name=”file_contents”,

    method=”read_file”

)

#…

def read_file(self) -> Data:

    path = self.filename

    with open(path, “r”) as f:

        content = f.read()

    self.status = f”Read {len(content)} chars from {path}”

    return Data(data={“content”: content})

Components with multiple outputs

A component can define multiple outputs. Each output can have a different corresponding method. For example:

outputs = [

    Output(display_name=”Processed Data”, name=”processed_data”, method=”process_data”),

    Output(display_name=”Debug Info”, name=”debug_info”, method=”provide_debug_info”),

]

Output Grouping Behavior with group_outputs

By default, components in Robility flow that produce multiple outputs only allow one output selection in the visual editor. The component will have only one output port where the user can select the preferred output type.

This behavior is controlled by the group_outputs parameter:

group_outputs=False (default): When a component has more than one output and group_outputs is false or not set, the outputs are grouped in the visual editor, and the user must select one.

Use this option when the component is expected to return only one type of output when used in a flow.

group_outputs=True: All outputs are available simultaneously in the visual editor. The component has one output port for each output, and the user can connect zero or more outputs to other components.

Use this option when the component is expected to return multiple values that are used in parallel by downstream components or processes.

a. False or not set
b. True

In this example, the visual editor provides a single output port, and the user can select one of the outputs. Since group_outputs=False is the default behavior, it doesn’t need to be explicitly set in the component, as shown in this example:

outputs = [

    Output(

        name=”structured_output”,

        display_name=”Structured Output”,

        method=”build_structured_output”,

    ),

    Output(

        name=”dataframe_output”,

        display_name=”DataFrame Output”,

        method=”build_structured_dataframe”,

    ),

]

Common internal patterns

_pre_run_setup()

To initialize a custom component with counters set:

def _pre_run_setup(self):

    if not hasattr(self, “_initialized”):

        self._initialized = True

        self.iteration = 0

Override run or _run

You can override async def _run(self): … to define custom execution logic, although the default behavior from the base class usually covers most cases.

Store data in self.ctx

Use self.ctx as a shared storage for data or counters across the component’s execution flow:

def some_method(self):

    count = self.ctx.get(“my_count”, 0)

    self.ctx[“my_count”] = count + 1

Directory structure requirements

By default, Robility flow looks for custom components in the component’s directory.

If you’re creating custom components in a different location using the ROBILITYFLOW_COMPONENTS_PATH environment variable, components must be organized in a specific directory structure to be properly loaded and displayed in the visual editor:

/your/custom/components/path/    # Base directory set by ROBILITYFLOW_COMPONENTS_PATH

    └── category_name/          # Required category subfolder that determines menu name

        └── custom_component.py # Component file

Components must be placed inside category folders, not directly in the base directory.

The category folder name determines where the component appears in the Robility flow Components menu. For example, to add a component to the Helpers category, place it in the helpers subfolder:

/app/custom_components/          # ROBILITYFLOW_COMPONENTS_PATH

    └── helpers/                 # Displayed within the “Helpers” category

        └── custom_component.py  # Your component

You can have multiple category folders to organize components into different categories:

/app/custom_components/

    ├── helpers/

    │   └── helper_component.py

    └── tools/

        └── tool_component.py

This folder structure is required for Robility flow to properly discover and load your custom components. Components placed directly in the base directory aren’t loaded.

/app/custom_components/          # ROBILITYFLOW_COMPONENTS_PATH

    └── custom_component.py      # Won’t be loaded – missing category folder!

Custom component inputs and outputs

Inputs and outputs define how data flows through the component, how it appears in the visual editor, and how connections to other components are validated.

Inputs

Inputs are defined in a class-level inputs list. When Robility flow loads the component, it uses this list to render component fields and ports in the visual editor. Users or other components provide values or connections to fill these inputs.

An input is usually an instance of a class from robilityflow.io (such as StrInput, DataInput, or MessageTextInput). The most common constructor parameters are:

a. name: The internal variable name, accessed with self.<name>. 
b. display_name: The label shown to users in the visual editor.
c. info (optional): A tooltip or short description.
d. value (optional): The default value.
e. advanced (optional): If true, moves the field into the “Advanced” section.
f. required (optional): If true, forces the user to provide a value.
g. is_list (optional): If true, allows multiple values.
h. input_types (optional): Restricts allowed connection types (e.g., [“Data”], [“LanguageModel”]).

Here are the most used input classes and their typical usage.

Text Inputs: For simple text entries.

a. StrInput creates a single-line text field. 
b. MultilineInput creates a multi-line text area.

Numeric and Boolean Inputs: Ensures users can only enter valid numeric or Boolean data.

BoolInputIntInput, and FloatInput provide fields for Boolean, integer, and float values, ensuring type consistency.

Dropdowns: For selecting from predefined options, useful for modes or levels – DropdownInput

Secrets: A specialized input for sensitive data, ensuring input is hidden in the visual editor- SecretStrInput for API keys and passwords.

Specialized Data Inputs: Ensures type-checking and color-coded connections in the visual editor.

a. DataInput expects a Data object (typically with .data and optional .text). 
b. MessageInput expects a Message object, used in chat or agent flows. 
c. MessageTextInput simplifies access to the .text field of a Message.

Handle-Based Inputs: Used to connect outputs of specific types, ensuring correct pipeline connections – HandleInput

File Uploads: Allows users to upload files directly through the visual editor or receive file paths from other components – FileInput

Lists: Set is_list=True to accept multiple values, ideal for batch or grouped operations.

This example defines three inputs: a text field (StrInput), a Boolean toggle (BoolInput), and a dropdown selection (DropdownInput).

from robilityflow.io import StrInput, BoolInput, DropdownInput

inputs = [

    StrInput(name=”title”, display_name=”Title”),

    BoolInput(name=”enabled”, display_name=”Enabled”, value=True),

    DropdownInput(name=”mode”, display_name=”Mode”, options=[“Fast”, “Safe”, “Experimental”], value=”Safe”)

]

Outputs

Outputs are defined in a class-level outputs list. When Robility flow renders a component, each output becomes a connector point in the visual editor. When you connect something to an output, Robility flow automatically calls the corresponding method and passes the returned object to the next component.

An output is usually an instance of Output from robilityflow.io, with common parameters:

  • name: The internal variable name.
  • display_name: The label shown in the visual editor.
  • method: The name of the method called to produce the output.
  • info (optional): Help text shown on hover.

The method must exist in the class, and it is recommended to annotate its return type for better type checking. You can also set a self.status message inside the method to show progress or logs.

Common Return Types:

  • Message: Structured chat messages.
  • Data: Flexible object with .data and optional .text.
  • DataFrame: Pandas-based tables (robilityflow.schema.DataFrame).
  • Primitive types: str, int, bool (not recommended if you need type/color consistency).

In this example, the DataToDataFrame component defines its output using the outputs list. The df_out output is linked to the build_df method, so when connected to another component (node), Robility flowcalls this method and passes its returned DataFrame to the next node. This demonstrates how each output maps to a method that generates the actual output data.

from robilityflow.custom import Component

from robilityflow.io import DataInput, Output

from robilityflow.schema import Data, DataFrame

class DataToDataFrame(Component):

    display_name = “Data to DataFrame”

    description = “Convert multiple Data objects into a DataFrame”

    icon = “table”

    name = “DataToDataFrame”

    inputs = [

        DataInput(

            name=”items”,

            display_name=”Data Items”,

            info=”List of Data objects to convert”,

            is_list=True

        )

    ]

    outputs = [

        Output(

            name=”df_out”,

            display_name=”DataFrame Output”,

            method=”build_df”

        )

    ]

    def build_df(self) -> DataFrame:

        rows = []

        for item in self.items:

            row_dict = item.data.copy() if item.data else {}

            row_dict[“text”] = item.get_text() or “”

            rows.append(row_dict)

        df = DataFrame(rows)

        self.status = f”Built DataFrame with {len(rows)} rows.”

        return df

Tool Mode

Components that support Tool Mode can be used as standalone components (when not in Tool Mode) or as tools for other components with a Tools input, such as Agent components.

You can allow a custom component to support Tool Mode by setting tool_mode=True:

inputs = [

    MessageTextInput(

        name=”message”,

        display_name=”Mensage”,

        info=”Enter the message that will be processed directly by the tool”,

        tool_mode=True,

    ),

]

Robility flow currently supports the following input types for Tool Mode:

a. DataInput
b. DataFrameInput
c. PromptInput
d. MessageTextInput
e. MultilineInput
f. DropdownInput

Typed annotations

In Robility flow, typed annotations allow Robility flow to visually guide users and maintain flow consistency.

Typed annotations provide:

a. Color-coding: Outputs like -> Data or -> Message get distinct colors. 
b. Validation: Robility flow blocks incompatible connections automatically.
c. Readability: Developers can quickly understand data flow.
d. Development tools: Better code suggestions and error checking in your code editor.

Common Return Types

Message: For chat-style outputs. Connects to any of several Message-compatible inputs.

def produce_message(self) -> Message:

    return Message(text=”Hello! from typed method!”, sender=”System”)

Data: For structured data like dicts or partial texts. Connects only to DataInput (ports that accept Data).

def get_processed_data(self) -> Data:

    processed = {“key1”: “value1”, “key2”: 123}

    return Data(data=processed)

DataFrame: For tabular data. Connects only to DataFrameInput (ports that accept DataFrame).

def build_df(self) -> DataFrame:

    pdf = pd.DataFrame({“A”: [1, 2], “B”: [3, 4]})

    return DataFrame(pdf)

Primitive Types (str, int, bool): Returning primitives is allowed but wrapping in Data or Message is recommended for better consistency in the visual editor.

def compute_sum(self) -> int:

    return sum(self.numbers)

Tips for typed annotations

When using typed annotations, consider the following best practices:

1. Always Annotate Outputs: Specify return types like -> Data, -> Message, or -> DataFrame to enable proper visual editor color-coding and validation. 
2. Wrap Raw Data: Use Data, Message, or DataFrame wrappers instead of returning plain structures. 
3. Use Primitives Carefully: Direct str or int returns are fine for simple flows, but wrapping improves flexibility. 
4. Annotate Helpers Too: Even if internal, typing improves maintainability and clarity.
5. Handle Edge Cases: Prefer returning structured Data with error fields when needed. 
6. Stay Consistent: Use the same types across your components to make flows predictable and easier to build.

Enable dynamic fields

In Robility flow, dynamic fields allow inputs to change or appear based on user interactions. You can make an input dynamic by setting dynamic=True. Optionally, setting real_time_refresh=True triggers the update_build_config method to adjust the input’s visibility or properties in real time, creating a contextual visual editor experience that only exposes relevant fields based on the user’s choices.

In this example, the operator field triggers updates with real_time_refresh=True. The regex_pattern field is initially hidden and controlled with dynamic=True.

from robilityflow.io import DropdownInput, StrInput

class RegexRouter(Component):

    display_name = “Regex Router”

    description = “Demonstrates dynamic fields for regex input.”

    inputs = [

        DropdownInput(

            name=”operator”,

            display_name=”Operator”,

            options=[“equals”, “contains”, “regex”],

            value=”equals”,

            real_time_refresh=True,

        ),

        StrInput(

            name=”regex_pattern”,

            display_name=”Regex Pattern”,

            info=”Used if operator=’regex'”,

            dynamic=True,

            show=False,

        ),

    ]

Implement update_build_config

When a field with real_time_refresh=True is modified, Robility flow calls the update_build_config method, passing the updated field name, value, and the component’s configuration to dynamically adjust the visibility or properties of other fields based on user input.

This example will show or hide the regex_pattern field when the user selects a different operator.

def update_build_config(self, build_config: dict, field_value: str, field_name: str | None = None) -> dict:

    if field_name == “operator”:

        if field_value == “regex”:

            build_config[“regex_pattern”][“show”] = True

        else:

            build_config[“regex_pattern”][“show”] = False

    return build_config

Additional Dynamic Field Controls

You can also modify other properties within update_build_config, such as:

1. required: Set build_config[“some_field”][“required”] = True/False
2. advanced: Set build_config[“some_field”][“advanced”] = True
3. options: Modify dynamic dropdown options.

Tips for Managing Dynamic Fields

When working with dynamic fields, consider the following best practices to ensure a smooth user experience:

a. Minimize field changes: Hide only fields that are truly irrelevant to avoid confusing users.
b. Test behavior: Ensure that adding or removing fields doesn’t accidentally erase user input.
c. Preserve data: Use build_config[“some_field”][“show”] = False to hide fields without losing their values. 
d. Clarify logic: Add info notes to explain why fields appear or disappear based on conditions. 
e. Keep it manageable: If the dynamic logic becomes too complex, consider breaking it into smaller components, unless it serves a clear purpose in a single node.

Error handling and logging

In Robilityflow, robust error handling ensures that your components behave predictably, even when unexpected situations occur, such as invalid inputs, external API failures, or internal logic errors.

Error handling techniques

1. Raise Exceptions: If a critical error occurs, you can raise standard Python exceptions such as ValueError, or specialized exceptions like ToolException. Robility flow will automatically catch these and display appropriate error messages in the visual editor, helping users quickly identify what went wrong.

def compute_result(self) -> str:

    if not self.user_input:

        raise ValueError(“No input provided.”)

    # …

2. Return Structured Error Data: Instead of stopping flowing abruptly, you can return a Data object containing an “error” field. This approach allows the flow to continue operating and enables downstream components to detect and handle the error gracefully.

def run_model(self) -> Data:

    try:

        # …

    except Exception as e:

        return Data(data={“error”: str(e)})

Improve debugging and flow management

1. Use self.status: Each component has a status field where you can store short messages about the execution result—such as success summaries, partial progress, or error notifications. These appear directly in the visual editor, making troubleshooting easier for users.

def parse_data(self) -> Data:

# …

self.status = f”Parsed {len(rows)} rows successfully.”

return Data(data={“rows”: rows})

2. Stop specific outputs with self.stop(…): You can halt individual output paths when certain conditions fail, without affecting the entire component. This is especially useful when working with components that have multiple output branches.

def some_output(self) -> Data:

if <some condition>:

    self.stop(“some_output”)  # Tells Robility flowno data flows

    return Data(data={“error”: “Condition not met”})

3. Log events: You can log key execution details inside components. Logs are displayed in the “Logs” or “Events” section of the component’s detail view and can be accessed later through the flow’s debug panel or exported files, providing a clear trace of the component’s behavior for easier debugging.

def process_file(self, file_path: str):

self.log(f”Processing file {file_path}”)

# …

Tips for error handling and logging

To build more reliable components, consider the following best practices:

a. Validate inputs early: Catch missing or invalid inputs at the start to prevent broken logic.
b. Summarize with self.status: Use short success or error summaries to help users understand results quickly.
c. Keep logs concise: Focus on meaningful messages to avoid cluttering the visual editor.
d. Return structured errors: When appropriate, return Data(data={“error”: …}) instead of raising exceptions to allow downstream handling.
e. Stop outputs selectively: Only halt specific outputs with self.stop(…) if necessary, to preserve correct flow behavior elsewhere.

Share this Doc

Create Custom Python Reference

Or copy link

CONTENTS