Code as Action

Code as Action is a powerful concept in BRX that allows you to use BRKs to generate and execute code, enabling your AI applications to perform real-world actions and integrate with external systems.

Understanding Code as Action

In traditional AI systems, the output is typically text that a human must then interpret and act upon. With Code as Action, BRX can:

  1. Generate executable code based on natural language inputs
  2. Execute that code to perform actions
  3. Process the results and provide meaningful feedback

This creates a closed loop where AI can directly impact the world through code execution.

How Code as Action Works

The Code as Action pattern typically involves the following steps:

  1. A BRK receives a natural language request
  2. The BRK generates code that accomplishes the requested task
  3. The code is executed in a controlled environment
  4. The results are captured and processed
  5. A response is generated based on the execution results

Implementation Patterns

Direct Code Generation

The simplest implementation of Code as Action is direct code generation:

const codeGenerationBrk = {
  brxId: 'code-generation-brk',
  brxName: 'Code Generation',
  description: 'Generates code based on a natural language request',
  prompt: {
    prompt: new Map([
      ['main', `
        Generate JavaScript code to accomplish the following task:
        
        {{task_description}}
        
        The code should be executable in a Node.js environment.
        Only include the code, no explanations or comments.
      `]
    ])
  },
  processParams: {
    processType: 0
  },
  dependantBrxIds: new Map([
    ['main_brx_entry_schema', 'code-generation-brk']
  ])
};

Code Generation and Execution

A more complete implementation includes both code generation and execution:

// Execute generated code
const executeGeneratedCode = async (taskDescription) => {
  // Step 1: Generate code
  const codeGenBrkSchema = await brx.get('code-generation-brk');
  const codeGenBrk = new BRK(codeGenBrkSchema);
  codeGenBrk.input['task_description'] = taskDescription;
  
  const codeGenResult = await brx.run(codeGenBrk);
  const generatedCode = codeGenResult[0].brxRes.output;
  
  // Step 2: Execute code
  try {
    // Using eval for demonstration purposes only
    // In production, use a safer execution environment
    const result = eval(generatedCode);
    return { success: true, result };
  } catch (error) {
    return { success: false, error: error.message };
  }
};

// Example usage
const result = await executeGeneratedCode('Create an array of 5 random numbers between 1 and 100');
console.log(result);

Sandboxed Execution

For safer execution, you can use a sandboxed environment:

const { VM } = require('vm2');

// Execute code in a sandbox
const executeSandboxedCode = async (taskDescription) => {
  // Step 1: Generate code
  const codeGenBrkSchema = await brx.get('code-generation-brk');
  const codeGenBrk = new BRK(codeGenBrkSchema);
  codeGenBrk.input['task_description'] = taskDescription;
  
  const codeGenResult = await brx.run(codeGenBrk);
  const generatedCode = codeGenResult[0].brxRes.output;
  
  // Step 2: Execute code in sandbox
  const vm = new VM({
    timeout: 1000, // 1 second timeout
    sandbox: {
      console: {
        log: (...args) => console.log('[Sandbox]', ...args)
      }
    }
  });
  
  try {
    const result = vm.run(generatedCode);
    return { success: true, result };
  } catch (error) {
    return { success: false, error: error.message };
  }
};

Multi-Step Code Generation

For complex tasks, you can use a multi-step approach:

const multiStepCodeGeneration = async (taskDescription) => {
  // Step 1: Generate a plan
  const planBrkSchema = await brx.get('code-plan-brk');
  const planBrk = new BRK(planBrkSchema);
  planBrk.input['task_description'] = taskDescription;
  
  const planResult = await brx.run(planBrk);
  const plan = planResult[0].brxRes.output;
  
  // Step 2: Generate code based on the plan
  const codeGenBrkSchema = await brx.get('code-generation-brk');
  const codeGenBrk = new BRK(codeGenBrkSchema);
  codeGenBrk.input['task_description'] = taskDescription;
  codeGenBrk.input['plan'] = plan;
  
  const codeGenResult = await brx.run(codeGenBrk);
  const generatedCode = codeGenResult[0].brxRes.output;
  
  // Step 3: Execute the code
  // ... (execution code from previous examples)
};

Use Cases

Data Processing

Code as Action is ideal for data processing tasks:

// Process data using generated code
const processData = async (data, processingInstructions) => {
  const codeGenBrkSchema = await brx.get('data-processing-brk');
  const codeGenBrk = new BRK(codeGenBrkSchema);
  
  codeGenBrk.input['data'] = JSON.stringify(data);
  codeGenBrk.input['instructions'] = processingInstructions;
  
  const codeGenResult = await brx.run(codeGenBrk);
  const processingCode = codeGenResult[0].brxRes.output;
  
  // Execute the processing code
  const vm = new VM({
    timeout: 5000,
    sandbox: { data: JSON.parse(JSON.stringify(data)) }
  });
  
  try {
    const processedData = vm.run(`${processingCode}; return processedData;`);
    return { success: true, data: processedData };
  } catch (error) {
    return { success: false, error: error.message };
  }
};

