---
question: How do I write a workflow class in a module?
kind: task
via_web: na
via_cli: available
via_python: available
via_api: na
via_config: na
ref_cli: abi new workflow
ref_python: Workflow
prereq: You need a module of your project. [Create a module](/capabilities/build/modules/creating-a-module) first.
next:
  - /capabilities/build/workflows/expose-as-a-tool
  - /capabilities/build/workflows/run-a-workflow
  - /capabilities/build/workflows/write-a-durable-workflow
---

# Create a workflow

Workflows implement business logic. They sit at the top of the stack, orchestrating integrations and querying the knowledge graph to fulfill specific user intents. A workflow class is a `naas_abi_sdk.workflow.Workflow` with an `async def run`. Its module gives it to its agents as a tool, and publishes it as the durable workflow `workflow.<slug>` that Nexus and other modules start by name.

For work in several steps that must survive a crash, or that spreads over other modules, write a [durable workflow](/capabilities/build/workflows/write-a-durable-workflow) (`@workflow`) instead.

## Role in the stack

```text
┌─────────────────┐
│    Workflows    │ ← Business logic. Query graph, call integrations, compose results.
├─────────────────┤
│    Pipelines    │ ← Data ingestion. Transform raw data into RDF.
├─────────────────┤
│  Integrations   │ ← External API communication. No business logic.
└─────────────────┘
```

A workflow:
- Implements a specific, named intent (e.g. "reward long-term customers").
- Can query the triple store directly with SPARQL.
- Can call integrations for write operations or real-time data.
- Returns a deterministic result for the same inputs.
- Is exposed as a LangChain tool (for agents) and as the durable workflow `workflow.<slug>`.

If your output is RDF, write a [pipeline](/capabilities/build/knowledge-graph/creating-a-pipeline) instead.

## Web UI

Not applicable. Nexus has no screen that writes a workflow: it is a Python class in a module. Use the CLI or Python on this page. Once the module runs, Nexus starts it from System › Jobs: see [Run a workflow](/capabilities/build/workflows/run-a-workflow?via=web).

## CLI

### Scaffold the workflow

From the module's folder:

```bash
abi new workflow Customers workflows
```

It writes `CustomersWorkflow.py`: the name is converted to PascalCase and `Workflow` is appended. The arguments are `<name> [path]`, and the path defaults to the package's `workflows/` folder. The file holds three classes: a configuration, the parameters, and the workflow, whose `async def run` echoes a message. `CustomersWorkflow_test.py` is written beside it. The command is [`abi new workflow`](/user-guide/reference/cli#abi-new-workflow).

The command prints the workflow's name (`customers_workflow`) and its durable name (`workflow.customers_workflow`). A path outside `workflows/` gets a warning: the module only builds classes from there.

## Python

### Write the class

Read services through the module, which `New(module)` receives:

```python title="src/reports/workflows/CustomersWorkflow.py"
from dataclasses import dataclass

from naas_abi_sdk.workflow import Workflow, WorkflowConfiguration, WorkflowParameters
from pydantic import Field


@dataclass
class CustomersWorkflowConfiguration(WorkflowConfiguration):
    """Configuration for CustomersWorkflow."""


class CustomersWorkflowParameters(WorkflowParameters):
    entity_id: str = Field(description="The ID of the entity to summarize")


class CustomersWorkflow(Workflow[CustomersWorkflowParameters]):
    """Summarize an entity from the knowledge graph."""

    def __init__(self, configuration: CustomersWorkflowConfiguration, module=None):
        super().__init__(configuration)
        self.module = module

    @classmethod
    def New(cls, module) -> "CustomersWorkflow":
        return cls(CustomersWorkflowConfiguration(), module)

    async def run(self, parameters: CustomersWorkflowParameters) -> dict:
        sparql = f"""
            PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
            SELECT ?label WHERE {{
                <http://ontology.naas.ai/abi/item/{parameters.entity_id}> rdfs:label ?label .
            }}
        """
        rows = await self.module.engine.services.triple_store.query(sparql)
        return {"entity_id": parameters.entity_id, "labels": [str(row[0]) for row in rows]}
```

