Skip to main content

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.

Why this matters

The Code component gives you a powerful way to calculate, transform, or filter data in-line without needing a server or API. Best when built-in tools aren’t flexible enough for your custom logic.

What You’ll Configure

Step 1: Write Your Code

Overview

In this section, you define and process data using JavaScript. By default, two inputs named A and B appear. You can rename, delete, or add inputs at any time. Each input is exposed as a variable prefixed with an underscore. Assign your final result to _output. Optionally assign a JSON object to _error if something goes wrong.

Inputs & Outputs Panel

TypePrefixDescription
Input_<inputName>Read-only. Every input you define appears here. Rename “A” or “B” under the Inputs tab.
Primary Output_outputWritable. Assign your final value—primitive or JSON—to this variable.
Error_errorWritable (optional). Assign a JSON object to signal an error. Downstream logic can catch this.
Naming Tip

Use clear, camelCase names for inputs (e.g., orderTotal, customerName). Then reference them as _orderTotal or _customerName in code. This prevents confusion later.

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.

Default template

When you first open the Code component, you’ll see boilerplate similar to this:

// 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, and message.

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:

  1. Open the Inputs tab in the Code component panel.

  2. 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.

    Add Input dialog showing Name, Type, Required/Optional toggle, Color and Default Value
    FieldRequired?Description
    NameYesIdentifier for this input. Use camelCase (for example csvUrl, userEmail, orderAmount). In code, reference it as _<Name> (e.g., _csvUrl).
    TypeYesData type of the input: string, number, boolean, object, file, etc.
    Required / OptionalYesSet to Required if your code cannot run without this input; otherwise choose Optional for fallback logic.
    Default ValueNoA literal value used when no input is provided at runtime (handy for debugging or testing).
    ColorNoAssign a hex label (for example #F35063) to color-code this input in the canvas for better organization.
    Naming tip

    Use clear, descriptive names for your inputs so your code is self-explanatory. For instance, use orderAmount instead of A, and taxRate instead of B.

  3. 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:

  1. Open the Outputs tab.

  2. Click + Add Output to open the Add Output modal:

    Add Output dialog showing Output Name and Advanced Options (Expression, Color)
    FieldRequired?Description
    Output NameYesThe identifier for this custom output (for example discountedTotal or message). Should correspond to a field in _output.
    ExpressionNoDot-notation path to extract from your _output object. For example, Output.discountedTotal, or Output.summary.totalRows.
    ColorNoChoose a hex label (for example #3C89F9) to color-code this output node on the canvas.
    Expression usage

    If inside your code you set _output = { total: 50, note: "OK" }, you can create a custom output named total with expression Output.total to extract just that number. Use nested paths like Output.user.address.city for deeper fields.

  3. 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.

Why use `_error`?

If a required input is missing or an unexpected exception occurs, assigning to _error lets your agent handle it gracefully (for example, send a notification or retry) rather than crashing.

  // 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.

  1. Agent Skill – Captures a csvUrl from the user (Type: string).
  2. API Call – Downloads the CSV:
    • Method: GET
    • URL: {{csvUrl}}
    • Output: apiResponse (plain CSV text)
  3. Code Component – Parses the CSV text into objects:
    • Input: apiResponse (Type: string)
    • Outputs: success (boolean), data (array of row objects), and summary (object with totalRows and headers).

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:

Tip

Split large or complex logic into multiple Code blocks so each block does one clear job and is easier to maintain.

Handling Other File Formats

FormatHow to Handle
JSONUse JSON.parse(_inputName) to convert string into an object.
XMLUse a lightweight parser or regex-based approach.
TextUse split('\n') and process line by line.
BinaryTreat 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

If your code fails…
  • Did you assign anything to _output?
  • Is each input name spelled exactly as defined (e.g. csvUrl_csvUrl)?
  • Did your script throw a JavaScript error? Check the Logs tab.
  • Is your input too large or the wrong type?
  • Try adding console.log() to inspect intermediate values in real time.

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.