// Example usage
const data = [
  { name: 'Alice', age: 30, city: 'New York' },
  { name: 'Bob', age: 25, city: 'Los Angeles' },
  { name: 'Charlie', age: 35, city: 'Chicago' }
];

const result = await processData(data, 'Filter people older than 30 and sort them by name');

API Integration

Code as Action can be used to integrate with external APIs:

// Generate API integration code
const generateApiIntegration = async (apiDescription, task) => {
  const apiIntegrationBrkSchema = await brx.get('api-integration-brk');
  const apiIntegrationBrk = new BRK(apiIntegrationBrkSchema);
  
  apiIntegrationBrk.input['api_description'] = apiDescription;
  apiIntegrationBrk.input['task'] = task;
  
  const result = await brx.run(apiIntegrationBrk);
  return result[0].brxRes.output;
};

// Example usage
const apiCode = await generateApiIntegration(
  `The Weather API is available at https://api.weather.com/v1/current
   It requires an API key passed as a query parameter 'key'
   It returns JSON with the current weather for a given location`,
  'Get the current weather for New York'
);

// Execute the generated API integration code
// (in a production environment, with proper security measures)

Automation

Code as Action enables automation of repetitive tasks:

// Generate automation script
const generateAutomationScript = async (taskDescription) => {
  const automationBrkSchema = await brx.get('automation-brk');
  const automationBrk = new BRK(automationBrkSchema);
  
  automationBrk.input['task_description'] = taskDescription;
  
  const result = await brx.run(automationBrk);
  return result[0].brxRes.output;
};

// Example usage
const automationScript = await generateAutomationScript(
  'Create a script that monitors a folder for new CSV files, processes them to calculate averages for each column, and saves the results to a summary file'
);

// Save the automation script to a file
fs.writeFileSync('automation.js', automationScript);

// Execute the automation script
// (in a production environment, with proper security measures)

Security Considerations

Code Validation

Before executing generated code, it’s important to validate it:

// Validate generated code
const validateCode = async (code) => {
  const validationBrkSchema = await brx.get('code-validation-brk');
  const validationBrk = new BRK(validationBrkSchema);
  
  validationBrk.input['code'] = code;
  
  const result = await brx.run(validationBrk);
  return JSON.parse(result[0].brxRes.output);
};

// Example usage
const code = '// Generated code here';
const validation = await validateCode(code);

if (validation.isValid) {
  // Execute the code
} else {
  console.error('Code validation failed:', validation.issues);
}

Sandboxing

Always execute generated code in a sandboxed environment:

const { VM } = require('vm2');

// Create a secure sandbox
const createSandbox = (allowedModules = []) => {
  const sandbox = {
    console: {
      log: (...args) => console.log('[Sandbox]', ...args)
    }
  };
  
  // Add allowed modules to the sandbox
  for (const moduleName of allowedModules) {
    try {
      sandbox[moduleName] = require(moduleName);
    } catch (error) {
      console.error(`Failed to load module ${moduleName}:`, error);
    }
  }
  
  return new VM({
    timeout: 5000, // 5 second timeout
    sandbox
  });
};

// Execute code in the sandbox
const executeSandboxed = (code, allowedModules = []) => {
  const vm = createSandbox(allowedModules);
  
  try {
    return { success: true, result: vm.run(code) };
  } catch (error) {
    return { success: false, error: error.message };
  }
};

Permission Management

Implement a permission system for code execution:

// Permission levels
const PermissionLevel = {
  NONE: 0,
  READ_ONLY: 1,
  FILE_SYSTEM: 2,
  NETWORK: 3,
  FULL: 4
};

// Execute code with permissions
const executeWithPermissions = (code, permissionLevel) => {
  // Create a sandbox with appropriate permissions
  const sandbox = {
    console: {
      log: (...args) => console.log('[Sandbox]', ...args)
    }
  };
  
  if (permissionLevel >= PermissionLevel.READ_ONLY) {
    // Add read-only capabilities
    sandbox.fs = {
      readFileSync: require('fs').readFileSync,
      readdirSync: require('fs').readdirSync
    };
  }
  
  if (permissionLevel >= PermissionLevel.FILE_SYSTEM) {
    // Add file system capabilities
    sandbox.fs = {
      ...sandbox.fs,
      writeFileSync: require('fs').writeFileSync,
      mkdirSync: require('fs').mkdirSync
    };
  }
  
  if (permissionLevel >= PermissionLevel.NETWORK) {
    // Add network capabilities
    sandbox.http = require('http');
    sandbox.https = require('https');
    sandbox.fetch = require('node-fetch');
  }
  
  if (permissionLevel >= PermissionLevel.FULL) {
    // Add full capabilities
    // Warning: This is dangerous and should be used with extreme caution
    sandbox.require = require;
    sandbox.process = process;
  }
  
  const vm = new VM({
    timeout: 5000,
    sandbox
  });
  
  try {
    return { success: true, result: vm.run(code) };
  } catch (error) {
    return { success: false, error: error.message };
  }
};

