> For the complete documentation index, see [llms.txt](https://docs.empowergpt.ai/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.empowergpt.ai/workflows/block-types/code.md).

# Code

The **Code Block** allows you to run custom **Python** or **JavaScript** code directly within a workflow.

Use the Code Block when you need custom logic that cannot be easily handled by standard workflow blocks. It can be used to transform data, perform calculations, validate information, manipulate arrays or objects, format values, and implement custom business logic.

<div data-with-frame="true"><figure><img src="https://2192711725-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2Fc2KRGWrkyRO0iZN5Lyeg%2Fuploads%2FI01PG1fbhdZCpMEMijyS%2Fimage.png?alt=media&amp;token=05a402e9-b0fb-4bc5-b59f-5a9beb036a2d" alt="" width="563"><figcaption></figcaption></figure></div>

Data from previous workflow blocks can be used within the code, and the result can then be passed to subsequent blocks.

### When to Use the Code Block

The Code Block is useful when your workflow requires deterministic processing or custom logic.

Common use cases include:

* Transforming or formatting data
* Performing mathematical calculations
* Applying custom business rules
* Parsing or manipulating JSON
* Filtering or processing arrays
* Validating and cleaning data
* Performing date and time operations
* Preparing data for subsequent workflow blocks

For example:

**Form Trigger → Code → If/Else → Output**

The Form Trigger can collect numerical inputs, the Code Block can perform a calculation, and the calculated result can then be evaluated by an If/Else block.

***

## Configuration

The Code Block contains two primary configuration options:

| **Configuration** | **Description**                                                                 |
| ----------------- | ------------------------------------------------------------------------------- |
| **Language**      | Select the programming language used to execute the code.                       |
| **Code**          | Write the custom logic that should execute when the workflow reaches the block. |

***

## Language

Use **Language** to select the programming language for the Code Block.

EmpowerGPT currently supports:

* **Python**
* **JavaScript**

Select the language that best fits the processing required by your workflow.

### Python

Select **Python** when you want to implement the block logic using Python.

Python is particularly useful for data manipulation, calculations, processing collections, and other programmatic transformations.

### JavaScript

Select **JavaScript** when you want to implement the block logic using JavaScript.

JavaScript can be used for data transformations, object and array manipulation, calculations, formatting, and custom workflow logic.

***

## Code Editor

Use the **Code** editor to write the Python or JavaScript that should execute when the workflow reaches the block.

The editor provides a dedicated area for writing and reviewing your code. You can also expand the editor when you need more space to work with larger code snippets.

The code should perform the required processing and return the information that needs to be used by subsequent workflow blocks.

***

## Returning Data from the Code Block

The Code Block can return processed values that can be used by subsequent workflow blocks.

When multiple values are required, return them in a structured object so that individual values can be referenced later in the workflow.

For example, a calculation could return:

```
{
  "total": 1250,
  "tax": 200,
  "final_amount": 1450
}
```

Subsequent blocks can then use the returned values for further processing, conditions, or outputs.

Returning structured objects also makes Code Block results easier to understand and reuse throughout the workflow.

***

## Example: Calculate an Average

Suppose a previous block provides a list of scores and you want to calculate their average.

The workflow could be:

**Previous Block → Code → Output**

#### Python

```
scores = [80, 90, 70, 100]
average = sum(scores) / len(scores)
return {"average": average}
```

The Code Block returns the calculated average, which can then be used by the Output Block or another subsequent block.

***

## Example: Transform Data

A Code Block can transform information into the format required by subsequent blocks.

For example, consider customer information containing separate first and last names.

#### JavaScript

```
const customer = {
    firstName: "John",
    lastName: "Smith"
};

return {
    fullName: `${customer.firstName} ${customer.lastName}`
};
```

The resulting `fullName` can then be used by another workflow block.

***

## Example: Filter an Array

The Code Block can also process arrays and return only the required items.

For example:

#### Python

```
scores = [45, 72, 88, 35, 91]
passing_scores = [
    score for score in scores    
    if score >= 50
]
return {
    "passing_scores": passing_scores
}
```

This can be useful before passing a collection to a Loop or another processing block.

***

## Example: Data Validation

You can use the Code Block to validate information before continuing the workflow.

For example:

#### JavaScript

```
const amount = 1500;

if (amount <= 0) {
    throw new Error("Amount must be greater than zero");
}

return {
    amount: amount,
    valid: true
};
```

This allows custom validation rules to be implemented when the standard workflow blocks are not sufficient.

***

## Example: Code with If/Else

The output of a Code Block can be passed to an **If/Else** block to control subsequent workflow execution.

For example:

**Form Trigger → Code → If/Else**

The Code Block could calculate a score:

```
score = 85
return {"score": score}
```

The If/Else block can then evaluate the returned value:

**Field:** Code → `score`\
**Operator:** Greater than or equal\
**Match Text:** `80`

The matching workflow branch can then execute.

***

## Code Block vs. Agent Block

Use the Code Block and Agent Block for different types of processing.

| Use Code Block When          | Use Agent Block When              |
| ---------------------------- | --------------------------------- |
| Performing calculations      | Understanding natural language    |
| Transforming data            | Summarizing documents             |
| Filtering arrays             | Categorizing unstructured content |
| Formatting values            | Generating content                |
| Applying deterministic rules | Making AI-based decisions         |
| Validating structured data   | Extracting meaning from text      |

For example, calculating a percentage is better suited to a **Code Block**, while determining the sentiment of customer feedback is better suited to an **Agent Block**.

***

## Best Practices

**Choose the appropriate language**\
Select Python or JavaScript according to the processing requirements and the language you are most comfortable using.

**Keep code focused**\
Use the Code Block for a specific transformation, calculation, or piece of business logic rather than combining unrelated processing into a single block.

**Return structured data**\
When the result will be used by subsequent blocks, return a structured object with clearly named values.

**Handle missing or unexpected data**\
Consider cases where input values may be empty, missing, or in an unexpected format.

**Handle errors appropriately**\
Add validation and error handling where necessary so that unexpected inputs produce meaningful errors instead of incorrect results.

**Add comments to complex code**\
Comments can make custom workflow logic easier for other users to understand and maintain.

**Test with representative inputs**\
Test the Code Block using realistic workflow data, including edge cases, before deploying the workflow.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

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

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.empowergpt.ai/workflows/block-types/code.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

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.
