The Custom Code app is a powerful infrastructure component in the Prisme.ai ecosystem that allows you to execute custom logic within your automations and workflows. It provides a secure, managed environment for running JavaScript and Python code, enabling complex data transformations, integrations, and calculations that go beyond what’s possible with standard automation steps.

Overview

Custom Code serves as a flexible extension point for your Prisme.ai solutions:

Code Execution

Run custom JavaScript and Python code in a secure environment

Data Transformation

Transform data with complex logic and algorithms

Integration Bridge

Connect to systems without pre-built integrations

Advanced Processing

Implement sophisticated data processing and analytics

This infrastructure app is particularly valuable for handling unique business logic, specialized calculations, and custom data processing requirements.

Key Features

A secure, controlled environment for running code:

  • JavaScript Runtime: Execute JavaScript/TypeScript
  • Python Runtime: Run Python 3.x code
  • Isolation: Code runs in a containerized environment
  • Resource Limits: CPU, memory, and execution time controls
  • Version Management: Control runtime versions

This execution environment balances flexibility with security and stability.

How Custom Code Works

Custom Code functions are defined, managed, and executed through a structured process:

1

Function Definition

Create a function with code, parameters, and metadata:

  • Write the function code
  • Define input parameters with types and validation
  • Specify output format
  • Add documentation
2

Storage and Management

Store functions in the Custom Code repository:

  • Save to the function library
  • Version and track changes
  • Organize by category or purpose
  • Control access permissions
3

Execution from Workflows

Call functions from automations:

  • Reference the function by name
  • Provide required parameters
  • Map workflow data to parameters
  • Capture the function output
4

Runtime Execution

Execute the function in a secure environment:

  • Validate input parameters
  • Run the code in an isolated container
  • Monitor execution and resource usage
  • Handle errors and exceptions
5

Result Processing

Return the result to the calling workflow:

  • Format the output according to specifications
  • Pass the result back to the workflow
  • Log execution details
  • Track performance metrics

This process provides a controlled yet flexible way to include custom logic in your automations.

JavaScript Functions

JavaScript functions in Custom Code allow you to implement a wide range of data processing and transformation tasks:

Python Functions

Python functions in Custom Code provide access to Python’s rich ecosystem for data analysis, machine learning, and scientific computing:

Integration with Prisme.ai Workflows

Custom Code is designed to integrate seamlessly with Prisme.ai automations:

1

Calling Functions from Automations

Reference Custom Code functions in your automation YAML:

slug: process-data-workflow
name: Process Data Workflow
do:
  - Custom Code.run function:
      function: processData
      parameters:
        data: '{{payload.items}}'
      output: processedData
  - emit:
      event: data-processed
      payload:
        result: '{{processedData}}'

This automation calls the processData function with input from the payload and emits the result as an event.

2

Handling Function Results

Process the output from Custom Code functions:

- conditions:
    '{{processedData.success}}':
      - Collection.insert:
          data: '{{processedData.items}}'
    default:
      - emit:
          event: processing-error
          payload:
            error: '{{processedData.error}}'

This example shows conditional logic based on the function’s output.

3

Error Handling

Implement robust error handling for Custom Code execution:

- Custom Code.run function:
    function: riskAnalysis
    parameters:
      data: '{{payload.clientData}}'
    output: riskResult
- conditions:
    '{{riskResult.error}}':
      - set:
          name: errorDetails
          value:
            message: "Error in risk analysis"
            details: '{{riskResult.error}}'
            timestamp: '{% now() %}'
      - Collection.insert:
          data: '{{errorDetails}}'
          collection: errors
      - break: {}
    default: []

This approach captures and logs errors from function execution.

Common Use Cases

Custom Code enables a wide range of use cases:

Data Transformation

Implement complex data transformations:

  • Format conversion
  • Schema mapping
  • Data normalization
  • Content extraction

Advanced Analysis

Perform sophisticated data analysis:

  • Statistical calculations
  • Pattern recognition
  • Trend identification
  • Risk assessment

Integration Logic

Create custom integration components:

  • API request formatting
  • Response processing
  • Protocol implementations
  • Legacy system connections

Business Logic

Implement specialized business rules:

  • Pricing calculations
  • Eligibility determinations
  • Approval workflows
  • Validation logic

Example: Data Classification

A common use case for Custom Code is classifying data based on content. Here’s an example that classifies documents:

