# DecisionRules Academy Introduction

Discover the capabilities of DecisionRules

This Academy has been thought for your first steps in the world of Business Rules Engines. The intended audience are beginners in <mark style="color:purple;">DecisionRules</mark>, therefore it goes step by step from the most basic actions in the app, such as creating an account or buying a plan to more complex functionalities, creating and managing the rules&#x20;

The focus is practical, we will show you how to do. In the blink of an eye, you will run the application at full capacity, your team divided into different spaces, each member's roles well defined, and your most important rules already deciding. Although some concepts will be necessary, more extensive explanations are available in our documentation; when it can be relevant we share with you links to specific sections of that documentation.  &#x20;

Let us see first the originality of <mark style="color:purple;">DecisionRules</mark>, how the system stands out from other rules engines by looking at some concrete examples. Examples of our use cases, rule types and deployment options.   &#x20;

## Benefits of a codeless solution

Many organizations use code-based rules. Thus, when any change is made to the logic or individual values such as insurance rates or seasonal sale discount code, a Business Description needs to be created by the development team who then implement the change in production. Such a change can take several days and requires a whole team of developers to implement it. But what if there was a way to transform your business logic into rules without having to use any code? Automate your processes with <mark style="color:purple;">DecisionRules</mark>. Create, deploy and manage your Business Rules thanks to our user friendly UI.

## Industries and uses cases

<mark style="color:purple;">DecisionRules</mark> is a really versatile tool which can be used across industries and use cases. To be a bit more concrete we would like to mention some examples currently used in industries such as Banking and Finance, Insurance, Healthcare, E-commerce, Logistics and more. In addition to industry-specific cases, you will find general use cases such as dynamic pricing and forms, client scoring and segmentation, product selection. And this is just a fraction of what <mark style="color:purple;">DecisionRules</mark> can be used for.

**Finance & Banking**

