Dashboard/Workflow Nodes

Code Run

FastGPT Code Run node documentation (for version 4.14.8 and above)

This document applies to FastGPT version 4.14.8 and above. For version 4.14.7 and earlier, see Code Run (Deprecated).

Features

The Code Run node executes JavaScript and Python code in a secure sandbox for data processing, format conversion, logic calculations, and similar tasks.

Supported Languages

  • JavaScript (Bun runtime)
  • Python 3

Important Notes

  • Self-hosted users need to deploy the fastgpt-sandbox image and configure the SANDBOX_URL environment variable.
  • The sandbox has a default maximum runtime of 60s (configurable).
  • Code runs in isolated process pools with no access to the file system or internal network.

Variable Input

Add variables needed for code execution in custom inputs.

JavaScript — Destructure in the main function parameters:

async function main({data1, data2}){
    return {
        result: data1 + data2
    }
}

Python — Receive variables by name in the main function parameters:

def main(data1, data2):
    return {"result": data1 + data2}

Result Output

Always return an object (JS) or dict (Python).

In custom outputs, add variable names to access values by their keys. For example, if you return:

{
  "result": "hello",
  "count": 42
}

Add result and count variables in custom outputs to retrieve their values.

Built-in Functions

httpRequest - Make HTTP Requests

Make external HTTP requests from within the sandbox. Internal network addresses are automatically blocked (SSRF protection).

JavaScript Example:

async function main({url}){
    const res = await SystemHelper.httpRequest(url, {
        method: 'GET',       // Request method, default GET
        headers: {},         // Custom request headers
        body: null,          // Request body (objects are auto JSON-serialized)
        timeout: 60          // Timeout in seconds, max 60s
    })
    return {
        status: res.status,
        data: res.data
    }
}

Python Example:

def main(url):
    res = SystemHelper.httpRequest(url, method="GET", headers={}, timeout=10)
    return {"status": res["status"], "data": res["data"]}

Limitations:

  • Maximum 30 requests per execution
  • Single request timeout: 60s
  • Maximum response body: 2MB
  • Only http/https protocols allowed
  • Internal IPs automatically blocked (127.0.0.0/8, 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16, etc.)

Available Modules

JavaScript Whitelist

The following npm modules are available via require():

ModuleDescriptionExample
lodashUtility libraryconst _ = require('lodash')
momentDate handlingconst moment = require('moment')
dayjsLightweight date libraryconst dayjs = require('dayjs')
crypto-jsEncryption libraryconst CryptoJS = require('crypto-js')
uuidUUID generationconst { v4 } = require('uuid')
qsQuery string parsingconst qs = require('qs')

Other modules (such as fs, child_process, net, etc.) are prohibited.

Python Whitelist

The following Python standard library and third-party modules can be imported directly:

Math and Numerical Computing

ModuleDescription
mathMathematical functions
cmathComplex number math
decimalDecimal floating-point arithmetic
fractionsFraction arithmetic
randomRandom number generation
statisticsStatistical functions

Data Structures and Algorithms

ModuleDescription
collectionsContainer data types
arrayArrays
heapqHeap queue
bisectArray bisection
queueQueues
copyShallow and deep copy

Functional Programming

ModuleDescription
itertoolsIterator tools
functoolsHigher-order functions
operatorStandard operators

String and Text Processing

ModuleDescription
stringString constants
reRegular expressions
difflibDiff calculation
textwrapText wrapping
unicodedataUnicode database
codecsCodec registry

Date and Time

ModuleDescription
datetimeDate and time
timeTime access
calendarCalendar

Data Serialization

ModuleDescription
jsonJSON encoding/decoding
csvCSV file handling
base64Base64 encoding/decoding
binasciiBinary-to-ASCII conversion
structByte string parsing

Encryption and Hashing

ModuleDescription
hashlibHash algorithms
hmacHMAC message authentication
secretsSecure random numbers
uuidUUID generation

Types and Abstractions

ModuleDescription
typingType hints
abcAbstract base classes
enumEnumeration types
dataclassesData classes
contextlibContext managers

Other Utilities

ModuleDescription
pprintPretty printing
weakrefWeak references

Third-party Libraries

ModuleDescription
numpyNumerical computing
pandasData analysis
matplotlibData visualization

Prohibited modules: os, sys, subprocess, socket, urllib, http, requests, and any modules involving system calls, network access, or file system operations.

Security Restrictions

The sandbox provides multiple layers of security protection:

  • Module Restrictions: Only whitelisted modules are allowed for both JS and Python
  • Network Isolation: Internal IP requests are automatically blocked (SSRF protection)
  • File Isolation: No read/write access to the container file system
  • Timeout Protection: Default 60s timeout prevents infinite loops
  • Process Isolation: Each execution runs in an independent sandbox process

Usage Examples

JavaScript Examples

Data Format Conversion
// Convert comma-separated string to array
function main({input}){
    const items = input.split(',').map(s => s.trim()).filter(Boolean)
    return { items, count: items.length }
}
Date Calculation
const dayjs = require('dayjs')

function main(){
    const now = dayjs()
    return {
        today: now.format('YYYY-MM-DD'),
        nextWeek: now.add(7, 'day').format('YYYY-MM-DD'),
        timestamp: now.valueOf()
    }
}
HTTP Request - Get Weather
async function main({city}){
    const res = await SystemHelper.httpRequest(
        `https://api.example.com/weather?city=${city}`,
        { method: 'GET', timeout: 10 }
    )

    return {
        temperature: res.data.temp,
        weather: res.data.condition
    }
}
Data Encryption
const CryptoJS = require('crypto-js')

function main({text, key}){
    const encrypted = CryptoJS.AES.encrypt(text, key).toString()
    return { encrypted }
}

Python Examples

Data Statistics
import math

def main(numbers):
    if not numbers:
        return {"error": "no data"}

    mean = sum(numbers) / len(numbers)
    variance = sum((x - mean)**2 for x in numbers) / len(numbers)

    return {
        "mean": mean,
        "max": max(numbers),
        "min": min(numbers),
        "std": math.sqrt(variance)
    }
Date Processing
from datetime import datetime, timedelta

def main(date_str):
    dt = datetime.strptime(date_str, "%Y-%m-%d")
    next_week = dt + timedelta(days=7)

    return {
        "input": date_str,
        "next_week": next_week.strftime("%Y-%m-%d"),
        "weekday": dt.strftime("%A")
    }
HTTP Request - API Call
def main(api_url, api_key):
    res = SystemHelper.httpRequest(
        api_url,
        method="GET",
        headers={"Authorization": f"Bearer {api_key}"},
        timeout=10
    )

    return {
        "status": res["status"],
        "data": res["data"]
    }
JSON Data Processing
import json

def main(json_str):
    data = json.loads(json_str)

    # Extract specific fields
    result = {
        "names": [item["name"] for item in data if "name" in item],
        "count": len(data)
    }

    return result
Regular Expression Matching
import re

def main(text):
    # Extract all email addresses
    emails = re.findall(r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b', text)

    return {
        "emails": emails,
        "count": len(emails)
    }
Edit on GitHub

File Updated