Code Component
Use the Code component when you want full control over how your agent processes data. You can run JavaScript to transform inputs, validate content, or add custom logic between steps—no external service needed.
What You’ll Configure
- Step 1: Write Your Code
- Step 2: Add or Edit Inputs
- Step 3: Configure Outputs
- Step 4: Add Error Handling
- Example: Parse CSV from URL
- Post-Processing Options
- Handling Other File Formats
- Best Practices
- Troubleshooting Tips
- What to Try Next
Step 1: Write Your Code
Inputs & Outputs Panel
Type | Prefix | Description |
---|---|---|
Input | _<inputName> | Read-only. Every input you define appears here. Rename “A” or “B” under the Inputs tab. |
Primary Output | _output | Writable. Assign your final value—primitive or JSON—to this variable. |
Error | _error | Writable (optional). Assign a JSON object to signal an error. Downstream logic can catch this. |
Coding Guidelines
Vanilla JavaScript
Write pure JavaScript—no external libraries or modules. All standard browser and Node APIs are available.
Size Limit
Each input is limited to 5 MB. If you need more, contact support.
Split Complex Logic
For heavy computations or external API calls, break your logic into multiple Code blocks or use an API Call component first.
// Use these variables to access your input values.
// By default, the inputs are named "A" and "B":
const _A = {{A}};
const _B = {{B}};
// This variable determines the output of your component:
let _output = undefined;
// Sample logic: add two numbers passed as inputs A and B.
let sum = _A + _B;
let message = `The sum of ${_A} and ${_B} is ${sum}`;
_output = { sum, message };
// To rename inputs later, click the Inputs tab and change "A" to something like "orderAmount",
// then refer to it as "_orderAmount" in your code.
Customizing Your Logic with Descriptive Names
Rather than using generic names like A
and B
, it’s often clearer to give each input a descriptive name. For example, if your component needs a customer’s name and purchase total, you might define inputs customerName
and purchaseTotal
. In code, you would then refer to _customerName
and _purchaseTotal
. Here’s how that looks:
// Suppose you have inputs named "customerName" (string) and "purchaseTotal" (number):
const _customerName = {{customerName}};
const _purchaseTotal = {{purchaseTotal}};
// Perform a discount calculation:
let discountRate = 0.1; // 10 % discount
let discountedTotal = _purchaseTotal * (1 - discountRate);
_output = {
name: _customerName,
original: _purchaseTotal,
discounted: discountedTotal,
message: `Hello ${_customerName}, your discounted total is $${discountedTotal.toFixed(2)}.`
};
In this example:
- We read
_customerName
and_purchaseTotal
. - We calculate a 10 % discount.
- We assign a JSON object to
_output
with four fields:name
,original
,discounted
, andmessage
.
Step 2: Add or Edit Inputs
By default, the Code component shows two inputs named A and B. You can rename these to match your use case, delete them, or create as many new inputs as you need:
-
Open the Inputs tab in the Code component panel.
-
Click + Add Input to create a new input, or click the pencil icon next to an existing input to edit its name, type, or settings.
Field Required? Description Name Yes Identifier for this input. Use camelCase (for example csvUrl
,userEmail
,orderAmount
). In code, reference it as_<Name>
(e.g.,_csvUrl
).Type Yes Data type of the input: string
,number
,boolean
,object
,file
, etc.Required / Optional Yes Set to Required if your code cannot run without this input; otherwise choose Optional for fallback logic. Default Value No A literal value used when no input is provided at runtime (handy for debugging or testing). Color No Assign a hex label (for example #F35063
) to color-code this input in the canvas for better organization.Naming tip -
Click Save. Any new input will appear as a special variable you can reference in Step 1’s code (for example,
_<inputName>
). To delete an input, click the trash icon next to its name.
Step 3: Configure Outputs
Every Code component must assign to the special _output
variable inside your script. This becomes the component’s primary Output. You can also define additional custom outputs if you want to extract subfields from a JSON object.
3.1 Default Output
- The primary Output is whatever you assign to the
_output
variable in your code. - If
_error
is not set, this value is passed downstream to the next component.
3.2 Adding Custom Outputs
If you want to expose specific fields from your JSON object as separate outputs, do the following:
-
Open the Outputs tab.
-
Click + Add Output to open the Add Output modal:
Field Required? Description Output Name Yes The identifier for this custom output (for example discountedTotal
ormessage
). Should correspond to a field in_output
.Expression No Dot-notation path to extract from your _output
object. For example,Output.discountedTotal
, orOutput.summary.totalRows
.Color No Choose a hex label (for example #3C89F9
) to color-code this output node on the canvas.Expression usage -
Click Save. The new output will appear under Outputs on the Code node. Downstream components can reference it directly.
Step 4: Add Error Handling
You can optionally assign a JSON object to the special _error
variable if something fails. That causes the component’s Error Output to fire instead of the normal output.
// Example of structured error:
_error = {
message: "Missing input: csvUrl",
context: { provided: _csvUrl }
};
When _error
is set, downstream logic can check for error outputs and decide how to proceed.
Example: Parse CSV from URL
This example shows how to take a link to a CSV file, fetch its contents using an API Call component first, and then convert the CSV text into a JSON array inside a Code block.
- Agent Skill – Captures a
csvUrl
from the user (Type:string
). - API Call – Downloads the CSV:
- Method:
GET
- URL:
{{csvUrl}}
- Output:
apiResponse
(plain CSV text)
- Method:
- Code Component – Parses the CSV text into objects:
- Input:
apiResponse
(Type:string
) - Outputs:
success
(boolean),data
(array of row objects), andsummary
(object withtotalRows
andheaders
).
- Input:
Parsing Code
// Read the raw CSV text from the API call output:
const _csvText = _apiResponse;
// Split into lines and ignore empty rows:
const lines = _csvText.split('\n').filter(line => line.trim() !== '');
// Extract headers from the first line:
const headers = lines[0].split(',').map(h => h.trim());
// Build an array of row objects:
const data = [];
for (let i = 1; i < lines.length; i++) {
const values = lines[i].split(',').map(v => v.trim());
const rowObj = {};
headers.forEach((header, index) => {
rowObj[header] = values[index] || '';
});
data.push(rowObj);
}
// Assign the structured output:
_output = {
success: true,
data,
summary: {
totalRows: data.length,
headers
}
};
Then define custom outputs under Outputs like this:
[
{
"Name": "success",
"Expression": "Output.success"
},
{
"Name": "totalRows",
"Expression": "Output.summary.totalRows"
},
{
"Name": "headers",
"Expression": "Output.summary.headers",
"Format": "json"
}
]
Post-Processing Options
Connect the structured output from your Code block to any of the following downstream actions:
- GenAI LLM – Summarize or explain the parsed data.
- RAG Remember – Store records for later retrieval.
- Another Code Component – Perform further calculations or validations.
Handling Other File Formats
Format | How to Handle |
---|---|
JSON | Use JSON.parse(_inputName) to convert string into an object. |
XML | Use a lightweight parser or regex-based approach. |
Text | Use split('\n') and process line by line. |
Binary | Treat as a file object and convert as needed (for example, Base64). |
Best Practices
- Always assign a value to
_output
(primitive or object). - Use
_error
to catch missing data or runtime issues. - Use
console.log()
statements to debug in the Logs tab. - Avoid processing more than 5 MB of input at once—chunk large files.
- Chain Code components so each block handles a single, focused task.
Troubleshooting Tips
What to Try Next
- Chain this Code block with another Code component to break logic into modular pieces.
- Feed your JSON output into GenAI LLM for human-readable summaries or analysis.
- Use RAG Remember to store parsed records for future queries.
- Wrap this component in an Agent Skill to make it a reusable action for end users.
- Experiment with replacing CSV parsing with JSON or XML to see how flexible this component can be with different formats.