`run` must be `async def`: a class whose `run` is a plain method raises `TypeError` as soon as it is defined. The class docstring is the description an agent reads to decide when to call it.

### Let the module build it

- **Discovery.** `BaseModule` finds the `Workflow` subclasses defined under the package's `workflows/` folder (test files, abstract classes and classes that are only imported aside), or the ones listed in `workflows = (...)` on the module class. It builds each one after `on_initialized`: `New(module)` (sync or async) if the class defines it, else the class with an empty configuration.
- **Arguments.** A class that needs more is bound in `on_initialized` with `self.expose_workflow("customers_workflow", instance)`. A class that is neither buildable nor bound stops the module from starting, with a message naming it.
- **Name.** The class name in snake case, `customers_workflow`. Its durable workflow is `workflow.customers_workflow`.
- **Tools.** `as_tools()` comes with the base class. An agent built in `on_initialized` needs `await self.build_processes()` first: see [Expose as a tool](/capabilities/build/workflows/expose-as-a-tool?via=python).
- **Dependencies.** The module declares the services the class calls (here `triple_store`), plus `document`, and runs with discovery. Importing the class needs `naas-abi-sdk[workflows]`, and `as_tools()` needs `[agents]`; a module that `abi new module` generated installs both.

## REST API

Not applicable. There is no HTTP call that writes the workflow class. Once the module runs, Nexus' `/api/workflows` starts its durable workflow `workflow.<slug>`: see [Run a workflow](/capabilities/build/workflows/run-a-workflow?via=api).

## Config

Not applicable. The class is not a `config.yaml` block: it lives in the module's code.

## Composing workflows

Inside one module, a workflow class can call another one's `run` directly, through the instances the module built:

```python
class RewardCustomersWorkflow(Workflow[RewardCustomersParameters]):
    """Add credits to every long-term customer."""

    def __init__(self, configuration: RewardCustomersWorkflowConfiguration, module=None):
        super().__init__(configuration)
        self.module = module

    @classmethod
    def New(cls, module) -> "RewardCustomersWorkflow":
        return cls(RewardCustomersWorkflowConfiguration(), module)

    async def run(self, parameters: RewardCustomersParameters) -> dict:
        find_customers = self.module.get_workflow_instance("find_customers_workflow")
        add_credits = self.module.get_workflow_instance("add_credits_workflow")

        # Step 1: find eligible customers
        customers = await find_customers.run(
            FindCustomersParameters(min_months=parameters.min_months)
        )
        rewarded = []
        for customer in customers:
            # Step 2: add credits
            await add_credits.run(AddCreditsParameters(
                customer_id=customer["id"],
                credits=parameters.credits,
            ))
            rewarded.append(customer["id"])

        return {"rewarded": len(rewarded), "customer_ids": rewarded}
```

`get_workflow_instance` returns the built instances, so look them up in `run`, not in `New()`: the module builds its classes one after the other.

A crash halfway through runs everything again. When the steps are costly, or call workflows of other modules, write a [durable workflow](/capabilities/build/workflows/write-a-durable-workflow) instead: each `ctx.step` is stored, and `ctx.call` starts another module's workflow as a child run.

## Running a workflow on a schedule

A class takes its triggers from `job = JobSettings(triggers=(...))`, and a `@workflow` from its decorator. Both are on [Schedule a workflow](/capabilities/build/workflows/schedule-a-workflow).

## Best practices

- **One intent per workflow**: `GetCustomersByRevenue`, `SendOnboardingEmail`, `UpdateCompanyProfile` - each focused, each composable.
- **Validate parameters**: Pydantic validation is free; use `Field(description=...)` so agents know how to call the tool correctly.
- **Return structured data**: return dicts or Pydantic models. Agents and API consumers both benefit.
- **Log with context**: use the standard `logging` module (`logger = logging.getLogger(__name__)`, then `logger.info(...)`), not `print()`.
- **Test `run()` directly**: build the workflow and await `run(...)` with a parameters instance, in `<Name>Workflow_test.py` next to the file. See [Test a workflow](/capabilities/build/workflows/test-a-workflow).
- **Safe to repeat**: a durable run is delivered at least once. Write to keys derived from the parameters, so a second run changes nothing.
