> ## Documentation Index
> Fetch the complete documentation index at: https://docs.hopx.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# User-Defined Functions Platform

> Build a Zapier/Make.com-style workflow automation platform with custom function execution, workflow orchestration, data transformation, and error handling

Build a production-ready user-defined functions platform where users can create custom functions for workflow automation. This cookbook demonstrates how to create a platform similar to Zapier or Make.com using HopX.

## Overview

User-defined functions platforms allow users to create custom functions for workflow automation. Users write functions, the platform executes them in workflows, transforms data, and handles errors gracefully.

## Prerequisites

* HopX API key ([Get one here](https://console.hopx.dev/api-keys))
* Python 3.8+ or Node.js 16+
* Understanding of workflow automation
* Basic knowledge of data transformation

## Architecture

```
┌──────────────┐
│   User       │ Define function
└──────┬───────┘
       │
       ▼
┌─────────────────┐
│  Workflow       │ Orchestrate steps
│   Engine        │
└──────┬──────────┘
       │
       ▼
┌─────────────────┐
│  HopX Sandbox   │ Execute function
└─────────────────┘
```

## Implementation

### Step 1: User Function Execution

Execute user-defined functions:

<CodeGroup>
  ```python Python theme={null}
  from hopx_ai import Sandbox
  import os
  from typing import Dict, Any, List

  class UserFunction:
      def __init__(self, function_id: str, code: str, inputs: List[str], outputs: List[str]):
          self.function_id = function_id
          self.code = code
          self.inputs = inputs
          self.outputs = outputs

  class UserFunctionPlatform:
      def __init__(self, api_key: str):
          self.api_key = api_key
          self.functions = {}
          self.sandbox = None
      
      def initialize(self):
          """Initialize platform"""
          self.sandbox = Sandbox.create(
              template="code-interpreter",
              api_key=self.api_key,
              timeout_seconds=3600
          )
      
      def register_function(self, function: UserFunction):
          """Register user function"""
          self.functions[function.function_id] = function
      
      def execute_function(self, function_id: str, inputs: Dict[str, Any]) -> Dict[str, Any]:
          """Execute user function with inputs"""
          if function_id not in self.functions:
              return {
                  "success": False,
                  "error": f"Function {function_id} not found"
              }
          
          function = self.functions[function_id]
          
          try:
              # Prepare function code with inputs
              import json
              function_code = f"""
  import json

  # Inputs
  inputs = {json.dumps(inputs)}

  # User function
  {function.code}
  """
              
              result = self.sandbox.run_code(function_code, timeout=30)
              
              return {
                  "success": result.success,
                  "output": result.stdout,
                  "error": result.stderr if not result.success else None
              }
          except Exception as e:
              return {
                  "success": False,
                  "error": str(e)
              }
      
      def cleanup(self):
          """Clean up platform resources"""
          if self.sandbox:
              self.sandbox.kill()
              self.sandbox = None

  # Usage
  platform = UserFunctionPlatform(api_key=os.getenv("HOPX_API_KEY"))
  platform.initialize()

  # Register function
  platform.register_function(UserFunction(
      function_id="add_numbers",
      code="result = inputs['a'] + inputs['b']\nprint(result)",
      inputs=["a", "b"],
      outputs=["result"]
  ))

  # Execute
  result = platform.execute_function("add_numbers", {"a": 5, "b": 3})
  print(result)

  platform.cleanup()
  ```

  ```javascript JavaScript theme={null}
  import { Sandbox } from '@hopx-ai/sdk';

  class UserFunction {
      constructor(functionId, code, inputs, outputs) {
          this.functionId = functionId;
          this.code = code;
          this.inputs = inputs;
          this.outputs = outputs;
      }
  }

  class UserFunctionPlatform {
      constructor(apiKey) {
          this.apiKey = apiKey;
          this.functions = {};
          this.sandbox = null;
      }
      
      async initialize() {
          this.sandbox = await Sandbox.create({
              template: 'code-interpreter',
              apiKey: this.apiKey,
              timeoutSeconds: 3600
          });
      }
      
      registerFunction(func) {
          this.functions[func.functionId] = func;
      }
      
      async executeFunction(functionId, inputs) {
          if (!this.functions[functionId]) {
              return {
                  success: false,
                  error: `Function ${functionId} not found`
              };
          }
          
          const func = this.functions[functionId];
          
          try {
              // Prepare function code with inputs
              const functionCode = `
  // Inputs
  const inputs = ${JSON.stringify(inputs)};

  // User function
  ${func.code}
  `;
              
              const result = await this.sandbox.runCode(functionCode, { timeout: 30 });
              
              return {
                  success: result.success,
                  output: result.stdout,
                  error: !result.success ? result.stderr : null
              };
          } catch (error) {
              return {
                  success: false,
                  error: error.message
              };
          }
      }
      
      async cleanup() {
          if (this.sandbox) {
              await this.sandbox.kill();
              this.sandbox = null;
          }
      }
  }

  // Usage
  const platform = new UserFunctionPlatform(process.env.HOPX_API_KEY);
  await platform.initialize();

  // Register function
  platform.registerFunction(new UserFunction(
      'add_numbers',
      "const result = inputs.a + inputs.b;\nconsole.log(result);",
      ['a', 'b'],
      ['result']
  ));

  // Execute
  const result = await platform.executeFunction('add_numbers', { a: 5, b: 3 });
  console.log(result);

  await platform.cleanup();
  ```
</CodeGroup>

## Best Practices

1. **Function Validation**: Validate function code before execution
2. **Input Validation**: Validate inputs before passing to functions
3. **Error Handling**: Handle errors gracefully
4. **Workflow Orchestration**: Chain functions efficiently

## Related Cookbooks

* [Plugin System](/cookbooks/marketplace/plugin-system) - Plugin architecture
* [Low-Code Platform Backend](/cookbooks/enterprise/low-code-backend) - Enterprise platforms

## Next Steps

1. Implement workflow builder
2. Add function marketplace
3. Create workflow execution engine
4. Implement data transformation
5. Add workflow monitoring
