# Gen AI

Nected’s GenAI feature is designed to help you minimize the struggle of writing custom conditions using JS Code and Formula Editors. It has two options **Ask AI** and **Explain Code.** Ask AI to help in your coding challenges while Explain Code provides a full explanation of your written code in the editor.

### How to Access Gen AI?

To access the Gen AI you can go to the [formula editor](/nected-docs/code-and-database-queries/formula-editor.md) and [JS editors](/nected-docs/code-and-database-queries/javascript-editor.md) available under additional data and data type options within Rules.

Similarly, it can be accessed in Workflows through the [Code node](/nected-docs/workflow/add-node/action-nodes/custom-code-node.md), [Response node](/nected-docs/workflow/add-node/control-nodes/response-node.md), and [Set Variable node](/nected-docs/workflow/add-node/control-nodes/set-variables-node.md).

See the image below for a better understanding:

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

> Note: The GenAI feature in Nected is available within the [Formula](https://docs.nected.ai/nected-docs/code-and-database-queries/formula-editor) and [JavaScript](https://docs.nected.ai/nected-docs/code-and-database-queries/javascript-editor) editors

Once you've selected from the options, you will see the editor screen where you can find two key features of GenAI:

<figure><img src="/files/WtfN9V76QqNoEaMvy3x2" alt=""><figcaption><p>The above image is for the JS Code Editor; the same applies to the formula editor.</p></figcaption></figure>

## Overview of GenAI Features

As discussed above, GenAI has two features: Explain Code and Ask AI. Below is the definition of each:

### **1. Explain Code**

Located after the "**Functions**" option, this button explains code snippets in plain text. Just click on it, and the code present on the screen will be explained.

**Let’s understand this feature taking a scenario below:**

**Code Example:**

`*{{.customInput.asset_price}}-({{.customInput.asset_price}}*{{.outputData.dynamic_discount}});*`

<figure><img src="/files/72Noh4D8pFH78Rk86pyu" alt=""><figcaption></figcaption></figure>

**Explanation given by** **GenAI:**

```html
The code calculates the result of the formula: 100 - (100 * 0.1). It multiplies 100 by 0.1, subtracts the result from 100 and returns the final value. The tokens used in the code are '{{.customInput.asset_price}}' which has an 'executableValue' of 100 and 'meta' of 'numeric', and '{{.outputData.dynamic_discount}}' which has an 'executableValue' of 0.1 and 'meta' of 'numeric'. These tokens can be accessed in the code as variables containing their respective executable values.
```

### **2. Ask AI**

Positioned on the right side of the screen, this feature provides coding assistance. You can copy-paste code or write a query to generate an answer.

Let’s take some use-case scenarios of Ask AI:

#### **→ Helps in Troubleshooting**

Ask AI can assist in identifying potential issues by analyzing your code, suggesting improvements, or offering troubleshooting tips directly within the editor.

**Example Scenario:** You have written a complex formula or script and need help identifying why it's not working as expected.

**Prompt given:**

```
The following formula isn't giving the expected result. Can you identify the issue?

let finalPrice = basePrice + (basePrice * taxRate) - (basePrice * discount);
if (finalPrice < 0) {
finalPrice = 0;
}
```

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

**Result:**

```html
The issue is with the order of operations when calculating the final price. Instead of subtracting the discount directly from the base price, we should calculate the taxed price first and then apply the discount.
```

#### **→ Get Suggestions on complex conditions**

Use the **Ask AI** feature to get code snippets or logic suggestions tailored to your needs.

**Example Scenario:** You want to implement a dynamic discount system that supports multiple coupons.

**Prompt Given:** *Write logic for applying dynamic discounts based on coupons, allowing multiple coupons to be applied.*

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

**Result**:

```
const coupons = {
  'FIRST_PURCHASE': 10,
  'WEEKEND_SALE': 15,
  'FREESHIPPING': 5
};

function applyCoupons(items, appliedCoupons) {
  let totalDiscount = 0;

  appliedCoupons.forEach(coupon => {
    if (coupon in coupons) {
      totalDiscount += coupons[coupon];
    } else {
      throw new Error('Invalid coupon code');
    }
  });

  return items.reduce((total, item) => total + item.price, 0) - totalDiscount;
}

const items = [
  { name: 'Item 1', price: 50 },
  { name: 'Item 2', price: 30 },
  { name: 'Item 3', price: 20 }
];
const appliedCoupons = ['FIRST_PURCHASE', 'WEEKEND_SALE'];

const finalPrice = applyCoupons(items, appliedCoupons);
console.log('Final Price after applying coupons:', finalPrice); //75
```

*The above code is generalised and can be adapted to work with different input formats e.g* [*tokens*](https://docs.nected.ai/nected-docs/references/pre-configured-tokens#available-pre-configured-tokens)*.*

#### **→ Generating Formula Expressions**

In cases where you need to create formulas involving multiple variables, the Ask AI can help generate accurate expressions, saving time and reducing errors.

**Example Scenario:** You want to calculate a final product price by considering multiple variables, such as base price, tax rate, and multiple discounts.

**Prompt Given:** *Create a formula to calculate the final price after applying a tax rate and two different discount percentages.*

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

**Result:**

```html
function calculateFinalPrice(initialPrice, taxRate, discount1, discount2) {
let priceAfterTax = initialPrice * (1 + taxRate);
let priceAfterDiscount1 = priceAfterTax * (1 - discount1);
let finalPrice = priceAfterDiscount1 * (1 - discount2);
return finalPrice;
}
```

### **Conclusion**

With the GenAI features seamlessly integrated into the formula and JavaScript editors, coding challenges become simpler and more efficient. Whether you’re defining complex conditions, generating expressions, debugging, or simply seeking to understand existing code, the GenAI is there to guide you.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.nected.ai/nected-docs/references/gen-ai.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
