> ## Documentation Index
> Fetch the complete documentation index at: https://docs.sarasfinance.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Workflows

> Architecting complex automation through multi-node agent orchestration.

## Overview

A **Workflow** is an orchestrated sequence of agents organized into nodes. While individual agents perform specific tasks, workflows define the logic, data flow, and control structures that connect these agents to solve end-to-end business problems.

## Workflow Structure

Workflows are built using a node-based architecture where each node represents a functional step in the process.

### Multi-Node Composition

A workflow can consist of multiple nodes connected in a directed graph. The output of one node (or a specific agent within it) is passed as the input to the next, ensuring a seamless data pipeline.

### Conditional Branching

Within a single node, you can implement **Conditional Branching**. This allows the workflow to evaluate data at runtime and decide which path to follow.

* **Logic-Based Routing:** Use "If-Then-Else" structures to route the flow.
* **Dynamic Paths:** Direct the workflow to different agents based on the success, failure, or specific value of a preceding agent's output.

### Agent Loops

Nodes support **Loops**, enabling an agent or a set of agents to execute repeatedly until a specific condition is met or a list of items is fully processed.

* **Batch Processing:** Loop through a list of invoices to extract data from each.
* **Retry Logic:** Re-run an agent if the initial output does not meet validation criteria.

### Workflow Node

A **Workflow Node** allows you to embed an existing workflow as a single step within your current process. This treats a complex sequence of agents as a reusable, modular function call.

#### Key Benefits

* **Logic Separation:** Decouple specialized business logic (e.g., a "Tax Calculation" workflow) from your main orchestration flow.
* **Reusability:** Build a workflow once and call it across multiple different parent workflows.
* **Reduced Complexity:** Keep your primary workflow canvas clean by collapsing multi-agent processes into a single functional node.
* **Independent Maintenance:** Update the nested workflow independently without needing to reconfigure every parent workflow that uses it.

#### Technical Behavior

When a Workflow Node is triggered, the platform executes it as a **Sub-Routine**:

| Feature                   | Execution Logic                                                                                                         |
| :------------------------ | :---------------------------------------------------------------------------------------------------------------------- |
| **Context Passing**       | Global slots from the parent workflow can be mapped into the child workflow's input slots.                              |
| **Synchronous Execution** | The parent workflow waits for the "Workflow Node" to complete its final agent execution before moving to the next node. |
| **Output Mapping**        | The final result of the nested workflow is returned to the parent's context for use in downstream nodes.                |

#### Best Practices for Modular Workflows

##### 1. Functional Encapsulation

Use Workflow Nodes for tasks that require a distinct set of permissions or specialized logic, such as:

* **ERP Syncing:** A dedicated workflow for handling complex data handshakes.
* **Compliance Audits:** A sub-workflow that loops through files and generates a report.

##### 2. Styling for Visual Hierarchy

To distinguish a **Workflow Node** from a standard **Agent Node**, use unique styling:

* **Custom Borders:** Use thicker borders for nested workflows to indicate depth.
* **Unique Icons:** Assign a folder or "sub-process" icon to quickly identify modular logic.

***

## Slot Management

Workflows utilize **Global Slots** to maintain state and share data across different nodes. These slots act as the "memory" of the workflow.

### Supported Slot Types

When defining a slot, you must specify its type to ensure data validation and prevent type-mismatch errors.

| Slot Type           | Description                                            |
| :------------------ | :----------------------------------------------------- |
| **Int**             | Whole numbers for counts or IDs.                       |
| **List of Int**     | An array of integers (e.g., a list of order IDs).      |
| **Decimal**         | Decimal numbers for floating values.                   |
| **List of Decimal** | An array of decimals (e.g., a list of temperatures).   |
| **Boolean**         | True/False flags for conditional logic.                |
| **List of Boolean** | An array of booleans (e.g., a list of switch values).  |
| **String**          | Alphanumeric text.                                     |
| **List of String**  | An array of text values (e.g., tags, names).           |
| **Files**           | References to uploaded documents or generated reports. |
| **Workbooks**       | References output of calculation engines.              |

***

## Workflow Process Context & Slot Mapping

When executing a workflow in the context of a process (via the `/v1/process/workflows/executeWorkflow` API), process data can be shared and mapped into the workflow.

### 1. Dynamic Slot Mapping (`slotsToFieldsMapper`)

In the stage configuration, you can map process field values to specific workflow input slots:

* **Config Format:** Use a dictionary key-value mapping under `slotsToFieldsMapper`, where keys are workflow slot IDs and values are the process field names.
* **Type Normalization:** For file/document field types, the platform automatically normalizes values into a list of file dictionaries (e.g. `[{"id": "file_123"}]`) before injecting them into the workflow's input slots.

### 2. Automatic Context Slots

In addition to the mapped slots, the platform automatically injects two global JSON-serialized slots into the workflow's execution environment:

| Slot ID        | Slot Type  | Structure                     | Description                                                                         |
| :------------- | :--------- | :---------------------------- | :---------------------------------------------------------------------------------- |
| `process`      | `JSON_OBJ` | `{"v": <process_as_dict>}`    | The full process record (including fields, stage, status, created time, and locks). |
| `fieldsConfig` | `JSON_OBJ` | `{"v": <fields_config_dict>}` | The sub-project field definitions/metadata.                                         |

### 3. Consuming Context in Workflow Agents

Agents running within the workflow nodes can access these global slots to inspect process-level metadata or look up configuration values dynamically. For instance, in a Python agent node:

```python theme={null}
# Extract the full process fields from the global JSON slot
process_slot = workflowContext.get("process", {}).get("v", {})
process_fields = process_slot.get("fields", {})

case_title = process_fields.get("caseTitle")
jurisdiction = process_fields.get("jurisdiction")

# Use process details in the agent's logic
```

***

## Human-in-the-Loop: Approvals

For sensitive operations (e.g., processing a payment or updating an ERP), you can enable **Approvals** for specific nodes.

* **Intervention:** The workflow pauses execution at the designated node.
* **Review:** A human operator reviews the agent's output.
* **Action:** The workflow resumes only after an "Approve" or "Reject" action is logged.
* You can also specify a list of approvers who should approve to ensure right team member is approving the execution.

***

## Visualization & Styling

To manage complex architectures, the platform provides **Node Styling** for clear visualization.

* **Color Coding:** Assign colors to nodes based on their function (e.g., Green for ERP, Blue for No-Code).
* **Custom Icons:** Visual identifiers for quick recognition of agent types within the workflow canvas.
* **Layout Organization:** Auto-align and group nodes to maintain a clean, readable map of the business logic.

***

## Implementation Example

<Steps>
  <Step title="Initialize Slots">
    Either define slots manually, or choose **Fill slots from Agents** to initialise slots.
  </Step>

  <Step title="Configure Node 1">
    Configure nodes by selecting the right agents from the list.
  </Step>

  <Step title="Add Conditional Branch">
    If you are configuring conditional node - specify the condition and select a list of agents that should run with that winning condition.
    Conditions should be run with slots in mind like this: `{{slotName}} > 10`
  </Step>

  <Step title="Approvals">
    Select Approvals if the node is needed to be approved before execution.
  </Step>

  <Step title="Styling">
    For visualisation purposes, you can choose to style your workflow with color / logo and custom name if needed.
  </Step>
</Steps>
