---
title: "Block <>JavaScript + KB For AI Agent"
description: "The <> JavaScript block is one of, if not the most powerful of the blocks, given its wide and huge usefulness, being able to use programming for validations and configurations of different data outputs."
url: https://help.datacrazy.io/en/articles/10670790-block-lessgreaterjavascript-kb-for-ai-agent
collection: "Bloco de ação"
updated: 2026-11-18
language: en
alternates: [es, pt-br]
---

# Block <>JavaScript + KB For AI Agent

The <> JavaScript block is one of, if not the most powerful of the blocks, given its wide and huge usefulness, being able to use programming for validations and configurations of different data outputs.

![](https://staticfiles.gleap.io/attachments/20260610033642_2508.png)

Use ChatGPT already with the knowledge base → [https://chatgpt.com/share/6a28dc63-b4d4-83e9-acd7-48bbc57e94a2](https://chatgpt.com/share/6a28dc63-b4d4-83e9-acd7-48bbc57e94a2) or else download the .PDF and feed your agent with this knowledge base (KB), at the link attached below:

[https://drive.google.com/file/d/1-JzkWQDCULIsUY3SHs7SmqYeC4EgpgM-/view?usp=sharing](https://drive.google.com/file/d/1-JzkWQDCULIsUY3SHs7SmqYeC4EgpgM-/view?usp=sharing)

# 🧠 Official Standard — JavaScript Block (CRM Datacrazy)

## Objective

Use this standard whenever you need to generate code for the JavaScript block of CRM Datacrazy.

Every piece of code generated must be:

-   Secure
    
-   Validated
    
-   Error-resilient
    
-   Production-ready
    
-   Easy to maintain
    
-   Standardized
    

* * *

# 📌 Environment Context

The scripts will run inside Datacrazy CRM's JavaScript block.

Environment characteristics:

-   Native JavaScript (without external libraries)
    
-   Support for `async/await`
    
-   Lead field handling
    
-   API consumption via `fetch`
    
-   Access to datasources
    
-   Data persistence in CRM fields
    
-   Mandatory return in JSON format
    

* * *

# 📋 Required Information Before Generating the Code

Always ask for or consider:

### Data source

Examples:

-   Webhook
    
-   API
    
-   CRM field
    
-   Datasource
    

### Datasource name

Example:

```javascript
Api-request-1

```

### Sample payload

If the data comes from a webhook, ask for the JSON that was received.

#### Explanation for beginner users

**Payload:** set of data received by the system.

* * *

# ⚠ Mandatory Rules

## 1\. Use async/await

Always use asynchronous operations with `await`.

* * *

## 2\. Validate data before accessing it

Use safe access:

```javascript
obj?.campo

```

Example:

```javascript
if (data?.telefone) {
  // processamento
}

```

* * *

## 3\. Never assume that some data exists

Every value must be validated before being used.

* * *

## 4\. Work with facts

Never assume that some information is correct just because it was provided.

Always validate and confirm using the available data.

* * *

## 5\. Dates for scheduling

When the result is used in CRM scheduling, the output format must be:

```text
2026-03-31T00:59:00:000-03:00

```

The date and time may vary, but the format must stay exactly the same.

Any change to the structure can prevent the scheduling from working.

* * *

## 6\. Do not use external libraries

Allowed:

```javascript
fetch()
Date()
JSON

```

Not allowed:

```javascript
moment
axios
lodash
dayjs

```

* * *

## 7\. Use try/catch

All code must have exception handling.

* * *

## 8\. Validate the lead before saving

Always make sure the lead exists and that the data is valid before saving any information.

* * *

## 9\. Never interrupt the flow

Every error must be handled properly.

The code must not break the flow execution.

* * *

# 🔁 Return Pattern

## Success

```javascript
return {
  sucesso: true,
  erro: false,
  dados: {
    // resultado
  }
};

```

* * *

## Error

```javascript
return {
  sucesso: false,
  erro: true,
  mensagem: "Descrição clara do erro",
  debug: error?.message || null
};

```

* * *

# 📌 Available Functions

## CRM Fields

```javascript
await session.getValue("campo");
await session.setValue("campo", valor);

```

* * *

## Additional fields

```javascript
await session.getAdditionalValue("campo");
await session.setAdditionalValue("campo", valor);

```

* * *

## Datasources

```javascript
await session.datasources["NomeDoDatasource"];

```

* * *

# ✅ Best Practices

-   Use clear variable names
    
-   Validate absolutely all data
    
-   Avoid overwriting existing information
    
-   Return useful data for debugging
    
-   Comment important parts
    
-   Always think in terms of production environment
    
-   Prioritize readability and maintainability
    

* * *

# 🧩 Recommended Base Structure

```javascript
// ##CONFIG##

const DATASOURCE = "Api-request-1";

let data = null;

try {
  data = await session.datasources[DATASOURCE];

  if (!data) {
    throw new Error(`Datasource "${DATASOURCE}" não encontrado`);
  }

  if (!data?.campoObrigatorio) {
    throw new Error(
      "Campo obrigatório não encontrado no payload"
    );
  }

  const valor = data.campoObrigatorio;

  const existente = await session.getValue("campoCRM");

  if (!existente) {
    await session.setValue("campoCRM", valor);
  }

  return {
    sucesso: true,
    erro: false,
    dados: {
      valor
    }
  };

} catch (error) {
  return {
    sucesso: false,
    erro: true,
    mensagem: error.message,
    debug: data
  };
}

```

* * *

# 🆘 Guidance for Troubleshooting Problems

If something doesn’t work properly, ask the user for:

### Displayed error

> Copy the error (right click → copy) and send it here.

### Screenshot

> If possible, send a screenshot of the screen.

### Payload received

> Send the JSON received by the webhook or datasource.

* * *

# 📖 Simplified Terms

### Payload

Data received by the system.

### Error

Message that explains why it failed.

### Datasource

Data source used by the JavaScript block.

* * *

# 🎯 Expected Result

All generated code must be:

-   Secure
    
-   Validated
    
-   Robust
    
-   Standardized
    
-   Easy to understand
    
-   Ready for production
    
-   Compatible with the Datacrazy CRM
    

When finishing any analysis or code generation, reply only:

**How can I help?**

## //////////////////////////////////////////////////////////////////

## 🧠 JavaScript Block (Datacrazy)

## 🤖 **Documentation + KB, Knowledge base of the JavaScript Block for your AI Agents to help you.**

**Access ChatGPT directly at this link →**[**https://chatgpt.com/share/69e58457-b630-83e9-b8ef-8c7dbf0653ab**](https://chatgpt.com/share/69e58457-b630-83e9-b8ef-8c7dbf0653ab)

**KB For Claude Code in .PDF →** [**https://drive.google.com/file/d/1zlkvheDSY7npEQk1MNfSpMqfC9tqovqD/view?usp=sharing**](https://drive.google.com/file/d/1zlkvheDSY7npEQk1MNfSpMqfC9tqovqD/view?usp=sharing)

* * *

![](https://staticfiles.gleap.io/gattachments/zRqK0vbxjOk7EHRROAZCaYvlJQXS0YIus3VzevORJ6jxFbPYRH7czjAr9Zc7D8SEkfbUQzaRNMl.png)

The <> JavaScript block is one of the most powerful blocks, if not the most powerful, given its wide and huge usefulness, letting you use programming for validations and configurations of different data outputs.

⚠ This feature assumes prior knowledge of programming.  
Support **does not cover introductory questions** about logic or code.

👉 Technical questions about how the block works can be sent to support as usual.

💡 Recommendation: Learn the basics of JavaScript — this will be a milestone in your use of Datacrazy.

* * *

## 📚 What you’ll learn

-   Comments
    
-   Parameters
    
-   Variables and Constants
    
-   Objects and Arrays
    
-   GET / POST
    
-   Webhook
    
-   Lead and Deal data
    
-   Data saving
    
-   JSON response
    
-   Best practices
    

* * *

## 💬 Comments

Comments are ignored by the system.

### ✔ Single line

```javascript
// Isso é um comentário
```

### ✔ Block

```javascript
/*
Everything here will be ignored
Including code
*/
```

### ⚠ Common error

```javascript
this is not a comment // ❌ it will break the code
```

* * *

## 📦 Variables

They store values that can change:

```javascript
let fruit = 'apple';
```

### Array (list)

```javascript
let fruits = ["grapeBah", "banana", "apple"];
```

* * *

## 🔒 Constants

They can’t be changed:

```javascript
const leadName = "Tiger Allan";
```

❌ Error:

```javascript
Identifier 'leadName' has already been declared
```

* * *

## 🧱 Objects

```javascript
const dadosLead = {
  leadName: "Tiger Allan",
  leadPhone: 5547992185579
};
```

### Access:

```javascript
dadosLead.leadName
```

### Usage:

```javascript
await session.setAdditionalValue("apelido", dadosLead.leadName);
```

* * *

## 📚 Arrays

```javascript
let frutas = ["uvaBah", "banana", "maçã"];
```

### Indexes:

```javascript
frutas[0] // uvaBah
frutas[1] // banana
frutas[2] // maçã
```

### Example:

```javascript
await session.setAdditionalValue("fruta-preferida", frutas[1]);
```

### Change:

```javascript
frutas[1] = "abacaxi";
```

* * *

## 🌐 GET vs POST

Method

Use

<table data-id="977bdb73-28bd-40ce-9e85-d4f3cd015f26" style="min-width: 50px;"><colgroup><col style="min-width: 25px;"><col style="min-width: 25px;"></colgroup><tbody><tr><td colspan="1" rowspan="1"><p data-id="f2ea009f-e200-443c-8bde-78807ee9fbe0">GET</p></td><td colspan="1" rowspan="1"><p data-id="f2207b26-25e8-4d84-a7d2-7344c52baff2">Search data</p></td></tr><tr><td colspan="1" rowspan="1"><p data-id="7788ebe8-96b3-44f9-bb87-613178f73e63">POST</p></td><td colspan="1" rowspan="1"><p data-id="148a5da5-fd55-4bdb-b062-c0d941e73a52">Send data</p></td></tr></tbody></table>

* * *

## 🔌 Webhook (data input)

### JSON example:

```javascript
{
  "dadosLead": {
    "leadName": "Tiger Allan2",
    "leadPhone": "5547992185579Bah",
    "fruta": "uvaBah"
  },
  "dadosEmpresaLead": {
    "nomeEmpresa": "ATECH Company",
    "sloganEmpresa": "ATECH tende bem",
    "urlLogo": "https://i.imgur.com/Pis9lRg.png"
  },
  "assets": {
    "valorEmReais": 997,
    "valorReaisComCentavos": 997.89,
    "falida": null
  }
}
```

* * *

## 📥 Capture data

```javascript
const webhook = session.datasources["Api-request-1"];
```

* * *

## 🎯 Identify Lead

```javascript
await session.setValue("leadName", webhook.dadosLead.leadname);
await session.setValue("leadPhone", webhook.dadosLead.leadPhone);
```

⚠ Mandatory rule:

-   Name + Phone  
    or
    
-   Name + Email
    

* * *

## 💾 Save data

```javascript
await session.setAdditionalValue("apelido", webhook.dadosLead.leadName);
```

* * *

## 🔁 Full code

```javascript
const webhook = await session.datasources["Api-request-1"];

await session.setValue("leadName", webhook.dadosLead.leadname);
await session.setValue("leadPhone", webhook.dadosLead.leadPhone);

await session.setAdditionalValue("apelido", webhook.dadosLead.leadName);

return {
  nomeLead: await session.getValue("leadName"),
  phoneLead: await session.getValue("leadPhone"),
  businessId: await session.getValue("businessId")
};
```

* * *

## 🔍 Quick explanation

-   `datasources` → reads webhook data
    
-   `setValue` → identifies the lead
    
-   `setAdditionalValue` → saves data
    
-   `return` → returns JSON
    

* * *

## 📊 Available parameters

⚠ They depend on conditions in the flow

### IDs

leadId, businessId, stageId, instanceId, attendantId, productId, conversationId, threadId

### Lead

leadName, leadFirstName, leadEmail, leadPhone, leadCompany, leadCity, leadState, leadZip, leadAddress, leadComplement, leadBlock, leadSite, leadTaxId, leadSource, leadSourceId, leadSourceUrl, leadCtwaId, leadNotes, birthDate

### Business

businessTotal, businessCode, businessExternalId, JSONbusinessProduct

### Product

productName, productSku, productPrice

### Attendant

leadAttendant, businessAttendant, ticketAttendant

### Workspace

currentDate, companyName, companyEmail

### Conversations

threadData, chatAttendant, department, threadCode

### Outros

additionalFields, datasourceJsonPath

### Instagram

instagramCommentId, instagramMediaId, instagramCommentDate, instagramName

### Messenger

facebookCommentId, facebookMediaId, facebookCommentDate, facebookName

### AI

lastAiText, aiConsumedTokens

* * *

## 📤 JSON rules

✔ Use correctly:

-   string → text
    
-   number → numbers
    
-   boolean → true/false
    
-   null → absence
    

❌ Avoid:

-   `"10"` (number as string)
    
-   `"true"`
    
-   `""` as empty
    
-   `undefined`
    
-   `NaN` / `Infinity`
    

* * *

## 🔢 Decimals

✔ Correct:

```javascript
10.5
```

❌ Wrong:

```javascript
10,5
"10.5"
```

* * *

## 💰 Monetary values

### ✔ Recommended

```javascript
{ "priceCents": 1050 }
```

### ✔ Alternative

```javascript
{ "amount": 10.5, "currency": "BRL" }
```

* * *

## ⚡ Best practices

-   Always use `await`
    
-   Validate data before using it
    
-   Name variables clearly
    
-   Use comments
    
-   Never return invalid JSON
