Sim

Function

The Function block lets you execute custom JavaScript or TypeScript code in your workflows. Use it to transform data, perform calculations, or implement custom logic that isn't available in other blocks.

Function Block with Code Editor

Overview

The Function block enables you to:

Transform data: Convert formats, parse text, manipulate arrays and objects

Perform calculations: Math operations, statistics, financial calculations

Implement custom logic: Complex conditionals, loops, and algorithms

Process external data: Parse responses, format requests, handle authentication

How It Works

The Function block runs your code in a secure, isolated environment:

  1. Receive Input: Access data from previous blocks via the input object
  2. Execute Code: Run your JavaScript/Python code
  3. Return Results: Use return to pass data to the next block
  4. Handle Errors: Built-in error handling and logging

Remote Execution (E2B)

  • Languages: Run JavaScript and Python in an isolated E2B sandbox.
  • How to enable: Toggle “Remote Code Execution” in the Function block.
  • When to use: Heavier logic, external libraries, or Python-specific code.
  • Performance: Slower than local JS due to sandbox startup and network overhead.
  • Notes: Requires E2B_API_KEY if running locally. For lowest latency, use natively local JS (Fast Mode).

Inputs and Outputs

  • Code: Your JavaScript/Python code to execute

  • Timeout: Maximum execution time (defaults to 30 seconds)

  • Input Data: All connected block outputs available via variables

  • function.result: The value returned from your function

  • function.stdout: Console.log() output from your code

Example Use Cases

Data Processing Pipeline

Scenario: Transform API response into structured data

  1. API block fetches raw customer data
  2. Function block processes and validates data
  3. Function block calculates derived metrics
  4. Response block returns formatted results

Business Logic Implementation

Scenario: Calculate loyalty scores and tiers

  1. Agent retrieves customer purchase history
  2. Function block calculates loyalty metrics
  3. Function block determines customer tier
  4. Condition block routes based on tier level

Data Validation and Sanitization

Scenario: Validate and clean user input

  1. User input received from form submission
  2. Function block validates email format and phone numbers
  3. Function block sanitizes and normalizes data
  4. API block saves validated data to database

Example: Loyalty Score Calculator

loyalty-calculator.js
// Process customer data and calculate loyalty score
const { purchaseHistory, accountAge, supportTickets } = <agent>;

// Calculate metrics
const totalSpent = purchaseHistory.reduce((sum, purchase) => sum + purchase.amount, 0);
const purchaseFrequency = purchaseHistory.length / (accountAge / 365);
const ticketRatio = supportTickets.resolved / supportTickets.total;

// Calculate loyalty score (0-100)
const spendScore = Math.min(totalSpent / 1000 * 30, 30);
const frequencyScore = Math.min(purchaseFrequency * 20, 40);
const supportScore = ticketRatio * 30;

const loyaltyScore = Math.round(spendScore + frequencyScore + supportScore);

return {
  customer: <agent.name>,
  loyaltyScore,
  loyaltyTier: loyaltyScore >= 80 ? "Platinum" : loyaltyScore >= 60 ? "Gold" : "Silver",
  metrics: { spendScore, frequencyScore, supportScore }
};

Best Practices

  • Keep functions focused: Write functions that do one thing well to improve maintainability and debugging
  • Handle errors gracefully: Use try/catch blocks to handle potential errors and provide meaningful error messages
  • Test edge cases: Ensure your code handles unusual inputs, null values, and boundary conditions correctly
  • Optimize for performance: Be mindful of computational complexity and memory usage for large datasets
  • Use console.log() for debugging: Leverage stdout output to debug and monitor function execution
Function