> For the complete documentation index, see [llms.txt](https://whitepaper.aitech.io/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://whitepaper.aitech.io/agentforge/blocks/function.md).

# function

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

### 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

{% stepper %}
{% step %}

### Receive Input

Access data from previous blocks via the `input` object
{% endstep %}

{% step %}

### Execute Code

Run your JavaScript/TypeScript code
{% endstep %}

{% step %}

### Return Results

Use `return` to pass data to the next block
{% endstep %}

{% step %}

### Handle Errors

Built-in error handling and logging
{% endstep %}
{% endstepper %}

### Configuration Options

#### Code Editor

Write your JavaScript/TypeScript code in a full-featured editor with:

* Syntax highlighting and error checking
* Line numbers and bracket matching
* Support for modern JavaScript features
* Native support for `fetch`

#### Accessing Input Data

Use the `input` object to access data from previous blocks:

```javascript
// Access data from connected blocks
const userData = <agent.userData>;
const orderData = <agent.orderData>;

// Access specific fields
const customerName = <agent.customer.name>;
const total = <agent.order.total>;
```

#### Common Examples

**Data Transformation**:

```javascript
// Convert and format data
const formatted = {
  name: <agent.user.firstName> + ' ' + <agent.user.lastName>,
  email: <agent.user.email>.toLowerCase(),
  joinDate: new Date(<agent.user.created>).toLocaleDateString()
};
return formatted;
```

**Calculations**:

```javascript
// Calculate discounts and totals
const subtotal = <agent.items>.reduce((sum, item) => sum + item.price, 0);
const discount = subtotal > 100 ? 0.1 : 0;
const total = subtotal * (1 - discount);

return { subtotal, discount, total };
```

**Data Validation**:

```javascript
// Validate email format
const email = <agent.email>;
const isValid = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);

if (!isValid) {
  throw new Error('Invalid email format');
}
return { email, isValid };
```

#### Accessing Results

After a function executes, you can access its outputs:

* **`<function.result>`**: The value returned from your function
* **`<function.stdout>`**: Any console.log() output from your code

### Advanced Features

#### Async/Await Support

Use async functions for complex operations:

```javascript
// Async function example
const processData = async () => {
  const data = <api.response>;
  
  // Process data with async operations
  const processed = await Promise.all(
    data.map(async (item) => {
      return {
        id: item.id,
        processed: true,
        timestamp: new Date().toISOString()
      };
    })
  );
  
  return processed;
};

return await processData();
```

#### Error Handling

Implement robust error handling:

```javascript
try {
  const result = <api.data>;
  
  if (!result || !result.length) {
    throw new Error('No data received');
  }
  
  return result.map(item => ({
    id: item.id,
    name: item.name.trim(),
    valid: true
  }));
} catch (error) {
  console.error('Processing failed:', error.message);
  return { error: error.message, valid: false };
}
```

#### Performance Optimization

Optimize for large datasets:

```javascript
// Efficient data processing
const data = <api.large_dataset>;

// Use efficient array methods
const processed = data
  .filter(item => item.status === 'active')
  .map(item => ({
    id: item.id,
    summary: item.description.substring(0, 100)
  }))
  .slice(0, 1000); // Limit results

return processed;
```

### Security and Limitations

{% hint style="warning" %}
Functions run in a secure environment with these restrictions:

* **Execution timeout**: 30 seconds maximum to prevent infinite loops
* **Memory limits**: Limited memory to prevent resource exhaustion
* **No network access**: Cannot make HTTP requests (use API blocks instead)
* **Limited APIs**: Only safe JavaScript APIs are available
  {% endhint %}

### Inputs and Outputs

{% tabs %}
{% tab title="Configuration" %}

* **Code**: Your JavaScript/TypeScript code to execute
* **Timeout**: Maximum execution time (defaults to 30 seconds)
* **Input Data**: All connected block outputs available via variables
  {% endtab %}

{% tab title="Variables" %}

* **function.result**: The value returned from your function
* **function.stdout**: Console.log() output from your code
* **function.error**: Error details if function failed
* **function.execution\_time**: Time taken to execute
  {% endtab %}

{% tab title="Results" %}

* **Function Result**: Primary output from your code
* **Debug Information**: Logs and execution details
* **Access**: Available in blocks after the function
  {% endtab %}
  {% endtabs %}

### 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

{% code title="loyalty-calculator.js" %}

```javascript
// 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 }
};
```

{% endcode %}

### 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


---

# 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 dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://whitepaper.aitech.io/agentforge/blocks/function.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
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.