* Loan approval
* Automation of the underwriting
* Creation of scorecards
* Client validation
* Examples of our clients in finance: [PayJustNow](https://payjustnow.com/),[ Swoop Funding](https://swoopfunding.com/), [First Response Finance](https://www.firstresponsefinance.co.uk/), [Teya](https://teya.com/cz/home), [Rupify](https://www.rupifi.com/), [Stone](https://www.stone.com.br/)
* [Case Study](https://www.decisionrules.io/articles/using-decision-rules-for-lending-financial-services)

**Insurance**

* Limit calculation
* Policy validation
* Client eligibility check
* Claim validation

**HealthCare**

* Medical information evaluation
* Treatment recommendation
* Compliance and policy rules
* Claims processing
* Our current clients in the health sector are Medical and Veterinary clinics and Insurance agencies&#x20;

**E-commerce**

* EAN code and product parameters validation
* Price and discount calculation
* Product categorization
* Examples of our clients in e-commerce: [Mix](https://mix.co.uk/), [Wolford](https://www.wolfordshop.cz/) or [Kotsovolos](https://www.kotsovolos.gr/)
* Case Study with [Mix.com](https://www.decisionrules.io/articles/clients-case-study-e-commerce)

**Telco**

* Creation of tailored offerings
* Individual pricing

**Logistics**

* Packaging selection
* Delivery method/ provider selection
* Warehouse and delivery route selection

<figure><img src="https://lh7-us.googleusercontent.com/q8J5gYu2S_c-4DApTWQeGVak97W-VgWa5ugMOvsg3JZgsLgrGECAl2fqM4zfgfJisaMyaeGLa8d6_G1gsWbGkux9kVw8FBrC-kYsHygYHtsngb8lzj9la2z2FGu905uCsWP9dEJUovAVP3jG1-P8tEs" alt=""><figcaption></figcaption></figure>

<figure><img src="https://lh7-us.googleusercontent.com/vIOcaUNZlQQP5e7qBoTLWjh_j5rTLfK28G_lxDyXkpth24jHS2EcAGqR9TFEVNAVrqBgpUNY9SoWidU-m61HFGCPzZlknEdSfWDViCvOpbWkRtUnIDA-ezuAfIFpSNCGANfZMlpS0hgg4KjpeZ3bRyw" alt=""><figcaption><p><mark style="color:purple;">Universal Use Cases</mark></p></figcaption></figure>

## Rule types

Currently there are six different types of rules in the engine: Decision Tree, Decision Table, Lookup Table, Scripting Rule, Decision Flow, and Integration Flow. One of our popular rules, the Rule Flow, is accessible but it has been improved by the new flows, Decision and Integration.&#x20;

Each type correspond to different levels of logical complexity and different types of decision. Depending of the process you want to automate you choose one rule or another. The criteria for this selection comes from experience, but for now, feel free to experiment with all of them. A more detailed explanation will be found below in the [RULES](https://academy.decisionrules.io/rules/what-is-a-rule) section.&#x20;

<figure><img src="/files/K0PSVtV5VcIAby6svbW3" alt="" width="513"><figcaption></figcaption></figure>

<figure><img src="/files/hh0MmYkJLxGUBktJqhev" alt="" width="513"><figcaption></figcaption></figure>

<figure><img src="/files/G5iPZPqe2seOzitVFIwe" alt="" width="514"><figcaption></figcaption></figure>

{% hint style="info" %}
*See* [*Rule Types*](/rule-types/decision-tables) *section for more information about each rule type.*
{% endhint %}

## Delivery of new rules or changes using versioning

With versioning, you can work on or use multiple versions at the same time. While your current version is in production, you can be already working on new versions that include changes or fixes to your logic. You can change the content of all versions separately and test them independently.

## DecisionRules Deployments Options

The easiest way to start using the <mark style="color:purple;">DecisionRules</mark> application is by using the Public Cloud. This Software as a Service (SaaS) solution, with global coverage and low response time, is ready to use in 2 minutes. All you have to do is create an account to use it. You can also use Regional Clouds, where you get all the benefits of Public Cloud with the guarantee of data residency in the region. You can choose from the following regions - European Union, The United States and Australia.

Another option is to use Private Managed Cloud, where the cloud instance is dedicated exclusively to you. You choose your favorite cloud provider (Amazon, Microsoft or Google) and tell us your performance requirements. Based on all your requirements, our certified professionals will build the environment for you. Another advantage is the availability of Single Sign On (SSO) options.

The last option is Private Cloud or On Premise. <mark style="color:purple;">DecisionRules</mark> can be deployed directly to your infrastructure either in your private cloud or on your own servers. Advantages are data privacy and residency, SSO and absolute control of your environment.

<figure><img src="/files/9yT95pekYipXfiCk3Kil" alt=""><figcaption><p><mark style="color:purple;">Deployment options of DecisionRules</mark></p></figcaption></figure>


# Create an Account

Find out how you can immediately start using DecisionRules

To create business rules, save your work and invite other colleagues to your workspace, you need to create an account.

## Sign up with credentials

Go to the [<mark style="color:purple;">DecisionRules</mark>](https://www.decisionrules.io/) page. Click on the <mark style="background-color:purple;">**LOGIN**</mark> button at the top of the page. A login screen will appear. There, below the boxes for email and password you will find the "REGISTER ACCOUNT" link. You will be redirected to a register page where you can fill in all the required fields.&#x20;

<figure><img src="/files/VO7FZwia9Z0ZUy6SuWnl" alt=""><figcaption><p><mark style="color:purple;">Sign up form</mark></p></figcaption></figure>

Then click on the <mark style="background-color:purple;">**REGISTER**</mark> button. You will be sent to your new workspace and a email verification will arrive in your inbox. Press the <mark style="background-color:purple;">**Verify email**</mark> button and set up your password.&#x20;

<figure><img src="/files/zUyRsnSE0szwFfoK8vjH" alt=""><figcaption><p><mark style="color:purple;">Create a new account with email and password</mark></p></figcaption></figure>

## Creating new account using your Google or Microsoft SSO

Are you tired of inventing new logins? With one click, you can create an account on <mark style="color:purple;">DecisionRules</mark> with Google and Microsoft SSO. Go to the [<mark style="color:purple;">DecisionRules</mark>](https://www.decisionrules.io/) page. Click on the <mark style="background-color:purple;">**LOGIN**</mark> button at the top of the page. A login page will appear. Simply click the button <mark style="background-color:red;">SIGN IN WITH Google</mark> or <mark style="background-color:green;">SIGN IN WITH Microsoft</mark> to start the sign up.&#x20;

You will be redirected to Google or Microsoft login. After successfully logging in to your Google or Microsoft account, you'll be asked to grant permissions for application to access certain information. Review the permissions, and if you agree, click Allow or Grant.

## Organization Single Sign On

If your organization has the single sign-on (SSO) option enabled, you can use your corporate email for sign up. Go to the [<mark style="color:purple;">DecisionRules</mark>](https://www.decisionrules.io/) page. Click on the <mark style="background-color:purple;">**LOGIN**</mark> at the top of the page. A login page will appear where you click on the “SIGN IN WITH SSO” button and the Single Sign On page will show. Enter your organization's name and click “LOGIN VIA SSO” button.&#x20;

<figure><img src="/files/p44k6sgDOqhr8YZFoQx9" alt=""><figcaption><p><mark style="color:purple;">Single Sign On</mark></p></figcaption></figure>

You will be directed to the provider's login page to log in. After successful login you will be redirected to <mark style="color:purple;">DecisionRules</mark>.

{% hint style="info" %}
For detailed information about organization SSO please see our documentation [here](https://docs.decisionrules.io/doc/other/single-sign-on-sso).
{% endhint %}

#### *This part is for users that have been invited to someone’s space and do not have their account yet.*

You received an invitation in your email inbox. In it you will find all the details about the invitation.

<figure><img src="/files/i4lV960NLeoNYlDkiciQ" alt=""><figcaption><p><mark style="color:purple;">Space Invitation in Your Inbox</mark></p></figcaption></figure>

<figure><img src="/files/sVhkEBSLbEU1JHiyGiMv" alt=""><figcaption><p><mark style="color:purple;">Invitation Email</mark></p></figcaption></figure>

Click on the <mark style="background-color:purple;">**Join {name} Space**</mark> button. You will be redirected to create an account. Click "Create account" option. Fill in all the required fields and click  <mark style="background-color:purple;">**REGISTER**</mark>  button.


# Log in

Get to know more about log in options

There are multiple ways to log in to your account - using credentials provided on sign up, Google and Microsoft Sign-in and SSO (Single Sign On).

<figure><img src="/files/3OR0j9zSHRtQsIz9Rn5i" alt="" width="375"><figcaption><p><mark style="color:purple;">Login Screen</mark></p></figcaption></figure>

## Email and password

To log in to our application using your registered email address and password, simply go to [<mark style="color:purple;">DecisionRules</mark>](https://www.decisionrules.io/). Click on the  <mark style="background-color:purple;">**LOGIN**</mark>  button at the top right. A login screen will appear where you fill in the correct combination of email address and password. Then click on the  <mark style="background-color:purple;">**LOGIN**</mark>  button and you will be redirected to the application.

<figure><img src="/files/B57NQwWVGympgrthbPMa" alt=""><figcaption><p><mark style="color:purple;">Log in with credentials</mark></p></figcaption></figure>

## Google or Microsoft Sign in

With one click, you can log in to <mark style="color:purple;">DecisionRules</mark> with Google and Microsoft SSO. Simply click the button "SIGN IN WITH Google" or "SIGN IN WITH Microsoft". You will be redirected to Google or Microsoft login. After successfully logging in to your Google or Microsoft account, you will be redirected to your account in <mark style="color:purple;">DecisionRules</mark>.

## Organization Single Sign On

If your organization has the single sign-on (SSO) option enabled, you can use your corporate email for login. On the login page click the “SIGN IN WITH SSO” button and the SSO login page will show.

<figure><img src="/files/YriBXgM3v41NtXrnwPaN" alt="" width="375"><figcaption><p><mark style="color:purple;">SSO login page</mark></p></figcaption></figure>

Enter your organization's name and click “LOGIN VIA SSO”. You will be directed to the provider's login page to log in. After successful login you will be redirected to the Dashboard in <mark style="color:purple;">DecisionRules</mark>. For detailed information about organization SSO please see our documentation [here](https://docs.decisionrules.io/doc/access/cloud/single-sign-on-sso).

## Forgotten Password

In case you forget your login password, you can easily reset it. This is done by clicking on the  "FORGOTTEN PASSWORD" link on the login screen. You will be redirected to a password recovery page where you will enter the email address you wish to reset your password to. Click on the  <mark style="background-color:purple;">**SEND ME INSTRUCTIONS**</mark> button.

Within moments, an email will arrive in your inbox with a link to reset your password. Click the  <mark style="background-color:purple;">**Reset My Password**</mark>  button and a page will appear where you will enter your new password. Click the  <mark style="background-color:purple;">**SET NEW PASSWORD**</mark>  button. Now that your password is changed, you can log in with it.

{% hint style="info" %}
*The password reset email is valid for 15 minutes. After this time, you need to create a new password change request.*
{% endhint %}

<figure><img src="/files/Ww7JFmUxgG9K4rE9aQg6" alt=""><figcaption><p><mark style="color:purple;">Reset password</mark></p></figcaption></figure>


# Plans

Discover the benefits and differences between individual Plans that we offer

[<mark style="color:purple;">DecisionRules offers a range of subscriptions.</mark>](https://www.decisionrules.io/pricing/public-cloud) These plans come with defined limits, such as the number of rules you can create, the workspaces you can manage, and the users you can invite to collaborate with you. However, we understand that as your business logic expands, so do your requirements. When you reach these limits, you can seamlessly transition to a higher subscription plan that better matches your evolving needs, with just a few clicks.

In the following sections, you can find information about how to change your existing plan:

* [<mark style="color:purple;">**How to Change a Plan**</mark>](/account/plans/how-to-change-your-subscription)


# How to change your subscription

Do you want to switch to a higher plan or turn on a new addon, find out how to do that

## How to access your plan any time

To change your plan, you must first log into your account. At the bottom of your Space, click on the "Profile" button and select your Username. Your profile page will then appear. Click "Plans" on the left-hand side to see the available plans.

<figure><img src="/files/C7W0CfAX15saKiAPoJbp" alt=""><figcaption></figcaption></figure>

## How to change your subscription when the rule limit is reached

Running out of space? Once you have reached the limits of your plan, an "Upgrade" button will appear on your profile page Dashboard. Clicking "Upgrade" will redirect you to the plans page, where you can easily choose a higher plan to fit your business needs.

<figure><img src="/files/oD5rMMqjddnaRTvWS3xK" alt=""><figcaption></figcaption></figure>

{% hint style="info" %}
*Of course every business has its own needs, so do not hesitate to contact us for a tailored plan. You can simply click Premium on a page of plans.*
{% endhint %}

## Changing the plan

On the page of available plans, you can find your current plan alongside others, each with a description. Select the plan you wish to change to and click on the "Select Plan" or "Get a Quote" button. You can also check your current limits and permissions in the "Limits" section on the left-hand side of the page.&#x20;

<figure><img src="/files/NM2gLZwcn7SlbXKKkDgq" alt=""><figcaption></figcaption></figure>

You will need to finish setting up your profile. Once you have done this, fill out your payment details within the pay-gate and click the "Pay and subscribe" button.

<figure><img src="/files/sIOHbmOWMX8vCx105Alt" alt=""><figcaption></figcaption></figure>

After a successful payment you will be redirected back to the plan page. Now your plan has been changed and a new invoice was created. Click the “Invoices” button to see all your invoices.

{% hint style="info" %}
*When a plan is changed to a higher plan, the higher plan takes effect immediately. If the plan is changed to a lower plan, the lower plan will not take effect until the next billing period.*
{% endhint %}


# Billing Information

How to fill out your billing information

To upgrade your plan to any other than Free/Tiny you need to enter some information such as:

* Billing email
* Name or Company
* Address
* City
* Country
* Postal code
* TAX ID

There are two ways to do so. First option is to fill out the billing information in your profile, the second one is to provide the information when changing to another plan.

{% hint style="info" %}
*Some fields of the form are required or/and have a strict format.*
{% endhint %}

## 1. Complete your profile

In order to fill out your billing information, you must first log into your account.  At the bottom of your Space, click on the "Profile" button and select your Username. Your profile page will then appear. In the "General" section, enter your Billing Info and confirm your changes by clicking "Save".

<figure><img src="/files/XXSVTWWpZt48XG4mWF3x" alt=""><figcaption><p><mark style="color:purple;">Complete you billing information</mark></p></figcaption></figure>

## 2. Provide the billing information when changing to a higher plan

{% hint style="info" %}
*This option is for users who have not yet entered their billing information. Once you have completed your billing information, you will not need to enter it again if you change your plan.*
{% endhint %}

In order to fill in your billing information, you must first log in to your account. At the bottom of your Space, click on the "Profile" button and select your Username.  Click on the "Plans" section. A page showing the available plans will appear. Select the plan you want to switch to. A Profile window will then appear where you can enter your Billing Info. Confirm the information by clicking the "Save" button. You will then be redirected to the payment gateway to finalize the change.&#x20;

<figure><img src="/files/4o9MTjsLKUPuZgsgtVNF" alt=""><figcaption></figcaption></figure>

{% hint style="info" %}
*Some fields of the form are required or/and have a strict format.*
{% endhint %}


# What Is a Space?

Find out how you can differentiate rules for individual teams or projects

Spaces can be thought of as work areas, containing projects linked by a particular logic. Usually, spaces are used to define teams and connect different departments. Invite your colleagues to collaborate on your Space and assign roles and permissions to create seamless workflows for your projects.

{% hint style="info" %}
*The number of Spaces and Rules you can create, the users you can invite is determined by your Subscription.*
{% endhint %}

{% hint style="info" %}
A more precise definition: A Space is a container for a set of rules. Visually, it is the interface where you organize your folders and rules in one place. The goal of a Space is to clarify which rules share common settings (such as API Keys or Connectors) and can be connected to one another.
{% endhint %}

## First steps

In order to create your business rules you will need your workspace. One Space will be automatically created when you register your account, so you can start transforming your business logic into decision rules right away.

### New Space

If you need to create a new space for another project, or for testing your rules for example, simply click on your "*Space Name"* at the top left corner, next to our logo. A list of the Spaces you are a user in will appear. At the top right corner, click the  <mark style="background-color:purple;">**+ Space**</mark>  button, select destination and enter a name for the new Space. Click on the "Create" button and the new Space will be created.

<figure><img src="/files/ctPHwQmW9OZT1IGtMUOB" alt=""><figcaption></figcaption></figure>

### Switching between Spaces

If you are a user of several Spaces, you can switch between them freely. Click on the "*Space Name"* next to our logo. A list of all the Spaces you are a user in will appear. The list is divided into your own Spaces and those that someone else owns and has invited you to.

{% hint style="warning" %}
*Before switching to another Space, make sure you have saved your progress.*
{% endhint %}

## Space description

Each Space has its own configurations, so its unique dashboard, its own API keys, and its own business rules. It means as well, that you can combine the logic of the business rules in the same Space, using Decision Flows and Integration Flows. Each Space generate audit logs for individual rules and for the relation between these rules within Decision Flows. In addition, relevant information about the Space can be saved and manage.

Each Space has users working within it. The creator of the Space must invite these users and assign them specific roles. A set of permissions is given based on these roles. You can also share administrative responsibilities with other users.&#x20;


# Space Side Menu

Find out the main settings of your Space

The side menu in the main interface gives you access to four main sections:&#x20;

| SECTION           | CONTENT                                                          | PURPOSE                                                                  |
| ----------------- | ---------------------------------------------------------------- | ------------------------------------------------------------------------ |
| **Rules**         | Contains all decision rules in the Space.                        | Manage the specific rules for your current Space.                        |
| **Space**         | Contains the settings of the Space.                              | Adjust settings and features of that particular Space.                   |
| **Intelligence**  | Contains audit reports and dashboards for the rules in the Space | Analyse your rules individually or in group, create grounded strategies. |
| **Organizations** | Contains the settings to manage a set of several Spaces.         | Manage all capabilities of your Spaces and get a comprehensive overview. |

## Rules

The decision rules that you create belong to your Space. You can find your list of rules in the "Rules" section of the menu, where you can either filter the list by rule type or sort it by name or date created.

In addition, you can also organise your rules in Folder Structure, which is very similar to the file structure on your computer.

{% hint style="info" %}
*More about the Rule List in your Space can be found* [*<mark style="color:purple;">here</mark>*](https://docs.decisionrules.io/doc/rules/rule-list)*.*
{% endhint %}

<figure><img src="/files/Uo5ew2XDjLiviR6GgAc0" alt=""><figcaption><p><mark style="color:purple;">Business Rules</mark></p></figcaption></figure>

## Space

Simply click on "Space" and explore the menu of your Space, you will be taken to their sections as you click on the different options.

### Info

General data management for your Space can be found in the Info section:

* Space Name
* Space Owner
* Your Space Role
* Number of Rules
* Number of Users
* API calls per period

<figure><img src="/files/9WqoGOh9DusEzfMoGmQK" alt=""><figcaption></figcaption></figure>

### Access

On this section, you can manage individual users and their roles. You can either assign predefined roles, such as Admin, Editor and Reader, or create new custom roles with the  <mark style="background-color:purple;">**+ Add Role**</mark>  button. A Role contains a list of permissions granted to the user. See the [Users in Spaces](https://academy.decisionrules.io/spaces/users-in-spaces) section for more detailed information.

Invite new users to your Space using the   <mark style="background-color:purple;">**+ Invite Teammates**</mark>  option. First, select whether the teammate is a new user and assign the appropriate role. You can also manage the invitations in the bottom section of the Rules window.

{% hint style="info" %}
*The number of users you can invite is predetermined by your Tariff Limit, which is compared to the sum of existing users and unique invitations.*
{% endhint %}

{% hint style="warning" %}
If you are using an Organization, the management of access and precise roles is handled in the Organizations' settings, not in this Space menu.
{% endhint %}

### API Keys

API Keys are an integral part of your Space. These are unique keys that are used for authorization when calling rules. Particularly, from an external tool.

There are three types of API Keys in <mark style="color:purple;">DecisionRules</mark>:

* Solver API Key
* Management API Key
* Business Intelligence API Key

The <mark style="color:purple;">Solver API Key</mark> is the most important, it gives you access to send requests that activate your decision rules and return output data.

{% hint style="info" %}
*This kind of key is used every time you solve your rule using the Test Bench. You may notice that this kind of key is generated automatically when a new Space is created. So you can build and test your rules right from the start.*
{% endhint %}

<mark style="color:purple;">Management API Keys</mark> are used for read and write access to your rules. They allow you to change parameters or values in your rules, add tags or change the status of a rule. You can create a new Management API Key by clicking on the  <mark style="background-color:purple;">**+ Add API Key**</mark>  button on API Keys section.

Use <mark style="color:purple;">Business Intelligence API Keys</mark> to access Audit Logs - data about the solving of your rules. In addition to output data, you will also receive additional metadata about individual rule solves. You can create a new Business Intelligence API Key by clicking on the same  <mark style="background-color:purple;">**+ Add API Key**</mark>  button on API Keys section.

<figure><img src="/files/ErdPUvcL5Z5iMTDWFj9Z" alt=""><figcaption><p><mark style="color:purple;">API Keys</mark></p></figcaption></figure>

### Jobs

When an asynchronous process is required, you can run your flows and then work on something else while they are running. The Job is the ticket to check the progress of your rules. This section manages all your jobs, their descriptions, statuses and results.

{% hint style="info" %}
To dive on the logic of asynchronous processes you can check our [Integration Flow](https://academy.decisionrules.io/rule-types/integration-flow).
{% endhint %}

### Connectors

The integration of DecisionRules with your particular database is possible through the native Connectors. If you want to access another database while making a decision, you can add a REST API or Connector section. The management of Connectors is provided in this section.

### Webhooks

Still related with asynchronous processes, this section allows you to create webhook links to receive a real-time report when your jobs are complete. Remember, webhooks are used in Integration Flows.

<figure><img src="/files/cfpsIvZglvDk3cfYYdKY" alt=""><figcaption></figcaption></figure>

### Audit

Auditing your company's activity within the platform is possible through the **Audit** feature in your Space. All audit data generated by your team, whether changes to rules or API integrations, is kept in this section.

At the top, the main menu features two tabs: **Event Logs** and **Service Logs**. The former tracks changes made to rules, such as creation, updates, deletions, and sharing. The latter shows records of all API calls made within the Space.&#x20;

<figure><img src="/files/vqbTQ9tgDCaVPHZ011HE" alt=""><figcaption></figcaption></figure>

If you click on an Event, a right-side panel will open where you will find two additional useful features. These are based on the log data structure in DecisionRules: every Event Log entry has a parent Service Log, and one Service Log can contain multiple child Events.

* **Correlation ID:** A unique identifier shared by every record produced by a single API call.
* **Related Log:** From an Event entry, click *Inspect Service Log* to jump to the API call that produced it. The reverse is also possible from the Service Log view.

<figure><img src="/files/sCd4kz1uLmwBqU88zpjI" alt=""><figcaption><p><mark style="color:purple;">Audit Logs</mark></p></figcaption></figure>

{% hint style="info" %}
For details on the different toolbar options or other functionalities in this view, our [documentation](https://docs.decisionrules.io/doc/space/events-logs-service-logs-and-notifications) offers a complete explanation.&#x20;
{% endhint %}

### Tests

A key capability in DecisionRules is **Rule Testing**. It allows you to verify rule behavior against saved scenarios. Each scenario uses a fixed input and expected output. You can rerun these same checks after any change to ensure consistency.

Individual tests belong to a single rule. At the Space level, it is possible to view all current tests by navigating to this setting.

The view has two tabs:

* **Tests:** This tab displays the structural organization of your testing assets, including individual Tests, Test Suites (groups of tests), and the Rules they are associated with.
* **Test Runs:** This tab provides a historical log of all test executions performed within the Space, allowing you to review past results and diagnose regressions.

<figure><img src="/files/TR4JQ2vmOSyoMJN9Pcsr" alt=""><figcaption></figcaption></figure>

{% hint style="info" %}
For more information about the features in your Space Menu read our [documentation](https://docs.decisionrules.io/doc/space/spaces).
{% endhint %}


# Users in Spaces

Get to know more about how you can limit control access and permissions for all users of DecisionRules

Work with your employees and colleagues in your Spaces and create dynamic environments. Thanks to the accessibility within <mark style="color:purple;">DecisionRules</mark>, you can create teams that work together independently of where your colleagues are.

In the following sections, you will find information about inviting other users and creating and managing roles with specific permissions.

* [<mark style="color:purple;">**Invitations**</mark>](/spaces/users-in-spaces/invitations)
* [<mark style="color:purple;">**Roles**</mark>](/spaces/users-in-spaces/roles)


# Invitations

How to invite your colleagues to collaborate

Two heads are better than one. Invite your colleagues and teammates you want to collaborate with to your space.

## 1. You want to invite other users

To invite other users to your space, log into your account and click on the  <mark style="background-color:purple;">**+ Invite Teammates**</mark>  button at the top right-side corner of your Space. A window will open with the title 'You are Inviting into {name} space'.&#x20;

{% hint style="info" %}
*Note that plans have limit for number of users you can invite to your space.*

*More information about Tariff Limits can be found* [*<mark style="color:purple;">here</mark>*](https://www.decisionrules.io/pricing/public-cloud) *and* [*<mark style="color:purple;">here</mark>*](https://app.decisionrules.io/profile)*.*
{% endhint %}

To invite another user, simply complete the configuration process. First, select any users with whom you have shared spaces previously; if you are inviting a new user, select "New User". Insert their email address of the person you want to collaborate. Select the role you want to assign to the new user and confirm with the “Invite” button. Invitation will be sent to the email address provided.

<figure><img src="/files/qH4NJApbw9dAswh2IXED" alt=""><figcaption><p><mark style="color:purple;">Invite a user to you space</mark></p></figcaption></figure>

Every new invitation will appear at the bottom of the page, where you can manage them and track their status. Once a user accepts your invitation, the status of the invitation is no longer "pending" and the user is moved to 'Users' where you can edit their role.

To delete a pending invitation or user from the space, click on the ![](/files/3NgSxXoJbCVXb3AiCtB1) button next to the user’s name.

<figure><img src="/files/giQLKkORR0rzRa77yNj6" alt=""><figcaption><p><mark style="color:purple;">Delete a user from your space</mark></p></figcaption></figure>

<figure><img src="/files/BJJM3BdU4N2N0cJA1yGq" alt=""><figcaption><p><mark style="color:purple;">Delete a pending invitation</mark></p></figcaption></figure>

## 2. You are invited

After another user invites you to the space, an invitation arrives in your inbox.

<figure><img src="/files/LrvtXo1Hs5Qncgx7thKf" alt=""><figcaption><p><mark style="color:purple;">Space invitation in your inbox</mark></p></figcaption></figure>

&#x20;

<figure><img src="/files/sVhkEBSLbEU1JHiyGiMv" alt=""><figcaption></figcaption></figure>

Inside is a link that will take you to the decisionrules.io login page. After logging in, you gain access to the space you were invited to.


# Roles

Manage access and permissions for users within the space

Use Roles to assign specific permissions to the users invited to your space.&#x20;

{% hint style="warning" %}
If you are using an Organization, the management of access and precise roles is handled in the Organizations' settings, not in this Space menu.
{% endhint %}

There are two ways to assign roles within the Space menu, you can either create a new custom role for the user or use one of our predefined roles. In addition, when creating new roles, you can use the predefined roles as templates that you copy to modify just a part of the permissions. See below for more details on the two types of role.

You can find role settings and assignment of roles under "Access" in the left sidebar menu of your Space settings.

<figure><img src="/files/O5PwriUR8qKdam9Y2BEh" alt=""><figcaption><p><mark style="color:purple;">Access Roles from the side menu</mark></p></figcaption></figure>

By assigning a role, you determine how individual users can interact with your space, your decision rules and other features. To assign a role to a user click on the 'Role' dropdown list next to the user’s name.

<figure><img src="/files/sRhwTex8Ke5ryTmm9qtz" alt=""><figcaption></figcaption></figure>

{% hint style="info" %}
*You can not change the role of the space owner*
{% endhint %}

## Predefined roles

A user with the <mark style="color:purple;">Admin</mark> role is allowed to perform all activities in the space and has access to all rules and features. The <mark style="color:purple;">Editor</mark> has the same rights as the Admin except for setting up the space, managing users, and deleting API Keys. <mark style="color:purple;">Reader</mark> is allowed to just view the data and settings in each feature.

## Creating a new role

As mentioned, you can create new user roles for your project. You can create them in two ways. You can also edit the permissions of these roles at any time.

One way is by copying one of our predefined roles, where you can modify part of the permissions. In the example below, a new role similar to the Editor will be created, but the user will only be able to work with decision table rules.<br>

<figure><img src="/files/TPvNHF05Xoj56QdVYQcT" alt=""><figcaption><p><mark style="color:purple;">Creating a role from a template</mark></p></figcaption></figure>

The other way is to create a completely new role where you customize the permissions as needed. For example, you can create a new role where the user is only allowed to work with Decision Trees, plus they can change the space settings.

<figure><img src="/files/NEokqdGJFHZSjXuhHnQY" alt=""><figcaption><p><mark style="color:purple;">Creating a role from scratch</mark> </p></figcaption></figure>

If you no longer need them, you can delete any roles except the predefined ones. Click the ![](/files/3NgSxXoJbCVXb3AiCtB1) button next to the selected role and confirm to delete the role.


# What Is an Organization?

The initial steps for working with organizations

An Organization is a management interface designed to set up several Spaces at one place. This feature is designed to allow company executives to unify the management and control of all Spaces in one central menu.&#x20;

**If you already have several Spaces and several users**, it is time to start, this feature will be one of your more useful tools.&#x20;

{% hint style="info" %}
Because the goal is centralisation, usually an enterprise will use just one Organization.
{% endhint %}

## First Steps

Unlike your first Space, no Organization is created automatically. Condition to start the construction of your Organization network, is that this capacity must be part of your subscription plan. Once the activations are ready, we can start with the creation of a new Organization.

### New Organization

Go to your DecisionRules side menu and click on "Organizations". A new window with a list of all your Organizations will open. To create a new one, go to the top right side of your window, and click on  <mark style="background-color:purple;">**+ Create Organization**</mark> . The app will require from you the name of the new Organization and its description. When the two fields are complete, select the "Create" button. &#x20;

Now you can press the new item that appeared in your list. The menu of your new Organization will open.&#x20;

<figure><img src="/files/NKLj8KI1EEcrPX0RHxXK" alt=""><figcaption></figcaption></figure>

### Switching between Organizations

If you want to return to the Organization List, to switch to the settings of another organization, just click on the Organizations section in your side menu again.

<figure><img src="/files/HMKIhIokz4HL47qcLaR0" alt=""><figcaption></figcaption></figure>

## Organization description

Before connecting Spaces and roles, or changing settings, try to design your organization in a paper or canvas. How many Spaces you have, which members, for which kind of rules? Draw your designs according to your form of thinking, maybe you like graphs, or indexes, or poems.&#x20;

Once you have a clear picture of your expectations, you are ready to build your Organization. The main four structures are:

1. Members with specific roles at the organization level&#x20;
2. Members with specific roles at the spaces level
3. The organization of your Spaces in Departments&#x20;
4. Secure core info like the billing data or the SSO settings.  &#x20;


# Building an Organization Part 1

On this page, we will build a sample Organization to learn how to use and navigate each section of the Organization menu.

The options in your menu are:

* [Members](#members)
* [Resources](#resources)
* [Departments](#departments)
* [Policies](/organizations/building-an-organization-part-2#policies)
* [Statistics](/organizations/building-an-organization-part-2#statistics)
* [Settings](#settings)

On this page, you will learn to use each of these options directly through the creation of a concrete mock Organization. To offer clarity on the main building blocks, you will find a group of useful definitions at the beginning of each section.

We can start by [creating a new Organization](/organizations/what-is-an-organization#new-organization) called: ***orgAcademy***. We will focus on a possible use case for Risk; for this mock example, we will require 5 users and 3 Spaces.&#x20;

{% hint style="info" %}
For detailed technical specifications regarding these functionalities, please refer to the official [documentation](https://docs.decisionrules.io/doc/organization/members).&#x20;
{% endhint %}

## Members

#### Definitions

* **Members:** A member is a user with access to some of the Spaces in your organization or to the settings of the organization. The access is given through the user's email address.&#x20;
* **Status:** Each member is at each time only in one of the three main status: Active, Inactive, Pending. This status describes the existence of the member in the Organization.&#x20;
* **Organizations Roles:** The [four possible roles](#four-organization-roles) within an organization define the four set of permissions a specific member can receive.

#### Construction

People are the heart of any Organization, so we will start by adding all the users who will participate.

First, click on "Members" in the left-hand menu. On the new screen, navigate to the far right and click the button in the top corner:  <mark style="background-color:purple;">**+ Invite Member**</mark> .&#x20;

Now, you can fill in the information to register your first user. In this example, the user is a risk manager who will update risk standards in Decision Tables. You will need:

1. Email address: (e.g. <user.one@decisionrules.io>)
2. Role of the user at the Organization level: (e.g. Member)

Don’t worry about the "Team" field for now; simply select **"Invite."** You are all set!&#x20;

<figure><img src="/files/YDzj5R6kv1UjNDscNnHv" alt=""><figcaption></figcaption></figure>

{% hint style="info" %}
A notification will pop up after the invitaion to confirm that you understand the steps your users must follow to accept the invitation.
{% endhint %}

You can follow these same steps to invite the remaining members.

| User description                                                        | Email Address                 | Organizations Role |
| ----------------------------------------------------------------------- | ----------------------------- | ------------------ |
| A risk consultant that change the risk standards on the Decision Tables | <user.two@decisionrules.io>   | Member             |
| A risk director in charge of the approvals                              | <user.three@decisionrules.io> | Admin              |
| A developer in charge of the integrations                               | <user.four@decisionrules.io>  | Member             |
| A developer in charge of the integrations                               | <user.five@decisionrules.io>  | Viewer             |

{% hint style="info" %}
**A Note on Terminology:** The term "Member" has two meanings. It is the general name for users within an Organization, but it is also the name of the Role for the most basic permission level.
{% endhint %}

The new members will appear in your list of members, showing their status, role, and other relevant data.

#### Viewing and Modifying Members

* **To View Profiles:** Click on a member's email address. A **details panel will appear**, allowing you to inspect specific user attributes.
* **To Revoke Access:** If you need to remove a user or cancel an invitation, click the **three-dot icon (⋮)** on the right side of the member row and select the remove option from the action menu.

<figure><img src="/files/8GertVN1gwlBhnqj70zs" alt=""><figcaption></figcaption></figure>

## Resources

#### Definitions

* **Spaces:** A Space is a container for a set of rules. Visually, it is the interface where you organize your folders and rules in one place. The goal of a Space is to clarify which rules share common settings (such as API Keys or Connectors) and can be connected to one another.
* **Teams:** A Team is a group of members. Teams offer an advantage because they save time and effort; instead of setting up members one by one, you can simply change a Team's configuration and all members will automatically inherit the new properties.
* **Space Roles:** The two default roles (Editor and Reader) define two basic sets of permissions for members within a Space. At the Space level, you can also create more granular roles according to your preferences.

#### Construction

#### Creating Spaces

The second step is to create the Workspaces where your members will manage the rules.\
Click on "Resources" in the left-side menu. The first tab you will see on this screen is "Spaces". Navigate to the far right and click the button in the top corner:  <mark style="background-color:purple;">**+ Add Space**</mark> .&#x20;

To give existence to your Space, only one field is mandatory: The Space Name.&#x20;

We will call the first Space: **Risk Development**. Although the other two fields are optional, we can establish a stable structure by assigning members right away. For this Space, all five members will have access with the **Editor** role. Once this is done, select "Create".

{% hint style="info" %}
Note: The options available in the Team and Role dropdown lists depend on your configurations in the Teams and Space Roles tabs.
{% endhint %}

<figure><img src="/files/H4JUfO9avicZyqavYNA6" alt=""><figcaption></figcaption></figure>

Repeat the process for the other two Spaces:

| Space Name      | Members and roles                                                                                                                                                      |
| --------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Risk Testing    | <p><user.one@decisionrules.io>: Editor<br><user.four@decisionrules.io>: Editor</p><p><user.three@decisionrules.io>: Editor<br><user.five@decisionrules.io>: Editor</p> |
| Risk Production | <p><user.three@decisionrules.io>: Editor<br><user.five@decisionrules.io>: Editor</p>                                                                                   |

{% hint style="info" %}
If you want more restrictions, some members can be assigned as a **Reader** (as the name suggests, they can see rules but lack permission to make changes).&#x20;
{% endhint %}

#### Managing Teams

Thinking of future use cases, we want to create a team for Developers to help build Spaces faster. Switch from the "Spaces" tab to the "Teams" tab. Again, go to the far right and select  <mark style="background-color:purple;">**+ Add Team**</mark> in the top corner. Only the Name and Color of the Team are mandatory. For this instance, our team will use the purple color and the name: **Devs**.

<figure><img src="/files/45y3i9qU2iyYuEH2HVm2" alt=""><figcaption></figcaption></figure>

Description, Department, and Members are optional (in fact, teams can be empty). After the team is created, you can always edit these fields, including the name and color.

#### Defining Advanced Space Roles

Finally, switch to the "Space Roles" tab. Go to the top right corner and click  <mark style="background-color:purple;">**+ Add Role**</mark> . We want to create a specific new role, called: **Trees Master**.&#x20;

In the role editor, begin by entering the name. Since we want a highly customised set of permissions, switch from "Simple Permissions" to "Advanced Permissions". We will enable the following capabilities for this role:

* *Basic Rule Permissions:* Create Rule, Import Rule, View Rule settings.
* *Decision Trees:* (All permissions).
* *Test Bench:* Run Test Bench.
* *Tests:* Create/Edit Test, View Test Run.

Select "Create" and our new role is ready.&#x20;

<figure><img src="/files/ptfYlxEc5ix4mXD7JkPm" alt=""><figcaption></figcaption></figure>

From now on, you can assign this Space role to any of your members.

## Departments

#### Definitions

* **Departments:** A department is a subset of the resources within the Organization. It provides management control over a specific group of Spaces, including control over teams and roles restricted to that group.

#### Four Organization Roles:

* Definitions for each role:
  * **Member:** The entry-level role. A user with this role cannot see any Organization-level information; they are limited to receiving Space roles and working within those assigned Spaces.
  * **Viewer:** This role has the same permissions as a Member, plus the ability to view Organization settings.
  * **Admin:** This role includes Viewer permissions, plus the ability to manage members, resources, and policies throughout the Organization.
  * **Owner:** This role has the same permissions as an Admin, plus the ability to view and change Billing information, the Organization’s name, and other core settings.
* **Manager:** This is a specialized role designed to grant Admin permissions to a user with a Viewer role, but only within specific departments.&#x20;

#### Construction

For our sample Organization: ***orgAcademy***, we will create a demonstration department called: **Non-prod environments**.

Click on **"Departments"** in the left-side menu. Navigate to the far right and click the top-corner button:  <mark style="background-color:purple;">**+ Add Department**</mark> . To give existence to your department, only the Department Name field is mandatory. Once named, the department can be created.

<figure><img src="/files/gV3H7E5NWD1zxxs1i0DR" alt=""><figcaption></figcaption></figure>

{% hint style="info" %}
You do not always have to assign a Manager, because any Admin in the Organization already has the authority to control any department.
{% endhint %}

#### Step-by-Step: Assigning Spaces to Departments

Now, click on the department's name and **a new panel will open** with tabs similar to the [Resources](#resources) section. From here, you can either repeat the previous process to create new Spaces for this department, or you can edit existing Spaces to assign them here. We will demonstrate the latter.

1. Click on "Resources" in the left-side menu.
2. Select the Space you want to edit. A new window displaying the users of that Space will appear.
3. Go to the far right and click the top-corner button: **Update Space**.
4. In the settings module that pops up, change the Department option to **Non-prod environments**.
5. Select **"Update"** and the process is complete.

By grouping Spaces into Departments, you can now apply more granular administrative controls and keep your decision-making environment organized.

<figure><img src="/files/YWTtkzRRsOrZSJcpZGIG" alt=""><figcaption></figcaption></figure>

**Congrats!** The basic settings for your Risk Spaces are complete and your team can begin rule creation right away. Before checking the Rule features, however, we will finish our tour of the Organization menu on the next page to understand the sources of reports and core information.

***


# Building an Organization Part 2

On this page, we will continue with the construction of our sample Organization and the final relevant settings

So far, the main structure of our ***orgAcademy*** Organization has been created; it is already enough to start working and getting results. In the next three sections, we will look at a more complete management overview of our sample.

## Policies

#### Definitions

* **Policy:** A policy is a record of one role assigned to one member within a specific Scope (a Space or Department).
* **Assignments:** Based on this definition, assigning the same role to another member creates a new policy. Similarly, if you assign a new role to the same member in the same Space, you generate a new policy. In this way, policies keep a granular record of all role assignments across all Spaces.
* **Policy Types:** There are two types of policies:
  1. Space Policies
  2. Department Policies (Only for [Manager role](/organizations/building-an-organization-part-1#four-organization-roles) assignments).

{% hint style="warning" %}
**Permission Logic:** In DecisionRules, permissions are **additive**. If a member is assigned two different roles within the same Space, the member will possess the combined permissions of both roles.
{% endhint %}

#### Construction

Click on **"Policies"** in the left-side menu. A new screen will open, and the list of all your policies will appear. This list has been populated automatically with each new Space creation.&#x20;

The utility of this section is to view the information of all members, their roles per Space, and their Space access in one single place.

<figure><img src="/files/K9QeloQ2aqrwpwBeqDAx" alt=""><figcaption></figcaption></figure>

Another advantage is the possibility to create policies directly from this section. We will show an example: We will create a policy for the next assignment.

> **ASSIGNMENT:** The **Trees Master role** to the **Devs Team** in the **Risk Production Space**.&#x20;

1. Navigate to the far right and click the top-corner button: <mark style="background-color:blue;">**+ Create Policies**</mark>.
2. In the settings module that appears, select the corresponding Space, Member(or Team), and Role.
3. Click **"Create"** and the process is complete.

<figure><img src="/files/6lUPR7aHeRKhMAtVld4w" alt=""><figcaption></figcaption></figure>

## Statistics

The **Statistics** module provides a clear, high-level overview of your Organization’s activity, specifically focusing on API consumption metrics.

* **API Usage Dashboard:** Monitor the total volume of API calls made across the entire Organization. This data can be filtered and visualized according to your needs.
  * **Custom Time Intervals:** To view data for a specific date range, click the "Current Billing Period" button. By switching from **Relative** to **Absolute**, you can define a precise custom timeframe for your report.
  * **Granular Filtering:** You can refine your statistics to see exactly how individual Spaces are performing. Simply use the Space selector at the bottom of the dashboard to filter the records by your chosen work environments.

<div><figure><img src="/files/dA6ZY4hDSfJ4VcsyI7PT" alt=""><figcaption></figcaption></figure> <figure><img src="/files/4zSzQHMGmCKBdwAHM6ci" alt=""><figcaption></figcaption></figure></div>

<figure><img src="/files/XRkucAofa9BgvsDf0p0r" alt=""><figcaption></figcaption></figure>

By regularly monitoring these statistics, you can ensure your Organization remains within its limits and track the growth of your decision-making traffic.&#x20;

## Settings

#### Definitions

* **SSO (Single Sign-On):** A centralized authentication protocol that allows users to access DecisionRules using their corporate credentials. This enhances security and eliminates the need for users to manage individual platform accounts.&#x20;

#### Organizations Overview

The settings interface displays basic information about the Organization: Name and ID, subscription and billing details, configuration options for Single Sign-On (SSO), and the ability to delete the Organization.

In this introduction, we will simply explore how to modify the name and description.&#x20;

To finalize our setup for ***orgAcademy***, let's update the Organization’s profile:

1. Navigate to the "Organization Info" tab.
2. Locate the details card (containing the Name and ID) and click the **Edit (pencil)** icon.
3. A configuration module will appear. Here, you can refine the Organization Name or add a professional description for your team.
4. Click "Update" to save your changes.

<figure><img src="/files/3YWuZ7AHXSGfubBUt6e0" alt=""><figcaption></figcaption></figure>

{% hint style="info" %}
**Note:** While updating text fields is straightforward, other modules (like SSO or Billing) will require specific technical or financial data to complete.
{% endhint %}

***

## Conclusion

**Congratulations!** You have successfully built the foundation for ***orgAcademy***. With your Members invited, Resources organized, and Policies defined, your environment is fully optimized. Your team is now ready to begin the rule-creation lifecycle.

In the next section, we will transition from Organization management to **Rule Features**, where the real decision logic begins.


# What is a Rule?

Understand what is a rule, its types, and how you can create and manage it

The term 'rule' is used as a shorthand term for 'decision rule' or 'business rule'. A decision rule is a logic of instructions or conditions for making a decision over a set of predefined outputs. Decision rules provide a useful and fast way to process decision-making according to an institution's guidelines.&#x20;

## Rule Types

There are several types of rules in <mark style="color:purple;">DecisionRules</mark>, and each can be used to create a different type of decision. For simple decisions following an IF - ELSE logic you can use [Decision Trees](https://academy.decisionrules.io/rule-types/decision-trees). For retrieving information by simple key-base search, you can maintain your data with [Lookup Tables](https://docs.decisionrules.io/doc/rules/lookup-table). For more complex logical processes use [Decision Tables](https://academy.decisionrules.io/rule-types/decision-tables), where each row corresponds to some combination of conditions and results.

Our business rule engine combines both, a low-code engine that does not require knowledge of programming languages, and an engine that still allows you to apply such expertise. One type of rule we do offer is a [Scripting Rule](https://academy.decisionrules.io/rule-types/scripting-rules), whose content is JavaScript code. This is a rule that allows you to enhance your decision-making process.

Lastly, we also offer the category of 'Rule Flows'. These are a special type of rules, where you can create an entire flow of decisions that share a common logic. [Decision Flow](https://academy.decisionrules.io/rule-types/decision-flow) is the rule that easily link individual rules together in the form of 'Nodes', as they logically follow each other, and solves your requests in real time. The design of the [Integration Flow](https://docs.decisionrules.io/doc/rules/flow/decision-flow-vs.-integration-flow) is similar, but oriented to long-running processes and database batch processing. &#x20;

Integrating AI capabilities in your decision-making process can be helpful when the user prefers to describe the rule in natural language rather than defining explicit conditions and outcomes.    Use our [AI Agent Rule](https://www.decisionrules.io/en/product/ai-agent/) to get typed-structured JSON response from informal rule descriptions. &#x20;

{% hint style="info" %}
Nodes are relevant rule blocks building the Flows, more about the possible nodes in your palette [here](https://docs.decisionrules.io/doc/rules/flow/flow-nodes-overview).&#x20;
{% endhint %}

## Rule Structure

Each rule consists of three main parts:

#### Rule Model

Our decision rules are built according to the *input/output* model. The structure of the rules implies the reception of an input and the returning of an output.&#x20;

In the Model part of your rules you can specify the data you will send to the rule as input and then receive back as output. There, you can also access the settings of the rule, where you manage its name, alias and status, enable audit logs and other features.

#### Rule Designer

In the Rule Designer interface, you create the rule itself. Based on the rule type, you create individual rows (Decision Table), blocks (Decision Tree), lines of code (Scripting Rule) or combine rules into one larger decision unit (Flows). The one feature of Rule Designer that is common to all rule types, and one of the main advantages of <mark style="color:purple;">DecisionRules</mark>, is the Test Bench.

#### Rule Tests

A crucial practice creating and updating a rule is testing it. In the Tests interface of your rule, you can create test samples, defining the inputs the rule will run and the expected outputs. You can collect dozens of tests on different Test Suits to evaluate different scenarios at once. The results are given with a comparison match between the current output and the expected ones according to each input.

To switch between the different parts of your rule interface, go to the center of your top-bar.

<figure><img src="/files/YdWO8CfCEHd0S8i2ErHv" alt=""><figcaption></figcaption></figure>

## Test Bench

This is an *input/output* editor that makes it easy to test the behavior of your new or existing rules when you insert certain input data. You can either enter data using a simple editor or you can use a JSON editor where you can put the entire input in JSON format.

## Share and Connect Rules

You can share your rules between spaces in two forms. First, if you are a user of the spaces in question, you can share directly in <mark style="color:purple;">DecisionRules.</mark> Go to the folder structure, your Rules List, and click on the context menu button  <mark style="background-color:purple;">**...**</mark>  corresponding to that rule, a dropdown menu will appear, select the 'Share with space' option.

Second, use the [export-import](https://academy.decisionrules.io/rules/export-and-import-of-the-rules) feature to download your rules and import them wherever you need them. By downloading as a JSON file to your local repository, you also create a backup for your rules.

Access your rules through REST API requests using external tools. Easily connect the DecisionRules engine to your existing logical processes. The most important connection is to make an external request for solving your decision rules and get an output for your team. You can send a request with the Solver API, which is located in the button  <mark style="background-color:purple;">**+ Integrations**</mark>  at the top bar of your rule. &#x20;

<figure><img src="/files/EFA9Zio2LwogEtWZze4X" alt=""><figcaption></figcaption></figure>

{% hint style="info" %}
*For more information about the API, see the documentation in the* [*API section*](https://docs.decisionrules.io/doc/api/api-introduction)*.*
{% endhint %}


# Export & Import of the Rules

How to migrate and share your rules

Export and import comes in handy if you want to move rules between spaces, add new rule versions, or create entirely new rules. For example, if you export decision tables in XLSX format, you can easily store data in your decision tables using Excel or Google Sheets. Or you can use a file import to create new rules in your spaces.

See the sections below to discover ways to migrate your rules between your spaces or environments.

* [<mark style="color:purple;">**Export Rule**</mark>](/rules/export-and-import-of-the-rules/export-rule)
* [<mark style="color:purple;">**Import Rule**</mark>](/rules/export-and-import-of-the-rules/import-rule)


# Export Rule

### Exporting from Rule List

As you know, your decision rules can be accessed from the “Rules” in the left sidebar menu. From there you can export your rule by clicking on the context menu button  <mark style="background-color:purple;">**...**</mark>  according to that rule, and choosing <mark style="background-color:purple;">**Export**</mark> .

<figure><img src="/files/7XvDgypcv09k20Y79Aer" alt=""><figcaption><p><mark style="color:purple;">Export Rule from Rule List</mark></p></figcaption></figure>

### Exporting from Rule Structure Design

At the top bar of your 'Rule' you can do various actions. Select the context menu button  <mark style="background-color:purple;">**...**</mark>  and a dropdown list will appear. Click on  <mark style="background-color:purple;">**Export**</mark> .

<figure><img src="/files/MWtWLKPBkQJOWGi8H86m" alt=""><figcaption><p><mark style="color:purple;">Export Rule from Rule Structure Design</mark></p></figcaption></figure>

## Choose export format

### Choosing export format of Decision Table:

When exporting the decision table you can choose from two different file formats based on your further actions. For transporting rules to another space you can choose JSON format. If you want to modify a decision table and for example input more data in it, choose XLSX format.

### Choosing export format of other Rule types:

Other rule types - Rule Flows, Decision Tree and Scripting rule have a single export option - JSON format. These types should be created and modified in the DecisionRules application.

Once you choose the right format, your export will start automatically. The exported file can be found where your browser stores downloaded files.

{% hint style="info" %}
*These are manual methods of exporting rules. Using Management API methods and external tools you can export rules in one click. More information about API functioning can be found in documentation link* [*<mark style="color:purple;">here</mark>*](https://docs.decisionrules.io/doc/api/api-introduction)
{% endhint %}


# Import Rule

When importing a rule, you can create a new rule, a new version of an existing rule, or overwrite an existing rule version.

{% hint style="info" %}
*For Decision Tables, the rule file can have the formats: <mark style="color:purple;">JSON</mark> or <mark style="color:purple;">XLSX</mark>. Other rule types: Decision Tree, Scripting Rule, Decision Flow and Integration Flow have a single export option - <mark style="color:purple;">JSON</mark> format.*
{% endhint %}

### Importing a new rule

Create a new rule in three places:

1. Import the rule in the folders structure directly. Open "Rules" on the side menu. In the folders structure of your Rule List you can find the  <mark style="background-color:purple;">**...**</mark>  button next to  <mark style="background-color:purple;">**+ Create**</mark>  in the search bar. Click on the  <mark style="background-color:purple;">**...**</mark>  and press  <mark style="background-color:purple;">**Import**</mark> . A new rule will be created immediately.&#x20;

<figure><img src="/files/vW6ERMpaR2KIe7M5cCm7" alt=""><figcaption><p><mark style="color:purple;">Import a Rule in Folder Structure</mark></p></figcaption></figure>

When you click on “Import”, you will be prompted to drop or choose a file from your system containing the rule.

<figure><img src="/files/nbfMaDR98eYoNcE22nze" alt=""><figcaption></figcaption></figure>

Once your rule file has been selected, click the <mark style="background-color:purple;">Import</mark> button.

{% hint style="info" %}
*You can import one file at a time.*
{% endhint %}

### Import a new version or overwrite an existing version

#### Import to:

You can import a rule as a new version of an existing rule, when you import the rule through a currently existing rule:

1. For using an existing rule you have two methods. First, Open "Rules" on the side menu. In the folders structure of your Rule List you can find a  <mark style="background-color:purple;">**...**</mark>  button corresponding to each rule. Click on the correspondent  <mark style="background-color:purple;">**...**</mark>  and press  <mark style="background-color:purple;">**Import**</mark> . Now, you can either create a new version of the rule or overwrite over the existing version.&#x20;

<figure><img src="/files/8Qf1K4fKv2docrtpycVD" alt=""><figcaption><p><mark style="color:purple;">Import a Rule in Folder Structure</mark></p></figcaption></figure>

2. Or just open your particular rule. Go to the top bar menu and select  <mark style="background-color:purple;">**...**</mark>  next to  <mark style="background-color:purple;">**+ Integrations**</mark> . A dropdown menu will appear. Select  <mark style="background-color:purple;">**Import**</mark> , and you have two options, create a new version of the rule or overwrite over the existing version.&#x20;

<figure><img src="/files/rAAjZ0ySOB5m89BCZF6v" alt=""><figcaption><p><mark style="color:purple;">Import a Rule in Business Rules</mark></p></figcaption></figure>

**Import version**

When you click on “Import”, “Import version dialog” will appear. There you select if you want to import the file to:

1. Create a new version of the rule
2. Overwrite an existing version

{% hint style="danger" %}
*Overwriting the version is an irreversible action, the overwritten rule is lost. Please use this option wisely.*
{% endhint %}

After selecting the method of import drop or choose a file from your system containing the rule.

<figure><img src="/files/sWNRVRvCZ8FBOnRsL8oT" alt=""><figcaption></figcaption></figure>

{% hint style="info" %}
*You can import one file at a time.*
{% endhint %}

{% hint style="info" %}
*These are manual methods of exporting rules. Using Management API methods and external tools you can export rules in one click. More information about API functioning can be found in documentation link* [*<mark style="color:purple;">here</mark>*](https://docs.decisionrules.io/doc/api/api-introduction)
{% endhint %}


# Decision Tables

## Introduction

Decision Tables are our most popular decision rule type as they are the market standard of decisioning. Thanks to their similarity to Excel and Google Sheets, Decision Tables are easy to learn, yet they can make more complex decisions. Decision Tables are by far our most scalable rule type.&#x20;

The Decision Tables have a really friendly interface, excellent for any non-technical person who has experience with Excel or Google Sheets. As you can see here it is nearly identical to a real table.

<figure><img src="/files/uFVeMtSTeg0XgY05HZNH" alt=""><figcaption></figcaption></figure>

## Decision Table Designer

As already mentioned, the Decision Table is very similar to an Excel table - it is also divided into columns and rows and you can enter values or functions into cells. The table is conceptually divided into two parts, a part with conditions and a part with results.

Conditions are created based on input values, so the condition columns are tied to the input model. On the other hand, the results are the values we want to obtain after evaluating the decision, so the result columns are tied to the output model. In the input-output model, you set the structure of the data and what values will go into the rule and what values will be received from it.

{% hint style="info" %}
*For more information about setting up the Input-Output model, see the* [*section*](https://docs.decisionrules.io/doc/rules/common-rule-features/input-and-output) *dedicated to it.*&#x20;
{% endhint %}

#### Adding and building columns

Once you have created the Input-Output model, you go into the Decision Table Designer and start adding individual columns for conditions and results. To add more columns, click on the "+" sign, located between the head of the columns. You can add columns at any time during the creation of your rule. To delete columns you do not need anymore, click the dropdown menu at the head of the column, select “Remove” from the list and continue.

You can also really easily create additional conditions or result columns for the same input or output variables. Just add an additional column with the same variable.

Simply link the values from the Input-Output model to the added columns. Once the values are mapped, you can begin to create individual conditions in the condition columns.

{% hint style="info" %}
In addition to the conditions columns, you can add calculation columns, they are a useful tool for enhancing the logical structure of the conditions. More about calculation columns in the [documentation](https://docs.decisionrules.io/doc/rules/decision-table/decision-table-designer).
{% endhint %}

The body of the table is made up of columns and rows. It's as if we could translate each row of the table into a sentence: **If all conditions are satisfied, show these results.** We can think of those rows as individual scenarios. By adding more rows to the table, we gradually cover all the scenarios that can occur.

#### Adding and building rows

To add a row, click on the  <mark style="background-color:purple;">**+ Row**</mark>  button in the bottom bar of the Decision Table Designer. You create a condition by selecting an operator or function in the row cell. Click on the green operator button to display a list of available operators and functions, e.g. <mark style="color:green;background-color:green;">**ANY**</mark> . You can find logical operators or text and mathematical functions in the menu.

{% hint style="info" %}
*Keep in mind that conditions must be clearly evaluable with the result of true or false - a boolean value.*
{% endhint %}

Now that we have the conditions set, it's time to create the results that will return if all the conditions in that row are met. As with the conditions, by clicking on the green operator button in the cell, you choose whether the result will be equal to some fixed value (at that point select the <mark style="color:green;background-color:green;">**=**</mark> sign) or whether it will be equal to the result of some function or calculation (at that point select <mark style="color:green;background-color:green;">**Fn**</mark> for function) to create a dynamic value.

Continue in this way with all the scenarios that may occur in your decision process.

{% hint style="info" %}
Once you have set up the Input-Output model, you can export your Decision Table in XLSX format. In Excel or Google Sheets, you can then add more data at once and re-import your rule into your space. For more information on creating tables using Excel or Google Sheets, click [here](https://docs.decisionrules.io/doc/rules/common-rule-features/rule-export-and-import/manage-tables-excel-gsheets).
{% endhint %}

There may be cases where the input values to the rule do not match any of your defined condition scenarios. Therefore, if none of your scenarios are met, no action is taken to return the results. If you also need to return a result when none of the conditions were met, add a Default (Else) Row. In the bottom bar, click  <mark style="background-color:purple;">**+ Else Row**</mark> . A row will be added to the table that will be filled with the ELSE operator in all cells of the conditions. You simply add to the results either what value or message to print if none of the conditions were met.

{% hint style="info" %}
*Note that by definition:*

* *there can always be at most one passing row containing the ELSE operator*
* *when the ELSE operator is evaluated, it only takes into account conditions above it*
  {% endhint %}

<figure><img src="/files/VM2OVrZi6VZBWdaCigrn" alt=""><figcaption><p><mark style="color:purple;">Building Rows for Deciding the Luggage Price</mark></p></figcaption></figure>

The Decision Table is evaluated from top to bottom row by row. First the first row is evaluated, then the second, etc. Depending on the chosen solving strategy, you can control the output of the Decision Table.

#### Testing your Decision Rule

Test the functioning of the created Decision Table using the "Test Bench" tool in the bottom bar of the designer. Open the Test Bench and enter the input values, then click the "Run" button to evaluate the rule. Switch to JSON Bench to view the input and output in JSON format. This is useful if you want to test an input that you already have available in JSON format (you can simply paste into the Test Bench), or if you want to for example test the Decision Table output in your logic where the output will be processed next.

Use Debug Mode to see how rows are evaluated. Enable Debug Mode in Test Bench by switching on the "Debug" toggle, which will solve your rule again. In this mode you will see each condition marked as green when met and marked as red when not met.

## Solving Strategies

You can use execution strategies to define the output of the Decision Table. In the Test Bench Tool, click the Standard button to open a list of possible strategies. These are as follows:&#x20;

* **Standard** - This is the default strategy that returns the results of all rows whose conditions have been met as output. If 3 rows match in your table, all 3 will appear in the output.
* **Array** - This strategy is similar to Standard, but returns the results of all rows whose conditions have been met, in the form of an array.
* **First Match** - if there are multiple rows whose conditions have been met, only the first matched row is returned
* **Evaluate All** - The strategy allows to get results from all rows of the table even if their conditions have not been met. The results are enriched with information whether the row is matched (true) or not (false). To see this information switch to the JSON Bench, where input and output is visible in JSON format.

<figure><img src="/files/bPWNRHu2eumDGuZuqRff" alt=""><figcaption><p><mark style="color:purple;">Different solving strategies in the Test Bench of the Decision Table</mark></p></figcaption></figure>


# Create a Simple Decision Table

This tutorial will walk you through the creation of a simple Decision Table.

Decision Tables are without a question one of the most important tools for creating business rules. Within DecisionRules, they are fairly easy to create and manage. We believe that, with the help of this tutorial, you can master the basics quickly.

{% embed url="<https://www.youtube.com/watch?v=UUnG2E4-BFI>" %}

## How to create a simple decision table

Let's advance one step at a time.

### 1. Log in

Becoming a superhero is a fairly straightforward process. After entering our [<mark style="color:purple;">login page</mark>](https://app.decisionrules.io/auth/login), you will be able to pass your credentials and log in.

<figure><img src="/files/3OR0j9zSHRtQsIz9Rn5i" alt="" width="375"><figcaption></figcaption></figure>

There are multiple options for user login. If you do not have an account yet, you can [<mark style="color:purple;">create one</mark>](https://app.decisionrules.io/auth/register?type=true-registration). After logging in to the application, the folder structure of your Rules List will be displayed.

### 2. Create a new Decision Table

To display the rules creation list, click the <mark style="background-color:purple;">**+ Create**</mark> button on the search bar. Select your rule and you will be prompted to provide a nam&#x65;**.** For this example, we will create a table for discounts, select a name for your rule as you wish and press "Confirm". The new rule will be created and its design interface will be displayed. We will continue in the Rule Setting menu.

<figure><img src="/files/c5lGgTmaj6Hv9GuGOoib" alt=""><figcaption></figcaption></figure>

### 3. Make basic settings

Rule Settings will be in a left-hand side menu, or you can access them by Rule Model at the top bar. Let's do some settings. Since we do not want this decision table to be available yet, we will change its status to **Pending**. To do this, switch on the current status **Published** to **Pending**.

To apply these changes, we have to click the <mark style="background-color:orange;">**Save**</mark> button at the top of the page, right corner.

### 4. Create the input and output model

We will now create the input and output model which is used to set conditions and results. There are two ways to create these models:

#### Using the simple editor

Let's start with the input model. First, you can switch from "Designer" to "Model" at the centre of the top bar. Delete the default attribute "input" by clicking the trash can icon next to the name. Then, add your own attributes: <mark style="color:purple;background-color:purple;">**period**</mark>, <mark style="color:purple;background-color:purple;">**productType**</mark> and <mark style="color:purple;background-color:purple;">**promoCode**</mark>. Create a root for each of them by clicking the **+Add Root** button.

Now, you can continue with the output model. It will be set similarly. As root attributes, add <mark style="color:green;background-color:green;">**prices**</mark> and <mark style="color:green;background-color:green;">**message**</mark>. Then, you can add a child attributes to the <mark style="color:green;background-color:green;">**prices**</mark>. You can do that by clicking the + icon within the prices field. Rename the New Attribute to <mark style="color:green;background-color:green;">**finalPrice**</mark> and then add one more, <mark style="color:green;background-color:green;">**crudePrice**</mark>.

<figure><img src="/files/EzDQNesNiOxtoO1Gfh1o" alt=""><figcaption></figcaption></figure>

{% hint style="warning" %}
After creating an input or output model, we must always confirm the changes with the <mark style="background-color:orange;">save</mark> button.
{% endhint %}

{% hint style="info" %}
More information on the simple editor is provided [<mark style="color:purple;">here</mark>](https://docs.decisionrules.io/doc/decision-tables/input-and-output/simple-editor).
{% endhint %}

#### Using the JSON editor

In the JSON editor, you can provide the input and output model in JSON format. In our case, the input/output model will read:

<figure><img src="/files/M3RajxcUGIqLHCqrIv4l" alt=""><figcaption></figcaption></figure>

For now, you may just enter these values and you are done!

{% hint style="info" %}
More information on the JSON editor can be found [<mark style="color:purple;">here</mark>](https://docs.decisionrules.io/doc/decision-tables/input-and-output/json-editor).
{% endhint %}

### 5. Set the conditions and results

To create conditions and results, you must go to the **Table Designer** tab. Now let's move on and bind our input and output models to our condition and result columns.

We already have one condition column and one result column. We start with the conditions. Click the space below Condition, <mark style="color:orange;background-color:orange;">**->**</mark>**&#x20;           &#x20;**&#x20;dropdown, and select <mark style="color:purple;background-color:purple;">**productType**</mark>. Then click the **+** button at the top of the conditions section twice to create two more columns. Bound these to our <mark style="color:purple;background-color:purple;">**period**</mark> and <mark style="color:purple;background-color:purple;">**promoCode**</mark> input attributes. These are all the conditions we will use.

<figure><img src="/files/bhasylf7ntXpIPHQIUjo" alt="" width="563"><figcaption></figcaption></figure>

Similarly, we add the result columns. One is already there, so click the <mark style="color:orange;background-color:orange;">**-> output**</mark> dropdown and select <mark style="color:green;background-color:green;">**prices.crudePrice**</mark>. Then create two more columns by clicking the **+** button at the top and bind them to <mark style="color:green;background-color:green;">**prices.finalPrice**</mark> and <mark style="color:green;background-color:green;">**message**</mark>. These are all the results we need.

{% hint style="info" %}
More information about creating conditions and results can be found in the [<mark style="color:purple;">Table Designer Section</mark>](https://docs.decisionrules.io/doc/decision-tables/decision-table-designer) and [<mark style="color:purple;">Binding to Model Section</mark>](https://docs.decisionrules.io/doc/decision-tables/binding-to-model).
{% endhint %}

After adding conditions and results, we can also set their names. For example, click on the name (currently reading **Condition**), and rewrite it.

{% hint style="warning" %}
Do not forget to click the <mark style="background-color:orange;">save</mark> button.
{% endhint %}

### 6. Edit rows

Currently, we have a single row in the Decision Table.

{% hint style="info" %}
Each row of the table corresponds to one set of conditions and results. When the Rule Solver is called, it goes through the individual rows and evaluates their condition values against the corresponding request input data. If values of the conditions in a row match, Rule Solver takes the values of the individual results on that row and places them in the output.
{% endhint %}

Let's set the conditions in the first row.

#### Product Type

Click the anything label, <mark style="color:green;background-color:green;">**ANY**</mark> , in the <mark style="color:purple;background-color:purple;">**productType**</mark> column. You can choose a type of condition from the Select type modal. We would like to activate the results of this row when the value of <mark style="color:purple;background-color:purple;">**productType**</mark> is `basic`. We can do that simply by selecting the "Equals" operator and entering the string `basic`.

<figure><img src="/files/Wv3PM9SfgtAo9tiohVuT" alt="" width="563"><figcaption></figcaption></figure>

#### Period

We will use the Equals operator for <mark style="color:purple;background-color:purple;">**period**</mark> as well. This row will activate when the <mark style="color:purple;background-color:purple;">**period**</mark> will be equal to `month`.

#### Promo Code

Here we want to check whether the customer's promo code is correct. We could again enter the desired value with an Equal operator, but we can do better. Let's go to Rule settings and open the Rule Variables section. Here we shall add two Rule Variables. The first one will have name `PromoCode` and value `SUMMER SALE` while the other will have name `PromoDiscount` and value  `30`. Rule variables make our rules easily manageable. If we later want to change the promo code, we do it only on a single place: in the Rule Settings.

Click Save and go back to the Decision Table Designer. Now you can add the condition for <mark style="color:purple;background-color:purple;">**promoCode**</mark>. Select again the Equals operator and enter `{PromoCode}` in the field. This expression refers to the `PromoCode` Rule variable.

<figure><img src="/files/ECZ4VVtDoLe5cQv294me" alt=""><figcaption></figcaption></figure>

{% hint style="info" %}
An overview of all operators is [<mark style="color:purple;">here</mark>](https://docs.decisionrules.io/doc/decision-tables/operators).\
An overview of all possible values is [<mark style="color:purple;">here</mark>](https://docs.decisionrules.io/doc/decision-tables/data-types).
{% endhint %}

Now we are going to continue with setting the results.

#### Crude Price

In the <mark style="color:green;background-color:green;">**prices.crudePrice**</mark> column, leave the simple value denoted by = and enter `8`. This is the crude price for our service in case of basic subscription for a month.

#### Final price

Because we are in the row where the promo code is matched, we will give a discount on the crude price. Click the = sign and select **Function**. Then enter the following expression:

{% hint style="warning" %}
Originally the expression of such a function was:&#x20;

* TIMES({prices.crudePrice},DIVIDED(MINUS(100,{PromoDiscount}),100))

However, some functions are updated and it is written:

* {prices.crudePrice}\*((100-{PromoDiscount})/100)
  {% endhint %}

<figure><img src="/files/ZH4PeopGd4zAHoL5n3qo" alt=""><figcaption></figcaption></figure>

It means that we calculate the final price by taking the crude price and subtracting 30% discount defined by the `PromoDiscount` variable. Note that we are referring to the <mark style="color:green;background-color:green;">**prices.crudePrice**</mark> column by writing `{prices.crudePrice}`.

#### Message

Finally, let's include some message about what happened on this row. In the <mark style="color:green;background-color:green;">**message**</mark> column, again select the **Function** type of the result and enter the following expression:

```
CONCAT({PromoDiscount},"% discount")
```

This function will take the `PromoDiscount` variable and concatenate it with the given string to generate the desired message.

{% hint style="warning" %}
Do not forget to click the <mark style="background-color:orange;">**Save**</mark> button.
{% endhint %}

You can now click the arrow at the beginning of the row and select **Insert**, and after click on **Below**. This will add another empty row below. Its conditions and results may be set analogically. More rows can be added in a similar fashion. In this way, you can create a rule similar to the following sample rule.

<figure><img src="/files/Z5laELqOzpMcM6SNwLpS" alt="" width="375"><figcaption></figcaption></figure>

{% file src="/files/zv8Lkd529bRZpN7N6cz8" %}

You can import this rule to your space by going to **Decision Tables** and clicking the **Import** button.

<figure><img src="/files/xp8LNqXSJVb1jkO3Y5lH" alt=""><figcaption></figcaption></figure>

### 7. Test the Decision Table

Now we can test our rule in Test Bench. Before testing the rule, we must go to Rule Settings and change the status of the decision table to **Published**.

If we want to test a certain row, we can click the <mark style="background-color:purple;">**Test Bench**</mark> icon at its beginning. After clicking the icon, the values from the row will be pre-filled in **Test Bench**, which will show up at the bottom of the page.&#x20;

Then we can click the <mark style="background-color:green;">**Run**</mark> button and the result will be displayed in right hand side of the Test Bench. Note that you can switch between the **Simple Bench** and the **JSON Bench**.

<figure><img src="/files/xxyrmhCCxyzci7DvlfFT" alt="" width="375"><figcaption></figcaption></figure>

For example, if we switch to the JSON Bench, we may input the following data.

```javascript
{
  "productType": "basic",
  "period": "month",
  "promoCode": "SUMMER SALE"
}
```

Upon hitting Run, we will get the following response.

```javascript
[
  {
    "prices": {
      "finalPrice": 5.6,
      "crudePrice": 8
    },
    "message": "30% discount"
  }
]
```

{% hint style="info" %}
More information about Test Bench can be found [<mark style="color:purple;">here</mark>](https://docs.decisionrules.io/doc/rules/common-rule-features/test-bench).
{% endhint %}

If you have arrived here, you have successfully completed the tutorial. Congratulations!


# Decision Trees

## Introduction

Decision Tree is an easy to learn type of decision rule based on if this then that structure. In a simple and user-friendly visual designer, you can easily create simple yet powerful rules. Such rules can then form the entire decision process or you can link it as a sub-rule to a Rule Flow, for example. We can think of creating a Decision Tree as writing a sentence:  **If this, then that**. If it rains, I'll take an umbrella. This is why Decision Tree is suitable for creating very simple rules. Or rules that have multiple levels of conditional branching. Such condition nesting would require the creation of all combinations of all input values in the Decision Table.

<figure><img src="/files/kjviO9uKTRRE8WgJaC61" alt=""><figcaption><p><mark style="color:purple;">Simple decision tree</mark></p></figcaption></figure>

<figure><img src="/files/PlKzwa8JfliltQMZ5sEy" alt=""><figcaption><p><mark style="color:purple;">Solution designed in DecisionRules</mark></p></figcaption></figure>

## Decision Tree Designer

The space where you create your decision tree looks like a canvas. Use mouse dragging to move around. Use the mouse wheel or the Zoom In and Zoom Out buttons in the bottom bar of the Designer to adjust the zoom level.

Use the Test Bench with Debug Mode in the bottom bar to quickly and easily test the functionality of your rule. In the bottom bar, you can also use the PDF export of your tree.

<figure><img src="/files/fbo2vBAypSTq5RvLUM9c" alt=""><figcaption><p><mark style="color:purple;">Decision Tree Designer</mark></p></figcaption></figure>

### What does the Decision Tree look like?

Decision Tree is a structure composed of individual logical blocks with conditions and results. We can think of the condition-result pair as a scenario: if a condition is met, an action will be performed. Set the variables that will form the conditions and results in Rule Settings in the Input-Output Model section.

#### Decision Tree Evaluation

The Decision Tree blocks are evaluated from top to bottom. If the condition of the block is met, the action is executed, and the property is returned with the value corresponding to the satisfaction of the condition. If we have multiple THEN blocks in the Decision Tree that return the same property, the property will eventually be overwritten by the THEN block that was evaluated last. Knowing this, it is worth adapting the architecture accordingly.

### Blocks

The block is the basic unit of the decision tree. It is marked with a colored bar on the left with the type of the block. Move blocks by clicking on the "two lines" symbol and then dragging to the desired position. Click on the cogwheel to display the drop down menu - clone the block or delete it. Below each block you will find an "add block" button to add another block. Click the button to select the type of block to add to your decision tree.

#### IF block

The 'If Block' is divided into two parts. In the left part you **always add conditions** on which you build the decision process. To add conditions, click on "Add Condition" button, then select which condition you want to add.&#x20;

1. Click on "Logic AND" to add a simple condition.
2. Click on "Logic OR" to add the entire OR block, which by default creates OR logic between the two conditions. Add conditions on both sides of the disjunction using the "Add" button.
3. To add another OR group, click the cogwheel in the OR block's operation bar.

<figure><img src="/files/d1A7xnEVAj3ULUyJ6dYX" alt=""><figcaption><p><mark style="color:purple;">How to add another OR group</mark></p></figcaption></figure>

The right part of the if block contains the action to be performed if the condition on the left side of the block is met. Depending on the structure of your decision process, you add a Then Block or If Block. Adding more If Blocks to the right side of a If Block is called 'branching'.

<figure><img src="/files/9e93LeHaWOuOskkoD8uK" alt=""><figcaption><p><mark style="color:purple;">Simple Decision Tree branching</mark></p></figcaption></figure>

#### THEN block

Then Block indicates the end of the decision process. In the Then Block you add an action to be performed, you **always add results**, if the conditions are met. Click on "add result" for each action you want to perform.&#x20;

#### ELSE block

Add an Else block as an action that will be executed if none of the conditions of the preceding If Blocks are met. You can add If Blocks within the Else Block to create another decision process, or simply add a Then Block.

{% hint style="info" %}
*By definition, it is obvious that the Else Block should be added at the end of a series of If Blocks to provide an output if none of the previous conditions is met.*
{% endhint %}

### Binding to input-output model

The newly added conditions and results have no variable assigned. Therefore, there is no setting for which variable will be evaluated (in case of conditions) or returned (in case of results).

By binding the input model variables to the left side of the 'IF Blocks', you create conditions. Click on <mark style="color:orange;background-color:orange;">**Not set ˇ**</mark> to see a list of all variables from your input model. Simply click to select the variable you want to base your condition on.&#x20;

The newly added result also has no variable assigned in your 'THEN Blocks'. Click on <mark style="color:orange;background-color:orange;">**Not set ˇ**</mark> to see a list of all the variables you have set in your output model. Simply select the desired variable you want to return as the result.

### Building conditions and results cells

We already know the types of blocks and why we need to have an input-output model set up. Now let's see how to build the conditions and results.

#### Conditions

Once you assign a variable from your input-output model, you select an operator or function. Click on the <mark style="color:green;background-color:green;">**=**</mark> green button to display a list of all operators and functions. Click to select the one you need. In the cell next to the operator, enter the value(s) according to the nature of the operator. If you have selected a function, fill in all its parameters.

<figure><img src="/files/7BEWQqIKaMD4vooQvgCM" alt=""><figcaption><p><mark style="color:purple;">Building conditions</mark></p></figcaption></figure>

{% hint style="warning" %}
*The conditions must be evaluated as true or false, so called boolean values. Therefore, when using functions, care must be taken that the function also returns boolean values. These are, for example, boolean operators or inequality signs.*
{% endhint %}

#### Results

After assigning variables from your output, assign a value to the variable. Click on the <mark style="color:green;background-color:green;">**Fn**</mark> green button to display the options for results. You can set the value as fixed if you choose <mark style="color:green;background-color:green;">**=**</mark> "Simple Value". If you choose a function, you can make the value dynamic. To create more complex functions, you can nest the functions.

<figure><img src="/files/F57HqM9bt88xWtrG2JD8" alt=""><figcaption><p><mark style="color:purple;">Building results</mark></p></figcaption></figure>

{% hint style="info" %}
*A list of all operators and functions with their examples can be found in the* [*Operators*](https://docs.decisionrules.io/doc/rules/data-types-and-functions/operators) *and* [*Functions*](https://docs.decisionrules.io/doc/rules/data-types-and-functions/operators/functions) *section of our documentation.*
{% endhint %}


# Create Simple Decision Tree

This tutorial will walk you through the creation of a simple Decision Tree.

## How to create a simple decision tree

Let's advance one step at a time.

### 1. Create a New Decision Tree

To display the rules creation list, click the <mark style="background-color:purple;">**+ Create**</mark> button on the search bar. Select your rule and you will be prompted to provide a nam&#x65;**.** For this example, we will create a tree for procrastination, select a name for your rule as you wish and press "Confirm". The new rule will be created and its design interface will be displayed. We will continue in the Rule Setting menu.

<figure><img src="/files/i1Pwf2UNT1TUA5kuSEEN" alt=""><figcaption></figcaption></figure>

### 2. Create the input and output model

We will now create the input and output model which is used to set conditions and results. There are two ways to create these models:

#### Using the simple editor

Let's start with the input model. First, you can switch from "Designer" to "Model" at the centre of the top bar. Delete the default attribute "input" by clicking the trash can icon next to the name. Then, add your own attributes: <mark style="color:purple;background-color:purple;">**inputAttribute**</mark>. Create a root for each new of them by clicking the **+Add Root** button.

Now, you can continue with the output model. It will be set similarly. As root attribute, add <mark style="color:green;background-color:green;">**output**</mark> . Then, you can add a child attribute to the this root. Click the + icon within the 'output' field. Rename the New Attribute to  <mark style="color:green;background-color:green;">**mission**</mark> .

<figure><img src="/files/Wpx2Vv3B7MEA0lDMUMmO" alt=""><figcaption></figcaption></figure>

{% hint style="warning" %}
After creating an input or output model, we must always confirm the changes with the <mark style="background-color:orange;">save</mark> button.
{% endhint %}

{% hint style="info" %}
More information on the simple editor is provided [<mark style="color:purple;">here</mark>](https://docs.decisionrules.io/doc/decision-tables/input-and-output/simple-editor).
{% endhint %}

### 3. Create First If Block

Click on "Create First Condition".

<figure><img src="/files/ICIBgQRLx2SP84EaIIYX" alt="" width="375"><figcaption></figcaption></figure>

### 4. Specify Condition Inside If Block

1\. Click on the first "Add Condition" button inside the If Block.&#x20;

<figure><img src="/files/gvdSwzTWRRsNThBaPuGG" alt="" width="343"><figcaption></figcaption></figure>

2\. Dropdown will be shown. Click on "Logic AND".

<figure><img src="/files/AJCULqYQ1SR7gpvN1x91" alt="" width="349"><figcaption></figcaption></figure>

3\. Click on the orange dropdown <mark style="color:orange;background-color:orange;">**Not set ˇ**</mark> . Here you will choose an input that later will be evaluated when solving the decision tree.

<figure><img src="/files/ahhOsSOO73ym4MYKk7Zx" alt="" width="563"><figcaption></figcaption></figure>

4\. Now click on the empty text to the right side of the operator <mark style="color:green;background-color:green;">**=**</mark> , and edit the value.

<figure><img src="/files/pW23Qal0TcOBPk0Siu2t" alt="" width="563"><figcaption></figcaption></figure>

5\. Now type in a value to which we will compare the input once solving the decision tree. Let's write "learning" for example.&#x20;

<figure><img src="/files/ytlvjumQBoGKkKc731kH" alt="" width="563"><figcaption></figcaption></figure>

6\. Now click on the <mark style="background-color:purple;">**Add Block**</mark> button at the right-side of the If Block. And Select "Then" from the list.

<figure><img src="/files/dXEzAIoprd0N10oxn70U" alt="" width="563"><figcaption></figcaption></figure>

7\. Click on "Add Result".

<figure><img src="/files/3CFim1kTmidxdKKrBuEL" alt="" width="563"><figcaption></figcaption></figure>

8\. Once again, click on the orange button saying <mark style="color:orange;background-color:orange;">**Not set ˇ**</mark> and choose the only Output you defined.

<figure><img src="/files/UzKF4hPUAwdCAo5vwvro" alt=""><figcaption></figcaption></figure>

9\. Change the operator from function <mark style="color:green;background-color:green;">**Fn**</mark> to equal <mark style="color:green;background-color:green;">**=**</mark> . Now, click on the empty text to the right side of the operator and edit the value as with the 'if condition'.

<figure><img src="/files/RfUYPHhcxaQrvYw84iOO" alt=""><figcaption></figcaption></figure>

Great, you now know how to create a simple condition :tada:.

### 5. Create Second If Block

To simplify the process, you can click on the cogwheel icon of the first If Block and select "Clone" from the dropdown list.

<figure><img src="/files/XEPuffxx27NlKdM558Aw" alt=""><figcaption></figcaption></figure>

This will create an exact copy of the If Block down below.

The only thing to do now is to change the values inside the newly created If block:

<figure><img src="/files/9W3Z6AySxSJ8DugtOmAm" alt=""><figcaption></figcaption></figure>

{% hint style="success" %}
These two If blocks are very similar to the If and Else-If behavior, if you are familiar with programming concepts.
{% endhint %}

### 6. Create Else Block

Finally we create an Else Block. The Else Block will be executed whenever none of the above If Blocks evaluate to true. In our case, if the Input is anything else than the values 'learning' or 'procrastinating'.

Now click on the <mark style="background-color:purple;">**Add Block**</mark> button under the If Block and add another "Else" block.

<figure><img src="/files/0NPPKqZBwpNvdPIFGSY1" alt=""><figcaption></figcaption></figure>

Now, inside the last Else Block simply press the <mark style="background-color:purple;">**Add Block**</mark> button and add a Then Block. Fill it out with whatever value you like. Remember to change the operator from function to equal.&#x20;

<figure><img src="/files/0jbEPdOHuyTUPv4SrNNk" alt=""><figcaption></figcaption></figure>

### 7. Test It!

Simply click on the <mark style="background-color:green;">**Test bench**</mark> in the bottom bar.

Type "learning" in the Input Property and click on <mark style="background-color:green;">**Run**</mark> .

<figure><img src="/files/8DYI36Ei0rankmoGuW9q" alt=""><figcaption></figcaption></figure>

{% hint style="success" %}
The first block was evaluated as expected.
{% endhint %}

Inputting the word "procrastinating" will return "mission failed".

<figure><img src="/files/2gm00UED1H3VfPKOvhGx" alt=""><figcaption></figcaption></figure>

Finally, you can try the Debug toggle and see true valuations in green, false valuations in red, and no color if the block was not evaluated.

<figure><img src="/files/NBV6MHXqzai0Ga7x7RV0" alt=""><figcaption></figcaption></figure>

{% hint style="info" %}
More information can be found [<mark style="color:purple;">here</mark>](https://docs.decisionrules.io/doc/decision-trees/decision-tree-designer).
{% endhint %}


# Scripting Rules

### Introduction

Scripting Rule is another type of rule that you can use in <mark style="color:purple;">DecisionRules</mark> to create your rules and conditions. However, it differs fundamentally from the others in that it does not have a graphical editor, it uses the *Monaco code editor* instead.

Just like the other rules, it has a unified Rule Settings form that is the same across all rule types.

So when you are creating a rule, the procedure is exactly the same, first, you create an input and output structure in Rule Model. You can also create your own [Rule Variables](https://docs.decisionrules.io/doc/rules/common-rule-features/variables/rule-variables).

Next, you move to the Scripting Rule Designer and create the rule and all the logic using JavaScript.&#x20;

The Scripting Rule Designer uses the standard and well-known *Monaco editor* from *VS Code* to help the user with code creation and editing. Of course, it also includes all the Functions and Operators that are available in Decision Table or Decision Tree.

*Below you can find example file with Scripting Rule. This rule contains a function that return random number from given range.*

{% file src="/files/vfYGxy2xrw9sFVmtkUA9" %}

{% hint style="warning" %}
*What is important to note is that you should always have “return output;” in the last line of your Scripting rule.*
{% endhint %}

### Intended Users and Use of the Scripting Rule

Although <mark style="color:purple;">DecisionRules</mark> is a No-code & Low-code solution, in some cases it is useful to take advantage of the flexibility that using the code offers. In particular the ability to create your own function or copy it from already created code. Using Scripting Rule is mainly meant for Developers, Analysts or anyone who is capable and willing to use JavaScript.

One of the most popular use cases is when a developer creates a generic script that processes data. This script then changes very little, because all the parameterization of that script happens in the Decision Table or Decision Tree, where it is already being modified by people from the business or product teams.

#### Rule Orchestration

Although Rule Flow was primarily intended for rule orchestration, with using Scripting Rule for rule orchestration, it is possible to enrich such orchestration with custom and more advanced features. An example of orchestration using Scripting Rule is the use of the [DR.solve function](https://docs.decisionrules.io/doc/rules/scripting-rule/call-embedded-rules-in-sr), which calls the required rules from code and can further manipulate the data that such rules return as output.

### GitHub

The Scripting Rule, like other rules in <mark style="color:purple;">DecisionRules</mark>, has its own versioning and change history. But what you can do more in the case of Scripting Rule is to use GitHub. Thanks to [the Management API](https://docs.decisionrules.io/doc/api/management-api), you can connect your GitHub to DecisionRules and use GitHub to manage code edits, versioning and merging of unique versions.

{% hint style="info" %}
*Whenever you make a change to a rule, save it with the Save button.*
{% endhint %}

### Summary

Thanks to Scripting Rules, DecisionRules can have the Best of Both Worlds.

The sheer flexibility offered by the code and the user-friendly interface of Decision Table or Decision Tree that can easily be used by a non-technical person. The key is to use the [solve function](https://docs.decisionrules.io/doc/rules/scripting-rule/call-embedded-rules-in-sr). Where Scripting Rule takes care of advanced data manipulation and uses the solve function to parameterize the Decision Table or Scripting Rule.&#x20;

Scripting Rule allows you to create custom functions, make advanced data manipulation, aggregations, iterations. You can also very easily copy functions and code that you have already created in JavaScript.


# Create Simple Scripting Rule

This tutorial will walk you through the creation of a simple Scripting Rule.

## How to create a simple decision table

Let's advance one step at a time.

### 1. Create a new Scripting Rule

To display the rules creation list, click the <mark style="background-color:purple;">**+ Create**</mark> button on the search bar. Select your rule and you will be prompted to provide a nam&#x65;**.** For this example, select a name for your rule as you wish and press "Confirm". The new rule will be created and its design interface will be displayed. We will continue in the Rule Setting menu.

<figure><img src="/files/Z1ycWfE7Mbu9dmcnuCUv" alt=""><figcaption></figcaption></figure>

### 2. Make basic settings

Rule Settings will be in a left-hand side menu, or you can access them by Rule Model at the top bar. Let's do some settings. Since we do not want this decision table to be available yet, we will change its status to **Pending**. To do this, switch on the current status **Published** to **Pending**.

To apply these changes, we have to click the <mark style="background-color:orange;">**Save**</mark> button at the top of the page, right corner.

### 3. Create an Input and Output model

We will now create an input and output model, which we will then use to set conditions and results. We create this model with a **JSON editor**.

{% hint style="info" %}
After creating an input or output model, we must always confirm the changes with the <mark style="background-color:purple;">**Save**</mark>  button.
{% endhint %}

#### **Input model**

First, we delete all created objects. Then we will add our specified requirements (**value1, value2**) as empty objects. Let's start with the input model. First, you can switch from "Designer" to "Model" at the centre of the top bar. Change from Simple Editor to JSON Editor at the toggle next to the "Rule Settings" button. Delete all default objects. Then add your specified requirements, e.g. **value1, value2**, as empty objects.&#x20;

{% hint style="info" %}
Because our model is simple, these objects do not contain any others. For more complex models, more information is [<mark style="color:purple;">here</mark>](https://docs.decisionrules.io/doc/decision-tables/input-and-output/json-editor).
{% endhint %}

#### **Input model Example:**

```javascript
{
  "value1": {},
  "value2": {}
}
```

#### **Output model**

We set the output model similarly, where we set it as root **result** (empty object).

**Output model Example:**

```javascript
{
  "result": {}
}
```

### 4. Creating rules

Now let's move on to code editor by clicking on **Scripting Rule Designer** it in the upper center and create individual rules.

{% hint style="success" %}
Our code editor is based on **Monaco Editor,** using its features, like autocomplete, syntax highlight, line numbers, etc.

**Shortcut Keys** are also working, but you need to be with a cursor in the editor.

**CTRL/CMD + S** - save

**CTRL/CMD + R** - run

**CTRL/CMD + Z** - undo

**CTRL/CMD + SHIFT + Z** - redo

**CTRL/CMD + F** - find

**SHIFT + ALT + F** - format
{% endhint %}

{% hint style="success" %}
Scripts must be written in **JavaScript** language.
{% endhint %}

For simplicity, we will remove the code from the code editor to create a new rule.

When to code editor is empty, we can start to create our own rule in **JavaScript.** It is straightforward, and you need to write your code which can look like below.

{% hint style="success" %}
Input must always be entered as input.yourInputVariable.

Output must always be entered as output.yourOutputVariable.

To return an output, always enter **return output** at the end of your script!
{% endhint %}

```javascript
/* 
    1.  Input variables
    Input body is set in input variable 
*/
let a = input.value1;
let b = input.value2;

/*
    2.  Define simple "multiply" function
*/
function multiply(a, b) {
    return a * b;
}

/*
    3.  Execute multiply function and store value result variable
*/
let resultMultiply = multiply(a, b);

/*
    4.  Set output model which is returned in REST API
*/
output.result = resultMultiply;

/*
    Optionally: It is possible print values to console
*/
log('Result multiply:', resultMultiply);

/*
    5.  Return output  
*/
return output;
```

{% hint style="info" %}
**console.log()** is forbidden due to performance, but you can use **log()** instead.
{% endhint %}

{% hint style="success" %}
You can use **log()** to print values in the console, which is at the bottom of the code editor.
{% endhint %}

{% hint style="info" %}
Always **save** your script using <mark style="background-color:purple;">**Save**</mark> (bottom of the page) or CTRL/CMD + S
{% endhint %}

### 5. Test created scripting rule

{% hint style="warning" %}
Don't forget to save your scripting rule!
{% endhint %}

Now we can test our rule. Before testing the rule, we must change the status of the rule to **"Published"**.

If we want to test a rule, we can click on the Test Bench button. An input and output window will show up at the bottom of the page. Press the <mark style="background-color:green;">**Run**</mark> icon at the center of the window.&#x20;

<figure><img src="/files/P1ZjstZniyNMRmopEr7n" alt=""><figcaption></figcaption></figure>

{% hint style="success" %}
You can find more information about input and result at [<mark style="color:purple;">Solver API</mark>](https://docs.decisionrules.io/doc/api/rule-solver-api).
{% endhint %}

The result will be displayed in the **Output window (the right one)**.

{% hint style="info" %}
The debug mode can be turned on by clicking on [ <mark style="background-color:purple;">**Debug off**</mark>](#user-content-fn-1)[^1] . In scripting rules, it will enable to write **log()** in the console.
{% endhint %}

#### Request body example:

```javascript
{
  "value1": 2,
  "value2": 4
}
```

#### Response body example:

```javascript
{
  "result": 8
}
```

{% hint style="info" %}
More information about Test Bench is [<mark style="color:purple;">here</mark>](https://docs.decisionrules.io/doc/rules/common-rule-features/test-bench).
{% endhint %}

[^1]:


# Decision Flow

This page introduces the DecisionRules Decision Flow feature, highlighting its key capabilities and applications.

### Decision Flow Basics

Decision Flows represent a new feature category within DecisionRules, enhancing the platform's capabilities. They integrate seamlessly with existing rules, maintaining a familiar structure. Decision Flows are built by placing nodes on a canvas and connecting them with lines, with various node types available.

<figure><img src="/files/UUpQClwVAZVcsPdzx0do" alt=""><figcaption><p>Workflow overview</p></figcaption></figure>

### Decision Flow Designer

The Designer features a canvas with a single **Start** node. On left side, you’ll find several tabs, with the **Palette** being the most important for now. The Palette lists all available node types with brief descriptions. To use a node, simply drag it from the palette onto the canvas.

Once a node is on the canvas, click it to open its detail settings. Each node type has different configuration options depending on its functionality. For detailed information on each node type, check the [**Workflow Nodes Overview**](https://docs.decisionrules.io/doc/rules/flow/flow-nodes-overview).

<figure><img src="/files/sjqXpx7bKKbFB1qDCRyt" alt="" width="563"><figcaption><p>Nodes Palette in Decision Flow</p></figcaption></figure>

With the tutorial below you will be able to create a simple Decision Flow and discover node types within the rule.

{% content-ref url="/pages/tNvAdxCSEkLpxbSRNtr3" %}
[Create a Decision Flow](/rule-types/decision-flow/create-a-decision-flow)
{% endcontent-ref %}


# Create a Decision Flow

Discover how to navigate Decision Flow features, understand its components, and follow a step-by-step guide to create a simple Decision Flow rule.

In this detailed end-to-end tutorial, we’ll guide you through creating a simple Decision Flow that processes order details to calculate the total price. This Decision Flow integrates two decision tables: one that evaluates product details based on product IDs and branch, and another that applies customer discounts based on their loyalty class and credit status.

{% hint style="success" %}
Both of those Decision Tables can be created as samples right in DecisionRules app
{% endhint %}

We'll cover navigating through the creation process, configuring Decision Flow nodes, and generating the final output, which includes missing items, the total price payable, and a personalized message for the customer. At the end we’ll test our new rule with several inputs to ensure it works as expected. This tutorial will help you understand key Decision Flow components and data manipulation techniques.&#x20;

{% hint style="info" %}
Only a few node types are used in this tutorial. For a complete list of available Decision Flow nodes, please refer to our dedicated [documentation page](https://docs.decisionrules.io/doc/rules/flow/flow-nodes-overview).
{% endhint %}

## Logic of the Flow

### IO Model

Our input model captures key details of an order, including items, branch information, and customer details such as loyalty class and credit balance.

```json
{
  "order": {
    "items": {},
    "branch": {},
    "customer": {
      "id": {},
      "loyaltyClass": {},
      "credit": {}
    }
  }
}
```

The output model includes calculated values like `initialTotal` and `totalPayable`, along with any missing items and a personalized message for the customer.

```json
{
  "finished_order": {
    "id": {},
    "missingItems": {},
    "initialTotal": {},
    "totalPayable": {},
    "message": {},
    "customer": {
      "id": {}
    }
  }
}
```

### Flow of the process

When designing the Decision Flow as a decision process, establishing a logical flow ensures efficient processing of order details.

1. [**Initial Price Calculation**](#id-1.-initial-price-calculation): Start by calculating the initial price of the customer’s order as a baseline for any potential discounts. This requires evaluating the price catalog decision table first. At this stage, we’ll also collect availability information for each item in the order to use later in the order message.
2. [**Discount Application**](#id-2.-discount-application): With the initial price determined, check if the customer qualifies for a discount by evaluating the loyalty discount decision table. Based on this, calculate the final price, either discounted or not.
3. [**Generating the Final Order**](#id-3.-generating-the-final-order): Use the values from the previous steps to populate the output properties specified in the output model. Additionally, if there are unavailable items, modify the order message accordingly.

## Building the Decision Flow

Now that we’ve outlined each step in the evaluation, it’s time to build our rule. In this section, we’ll configure the IO model, add and connect nodes to create the process flow.

### 1. Initial Price Calculation

Create a new blank Decision Flow. First, you can switch from "Designer" to "Model" at the centre of the top bar. Set up the input and output model as described above. Once set, properties of the model can be easily used in the Decision Flow.

<figure><img src="/files/j6EcWM0LT1qyPdcnFD8a" alt=""><figcaption><p>Decision Flow IO model</p></figcaption></figure>

{% hint style="warning" %}
Don't forget to save your I/O model.
{% endhint %}

Now it's time for adding first nodes to the canvas. Start by adding a **Declare** node to define `initialTotal`. In this variable we will store the price of the order before potential discount. Simple drag and drop the node from the Palette tab on the left. When the node is on the canvas click on the node, it will open, and set the variable. Save the modal and connect the **Start** node to it.

<figure><img src="/files/uIRBmhemJKacz3orpHt9" alt=""><figcaption><p>Declaration of the initialTotal variable</p></figcaption></figure>

The next step is the *Initial Price Calculation*. Since orders often contain multiple items, we need to calculate each item’s price and after, to get the overall total summing of all prices. We will use the **Foreach** node to repeat the evaluation of the price of each item, eliminating the need to manually add multiple **Business Rule** nodes to the canvas.

{% hint style="info" %}
Using the **Foreach** node, you apply a specific process to each element of an array, one by one. This allows efficient way to manage complex, repetitive tasks across datasets. More details can be found in our [documentation](https://docs.decisionrules.io/doc/rules/flow/flow-nodes-overview#foreach).
{% endhint %}

Drag and drop the **Foreach** node onto the canvas, then click on it to open its configuration modal. In the modal, specify the list of order items that the node will process (the list is often offered in the input as an array of names ID). You can do this by either manually entering the input variable or by dragging it from the Data Dictionary tab. When you are done, you have to connect it to the **Declare** node.

{% hint style="success" %}
Note that Data Dictionary tab and input whisperer store all already declared variables for easy access
{% endhint %}

<figure><img src="/files/9WQBahWHtjgIXWfTojHI" alt=""><figcaption><p>Setting the list of order's items</p></figcaption></figure>

Now comes the part when we create a set of actions that will be performed for each item in the order list. As mentioned we need to run the Product Catalogue decision table to know and add the item price to total. In addition if the item is not available add it to the list of unavailable items.

In the first **Business Rule** we will use the *Product Catalog* table (a template example for such a table is available in the templates section of your Rules List): &#x20;

<figure><img src="/files/hp16OXcshd4fTIHIlXlS" alt=""><figcaption></figcaption></figure>

First, we place the **Business Rule** node on the canvas and open it. We select the Product Catalog rule. After selected, its input model shows. We need a mapping from our data to the business rule: For the *productId* we will use the item that will be provided by the **Foreach** node, which takes one item from the original list at time. For the *branch* - we want the branch property passed from the main Decision Flow input.

<figure><img src="/files/xjJKxYKxxjpyRSJ1o7vM" alt=""><figcaption><p>Business Rule node - item price evaluation</p></figcaption></figure>

{% hint style="info" %}
Those mentioned actions, represented by individual nodes, must be connected to the "Loop" connector of the **Foreach node**. So all nodes that you connect in this way will be evaluated in each iteration of the **Foreach** node.
{% endhint %}

When the **Business Rule** node retrieves the item price from the product catalog, we want to incrementally add this price in each iteration of the For Each loop. To set this up, add an **Assign** node to the canvas and open its configuration modal. In the Target field, we write the variable we want to assign it a value:

```
{declare.initialTotal}
```

In the Source field, we create a formula that continuously updates the total by adding each item's price to the previous total:&#x20;

```
{declare.initialTotal}+{rule.currentItem.product.basicPrice}
```

This formula will overwrite the initial price, increasing it as each item’s price is processed. Then save the modal and connect the new node to **Business Rule** node.

<figure><img src="/files/H0wJSLqvoBhyK7Dq5TCG" alt="" width="563"><figcaption><p>Incrementally Adding Each Item’s Price</p></figcaption></figure>

To collect the `productId` of each unavailable product, start by adding a **Switch** node and an **Append** node. The **Switch** node will check each item’s availability from the output of the decision table. If the item is unavailable, the **Append** node will add its `productId`, also from the output of the decision table, to an array named `items_unavailable`. This array will then be used in the order message to notify the customer about any items that are out of stock.

<figure><img src="/files/v9npOx1tAUiWKNgQRxvI" alt="" width="563"><figcaption><p>Product availability check</p></figcaption></figure>

{% hint style="info" %}
See that the `items_unavailable` array can be created in the **Append** node
{% endhint %}

<figure><img src="/files/Ewe3iyJrfrxZ1ZGSL55j" alt="" width="375"><figcaption><p>Append out of stock productId</p></figcaption></figure>

We’ve now completed the first phase by calculating the initial order price (see the reference image below). With this foundation set, we’ll move forward to evaluate whether the customer qualifies for a discount. This next step will involve applying the Loyalty Discount rule, factoring in customer-specific details such as loyalty class and credit, to determine the final payable amount. The next node will be added after the **Foreach** node, it will be connected to its "After Loop" connector, so we will continue in our process.

<figure><img src="/files/GGD668BU834NJfLcunVg" alt=""><figcaption><p>Process of initial price calculation</p></figcaption></figure>

### 2. **Discount Application**

After calculating the initial order price, we’ll use it as the baseline for applying the loyalty discount, taking into account the customer's credit to calculate the discounted total (Also in the templates).

<figure><img src="/files/fXBSPTJwoQiX1DBJH8Ni" alt=""><figcaption></figcaption></figure>

Add another **Business Rule** node to the canvas and select the Loyalty Discount decision table. Map the `initialTotal` to the `basicPrice` input field.

When mapping the customer's loyalty information, you have two options:

* **Map the entire customer object**: Use this if you want to pass all customer properties without making any alterations.

or

* **Map properties individually**: This is ideal if customer details are sourced from multiple variables, allowing you to map each property directly.

Both options work interchangeably, but note that they are mutually exclusive, as selecting one disables the other.

<figure><img src="/files/iWDqKJPfECAZZ7XrpLar" alt=""><figcaption><p>Mapping the Business Rule input</p></figcaption></figure>

### 3. **Generating the Order details**

Now that we have gathered all the necessary values, we can create the final order, which will include the total payable price, any missing items, and a personalized message. To map these values for display in the Decision Flow output, we'll utilize an **Assign** node. In the modal we will map all the information to output properties.

To generate a simple order ID, we can utilize the [**CONCAT** function](https://docs.decisionrules.io/doc/rules/data-types-and-functions/operators/functions/text#concatenation-concat), which combines today's date with the user's ID. This method ensures that each order ID is unique and easily traceable back to the specific user and the date of the order.

<figure><img src="/files/od5QYeqhOkE0AgDpss5B" alt=""><figcaption><p>Assigning values to Decision Flow Output</p></figcaption></figure>

To personalize the message shown to the customer, we will use a **Switch** node that checks for any items in the array created by the **Append** node.

<figure><img src="/files/HnfatMRoLPm6C8YoaS4W" alt=""><figcaption><p>Checking for any missing items</p></figcaption></figure>

If any items are out of stock, their identifiers will be stored in this array. The **Switch** node will direct the flow of the process based on the content of the array.  We will then use the contents of the array to craft a message for the customer, informing them about the unavailable items using **Assign** node to create tailored messages.

If all the items are available we can use message:&#x20;

```
"Thank you for your order! Your order will be shipped next business day." 
```

If any of the ordered items is missing, we can use the **CONCAT** function to generate a parameterized message that informs the customer specifically about the unavailable items:

{% code overflow="wrap" %}

```
CONCAT("Thank you for your order! Unfortunately, the following item(s) are currently out of stock: ",{items_unavailable},". We appreciate your understanding and the order will be shipped as soon as the items become available.")
```

{% endcode %}

{% hint style="info" %}
More about functions, their types and syntax can be found in [dedicated section of our documentation](https://docs.decisionrules.io/doc/rules/data-types-and-functions/operators/functions).
{% endhint %}

<figure><img src="/files/dWvZfidNHGG6I8ls99fx" alt=""><figcaption><p>Detail of Switch node directing the process</p></figcaption></figure>

To get a complete view of how data appears at the end of the Decision Flow, add **End** nodes right after the **Assign** nodes. When you run the Decision Flow, you’ll see the final data in each End’s **Inspect** tab, showing the actual results once the rule has fully executed. This provides a clear, final snapshot of all processed data.

<figure><img src="/files/V1YaCzgT1vkRJXrpo69C" alt=""><figcaption><p>Adding End nod for branches</p></figcaption></figure>

Congratulations! :tada: You've completed the Decision Flow, which might look something like this:

<figure><img src="/files/jGF5l6R9pSzoEZVibPaP" alt=""><figcaption><p>Decision Flow overview</p></figcaption></figure>

In the next section, we’ll test the Decision Flow with some inputs to ensure it’s functioning correctly. Before proceeding, please double-check that all Decision Flow nodes are fully configured and properly connected.

## Testing the Decision Flow

Testing your Decision Flow with sample inputs is an essential step to confirm it works as expected. We will start with main cases that cover scenarios, such as orders with available items, orders with missing items, and orders eligible for discounts.

Run the Decision Flow with these inputs and use the **Inspect** tab in the **End** nodes or Decision Flow Testbench to review the results. This allows you to verify that each node is executing correctly and that data flows through the Decision Flow as intended.

{% hint style="info" %}
Learn more about Decision Flow evaluation process [here](https://docs.decisionrules.io/doc/rules/flow#workflow-evaluation).
{% endhint %}

<details>

<summary>One item is not available, customer's first order (no discount)</summary>

```json
{
  "order": { 
    "items": ["P_0011","P_0009","P_0032","P_0021"],
    "branch": "SHOP_B",
    "customer": {
      "id": 123,
      "loyaltyClass": "FIRST_VISIT",
      "credit": 0
    }
  }
}
```

</details>

<details>

<summary>One item is not available, customer has loyalty class and credit</summary>

```json
{
  "order": { 
    "items": ["P_0011","P_0009","P_0032","P_0021"],
    "branch": "SHOP_B",
    "customer": {
      "id": 123,
      "loyaltyClass": "LOYALTY1",
      "credit": 32
    }
  }
}
```

</details>

<details>

<summary>All items are available, customer has loyalty class and credit</summary>

```json
{
  "order": { 
    "items": ["P_0011","P_0009","P_0032","P_0021"],
    "branch": "SHOP_A",
    "customer": {
      "id": 123,
      "loyaltyClass": "LOYALTY1",
      "credit": 32
    }
  }
}
```

</details>

## Summary

In this tutorial, we built a Decision Flow to process an order by calculating the initial price, checking for discounts, and identifying any out-of-stock items. We configured nodes to perform actions such as summing item prices, applying loyalty discounts, and generating a personalized message. Each node was mapped to the output model, giving us a complete order summary. Finally, we ran tests with sample inputs to validate the Decision Flow, ensuring that each component works as intended and provides accurate, actionable output for the customer.

To wrap up, let’s go over a few best practices to enhance your Decision Flow’s effectiveness and maintainability. These tips can help ensure smooth operation, improve readability, and make troubleshooting easier down the line:

* rename nodes added to the canvas to better fit your process and increase the readability
* test your Decision Flow during the process of creation to discover potentials errors as soon as possible
* use Sticky Notes to document the process for better understanding

See the Decision Flow below that you can easily import into your environment. This completed Decision Flow demonstrates all the processes we’ve covered, providing a clear example of how to configure and connect everything for effective order processing.

{% hint style="info" %}
Clicking the file below opens the file content in current tab. Once opened, right click and choose  "Save as" option to save the content as json file. Then you can use such file for folder import.
{% endhint %}

{% file src="/files/klz7Fiw4AEjqI0Zt7ke1" %}
Decision Flow tutorial folder json file
{% endfile %}


# Integration Flow

This page introduces the DecisionRules Integration Flow feature, highlighting its key capabilities and applications.

## Integration Flow Basics

Similar to the Decision Flow, this rule type is composed of a sequence of other rules. It orchestrates independent logical steps within a consistent process. Because they share a similar structure, Integration Flows are built as well by placing nodes on a canvas and connecting them with lines, utilizing a variety of available node types.

<figure><img src="/files/sCduXxtoh2DJ6wlepuGg" alt=""><figcaption></figcaption></figure>

However, the Integration Flow also features unique functionalities. The main distinction between a Decision Flow and an Integration Flow is that the former is designed for **synchronous** execution, while the latter is designed for **asynchronous** execution. Let’s briefly define these two concepts:

* **Synchronous:** This is a communication model where results are updated immediately (in real-time). When System A sends a request to System B, System A waits until the process is finished before continuing.
  * *Example*: This is like making a **phone call** to resolve an issue. You must stay on the line the entire time, but if the operator is efficient, the problem is resolved by the time you hang up. This is highly effective when results are generated in milliseconds.
* **Asynchronous:** This is a communication model where the request is sent, but the results are updated at a later time. When System A sends a request to System B, System A can continue with its usual processes and receive a notification only when the result is ready.
  * *Example*: This is like sending an **email** to resolve an issue. After sending it, you can ignore the request and continue with other tasks. Once you eventually receive a response, the problem is resolved. This model provides more freedom but typically involves a longer total wait time.

Therefore, consider these aspects to select the flow for your project:

| Quality      | Decision Flow                                                               | Integration Flow                                                      |
| ------------ | --------------------------------------------------------------------------- | --------------------------------------------------------------------- |
| Primary Goal | Daily business decisions for real-time response and high-performance logic. | Integration with external systems, long-running and batch processing. |
| Performance  | Optimized for millisecond response times.                                   | Optimized for reliability and connectivity.                           |

## Integration Flow Designer

The Designer features a canvas with a single **Start** node. On left side, you’ll find several tabs, with the **Palette** being the most important for now. The Palette lists all available node types with brief descriptions. To use a node, simply drag it from the palette onto the canvas.

Once a node is on the canvas, click it to open its detail settings. Each node type has different configuration options depending on its functionality. For detailed information on each node type, check the [**Workflow Nodes Overview**](https://docs.decisionrules.io/doc/rules/flow/flow-nodes-overview).

<figure><img src="/files/sjqXpx7bKKbFB1qDCRyt" alt="" width="563"><figcaption></figcaption></figure>

## Parallel Jobs

#### Jobs

For the sake of clarity, we refer to the execution of a Decision Flow as "solving a rule," whereas the execution of an Integration Flow is referred to as **running a job**. So, Jobs are the processes of Integration Flows and can take anywhere from a few minutes to several hours to complete.&#x20;

#### Parallel

Because of the asynchronous nature mentioned above, the Integration Flow is enhanced with a powerful capability: it can run jobs in **parallel**. This means that inputs are not necessarily executed sequentially; instead, the rule can handle multiple different jobs at once. In summary, an Integration Flow:

* Can be triggered by multiple external requests at the same time.
* Can trigger multiple external requests (e.g., calling three different credit bureaus) simultaneously.

This significantly reduces the total "waiting time" for the user or the system calling the flow.

{% hint style="info" %}
Note that the number of parallel jobs available for your Integration Flows depends on your specific subscription plan.&#x20;
{% endhint %}

## Connectors

While you can make standard REST API calls from any rule using functions to fetch external data, Integration Flows offer specialized nodes to connect directly and more efficiently with your databases. These are our *Data & Integration Nodes* (or Connectors).

We support a wide range of relevant databases for our connectors and continuously expand this list based on client requests.&#x20;

The most important aspect of implementation is as follows: "*To use these nodes, you must first connect your database to your DecisionRules Space*".&#x20;

#### Steps to connect your database

1. Go to left-side menu and click on <mark style="background-color:purple;">**Space**</mark>
2. On the new menu opened next to it, select <mark style="background-color:purple;">**Connectors**</mark>&#x20;
3. Click on the main purple frame: "Add Connector"
4. Select among the database options
5. Fill in the information required
6. Test the connector using the homonymous button <mark style="background-color:purple;">**Test Connector**</mark>
7. Press <mark style="background-color:purple;">**Create**</mark>&#x20;

&#x20;&#x20;

<figure><img src="/files/F6mE2QtWJI8OnBQKtIas" alt=""><figcaption></figcaption></figure>

## Webhooks

Since Integration Flows run as background Jobs, **Webhooks** are the primary mechanism for receiving notifications and output data once a process is finished. Instead of manually polling the [Jobs API](https://www.google.com/url?sa=E\&q=https%3A%2F%2Fdocs.decisionrules.io%2Fdoc%2Fapi%2Fjobs-api) to check if a task is done, a webhook automatically "pushes" the result to your system the moment the job reaches a final state.

* **Outbound Notifications:** You can use a Webhook to send a "callback" to another system. This is ideal for notifying a frontend application that a long-running process has finished or for logging results in an external monitoring tool.
* **Event-Driven Architecture:** This makes DecisionRules a central hub in an event-driven architecture, where your entire tech stack can act and react to changes in harmony.

{% hint style="info" %}
For more information about the Webhooks, see our dedicated [documentation](https://docs.decisionrules.io/doc/space/webhooks) section.
{% endhint %}


# Create an Integration Flow

Discover how to navigate Integration Flow features, understand its components, and follow a step-by-step guide to create a simple Integration Flow rule.

In this detailed end-to-end tutorial, we will guide you through the process of creating an Integration Flow. For this use case, we will build an employee segmentation and salary increment system.

This Integration Flow orchestrates a process involving a Decision Table, where the input to the table depends on values retrieved from a PostgreSQL database based on a specific region. Finally, the same database is updated with the decision reached by that Decision Table.

{% hint style="success" %}
The Decision Table can be created as sample right in DecisionRules platform
{% endhint %}

We'll cover navigating through the creation process, configuring Integration Flow nodes, and generating a final reporting-output containing the data updated in the database. At the end we’ll test our new rule with a couple of inputs to ensure it works as expected. This tutorial will help you understand key Integration Flow components and data manipulation techniques.&#x20;

{% hint style="info" %}
Only a few node types are used in this tutorial. For a complete list of available Decision Flow nodes, please refer to our dedicated [documentation page](https://docs.decisionrules.io/doc/rules/flow/flow-nodes-overview).
{% endhint %}

## Logic of the Flow

### IO Model

Our input model captures the key region to evaluate during the Job.

```json
{
  "employeesRegion": {}
}
```

The output model contains the list of employees receiving a raise `employeesBiggerSalary` , including their names, original salary, and the percentage increase. It also includes a `message` indicating the total number of employees processed. &#x20;

```json
{
  "employeesBiggerSalary": {},
  "message": {}
}
```

### Flow Steps

Establishing clear logical steps ensures an efficient design process:

1. **Data Retrieval:** Retrieve the list of employees for a specific region and the necessary data required to determine their percentage increase.
2. **Logic Execution:** Iterate through each employee to decide the appropriate percentage increase based on business conditions.
3. **Data Update & Reporting:** Update the database with the new calculated salary and collect key values to generate a final report.

## Building the Integration Flow

Now that we’ve outlined each step in the flow, it’s time to build our rule. In this section, we’ll configure the IO model, add and connect nodes, and map data across the flow to create the process.

Create a new blank **Integration Flow**. Switch from the "Designer" tab to the **"Model"** tab at the top of the screen to set up your Input and Output models as described above. Once defined, these variables (`employeesRegion` , `employeesBiggerSalary` , `message`) will be available throughout the flow.

<figure><img src="/files/FyQiVURmLSoK0inF0roJ" alt=""><figcaption></figcaption></figure>

{% hint style="danger" %}
Don't forget to save your I/O model.&#x20;
{% endhint %}

### 1. Data Management Input

Now it's time for adding first nodes to the canvas. Start by adding a **PostgreSQL** node, *drag-and-drop* this node from the palette on the left, and connect the **Start** node to it. This node will define the list of employees to be evaluated.

Click the node to open the configuration window and set the following:

* **Connector:** Select your pre-configured PostgreSQL connector.
* **SQL Statement:** Enter the query to retrieve the precise data.
* **Mapping:** Use the Data Dictionary to map the input variables.

&#x20;Recommended SQL statement:

```sql
SELECT employee_id, last_name, salary FROM australia_employees WHERE region = {input.employeesRegion}
```

{% hint style="warning" %}
The SQL statement will diverge according to the nature and structure of your database.
{% endhint %}

<figure><img src="/files/QxQAncIZWXs6wddO0o3y" alt=""><figcaption></figcaption></figure>

{% hint style="info" %}
Remember that you can '*drag-and-drop*' the attributes for mapping data, from the Data Dictionary inside the nodes.
{% endhint %}

### 2. Percentage Increase Selection

We will now use a Decision Table called **"Salary Increase Table"** to decide the percentage increase for each employee.

```json
//Table Input
{"salary": {}}
```

```json
//Table Output
{"pctIncrease": {}}
```

<figure><img src="/files/j8OBIxfAIHy6MpV71Qd3" alt=""><figcaption></figcaption></figure>

Because we are processing multiple employees, we will use the *Loop hook* at the bottom of the PostgreSQL node to repeat the evaluation for every row retrieved.&#x20;

To call the Salary Increase rule in the flow, drag a **Business Rule** node onto the canvas and connect it to the *Loop hook* of the PostgreSQL node. Inside the Business Rule node:

1. Select the **Salary Increase Table**.
2. You can keep Strategy and Rule Version configurations as they are.
3. Since you are in a loop, in the **Input Mapping**, map the *salary* from the *postgresql.currentRow* to the rule input.&#x20;

<figure><img src="/files/H621uiQWLmtkqVrvX3K3" alt=""><figcaption></figcaption></figure>

### 3. Data Management Updating

This step is divided into two parts: pushing results to the database and generating a report.

**Part A: Updating the Database**\
To update the salary in each iteration of the loop, drag a **PostgreSQL Single Row** node onto the canvas and connect it to the **Business Rule** node.&#x20;

To set this node follow similar steps to the last Data & Integration node, but in the Query field, enter the following statement:

```sql
UPDATE australia_employees 
SET latest_salary = {postgresql.currentRow.salary} * (1 + ({rule.currentItem.pctIncrease} / 100.0))
WHERE employee_id = {postgresql.currentRow.employee_id}; 
```

Becareful mapping the attributes-variables.

<figure><img src="/files/xYXvNUBr77VJyZrnzCJz" alt=""><figcaption></figcaption></figure>

**Part B: Generating the Report**

We’ve now completed the main goal of the Integration Flow. But as a corollary, a second part generates a simple job's report for immediate checking.&#x20;

To collect a list of all processed employees (including ID, Last Name, Original Salary, and Pct Increase), start by adding a **Collect** node. Drop it and connect it. Open the node and create a new *Target* called  `salary_report` . Configure the data structure of this new object creating an *Attribute* for each of the properties you want to report. After it, map the data from the Data Dictionary corresponding to the properties in the loop.&#x20;

<figure><img src="/files/3hgG4rSdoRYYkirFIrW9" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/rYsNQG4RbO4dvtodqc3x" alt="" width="563"><figcaption></figcaption></figure>

After collecting all the information, we'll use the `salary_report` to populate the output attribute  `employeesBiggerSalary` . Drag an **Assign** node from the palette and drop it on the canvas next to the first **PostgreSQL** node. Connect the *Exit hook* of the **PostgreSQL** node to the new **Assign** node. This ensures the branch executes only after the entire loop is complete.

Map the data for the assignment: Open the new node, move the two outputs of your model to the *Target* fields, and use the `salary_report` for the first one; use the native *rowCount* of the **PostgreSQL** node to paremeterize the message of the second one:&#x20;

<figure><img src="/files/yAVXmMTLLxThFPB9UrIt" alt=""><figcaption></figcaption></figure>

Finally, add an **End** node after the Assign node. You can use the **Inspect** tab on the End node during execution to see a final snapshot of all processed data.

Congratulations! 🎉 You've completed the Integration Flow, which might look something like this:

<figure><img src="/files/40BpyXFPW2GvAlQQQCrd" alt=""><figcaption></figcaption></figure>

In the next section, we’ll test the Integration Flow with a couple of inputs to ensure it’s functioning correctly. Before proceeding, please double-check that all Integration Flow nodes are fully configured and properly connected.

## Testing the Integration Flow

Testing your Integration Flow with sample inputs is essential to confirm it works as expected. We recommend testing with different regions (e.g., "West" and "East Australia").

{% hint style="warning" %}
The good performance of the flow depends strongly on the content and structure of your database. This example is for a possible table called "employees\_australia".
{% endhint %}

1. Open the **Test Bench**.
2. Input a sample region: {"employeesRegion": "West"}.
3. Click <mark style="color:purple;background-color:purple;">**Start a New Job**</mark> to test and review the results. This allows you to verify that each node is executing correctly and that data flows as intended.

<details>

<summary>West Australia</summary>

Input:

```json
{
  "employeesRegion": "West"
}
```

</details>

<details>

<summary>East Australia</summary>

Input:

```json
{
  "employeesRegion": "East"
}
```

</details>

<figure><img src="/files/xenZLEj1B3S7ACXIJz4N" alt=""><figcaption></figcaption></figure>

If the database is very big or complex, the process could take several minutes. Running this Jobs you will have a dashboard to check the *status* of each one. Navigate to the menu through Space → Jobs:

<figure><img src="/files/xdQnineb1mjYvmWubpTF" alt=""><figcaption></figcaption></figure>

#### Webhooks

To complete your setup, you can integrate Webhooks to notify your external systems when a job finishes.

First, you have to link the Webhook to your Space.

1. **Global Management:** Navigate to Space → Webhooks and click the *+ Add Webhook* button.
2. **Endpoint URL:** The destination address where DecisionRules will send the data.
3. **Alias:** A unique name to identify the webhook within your Space.
4. **Events to Send:** You can choose which Job statuses trigger the webhook. For example, you might have one webhook for *Successful* executions and another for *Cancellations* or *Errors*.
5. **Status:** A toggle to quickly enable or disable the webhook without deleting its configuration.

<figure><img src="/files/9UVfEWY3P48c8bHFxy6l" alt=""><figcaption></figcaption></figure>

Second, inside your Integration Flow, click the *"Webhooks"* button in the top-right corner and select the webhook you just created.

{% hint style="info" %}
To verify that your setup is working correctly before connecting your production systems, we recommend using a tool like [webhook.site](https://www.google.com/url?sa=E\&q=https%3A%2F%2Fwebhook.site).
{% endhint %}

<figure><img src="/files/MYgxzZHWHMNrj2fZwz3b" alt=""><figcaption></figcaption></figure>

Test final connection of your Webhooks in similar way, starting a new Job for the flow, either in the Test Bench or through an external API call.&#x20;


# Lookup Tables

## Introduction

Lookup Tables are not rules in the proper sense; however, they are a fundamental component of many business logic workflows because they store the data used during the execution of other rule types.

The first step in understanding this key element is distinguishing it from two similar concepts: our **Decision Tables** and the term "lookup table" as it is used in general data structure practices. Let’s start with Decision Tables:

By comparison, Decision Tables act as a **Decision Engine**, whereas Lookup Tables serve as a **Retrieval Engine**. The former evaluates complex conditions using calculations and variables to get results, while the latter is designed for fast and efficient data retrieval. Lookup Tables serve as a repository for your data; Decision Tables process that data to reach a specific decision. Even though both tables may look similar externally, they have different goals, which in turn drive their specific design and performance.

It is also important to distinguish this from similar concepts in other fields. In general data literature, the term "lookup table" is actually closer to our Decision Tables than the Lookup Tables presented here. Traditionally, a "lookup table" is a data structure that replaces runtime calculations with a table of pre-calculated results. By replacing mathematical operations with direct memory access, it increases speed. However, this usually implies a mapping from multiple inputs to multiple outputs. Lookup Tables in DecisionRules are different: the only way to retrieve the data in a row is through a single value—the **Primary Key**.

In conclusion, a Lookup Table is a structured way to store and retrieve reference data using a high-performance key-value approach.

<figure><img src="/files/JaFVsP2JJu50GWiaEbar" alt=""><figcaption></figcaption></figure>

## Look up Table Designer

Externally, a Lookup Table also resembles an Excel spreadsheet; it is divided into columns and rows where you can enter values into cells. However, it is simpler because it does not use functions. The table is conceptually divided into two parts: the column for the Primary Key and the columns storing all the data related to each key.

Because of the architectural differences mentioned above, these tables do not use an Input/Output model. Instead, the only attributes used to call the rule are the **Primary Key** and, optionally, a specific **Output Column**. If the output column is not specified, the rule retrieves values from all columns associated with that key.

<figure><img src="/files/4tcaPFV0jEFgFNjggn9Z" alt=""><figcaption></figcaption></figure>

#### Adding and building columns

The columns in a Lookup Table define the "shape" and structure of your data. Instead of "If" and "Then" columns, you simply define a Primary Key and as many standard data columns as your use case requires.

Setting up this structure is a visual and intuitive process. To expand your table, simply click the "**+**" sign located next to your rightmost column. If you need to rename a column to better reflect your data, you can do so instantly by *double-clicking* the header or using the *right-click* context menu.

The designer also allows for easy organization; if you decide a different column order would be more readable, you can *click and drag* headers to reposition them. To remove a column, just select **Delete Column** from the header’s dropdown menu and continue with your design.

{% hint style="warning" %}
**The Primary Key Rule:**\
The Primary Key column is the "anchor" of your table and is always pinned to the far left. To ensure data integrity, it cannot be moved, deleted, or changed once the table is established. If your project requires a different Primary Key, you will need to create a new Lookup Table.
{% endhint %}

<figure><img src="/files/2bSj20Lt75mCurdOyTTK" alt=""><figcaption></figcaption></figure>

#### Adding and building rows

Once your structure is in place, the body of the table is where you bring your data to life. Adding a single record is as simple as clicking the  <mark style="background-color:purple;">**+ Add Row**</mark>  button in the bottom toolbar, which generates an empty row at the end of your list.

For more complex data management, the designer offers a suite of Row Operations accessible via a *right-click* on any row header. From here, you can **Duplicate** a row to quickly create similar records, or **Insert** new rows exactly where you need them—either above or below your current selection. If you are handling large datasets, you can save time by editing **multiple rows at once**; simply hold **Ctrl** (or **Cmd**) to select specific rows, or use **Shift** to highlight an entire range.

<figure><img src="/files/KsVvcU8cdSSAUzzIjZTY" alt=""><figcaption></figcaption></figure>

{% hint style="info" %}
For more details on the Lookup Table Designer, please consult our [official documentation](https://docs.decisionrules.io/doc/rules/lookup-table/lookup-table-designer).&#x20;
{% endhint %}

#### Primary Key Validation

Because Lookup Tables are built for absolute precision, the **Primary Key** is the most critical element of your table. To prevent errors in your decision logic, the designer acts as a guardian, automatically validating your keys in real-time as you type.

If you accidentally enter a key that already exists, the cell will immediately turn **red**, and a validation error will notify you of the **Duplicate Detection**. Similarly, the system ensures you never leave a "blind spot" in your data; because every row must be findable, the **Empty Key** validation will highlight any blank primary key cells that require attention.

To keep your workflow smooth, you cannot save a version of the table that contains errors. If you are working with thousands of rows, you don't need to hunt for mistakes manually—simply use the **Error Navigator** in the toolbar to jump directly to any row that needs a correction.


# Create a Simple Lookup Table

This tutorial will walk you through the creation of a simple Lookup Table.

In this detailed end-to-end tutorial, we’ll guide you through creating a simple Lookup Table that keeps in one repository the data of different banks, that after is used for transactions. This Lookup Table integrates to a decision table for evaluating a transaction fee according to the bank's country.&#x20;

## How to create a simple lookup table

Let's advance one step at a time.

### 1. Create a new Decision Table

To display the rules creation list, click the <mark style="background-color:purple;">**+ Create**</mark> button on the search bar. Select your rule and you will be prompted to provide a nam&#x65;**.** For this example, we will create a table for Bank Data Catalog, select a name for your rule as you wish and press "Confirm". The new rule will be created and its design interface will be displayed.

<figure><img src="/files/PCiogJfrPrXfNjyaYrq7" alt=""><figcaption></figcaption></figure>

### 2. Make basic settings

Rule Settings will be in a left-hand side menu. Let's do some settings. You can switch the toggle status between **Published** and **Pending**. Modify the Rule name or the Alias. Write a short description of the table.

To apply these changes, we have to click the <mark style="background-color:orange;">**Save**</mark> button at the top of the page, right corner.

### 3. Set the columns

To define your data columns, navigate to the first column after the Primary Key. *Double-click* the header to rename it; enter the name of the first property, i.e.  `BankName` . To expand your table, simply click the **"+"** sign located next to your rightmost column. You can rename the next column  `Country` with the same method, or using the dropdown menu clicking the small arrow on the header. The last one must contains the specific `RoutingMethod` , repeat the same steps. &#x20;

<figure><img src="/files/39OfWdK3z1DjDiSp0ITY" alt=""><figcaption></figcaption></figure>

### 4. Set the rows

Now, begin filling in the information for each bank. In this example, banks are indexed by their unique SWIFT Codes, so the **Primary Key** must contain these codes. This maps each Swift Code to the critical banking attributes defined in your columns.&#x20;

Let’s start with "Bank of America":

| Swift Code | BankName        | Country | RoutingMethod |
| ---------- | --------------- | ------- | ------------- |
| BOFAUS3N   | Bank of America | USA     | WIRE\_FAST    |

Click the  <mark style="background-color:purple;">**+ Add Row**</mark>  button in the bottom toolbar, and fill in the data for the next bank, for instance *JPMorgan Chase*. Iterate the process for each new bank you want to add to the table.&#x20;

<figure><img src="/files/JaFVsP2JJu50GWiaEbar" alt=""><figcaption></figcaption></figure>

{% hint style="info" %}
You can find a JSON file of this rule containing all countries here below. You may download it and import it directly into your Space.
{% endhint %}

{% file src="/files/naNWTjqKJXOHWWtsbFuW" %}

### 5. Using Lookup Tables within other Rules

Next, create a **Decision Table** called *Fee Multiplier* to calculate transaction fees based on the bank in use. The Input/Output model will be:

```
// Input model
{
  "swiftCode": {},
  "originCountry": {}
}
```

```
// Output model
{
  "feeMultiplier": {},
  "message": {}
}
```

The table will evaluate two conditions: **SWIFT Code Validity** and **Country of Origin**. The three logic scenarios are as follows:

1. **Invalid Code:** IF the Swift Code does not exist, THEN the transaction is invalid.
2. **Domestic Transfer:** IF the Code exists and the bank's country matches the *originCountry*, THEN the transaction is valid with no fee.
3. **International Transfer:** IF the Code exists but the bank's country is different from the *originCountry*, THEN the transaction is valid with a 30% fee.

To evaluate these conditions dynamically, add a **Calculation Column** to retrieve the country data from your Lookup Table. Use the [LOOKUP\_VALUE()](https://docs.decisionrules.io/doc/rules/lookup-table/using-lookup-tables-in-rules) function, which requires four parameters: the table's alias, the primary key, the table version, and the column name.

```
LOOKUP_VALUE("bank-catalog-alias", {swiftCode}, null,"Country")
```

You can now use the country retrieved from your Lookup Table to set your conditions. The first condition column validates that the function result is **not null**; if it is null, the SWIFT code does not exist in our catalog. The second condition column matches the *originCountry* from the input with the data gathered from the Lookup Table.

<figure><img src="/files/OC8KgzlpFKg04Vmmua4j" alt=""><figcaption></figcaption></figure>

Finally, set the results. For the first row, the *feeMultiplier* is empty (invalid). For the second row, it is **1** (no fee). For the third row, it is **1.3** (representing the 30% increase). You can customize the messages as you see fit.&#x20;

<figure><img src="/files/3weRs7ACPDR8A03e5Mbb" alt=""><figcaption></figcaption></figure>

### 6. Test the Decision Table

You can now test the functionality of your Lookup Table by evaluating the Decision Table we just created. Open the **Test Bench** at the bottom of your the designer for your *Fee Multiplier* **Decision Table**.

Enter your input data and click the <mark style="background-color:green;">**Run**</mark> button; the results will be displayed on the right-hand side. Note that you can switch between the **Simple Bench** and the **JSON Bench**.

<figure><img src="/files/TZ1LOqzmKuNtbg9WDoop" alt="" width="563"><figcaption></figcaption></figure>

For example, using the **JSON Bench**, input the following data:

```javascript
{
  "swiftCode": "HBUSGB4B",
  "originCountry": "UK"
}
```

Upon hitting <mark style="background-color:green;">**Run**</mark> , we will get the following response.

```javascript
[
  {
    "feeMultiplier": 1,
    "message": "Domestic transfer to UK"
  }
]
```

{% hint style="info" %}
More information about Test Bench can be found [<mark style="color:purple;">here</mark>](https://docs.decisionrules.io/doc/rules/common-rule-features/test-bench).
{% endhint %}

If you have arrived here, you have successfully completed the tutorial. Congratulations!


# AI Agent Rules

This page is an introduction to the DecisionRules AI Rule.

## Introduction

DecisionRules features two core AI capabilities:

* **AI Assistant:** For authoring and navigating rules faster, supporting your business rule construction.
* **AI Agent Rule:** For the integration of Large Language Model (LLM) technology into precise and deterministic decision-making flows.

In this section we will focus on the second one, you can find more information about the [AI Assistant](https://docs.decisionrules.io/doc/ai-assistant/about-ai-assistant) in our documentation.&#x20;

While current LLMs work with probability predictions and so can lead to 'hallucinations', Decision Engines are designed for deterministic outcomes and strong auditing. Therefore, for effective integration with our reliable rules, DecisionRules constrains LLMs to an input/output model with a precise structure to guarantee an explainable and predictable business rule.

The **AI Agent Rule** able to handle unstructured tasks— language reasoning, document analysis, handling ambiguity— otherwise not covered by more rigid rules. It transforms unstructured or complex data into **typed, structured JSON responses**, ensuring that even when you use AI, the final outcome remains integrated into a predictable and stable Decision Flow.

{% hint style="info" %}
You can always use the AI Agent by itself, and it is the main advantage, because you define all the logic in natural language without explicit conditional sentences. However, it is a good practice to use an AI Agent to handle the "messy" data at the start of a process, and then pass its structured JSON output to other rules for a final, 100% deterministic result.
{% endhint %}

<figure><img src="/files/auOGBwXH1V7lepZoH4qT" alt=""><figcaption></figcaption></figure>

## AI Agent Rule Designer

The AI Agent Designer is optimized to help you bridge the gap between natural language instructions and clear decisions. The interface is split into two primary areas: the **Left Sidebar** for configurations and the **Main Panel** for building your logic.

### Left Sidebar

The sidebar handles the environment in which your model operates. To set up this background you configure the rule sources and the optional features:

* **AI Model:** Select the specific Large Language Model (LLM) you wish to use (e.g., GPT-4, Claude, etc.).
* **Connector:** Manages the authenticated link between DecisionRules and the AI provider, ensuring secure communication.
* **Cache AI Response (Toggle):** A toggle to enable [caching](https://docs.decisionrules.io/doc/rules/ai-agent/caching). This ensures that identical inputs return the same result instantly, reducing costs and increasing speed for repeated requests.
* **Explainable AI (Toggle):** Enables the generation of a system-defined [explanation text](https://docs.decisionrules.io/doc/rules/ai-agent/explainable-ai), providing transparency into why the model reached a specific conclusion.
* **Data Dictionary:** A live reference panel of all available data. This allows you to drag and drop *Input variables*, *Rule Variables*, and *Attachments* directly into your instructions.

<figure><img src="/files/R7phif83qFgcb24ebKHX" alt=""><figcaption></figcaption></figure>

### The Main Panel

This panel is the blank notebook where you describe the plot of your rule. It is organised into four specialized bookmarks:

* **Prompt / Instruction:** The core of the rule. Here, you write natural language instructions telling the AI what to do. You can use {*variables*} from your Data Dictionary to inject real-time data into your prompt.
* **Annotations:** This is the most critical tab for deterministic results. Here, you define exactly what the output JSON should look like, providing data types (Text, Number, Boolean, etc.) and descriptions for every field the model returns.
* **Explainable AI:** Active only when toggled in the sidebar, this tab lets you configure four fields that help auditing the model's logic: `probability`, `reason`, `source_fragments`, and `warnings`. These fields are injected automatically.
* **Attachments:** Allows you to upload reference documents (PDFs, TXT, etc.). These files become part of the rule's versioned logic, allowing the AI to "read" specific policies or guidelines before making a decision.

<figure><img src="/files/YXH5cplQ3O5jHjlsufvq" alt=""><figcaption></figcaption></figure>

## Connectors

DecisionRules Spaces allow you to connect directly and more efficiently with your AI provider. These AI models that are set by a secure communication as authentizise provider for all the rules in the Space are counted as [**Connectors**](https://docs.decisionrules.io/doc/space/connectors), it means, you can manage them along side Data and Integration providers. &#x20;

We support a wide range of relevant Large Language Models for our connectors and continuously expand this list based on client requests.&#x20;

**The most important aspect of implementation is as follows:** "*To use a model in the AI Agent Rule, you must first connect your LLM to your DecisionRules Space*".&#x20;

#### Steps to connect your LLM

1. Go to left-side menu and click on <mark style="background-color:purple;">**Space**</mark>
2. On the new menu opened next to it, select <mark style="background-color:purple;">**Connectors**</mark>&#x20;
3. Click on the main purple frame: "Add Connector"
4. Select among the AI models options
5. Fill in the information required
6. Press <mark style="background-color:purple;">**Create**</mark>&#x20;

&#x20;&#x20;

<figure><img src="/files/F6mE2QtWJI8OnBQKtIas" alt=""><figcaption></figcaption></figure>

{% hint style="info" %}
You can also configure the connection of a new model within the **Left sidebar** of the *AI Agent Designer*, just click the <mark style="background-color:purple;">**+ Create**</mark> button next to Connectors.&#x20;
{% endhint %}

With the tutorial below you will be able to create a simple AI Agent Rule and discover how to integrate the new funcionalities within a Decision Flow.&#x20;

{% content-ref url="/pages/zUvVqvVlKPzXlvtuk9No" %}
[Create a Simple AI Agent Rule](/rule-types/ai-agent-rules/create-a-simple-ai-agent-rule)
{% endcontent-ref %}


# Create a Simple AI Agent Rule

{% hint style="success" %}
All steps in this tutorial can be created and managed directly within the DecisionRules app.
{% endhint %}

**Use Case:** The rules in this tutorial are designed to be called by a user when a new NDA arrives and the team needs to determine necessary redlines in real time.

**Goal:** The goal is to automate the process so the system sends the NDA to DecisionRules and retrieves data identifying the redlines that must be addressed.

The primary features in DecisionRules used to achieve this goal are the **AI Agent Rule** and the **Decision Flow**. In this detailed end-to-end tutorial, we will guide you through building an AI Agent Rule to analyze the unstructured data in a new NDA and return it in a structured JSON format. In the second part, we will model a Decision Flow that integrates the AI Agent Rule to achieve the goal in a predictable, deterministic way.

We will cover navigating the creation process, configuring Decision Flow nodes, and generating the final output. This includes: Identifying redlines based on rule evaluations, providing text references for those redlines, and creating personalized messages in case of misbehaviour because the unstructured data is inconsistent.&#x20;

At the end we’ll test our new rule with one mock example. This tutorial will help you understand key **AI Agent Rule** practices and data manipulation techniques.&#x20;

## 1st Part: How to create a simple AI agent rule

Let's advance one step at a time.

### 1. Create a new AI Agent Rule

To display the rules creation list, click the <mark style="background-color:purple;">**+ Create**</mark> button on the search bar. Select your rule and you will be prompted to provide a nam&#x65;**.** For this example, we will create a **AI Agent Rule** for analysing a new NDA, select a name for your rule as you wish and press "Confirm". The new rule will be created and its design interface will be displayed.

<figure><img src="/files/2SW6hS5WJPSP6l5McWKm" alt=""><figcaption></figcaption></figure>

### 2. Create the input and output (I/O) model

We will now create the **Input/Output** model which is used to set the instructions for the AI and the fields of the output. Similar to the other rules, there are two ways to write these models:

#### Using the simple editor

First, you can switch from "Designer" to "Model" at the centre of the top bar.&#x20;

<figure><img src="/files/YdWO8CfCEHd0S8i2ErHv" alt=""><figcaption></figcaption></figure>

**Delete the default attribute "input"** by clicking the trash can icon next to the name. Then, add your own attributes: First create the root of your attributes clicking the **+Add** button. For this example, you will only need one root: <mark style="color:purple;background-color:purple;">**nda**</mark>. AAfterward, you can add all the data required for the analysis of that `nda` object: <mark style="color:purple;background-color:purple;">**originatingParty**</mark>, <mark style="color:purple;background-color:purple;">**disclosingParty**</mark>, <mark style="color:purple;background-color:purple;">**receivingParty**</mark>, and <mark style="color:purple;background-color:purple;">**text**</mark>.&#x20;

<figure><img src="/files/afxGRVJZyV5XQclSv8m2" alt=""><figcaption></figcaption></figure>

Now, let's proceed with the output model. It is configured in the same way. Add two root attributes: <mark style="color:green;background-color:green;">**terms**</mark> and <mark style="color:green;background-color:green;">**reference**</mark>. Then, add identical child attributes to both roots, as they are logically connected.

* **The `terms` fields** are designed to capture the precise data, indicating whether the information exists and providing the exact number, name, or sentence.
* **The `reference` fields** will store the exact words from the text that the AI used to generate the corresponding "terms" report.

Rename the new attributes according to the information you wish to obtain. A comprehensive list of attributes that will be useful for future examples and exercises includes:

* <mark style="color:green;background-color:green;">**scope\_and\_definition**</mark>, <mark style="color:green;background-color:green;">**confidentiality\_period\_years**</mark>, <mark style="color:green;background-color:green;">**governing\_law**</mark>, <mark style="color:green;background-color:green;">**notice\_period\_days**</mark>, <mark style="color:green;background-color:green;">**reciprocity**</mark>, <mark style="color:green;background-color:green;">**exclusions**</mark>, <mark style="color:green;background-color:green;">**permitted\_disclosures**</mark>, <mark style="color:green;background-color:green;">**liability\_cap\_usd**</mark>, <mark style="color:green;background-color:green;">**return\_of\_information\_required**</mark>, <mark style="color:green;background-color:green;">**return\_deadline\_days**</mark>, and <mark style="color:green;background-color:green;">**residuals\_clause**</mark>.&#x20;

{% hint style="warning" %}
You don't have to write one by one the attributes, see how to use the **JSON editor** below.
{% endhint %}

<figure><img src="/files/FS2MeeCahVDYdLGvMNbl" alt="" width="375"><figcaption></figcaption></figure>

#### Using the JSON editor

Alternatively, **the JSON editor can reduce the time required to define your I/O model** through simple copying and pasting. You can provide the input and output models in JSON format from any external source. For this tutorial, use the following format to copy and paste into your editor:

{% tabs %}
{% tab title="Input Model" %}

```json
{
  "nda": {
    "originatingParty": {},
    "disclousingParty": {},
    "receivingParty": {},
    "text": {}
  }
}
```

{% endtab %}

{% tab title="Output Model" %}

```json
{
  "terms": {
    "scope_and_definition": {},
    "confidentiality_period_years": {},
    "governing_law": {},
    "notice_period_days": {},
    "reciprocity": {},
    "exclusions": {},
    "permitted_disclosures": {},
    "liability_cap_usd": {},
    "return_of_information_required": {},
    "return_deadline_days": {},
    "residuals_clause": {}
  },
  "reference": {
    "scope_and_definition": {},
    "confidentiality_period_years": {},
    "governing_law": {},
    "notice_period_days": {},
    "reciprocity": {},
    "exclusions": {},
    "permitted_disclosures": {},
    "liability_cap_usd": {},
    "return_of_information_required": {},
    "return_deadline_days": {},
    "residuals_clause": {}
  }
}
```

{% endtab %}
{% endtabs %}

<figure><img src="/files/HTpi4UnTMFw3j7BHeOxD" alt=""><figcaption></figcaption></figure>

For now, we are done!

{% hint style="warning" %}
After creating an input and output (I/O) model, we must always confirm the changes with the <mark style="color:orange;background-color:orange;">**Save**</mark> button.
{% endhint %}

{% hint style="info" %}
More information on the JSON editor can be found [<mark style="color:purple;">here</mark>](https://docs.decisionrules.io/doc/decision-tables/input-and-output/json-editor).
{% endhint %}

### 3. Set the configurations of the background

To set up the environment where your LLM will operate, switch back from the "Model" view to the "Designer" view. Use the left sidebar to configure the settings according to your requirements:

* **AI Model:** We will use *Gemini 1.5 Flash* as an example. You can, of course, select any other available model from the dropdown list in your rule.
* **Connector:** For this example, our LLM is connected via a [connector](https://docs.decisionrules.io/doc/space/connectors) named *gemini (connection-vhksg)*. The options shown to you will depend on the connectors you have already created in your Space.
* **Cache AI Response (Toggle):** During the creation and testing of this new rule, you should activate the **Cache**.
* **Explainable AI (Toggle):** For this tutorial, Explainable AI is not necessary. It is better suited for more advanced exercises.
* **Data Dictionary:** Briefly check this panel to ensure you have all the information required to build your prompt.

{% hint style="success" %}
**Best Practices:** Activating the **Cache** allows you to perform faster tests and ensures consistent analysis when using the same input repeatedly. This is highly recommended during the rule construction phase.
{% endhint %}

<figure><img src="/files/HlPVL7dxCsjD9oVOf2aP" alt=""><figcaption></figcaption></figure>

### 4. Build the Prompt

Prompt engineering practices evolve rapidly; therefore, the suggestions in this section will be continuously improved. What is relevant to notice is to apply the best DecisionRules practices for instructions: Ensure your input model is framed with precision, use the Data Dictionary as direct reference, and write with your best clarity.&#x20;

For this example, we will explicitly define the **Role** assumed by the AI, the **Context** of the analysis, and the **Task** required from the model.&#x20;

{% prompt description="" %}

```markdown
## ROLE
You are a senior legal compliance analyst with deep expertise in NDA review, contract standards enforcement, and commercial contract negotiation.

## CONTEXT
You are analyzing a NDA submitted by {nda.originatingParty} for legal revision and red-line version. The disclousing party of the NDA is {nda.disclousingParty}  and the receiving party is {nda.receivingParty}. 

NDA = {nda.text}

## TASK
Read the NDA and extract all structured fields defined in the output schema. 

terms' fields are expecting a report: whether the data exist; what exact number, name or sentence it is; a judgemnet if the information is not clear.

reference's fields are expecting: the precise words in the text from where you are taking the report for terms. 

Use only the allowed values listed in each field annotation. Extract values directly from the nda.
For every output field that cannot be determined from the report — return null.
For every output field that can be determined and the answer is explicitely negative - return false.
```

{% endprompt %}

The placeholders in the form *{a.b}* (such as *{nda.text}*) are dynamic attributes. At runtime, DecisionRules replaces these placeholders with the actual content of your input payload. This allows a single AI Agent rule to analyze thousands of different NDAs. &#x20;

**Remark:** If your analysis requires a reference document (such as a company standard or a regulatory guideline), you can use the **Attachments** feature:

1. Navigate to the Attachments tab and click Add Attachment to upload your file (PDF, TXT, etc.).
2. Return to the Prompt/Instruction editor.
3. Drag the file from the Data Dictionary into your prompt. The AI will now be able to reason across both the input data and the attached document.

### 5. Edit the Annotations

Annotations are the most critical part of the AI Agent rule because they define the conditions of engagement for the model's response. Here you will find the most extensive work. We will cover each detail.

In the main panel, navigate to the "Annotations" tab. The interface is organised into three columns:

The first column reflects your **output model**. The second column is for the specification of the **data types** expected in each particular output attribute. The third column is **a description** of what exactly you are expecting and how.  &#x20;

<figure><img src="/files/y6tvN1djR9T7iqaSiEBV" alt=""><figcaption></figcaption></figure>

**Setting Data Types:** Root attributes (like `terms` and  `reference` ) will always be of the **{} Object** type. For the "child" attributes under *terms*, select the type that best fits the logic. For instance, using **Number** for years or **Boolean** for the presence of a clause. This ensures your downstream Decision Flows can process the data without errors.

| Attribute                      | Data Type |
| ------------------------------ | --------- |
| scope\_and\_definition         | Text      |
| confidentiality\_period\_years | Number    |
| governing\_law                 | Text      |
| liability\_cap\_usd            | Number    |
| permitted\_disclosures         | Boolean   |
| residuals\_clause              | Boolean   |

<figure><img src="/files/PmBw95OaqlzvgnGUglQH" alt=""><figcaption></figcaption></figure>

**Writing Effective Descriptions:** Your descriptions should be treated as "mini-prompts." A good description includes the conditions required to satisfy the field. To exemplify this feature, we will focus on the *reference* root, and the description of its "child" attributes.

First, ensure all its child attributes are set to the **Text** data type. These descriptions should follow a consistent pattern, instructing the AI to provide the verbatim evidence from the NDA. For instance:

| Attribute                      | Description                                                                                                                                            |
| ------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------ |
| scope\_and\_definition         | Return a string with the exact words in the text of the nda, where you extracted the info for the ouput above: *terms.scope\_and\_definition*.         |
| confidentiality\_period\_years | Return a string with the exact words in the text of the nda, where you extracted the info for the ouput above: *terms.confidentiality\_period\_years*. |

{% hint style="warning" %}
**Note:** The last column must be filled for every object in the output, including the root folders. Providing a description for the root helps the model understand the overall context of that data group.
{% endhint %}

### 6. Test the Agent

Now we can test our rule in the **Test Bench**. Click the **Test Bench** icon on the far left of the bottom bar. Once clicked, the Test Bench will appear at the bottom of the page.

You can then fill in some mock data using the sample NDA provided below. Use the specifications from the document to complete the input fields, and remember to paste the full text of the NDA into the nda.text field. Click the **Run** button, and the results will be displayed on the right-hand side of the Bench. Note that you can switch between the **Simple Bench** and the **JSON Bench** to view the output.

{% file src="/files/Q4v6WkWUloEFqQ0dXUZL" %}

<figure><img src="/files/Id8VKYKXBIZDmgeDTLJN" alt=""><figcaption></figcaption></figure>

## 2nd Part: How to integrate **the AI Agent Rule into a Decision Flow**

In this section, we will create a Decision Flow that uses the structured data provided by the AI Agent rule to validate NDA parameters against company standards and determine which redlines are pertinent.

### Intro: Logic of the flow

#### IO Model

Our **Input Model** captures the data required to run the AI Agent rule from Part 1; therefore, it will replicate that rule's input model. This design is due to the fact that the results from the AI node contain all the information necessary to drive the other rules and nodes in the flow, and it will be the first node.

Our **Output Model** is constructed slightly different. It includes `redline` validation, the specific text `reference` used to accept or reject those redlines, and `error` handling options to manage potential drawbacks. In this sample, the company evaluates four minimal standards for accepting an NDA (more complex sets of standards will be handled in future examples).

{% tabs %}
{% tab title="Input Model" %}

```json
{
  "nda": {
    "originatingParty": {},
    "disclousingParty": {},
    "receivingParty": {},
    "text": {}
  }
}
```

{% endtab %}

{% tab title="Output Model" %}

```jsonl
{
  "redline": {
    "confidentiality_period_years": {},
    "governing_law": {},
    "notice_period_days": {},
    "reciprocity": {}
  },
  "reference": {
    "confidentiality_period_years": {},
    "governing_law": {},
    "notice_period_days": {},
    "reciprocity": {}
  },
  "errors": {
    "types": {},
    "message": {}
  }
}
```

{% endtab %}
{% endtabs %}

#### Flow of the Process

When designing the Decision Flow as a decision process, establishing a logical steps ensures a faster selection and location of the nodes.&#x20;

1. **AI Analysis**: Start by converting the unstructured data of the NDA text into a typed JSON response. This step enables the precise extraction of attributes from the NDA for evaluation. At this stage, the AI analysis is key to using other strong, predictable rules over the NDA.
2. **Validation of Company Standards**: This is the core of the flow; the company's standards are saved as Rules within the Space. The flow will call four rules to evaluate a set of four minimal standards: *the confidentiality period*, *the governing law country*, *the notice period*, and *the reciprocity of the agreement*. Based on these rules, the system decides which sections of the NDA should be redlined.
3. **Error Handling:** Due to the nature of AI, it is not guaranteed that the NDA will provide all necessary data in the first call, and LLM response times can vary. With a couple of nodes, we design a path to follow in case the NDA is missing information or the LLM request times out. These nodes provide a warning and a message to help resolve the issues quickly.
4. **Generating the Final Redlines:** Use the values from the previous steps to populate the properties specified in the output model. Additionally, if there are errors, an appropriate error message is sent.

### 1. AI Analysis

It is time to add the first node to the canvas. Begin by adding an **AI Agent node** and connecting the **Start node** to it. Open the node settings, click the *Select Agent* dropdown, and choose the AI Agent rule you created to analyze the NDA. Once selected, the rule's input model will be displayed. You now need to map the data from the Data Dictionary to the rule's input: drag and drop the `nda` root from the Data Dictionary into the *Rule Inputs* section for the attribute named  `nda` . Save the values in the modal.

<figure><img src="/files/l6m8Zdfwidvv13nzS941" alt=""><figcaption><p>Adding the AI Agent node</p></figcaption></figure>

### 2. Validation of Company Standards

Drag and drop four Business Rule nodes onto the canvas and position them in parallel to the right of the AI Agent node.&#x20;

In the first **Business Rule** we will use the *Reciprocity* tree (A JSON file with the design of the rule is here below). The standard is simple: **The NDA must be reciprocal**. The logic of the standard can be expressed in a Decision Tree keeping the simplicity:&#x20;

1. **Missed information:** IF the field for the NDA reciprocity report is empty, THEN return error message (Remember the AI can result null if the NDA is not clear).
2. **Reciprocal NDA:** IF the NDA reciprocity report contains true, THEN return passed.
3. **No Reciprocal NDA:** IF the NDA reciprocity report contains false, THEN return failed and the reason.&#x20;

{% file src="/files/NsR33iTd6HVa2O0ZHnEm" %}

In the second **Business Rule** we will use the *Notice Period* tree (A JSON file with the design of the rule is here below). The standard is simple: **We must have minimum 30 days to solve and communicate leaks**. The logic of the standard can be expressed in a Decision Tree keeping the simplicity:&#x20;

1. **Missed information:** IF the field for the NDA notice period is empty, THEN return error message (Remember the AI result null if the NDA misses this information).
2. **Enough Notice Period:** IF the NDA notice period is greater or equal to 30 days, THEN return passed.
3. **Not Enough Notice Period:** IF the NDA notice period is less than 30 days, THEN return failed and the reason.&#x20;

{% file src="/files/RQF830Lz8Aw6weJpeV8C" %}

In the third **Business Rule** we will use the *Confidentiality Period* tree (A JSON file with the design of the rule is here below). The standard is simple: **We must have maximum 15 years for confidentiality**. The logic of the standard can be expressed in a Decision Tree keeping the simplicity:&#x20;

1. **Missed information:** IF the field for the NDA confidentiality period is empty, THEN return error message (Remember the AI result null if the NDA misses this information).
2. **Under the limit period:** IF the NDA confidentiality period is less or equal to 15 years, THEN return passed.
3. **Over the limit period:** IF the NDA confidentiality period is greater than 15 years, THEN return failed and the reason.&#x20;

{% file src="/files/eCXfQDMpdao4uJn9h4dK" %}

In the fourth **Business Rule** we will use the *Governing Law* tree (A JSON file with the design of the rule is here below). The standard is simple: **We only accept the governing law from United States**. The logic of the standard can be expressed in a Decision Tree keeping the simplicity:&#x20;

1. **Missed information:** IF the field for the NDA governing law is empty, THEN return error message (Remember the AI can result null if the NDA is not clear).
2. **Under the limit period:** IF the NDA governing law is from US, THEN return passed.
3. **Over the limit period:** IF the NDA governing law is from any other country, THEN return failed and the reason.&#x20;

{% file src="/files/JhJVTtJG2zHQuQHAKDv0" %}

The AI Agent node features two output ports; connect the *green (success) port* to each of the four Decision Trees you just configured.

<figure><img src="/files/N66Plh7xLRbyJxIXCRXm" alt=""><figcaption></figcaption></figure>

### 3. Error handle

Place an **Assign node** below the column of Business Rule nodes and connect the *red (failure) anchor* of the AI Agent node to it. The red path is triggered if the AI request times out or fails. Open the Assign node and create a target to report the LLM error (e.g. `AnalyzerError.code` ). Then, assign a static error code such as AI\_PROCESSING\_ERROR.&#x20;

<figure><img src="/files/j5NOeizYwFFZA3tC05L9" alt="" width="563"><figcaption></figcaption></figure>

Add an **Append node** to the right of your design and connect it to all the nodes in the preceding parallel column (the four Business Rule nodes and the error-handling Assign node). So far, we have identified two types of errors: AI timeouts and empty fields within the NDA report. This node will store a single array containing all potential issues. In the node settings, create a target array called `errors` and drag all attributes that report errors into the "Values to Append" section.

<figure><img src="/files/2eOhb9CMUSAJAiZ2aoA4" alt="" width="375"><figcaption></figcaption></figure>

<figure><img src="/files/Whdh0lWfzeq40XOpS80K" alt=""><figcaption></figcaption></figure>

Finally, place a **Switch node** on the canvas and connect the output of the **Append node** to it. Open the Switch settings and create a case for "Errors in evaluation". The logic is as follows: IF the errors array from the Append node is not empty, THEN follow the path for error mapping; OTHERWISE, proceed to the redline mapping.

To configure this, drag and drop the `errors` object created in the **Append node** into the *Condition* field. Select the <mark style="color:green;background-color:green;">**Contains Text**</mark> function and enter the value: ERROR. The *Default case* will automatically handle the "otherwise" scenario, directing the flow when no errors are present.

<figure><img src="/files/FPTrIjGGUYNi3Sy63md9" alt=""><figcaption></figcaption></figure>

### 4. Generating the final redlines

Now that all necessary values have been gathered, we can generate the final redlines, including the validation results for the four minimal standards and their corresponding text references. To map these for the final output, we will use an **Assign node**.

1. **Success Path:** Connect the *Default port* of the **Switch node** to a new Assign node. Open the configuration.
2. **Map Results:** On the *Target* side, add all eight output attributes for redlines and references. For the redlines, map the results from the four Decision Trees as the *Source*. For the references, map the corresponding data from the AI Agent rule.

<figure><img src="/files/ajzCfT3sobGeu2ykL4bT" alt=""><figcaption><p>Assigning values to Decision Flow Output</p></figcaption></figure>

To manage exceptions, add a second **Assign node**. Connect the "*AI error in the evaluation" port* of the **Switch node** to this new node.

{% hint style="info" %}
**Note:** If errors are stored in our array, the Switch node can direct the flow to both the success Assign node (to provide any partially processed info) and the error Assign node simultaneously.
{% endhint %}

In the **error** **Assign node**, set the *Target* to your two error output attributes:

* **output.errors.types:** Map the errors array from the Append node.
* **output.errors.message:** Enter a customized message such as:

```
Please check the list of errors.types . 
If some of the rules are mentioned, it means {input.nda.originatingParty} didn't give enough information in the NDA to evaluate the standard, request them to complete the NDA please.
If the type is AI_PROCESSING_ERROR, verify your connection to the LLM and run the rule again.
```

<figure><img src="/files/0mSFyf6es1ccZ9pwqXm4" alt=""><figcaption><p>Detail of Switch node directing the process</p></figcaption></figure>

Congratulations! :tada: You've completed the Decision Flow, which might look something like this:

<figure><img src="/files/auOGBwXH1V7lepZoH4qT" alt=""><figcaption><p>Decision Flow overview</p></figcaption></figure>

In the next section, we’ll test the Decision Flow with some inputs to ensure it’s functioning correctly. Before proceeding, please double-check that all Decision Flow nodes are fully configured and properly connected.

### 5. Testing the Decision Flow and the AI Agent Rule

Now we can test our rule in Test Bench.

We can click the <mark style="background-color:purple;">**Test Bench**</mark> icon at the beginning of the bottombar. After clicking the icon, the Test Bench will show up at the bottom of the page.&#x20;

Then we can fill in some mock data. We can use the same mock example from above. You can download the document here below as well. Use the specifications of the document to complete the input, and remember to paste the entire text of the NDA in nda.text. Click the <mark style="background-color:green;">**Run**</mark> button and the result will be displayed in right hand side of the Test Bench. Note that you can switch between the **Simple Bench** and the **JSON Bench**.

{% file src="/files/Q4v6WkWUloEFqQ0dXUZL" %}

<figure><img src="/files/RoJ9CdgI3ZzV0v7jCInR" alt=""><figcaption></figcaption></figure>

{% tabs %}
{% tab title="Testing Input" %}

```json
//Complete the input with the Mock_NDA
{
  "nda": {
    "originatingParty": "Zenith Logic Pty Ltd",
    "disclousingParty": "Vanguard Analytics Inc.",
    "receivingParty": "Zenith Logic Pty Ltd",
    "type": "NDA for PoC information",
    "text": [
      "MUTUAL NON-DISCLOSURE AGREEMENT This Mutual Non-Disclosure Agreement (the \"Agreement\") is entered into as of October 25",
      " 2023 (the \"Effective Date\")",
      " by and between: Vanguard Analytics Inc.",
      " a corporation organized under the laws of Delaware",
      " etc, etc, etc..."
    ]
  }
}
```

{% endtab %}

{% tab title="Testing Output" %}

```json
[
  {
    "redline": {
      "confidentiality_period_years": "passed",
      "governing_law": "failed, governing law is not from US",
      "notice_period_days": "failed, it requires notice in less than 30 days",
      "reciprocity": "passed"
    },
    "reference": {
      "confidentiality_period_years": "continue for a period of ten (10) years",
      "governing_law": "governed by... the laws of New South Wales, Australia",
      "notice_period_days": "providing twenty (20) days prior written notice",
      "reciprocity": "Mutual Non-Disclosure Agreement... Vanguard and Zenith may exchange"
    },
    "errors": {
      "types": {},
      "message": {}
    }
  }
]
```

{% endtab %}
{% endtabs %}

### Summary

The rules of this tutorial were designed to be called by a user when a new NDA arrives and the team want to decide the necessary redlines in real time. The goal was to automate the process such that the system sends the NDA to DecisionRules and retrieve the evaluation of the document with the redlines that must be pointed out. The main features in DecisionRules to achieve this goal are the **AI Agent Rule** and the **Decision Flow**. In this tutorial, we built an **AI Agent Rule** for the analysis of the unstructured data given in the new NDA, getting back the data of the NDA in structured JSON format. The attributes of the JSON were designed to be precise and some of them required by the standards to be evaluated. The second part of this section was the elaboration of a **Decision Flow** to complete the goal in a predictable way. The flow uses the results of the AI rule and runs:

* The evaluation of precise NDA attributes, according to the standards of the company, using **Decision Trees**.
* Because the original NDA is unstructured, the data in the flow may misbehave, and so, the detection of information gaps and the report of times out.
* The presentation of the redlines, with the corresponding references, and in case of misbehaviours, error messages for the solution of relevant gaps or the solution of the connected LLM performance.   &#x20;

To wrap up, let’s go over the management and maintenance of this Decision Flow. Once the rules are built, the Business Users only have to manage the **Decision Trees**. In fact, the Business User not just know the company's standards, but these users have the decision capacity and knowledge to change those standards, so when some of the standards must be changed, for example:

* **The NDA must be reciprocal - to - It is not relevant if the NDA is reciprocal.**
* **We must have minimum 30 days to solve and communicate leaks - to - 20 days.**
* **We must have maximum 15 years for confidentiality - to - 20 years.**
* **We only accept the governing law from United States - to - the law from Australia.**

These changes can be done directly by them, just changing values on Decision Trees, for instance from 15 to 20. See that the roles of the users can be very different, but everyone collaborate to directly on the hand of the right expert, the capacity to make changes in the company's applications for prediction, transparency and velocity. &#x20;


# Rule Flow

Introduction

Rule Flow is a type of rule with which you can easily create a complex decision-making process. Using a visual Rule Designer, you simply connect the individual rules that are part of the decision process. In the Rule Flow, you can use any rule type and any version of the rule. This means that a Rule Flow can be included in another rule flow, or 2 versions of the same rule can be used in the same Rule Flow.

In the images below you can see a simple business diagram of the client loan approval process. This will calculate the loan amount and the total amount payable based on inputs such as salary, age of the client and other inputs.

<figure><img src="/files/9UwY3BKUXQFhVqycPeJP" alt=""><figcaption></figcaption></figure>

The second image shows what the solution might look like in Rule Flow. Note that our solution does not differ from the original diagram. Even complex processes can look simple thanks to <mark style="color:purple;">DecisionRules</mark>, just as you have designed them.

<figure><img src="/files/vU6QbNTpvwZzKWCRIvoF" alt=""><figcaption><p><mark style="color:purple;">Solution designed in Rule Flow</mark></p></figcaption></figure>

### From simple rules to complex decision-making process

Make individual subdecision rules simple and easy to manage, adding complexity and consistency just by connecting them in the Rule Flow. This makes it easy to maintain in case something changes in your process. For example, if one tax rate changes or a new product is introduced, you can easily update or add values in the Decision Table or Decision Tree without having to rebuild your entire decision process. Thanks to the Rule Flow you can connect rules to create even more complex decisioning logic.

### Rule Flow Designer

#### Interface

Like other rules, Rule Flow is different in Rule Designer. It is designed like a blank canvas on which you add the rules and connect them together. Use mouse dragging to move around. Use the mouse wheel or the Zoom In and Zoom Out buttons in the bottom bar of the Designer to adjust the zoom level.

#### How does the Rule Flow look like

Rule flow is actually a graphical representation, an interactive diagram, of the decision-making process in which you create one larger rule from the individual decision rules. Each rule you add to the Rule Flow will be represented by a box. In addition, the Input and Output boxes, graphical representations of the input-output model defined in Rule Settings, are an integral part of the Rule Flow. Use them to create the flow of data through your Rule Flow.

#### Adding Rules to Rule Flow

When you create a new Rule Flow, you will see a blank Rule Flow Designer where you will add and connect your rules. Down in the bottom bar, click on the "+ Input" and "+ Output" buttons to add the Input and Output boxes that will represent the I/O model mentioned above.

To add individual rules, click on the "+ Rule" button or Ctrl+click on your Rule Flow canvas. A box will appear in the Designer to which you assign the rule of your choice. To delete the box you no longer need, select the rule and press the Delete key on your keyboard or right click on a box and click black button with “x” in it.

<figure><img src="/files/wpkDYhARim6shu56CkIW" alt=""><figcaption><p><mark style="color:purple;">See how to add and remove rule boxes</mark></p></figcaption></figure>

#### Assigning Rules to boxes

Clicking on the box will bring up a side menu which will give you various information about the rule once you have assigned it. To do so, click on the "Select Rule" button in the side menu and select the desired rule from the drop-down list. To find the rule more easily, you can use the Search field. After selecting a rule, you can specify the version of the rule you want to use. The default version setting is Latest Version.

<figure><img src="/files/dw1DwMV2C1tX0gb5Xc14" alt=""><figcaption><p><mark style="color:purple;">How to assign rules to boxes in your Rule Flow</mark></p></figcaption></figure>

The assigned rule box contains basic information to easily identify rules in your Rule Flow. You will find the rule name, global variable, rule type, and rule version. You can also access the Data Mapping of the rule from the box or open the rule in a new browser tab.

<figure><img src="/files/EqqQhBzuvrlY94RwRRHK" alt="" width="295"><figcaption><p><mark style="color:purple;">Assigner rule box</mark></p></figcaption></figure>

Rule boxes are rewritable. This means that if in your decision making process you need to replace a rule with a newer version or a completely different rule, you can easily do so by clicking on the rule box and selecting the rule you wish to add to Rule Flow from the list in the side menu that opens.

#### Rule Properties

Once you've assigned a rule to the box, you can click on it to view useful information. In the side menu, in addition to changing the rule or its version, you can see the global variable used to map the rule (see below) and the rule input/output model.

<figure><img src="/files/Q2k4Bzb35cbdCCLP6x8x" alt=""><figcaption><p><mark style="color:purple;">Description of Rule Properties menu</mark></p></figcaption></figure>

#### Rule Flow mapping and rule connection

Once you have assigned the rules to the added boxes, you can start connecting them together as your decision logic requires. Each box has handles from which you drag a line to other boxes.

<figure><img src="/files/HXSZjTjvHlyrti1y054p" alt=""><figcaption></figcaption></figure>

Linked rules form a path for rule input and output data. Use Rule Flow Mapping to easily set what data enters and exits a rule. The mapping can be accessed from two places - from the box where the rule is assigned or from the side menu that opens when you click on the desired rule. Click on the “Data Mapping” button to show the Mapping window.

<figure><img src="/files/4sZZdlme8NIHi8SpPaU7" alt=""><figcaption></figcaption></figure>

The Mapping window displays information about the selected rule in the header. The main part of the window is the mapping table itself. In the "Source" section on the left, you select the source rule (its global variable) from which the input data entering your rule will come. Next, you select a specific value from the source rule's output that will input the corresponding value on the right in the "Target" section. Once you link these two values, the input values of your mapped rule will change color to green. Save the mapping using the "Confirm" button on the bottom right. If you need to delete existing mapping, open Data Mapping then click the “Delete Mapping” button and save with Confirm button.

<figure><img src="/files/Dn9nBnhbgCOUlrm0jk0P" alt=""><figcaption></figcaption></figure>

{% hint style="warning" %}
Once you replace a rule in a box with another one or delete a rule from the rule flow, you need to check the mapping of the rule flow, as it is probably outdated and you will need to remap the Rule Flow to restore the dataflow.
{% endhint %}

#### Testing Rule Flow

Like other types of rules, you can test the functionality of your Rule Flow using the Test Bench in the bottom bar. Open the Test Bench and enter the input values, then click the "Run" button to evaluate the rule.

Use Debug Mode to see how the data is evaluated in each rule of your Rule Flow. Enable Debug Mode in Test Bench by clicking the "Debug" button, which will solve your rule again. You can select the "Show Data" option for each rule. The table will display the input and output data for the selected rule.

<figure><img src="/files/D3cDDnsDNKlMvKkuQlng" alt=""><figcaption><p><mark style="color:purple;">Test your Rule Flow in the Test Bench with Debug Mode</mark></p></figcaption></figure>


# Create Simple Rule Flow

This tutorial will walk you through the creation of a Rule Flow.

## How to create a simple decision tree

Let's advance one step at a time.

{% hint style="info" %}
In this tutorial, you need to have knowledge of [<mark style="color:purple;">Decision Tables</mark>](/rule-types/decision-tables) or [<mark style="color:purple;">Scripting Rules</mark>](/rule-types/scripting-rules).
{% endhint %}

### 1. Create Decision Tables

We have already learned how to create rules in previous tutorials, so let's skip it now and import these decision tables:

{% file src="/files/CPrxaOnDE9yIHFw6NmT6" %}
Clients
{% endfile %}

* **Clients -** a rule that determines the maximum loan according to the client's age and salary

{% file src="/files/firKugJeRmggxAy3FKy8" %}

* **Loan Type -** a rule that determines the maximum loan tax according to how much and for what the client wants to borrow

{% file src="/files/QS88bDsu4rYYuiHOYdB6" %}

* **Bank Solver -** a rule that calculates how much the client pays in total

{% hint style="warning" %}
How to import [<mark style="color:purple;">Rule</mark>](/rules/export-and-import-of-the-rules/import-rule)
{% endhint %}

### 2. Go to Create rule

To display the rule creation pop-up click the <mark style="background-color:purple;">**Create Rule**</mark> button on the sidebar.

<figure><img src="/files/fwDP0Ehzu1LoGDJS9PnS" alt=""><figcaption></figcaption></figure>

### 3. Create a new Rule Flow

You will be prompted to provide a name and choose between **SAMPLE RULE** or **EMPTY RULE**. The new rule will be created and its detail will be displayed. We will continue in the Rule Settings tab.

{% hint style="info" %}
In our case, we recommend you select the empty rule.
{% endhint %}

### 4. Set Rule Flow settings

When you click on RULE SETTINGS on the top left corner, the scripting rule's detail will appear first to set some information. We will change the name of our script. To do this, click on it's name, enter one you like and press Enter.&#x20;

Since we do not want this rule to be available yet, we will change its status to **"Pending"**. To do this, click on the current status **"Published"** and then select **"Pending"**.

To apply these changes, we have to click on the <mark style="background-color:orange;">**Save**</mark> button at the bottom of the page.

### 5. Create an Input and Output model

We will now create an input and output model, which will then be used to set conditions and results. You must be in **Rule Flow Settings.** There are 2 ways to create these models:

* **Simple editor:** It is intended for inexperienced users who do not know the syntax of JSON files.
* **JSON editor:** It is intended for an experienced user, with JSON knowledge.

#### Create with a simple editor

{% hint style="warning" %}
After creating an input or output model, we must always confirm the changes with&#x20;

the <mark style="background-color:orange;">**Save**</mark> button
{% endhint %}

#### **Input model**

First, we delete all created objects by clicking on the icon (in case you chose Sample Rule Flow). Then we will add our specified requirements (**age, salary, loan, loanType**). In our case, we create a root for each request by clicking on the button.

{% hint style="info" %}
If our model were more complex, we would add descendants. More information is described [here](https://docs.decisionrules.io/doc/decision-tables/input-and-output/simple-editor).
{% endhint %}

#### **Input model Example:**

<figure><img src="/files/S9QwRJSEcgp7kohYyyGI" alt=""><figcaption></figcaption></figure>

#### **Output model**

We set the output model similarly, where we set as root **loan**, **tax**, **totalPay** and **message**.

**Output model Example:**

<figure><img src="/files/v86PCcAfxTeOTXb3DnXu" alt=""><figcaption></figcaption></figure>

### Create using JSON editor

#### **Input model**

First, we will create one object into which we will put other objects with our requirements. We will create one empty object for each request.

{% hint style="info" %}
Our model is simple, these objects do not contain any others (embedded attributes). For more complex models, more information is [here](https://docs.decisionrules.io/doc/decision-tables/input-and-output/json-editor).
{% endhint %}

#### **Input model Example:**

```javascript
{
  "age": {},
  "salary": {},
  "loanType": {},
  "loan": {}
}
```

#### **Output model**

We set the output model similarly, where we set as root **loan**, **tax**, **totalPay** and **message**.

**Output model Example:**

```javascript
{
  "loan": {},
  "tax": {},
  "totalPay": {},
  "message": {}
}
```

### 6. Creating Rule Flow schema

1. To create Rule Flow schema go to the Rule Flow Designer tab. At the start the canvas is empty. Add there input, output, and three empty rules with buttons in the top-right corner: <mark style="background-color:purple;">**Add Input**</mark> , <mark style="background-color:purple;">**Add Output**</mark> , <mark style="background-color:purple;">**Add Rule**</mark> .
2. Click on the Empty rule to display the sidebar. By button <mark style="background-color:purple;">**Select Rule**</mark> choose a rule, that will be in place of the empty rule.
3. Connect rules together and to input box and output box. In this case, the correct connect is as follows:

<figure><img src="/files/Qa2XCq0fnUDau2UtZuUI" alt=""><figcaption></figcaption></figure>

{% hint style="warning" %}
The rule should look as in the picture above.
{% endhint %}

### 7. Map data

To know, which data has to go where we have to map the data.

{% hint style="info" %}
If the rule has no inputs mapped. It borders in orange and displays a <mark style="background-color:orange;">warning icon</mark>&#x20;
{% endhint %}

The example Rule Flow - **Clients** and **Loan type** works with user input data and subsequently, **Bank solver** works with input of user data and with outputs from previous rules makes the decision and sends final outputs to the output box.

#### 7.1 Data mapping Clients

Open data mapping by clicking on <mark style="background-color:purple;">**Data Mapping**</mark> .

<figure><img src="/files/7kZs6HYZTWHJQOhT4Cs8" alt=""><figcaption></figcaption></figure>

**Global variable** means where the rule takes data from and **output** means what data. Because this rule is connected immediately after the input box, only **user input data** can enter it.

Correct mapping of **Clients** from example:

<figure><img src="/files/mukioYbT15zMDHRoQqZL" alt=""><figcaption></figcaption></figure>

#### 7.2 Data mapping Loan type

The loan type is also directly connected after the input box, so only **input user data** will also enter it.

Correct mapping of Loan type from example:

<figure><img src="/files/jhUcrbi70PHfThBT07cR" alt=""><figcaption></figcaption></figure>

#### 7.3 Data mapping Bank solver

The **bank solver** is the final rule, that takes data from both the **previous rules** and the **input box.**

Correct mapping of Bank solver from example:

<figure><img src="/files/6EPCsl6iofYHRqKq4hAk" alt=""><figcaption></figcaption></figure>

#### 7.4 Data mapping Output box

The final output can be data from any rule, so it is necessary to map the Output as well. In this example we want the following data to be in the output:

* **Loan** - the amount the customer wants to borrow
* **Tax** - tax of the loan
* **TotalPay** - the amount the customer pays
* **Message** - that confirming the loan or explaining its refusal

Correct mapping for output:

<figure><img src="/files/EAKvkqpz8e3NSb6NIfpA" alt=""><figcaption></figcaption></figure>

### 8. Test of created Rule Flow

Now we can test our Rule Flow in Test Bench. Before testing the rule, we must change the status of the decision table to **"Published"** or have to **debug mode ON**. Debug mode allows you to test Rule Flow even when it is pending and at the same time writes data information to the debug mode console.

Now you can test your Rule Flow as you like, but for a positive result, it is necessary to have loanType set on **"household", "car"** or **"vacation"** because our bank does not lend to anything else.

{% hint style="info" %}
You can add new loanType variables in the Loan Type rule via [<mark style="color:purple;">Preset values</mark>](https://docs.decisionrules.io/doc/decision-tables/table-operations/valid-values).
{% endhint %}

{% hint style="success" %}
You can find more information about input and result at [<mark style="color:purple;">Solver API</mark>](https://docs.decisionrules.io/doc/api/rule-solver-api).
{% endhint %}

#### Request body example:

```javascript
{
  "age": 30,
  "salary": 4000,
  "loanType": "household",
  "loan": 30000
}
```

#### Response body example:

```javascript
[
  {
    "loan": 30000,
    "tax": 1.15,
    "totalPay": 34500,
    "message": "eligible for the loan"
  }
]
```

{% hint style="info" %}
More information about Test Bench is [<mark style="color:purple;">here</mark>](https://docs.decisionrules.io/doc/other/test-bench).
{% endhint %}


# Observability with OpenTelemetry

Learn how OpenTelemetry helps you monitor and troubleshoot your DecisionRules workloads

{% embed url="<https://youtu.be/KbF9vFweY7k?si=jx7GUoy--fEYHeYq>" %}

## Introduction

A single call to the DecisionRules Solver looks simple from the outside. You send input, you get output. Inside, that call can be a Decision Flow calling a dozen child rules, each with its own conditions and its own outputs. In production, flows grow, and when a decision comes back with an unexpected result, the input and the output alone will not tell you what happened in between.

DecisionRules provides built-in observability through OpenTelemetry (OTLP) and structured logging. You can export traces, logs and metrics to Grafana, Datadog, an OpenTelemetry Collector or any other OTLP-compatible platform. Jaeger can be used for distributed traces. Everything is configured through environment variables on the server container, so there is no agent to install and no change to your rules or Decision Flows.

Observability is available in self-hosted deployments running on Docker or Kubernetes, from version **1.25.2 onwards**, and requires a license with telemetry enabled. If telemetry is not enabled by your license, OTLP traces, logs, metrics and stdout logging all remain disabled and `OTLP_URL` is ignored.

{% hint style="info" %}
*For the complete list of environment variables and their default values, see the* [*OpenTelemetry and Access Logging*](https://docs.decisionrules.io/doc/other-deployment-options/docker-and-on-premise/opentelemetry-and-access-logging) *section of the documentation.*
{% endhint %}

## What Traces, Logs and Metrics Tell You

The three signals answer three different questions, and choosing the wrong one is the most common mistake when troubleshooting a decision.

#### Traces

Traces show the execution flow of a request as a tree of spans, including instrumented HTTP and dependency calls made during rule or Decision Flow execution. Use traces when you want to know how a request moved through the system and how long each instrumented step took.

#### Logs

Logs are structured JSON records of what came in and what went out. There are three types. Access logs cover inbound and outbound requests and responses. Audit logs cover rule execution and contain the rule alias, the input data, the output data and the execution time. Application logs cover internal runtime errors.

If someone asks which decision was made and on what inputs, the answer is in the audit log, not in the trace.

#### Metrics

Metrics are aggregate runtime and service measurements across the deployment. They describe the health of the environment rather than individual requests.

Traces, access logs and audit logs can share the same `traceId`, so a trace, the access log for that request and the audit record for that rule execution can be lined up next to each other. Metrics are exported as aggregate measurements and are not tied to an individual request `traceId`.

## Turning Telemetry On

Telemetry is activated by one variable, and each signal is then switched on separately.

| Environment Variable   | Description                                                     | Default Value |
| ---------------------- | --------------------------------------------------------------- | ------------- |
| ---                    | ---                                                             | ---           |
| `OTLP_URL`             | Base OTLP endpoint, required to activate the telemetry pipeline | `undefined`   |
| `OTLP_TRACES_ENABLED`  | Enables the trace exporter and runtime instrumentations         | `false`       |
| `OTLP_LOGS_ENABLED`    | Enables the OTLP log exporter                                   | `false`       |
| `OTLP_METRICS_ENABLED` | Enables the periodic metric reader and exporter                 | `false`       |

{% hint style="info" %}
*If no telemetry appears at all, check* `OTLP_URL` *first. The signal toggles have no effect until it is set, and telemetry also has to be enabled by your license.*
{% endhint %}

## Deployment Patterns

DecisionRules supports several observability patterns. Which one you choose depends on the infrastructure you already have rather than on what you want to see.

{% stepper %}
{% step %}

### Full OpenTelemetry Integration

This pattern exports telemetry directly to an OTLP-compatible platform. Use it for centralized monitoring, distributed tracing, production diagnostics and SLA monitoring.

```yaml
env:
  - name: OTLP_URL
    value: "otel-collector:4318"
  - name: OTLP_TRACES_ENABLED
    value: "true"
  - name: OTLP_LOGS_ENABLED
    value: "true"
  - name: OTLP_METRICS_ENABLED
    value: "true"
```

A logs-only variant works the same way, with only `OTLP_LOGS_ENABLED` set. It is useful when a centralized logging platform is available but distributed tracing is not required.
{% endstep %}

{% step %}

### Structured Logging to Stdout

DecisionRules can emit structured JSON logs directly to stdout without any telemetry collector. This is often enough for troubleshooting and operational monitoring, and it works with Kubernetes log collection out of the box.

```yaml
env:
  - name: OTLP_URL
    value: "."
  - name: OTLP_STDOUT_ACCESS_LOGS_ENABLED
    value: "true"
  - name: OTLP_STDOUT_AUDIT_LOGS_ENABLED
    value: "true"
```

Access and audit logs can still be correlated through `traceId` and `spanId` where trace context is available or generated by the observability flow. With traces disabled, an inbound access log does not always carry an active span context.

{% hint style="info" %}
*You do not need an OpenTelemetry collector for this pattern.* `OTLP_URL` *is still set, as a placeholder, because it is what activates the observability pipeline.*
{% endhint %}
{% endstep %}

{% step %}

### Stdout Logging with Audit Persistence Disabled

By default, audit logs are persisted to the audit database. Some deployments prefer audit records to leave through the logging pipeline only, with retention handled by an external platform. In this pattern audit logs are still generated and still emitted to stdout, they are simply not stored in MongoDB.

```yaml
env:
  - name: OTLP_URL
    value: "."
  - name: OTLP_STDOUT_AUDIT_LOGS_ENABLED
    value: "true"
  - name: AUDIT_MONGO_ENABLED
    value: "false"
```

{% endstep %}

{% step %}

### Hybrid Mode

OTLP export and stdout logging can run at the same time. You get centralized telemetry plus local container visibility, which makes debugging easier during deployments and migrations.

```yaml
env:
  - name: OTLP_URL
    value: "otel-collector:4318"
  - name: OTLP_TRACES_ENABLED
    value: "true"
  - name: OTLP_LOGS_ENABLED
    value: "true"
  - name: OTLP_STDOUT_ACCESS_LOGS_ENABLED
    value: "true"
  - name: OTLP_STDOUT_AUDIT_LOGS_ENABLED
    value: "true"
```

{% endstep %}
{% endstepper %}

#### Choosing a pattern

| If you have                                                                            | Use                                            |
| -------------------------------------------------------------------------------------- | ---------------------------------------------- |
| Grafana, Datadog, an OpenTelemetry Collector or another OTLP platform in production    | Full OpenTelemetry integration                 |
| Kubernetes log collection and no observability platform                                | Structured logging to stdout                   |
| An external log retention platform and a requirement to keep audit data out of MongoDB | Stdout logging with audit persistence disabled |
| A migration or rollout in progress and you want both views                             | Hybrid mode                                    |

## Controlling What Leaves Your Deployment

Sensitive keys such as authorization headers and API keys are redacted before telemetry leaves the container. Both `OTLP_LOG_SANITIZATION_ENABLED` and `OTLP_TRACE_SANITIZATION_ENABLED` default to `true`.

{% hint style="info" %}
*Sanitization is enabled by default for both logs and traces. You opt out of redaction, you do not opt in.*
{% endhint %}

Beyond redaction, you can shape what is emitted.

| Environment Variable              | Description                                                                                                                                                                                                  | Default Value |
| --------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------- |
| `OTLP_LOG_ATTRIBUTE_ALLOWLIST`    | Comma-separated allowlist of log fields emitted by the OTLP log pipeline, applied before both stdout emission and collector export. `traceId`, `spanId` and `level` are always present even when not listed. | `undefined`   |
| `OTLP_ACCESS_EXCLUDE_HEALTHCHECK` | Excludes health endpoints from access traces and logs                                                                                                                                                        | `false`       |
| `OTLP_ACCESS_ONLY_SOLVER`         | Limits telemetry to Solver and job related traffic paths                                                                                                                                                     | `false`       |
| `OTLP_STDOUT_ACCESS_BODY_FORMAT`  | Body formatting strategy for access logs in stdout. Valid values: `JSON`, `string`, `string-pretty`.                                                                                                         | `'JSON'`      |
| `OTLP_STDOUT_WRAPPER_KEY`         | Wraps the stdout payload into a nested key for downstream parsers                                                                                                                                            | `undefined`   |
| `LOGGER_TYPE`                     | Controls console log format. Valid values: `STRING`, `JSON`, `NONE`.                                                                                                                                         | `STRING`      |
| `LOGGER_LEVEL`                    | Minimum log level to print or emit, for example `error`, `warn`, `info`, `debug`                                                                                                                             | `info`        |

If you run a busy deployment, switching on `OTLP_ACCESS_EXCLUDE_HEALTHCHECK` and `OTLP_ACCESS_ONLY_SOLVER` together removes a large amount of noise before it reaches your collector. That matters when your observability platform charges by ingest volume.

## Reading the Output

#### Traces

A trace is a tree. The root span is the inbound API request, and instrumented HTTP and dependency calls made during execution appear as nested spans underneath. On a real production Decision Flow this tree gets deep, and that depth is exactly what you cannot see from the request and the response alone.

#### Logs

Every log is structured JSON and carries `traceId` and `spanId`.

An inbound access request log, generated when the API receives a request:

```json
{
  "logType": "access",
  "direction": "inbound",
  "role": "request",
  "method": "POST",
  "url": "/rule/solve/my-rule/1",
  "traceId": "0f976b707efdd319550484483ab5f222",
  "spanId": "1e1ea1c52b642277",
  "body": {
    "input": {}
  }
}
```

An audit log, generated only when audit logging is enabled on the rule:

```json
{
  "logType": "audit",
  "statusCode": 200,
  "traceId": "0f976b707efdd319550484483ab5f222",
  "spanId": "1e1ea1c52b642277",
  "body": {
    "ruleAlias": "my-rule",
    "executionTime": 0.5,
    "inputData": {
      "input": {}
    },
    "outputData": [
      {
        "output": "Hello from Solver"
      }
    ]
  }
}
```

Outbound access logs follow the same shape with `"direction": "outbound"`. Application error logs use `"logType": "application"` together with a `level`, an `errorType` and a `message`.

{% hint style="info" %}
*For inbound and outbound response examples and the application error log format, see the* [*log examples*](https://docs.decisionrules.io/doc/other-deployment-options/docker-and-on-premise/opentelemetry-and-access-logging) *in the documentation.*
{% endhint %}

#### Correlation fields

| Field        | Purpose                                                      |
| ------------ | ------------------------------------------------------------ |
| `traceId`    | Correlates logs and spans belonging to the same request flow |
| `spanId`     | Identifies the specific operation or span within a trace     |
| `logType`    | Distinguishes access, audit and application logs             |
| `timestamp`  | Event creation time                                          |
| `statusCode` | HTTP response status when applicable                         |

## Verifying Your Setup

To verify traces, set `OTLP_URL` and `OTLP_TRACES_ENABLED` to `true`, then restart the server container. Run any rule from the DecisionRules application, or send a Solver request. Find the access log whose `url` matches your Solver endpoint, copy its `traceId` and search for that value in traces. You should see the execution tree for that request.

To verify logs only, set `OTLP_URL` and the relevant log toggle, restart the container and run a rule. Then search for the structured access or audit log in your log destination, whether that is your collector or the container's stdout.

In both cases, confirm that authorization headers and API keys appear redacted. If they do not, check that sanitization has not been switched off.


# How to Create a Support Ticket

Learn how to create a support ticket to quickly find a solution to your problems

Something went wrong? Let us know. You can submit a ticket through our support portal. Simply fill out the form detailing the issue.

## How do I get to the support site?

The link can be found in the left side bar menu. In the Help section, click on Service Desk and you will be redirected to the [<mark style="color:purple;">support site</mark>](https://support.decisionrules.io/support/home).

<figure><img src="/files/o8MOitNuZ29BJ4rQ2z6h" alt=""><figcaption></figcaption></figure>

## Submit a ticket

To submit a ticket, click on the  <mark style="background-color:purple;">**Submit a ticket**</mark>  button in the top bar or in the middle of the page.

<figure><img src="/files/5uHs9WfYNkOGzopo2SjI" alt=""><figcaption></figcaption></figure>

You will then be taken to a form page where you fill in all the details needed to describe your issue.

<figure><img src="/files/g3fCrAGAkpZqfiSuMSdY" alt=""><figcaption></figcaption></figure>

{% hint style="info" %}
*Please keep in mind that the better you describe your work environment and the problem in detail, the easier it will be to locate the problem and eventually resolve the issue.*
{% endhint %}

### Requester

Fill in your email address here where you want us to reply to you

### Subject

A brief title of what the problem concerns

### Priority

We take all reported problems seriously. However, some may be less serious than others. Please consider the priority of the problem and set it in the form.

### Deployment Model & App Version

These fields are not required, but may make it easier to solve the problem. Please specify the version if you are using our Docker Containers.

### Description

This field should include a detailed description of your problem. Be as specific as you can. Describe the environment and the area (of our application) where the problem occurred. You can take the following problem description as an example.

> *I am writing to request assistance with a technical issue I've encountered while attempting to import a JSON file into my application.*
>
> 1. *I initially exported the JSON file, "InsuranceGroup.json," from another space ("Risk evaluator Space"), where it was generated and needed for my current project on target space ("Insurance Space").*&#x20;
>
> 2. *Upon trying to import the file into my target space, I have followed the standard procedures for importing JSON files - import in Folders.*
>
> 3. *Unfortunately, I have repeatedly encountered an error message that prevents me from completing the import process.*
>
> 4. *I tried importing the file using import in Business Rules as well with the same result.*
>
> *To provide you with a better understanding of the problem, I have attached the following to this support ticket:*
>
> ***Plan:** Medium*
>
> ***My role:** Editor*
>
> ***Screenshots:** I have included screenshots of the error messages that appear during the import process.*
>
> *JSON File: The file "InsuranceGroup.json" is also attached to this ticket, allowing you to examine its contents directly.*
>
> *If there are any additional details or diagnostic information you require to assist me in resolving this issue, please let me know. I look forward to your response.*

### Attachments

Include files such as screenshots and gifs. If you have a problem with one of your decision rules, export it and attach it as well.

**For better resolve of your problem please download Support file which you can find under Info and Help button in the left side bar under section Support.**

<figure><img src="/files/c8FmHESiHsNz1xMfRX91" alt=""><figcaption></figcaption></figure>

{% hint style="info" %}
*Cumulative file size cannot exceed 20 MB.*
{% endhint %}

### Ticket submitted

Once you submit a ticket, our support team will receive it and begin analyzing your issue. You will be contacted by support no later than the next business day for further information or to resolve your issue.