// Function to classify documents
function classifyDocument(document) {
  // Extract text content
  const text = document.content.toLowerCase();
  
  // Define classification patterns
  const classifications = [
    {
      category: "invoice",
      patterns: ["invoice", "bill to", "payment due", "invoice number", "total amount"]
    },
    {
      category: "contract",
      patterns: ["agreement", "terms and conditions", "parties", "hereby agree", "signature"]
    },
    {
      category: "resume",
      patterns: ["experience", "education", "skills", "employment", "qualification"]
    },
    {
      category: "report",
      patterns: ["analysis", "findings", "conclusion", "summary", "recommendations"]
    }
  ];
  
  // Score each category
  const scores = classifications.map(classification => {
    let score = 0;
    
    // Count pattern matches
    for (const pattern of classification.patterns) {
      if (text.includes(pattern)) {
        score += 1;
      }
    }
    
    return {
      category: classification.category,
      score: score / classification.patterns.length
    };
  });
  
  // Find the highest scoring category
  const bestMatch = scores.reduce((best, current) => 
    current.score > best.score ? current : best, 
    { category: "other", score: 0 }
  );
  
  // Only classify if score is above threshold
  if (bestMatch.score >= 0.3) {
    return {
      category: bestMatch.category,
      confidence: bestMatch.score,
      document_id: document.id
    };
  } else {
    return {
      category: "unknown",
      confidence: 0,
      document_id: document.id
    };
  }
}

// Execute the function and return result
return classifyDocument(document);

This function analyzes document content, scoring it against different category patterns, and assigns the most likely classification if it meets a minimum confidence threshold.

Example: Advanced Data Analysis with Python

When you need sophisticated data analysis, Python’s ecosystem provides powerful capabilities:

import pandas as pd
import numpy as np
from sklearn.ensemble import IsolationForest

def detect_anomalies(transactions):
    # Convert to DataFrame
    df = pd.DataFrame(transactions)
    
    # Select numeric features
    features = df[['amount', 'transaction_count', 'average_value']]
    
    # Fit isolation forest model
    model = IsolationForest(contamination=0.05, random_state=42)
    df['anomaly'] = model.fit_predict(features)
    
    # Anomaly is -1, normal is 1, convert to boolean
    df['is_anomaly'] = df['anomaly'] == -1
    
    # Calculate anomaly score (higher means more anomalous)
    df['anomaly_score'] = model.score_samples(features)
    df['anomaly_score'] = 1 - (df['anomaly_score'] - df['anomaly_score'].min()) / (df['anomaly_score'].max() - df['anomaly_score'].min())
    
    # Identify anomalous transactions
    anomalies = df[df['is_anomaly']].sort_values('anomaly_score', ascending=False)
    
    # Prepare results
    result = {
        'anomaly_count': len(anomalies),
        'anomaly_percentage': (len(anomalies) / len(df)) * 100,
        'anomalies': anomalies.to_dict(orient='records'),
        'anomaly_statistics': {
            'amount': {
                'mean': anomalies['amount'].mean(),
                'min': anomalies['amount'].min(),
                'max': anomalies['amount'].max()
            },
            'transaction_count': {
                'mean': anomalies['transaction_count'].mean(),
                'min': anomalies['transaction_count'].min(),
                'max': anomalies['transaction_count'].max()
            }
        }
    }
    
    return result

# Execute the function
result = detect_anomalies(transactions)

This Python function uses the Isolation Forest algorithm to detect anomalous transactions based on multiple features, providing detailed information about the detected anomalies.

Best Practices

Follow these recommendations to get the most from Custom Code:

Limitations and Considerations

When using Custom Code, be aware of these considerations:

  • Execution Environment: Code runs in a controlled environment with resource limits. Very compute-intensive operations may not be suitable.

  • External Access: For security reasons, network access is restricted. External API calls and file system access follow platform security policies.

  • Runtime Duration: Functions have maximum execution times. Long-running operations should be designed with this in mind.

  • Library Availability: While many common libraries are available, some specialized packages may not be pre-installed. Check documentation for the current list.

  • State Management: Functions are stateless by default. Persistent state should be stored using platform services like Collection.

Integration with Other Prisme.ai Products

Custom Code works seamlessly with other Prisme.ai products:

Enhance AI Knowledge with custom processing:

  • Pre-process documents before ingestion
  • Create custom embedding algorithms
  • Implement specialized reranking logic
  • Generate synthetic training data
  • Analyze query patterns and performance

This integration improves retrieval accuracy and knowledge base utility.

Next Steps