Best Practices

Prompt Engineering

Design your prompts to generate safe, efficient code:

Generate JavaScript code to accomplish the following task:

{{task_description}}

Requirements:
1. The code should be efficient and use modern JavaScript features
2. Do not use any dangerous functions like eval, exec, or Function constructor
3. Handle errors gracefully
4. Include appropriate input validation
5. Only use the following allowed modules: {{allowed_modules}}

Only include the code, no explanations or comments.

Testing Generated Code

Implement thorough testing for generated code:

// Test generated code
const testGeneratedCode = async (code, testCases) => {
  const vm = new VM({
    timeout: 5000,
    sandbox: {}
  });
  
  const results = [];
  
  for (const testCase of testCases) {
    try {
      // Create a function from the code
      const fn = vm.run(`(function(input) { ${code} })`);
      
      // Execute the function with the test case input
      const result = fn(testCase.input);
      
      // Check if the result matches the expected output
      const passed = JSON.stringify(result) === JSON.stringify(testCase.expected);
      
      results.push({
        testCase,
        result,
        passed
      });
    } catch (error) {
      results.push({
        testCase,
        error: error.message,
        passed: false
      });
    }
  }
  
  return {
    passed: results.every(r => r.passed),
    results
  };
};

// Example usage
const code = '// Generated code here';
const testCases = [
  { input: [1, 2, 3], expected: 6 },
  { input: [4, 5, 6], expected: 15 }
];

const testResults = await testGeneratedCode(code, testCases);

Iterative Refinement

Implement iterative refinement for generated code:

// Refine code based on feedback
const refineCode = async (code, feedback) => {
  const codeRefinementBrkSchema = await brx.get('code-refinement-brk');
  const codeRefinementBrk = new BRK(codeRefinementBrkSchema);
  
  codeRefinementBrk.input['code'] = code;
  codeRefinementBrk.input['feedback'] = feedback;
  
  const result = await brx.run(codeRefinementBrk);
  return result[0].brxRes.output;
};

// Example usage
let code = '// Initial generated code';
let testResults = await testGeneratedCode(code, testCases);

if (!testResults.passed) {
  const feedback = testResults.results
    .filter(r => !r.passed)
    .map(r => `Test failed: Input ${JSON.stringify(r.input)}, Expected ${JSON.stringify(r.expected)}, Got ${JSON.stringify(r.result)}`)
    .join('\n');
  
  code = await refineCode(code, feedback);
  testResults = await testGeneratedCode(code, testCases);
}

Advanced Techniques

Code Generation with Context

Provide context to improve code generation:

// Generate code with context
const generateCodeWithContext = async (taskDescription, codebase) => {
  const contextAwareBrkSchema = await brx.get('context-aware-code-brk');
  const contextAwareBrk = new BRK(contextAwareBrkSchema);
  
  contextAwareBrk.input['task_description'] = taskDescription;
  contextAwareBrk.input['codebase'] = codebase;
  
  const result = await brx.run(contextAwareBrk);
  return result[0].brxRes.output;
};

// Example usage
const codebase = {
  'utils.js': '// Utility functions...',
  'models.js': '// Data models...',
  'api.js': '// API integration...'
};

const code = await generateCodeWithContext(
  'Add a function to calculate the average rating for a product',
  codebase
);

Multi-Language Code Generation

Generate code in multiple languages:

// Generate code in multiple languages
const generateMultiLanguageCode = async (taskDescription, languages) => {
  const multiLangBrkSchema = await brx.get('multi-language-code-brk');
  const multiLangBrk = new BRK(multiLangBrkSchema);
  
  multiLangBrk.input['task_description'] = taskDescription;
  multiLangBrk.input['languages'] = languages.join(',');
  
  const result = await brx.run(multiLangBrk);
  return JSON.parse(result[0].brxRes.output);
};

// Example usage
const code = await generateMultiLanguageCode(
  'Create a function to calculate the Fibonacci sequence',
  ['javascript', 'python', 'rust']
);

console.log('JavaScript:', code.javascript);
console.log('Python:', code.python);
console.log('Rust:', code.rust);

Code Explanation and Documentation

Generate explanations and documentation for code:

// Generate code documentation
const generateCodeDocumentation = async (code) => {
  const docBrkSchema = await brx.get('code-documentation-brk');
  const docBrk = new BRK(docBrkSchema);
  
  docBrk.input['code'] = code;
  
  const result = await brx.run(docBrk);
  return result[0].brxRes.output;
};

// Example usage
const code = '// Some complex code...';
const documentation = await generateCodeDocumentation(code);

Conclusion

Code as Action is a powerful paradigm that enables BRX to bridge the gap between natural language and executable code. By following the patterns and best practices outlined in this guide, you can create AI applications that not only understand user requests but can also take concrete actions to fulfill them.

When implementing Code as Action, always prioritize security and robustness. Generated code should be thoroughly validated, tested, and executed in a controlled environment to prevent unintended consequences.

With the right approach, Code as Action can unlock new possibilities for AI-powered automation, integration, and problem-solving.