Code execution
Definition
The Code node lets you run Python or NodeJS code in a workflow to perform powerful data transformations. It greatly simplifies your workflow. It is ideal for scenarios such as arithmetic operations, JSON transformations, and text processing.
This node provides developers with great flexibility. It lets you embed custom Python or JavaScript scripts in your workflow to manipulate variables in ways that preset nodes cannot. With a simple configuration, you can specify the required input variables and output variables and write the corresponding execution code.
Prerequisites
Node configuration
After the Start node, click
to add a Code Execution node.
To use variables from other nodes in the Code node, define the variable names in Input Variables and reference them.
Scenarios
You can use the Code node to perform the following common operations.
Structured data processing
Workflows often involve processing unstructured data, such as parsing, fetching, and transforming JSON strings. For example, API responses from an HTTP node often nest data within multiple layers of JSON objects, and you need to fetch specific fields. The Code node helps you perform these operations. The following example fetches the data.name field from a JSON string returned by an HTTP node:
def main(http_response: str) -> dict:
import json
data = json.loads(http_response)
return {
# Note: Declare 'result' in the output variables.
'result': data['data']['name']
}
Mathematical calculations
You can use the Code node for complex mathematical calculations in your workflow, such as calculating a complex formula or performing statistical analysis on data. The following example calculates the variance of an array.
def main(x: list) -> dict:
return {
# Note: Declare 'result' in the output variables.
'result' : sum([(i - sum(x) / len(x)) ** 2 for i in x]) / len(x)
}
Concatenating data
Sometimes, you need to combine multiple data sources, such as from knowledge base retrievals, data searches, or API calls. The Code node helps you integrate these data sources. The following example merges data from two knowledge bases.
def main(knowledge1: list, knowledge2: list) -> dict:
return {
# Note: Declare 'result' in the output variables.
'result': knowledge1 + knowledge2
}