wand-magic-sparklesBuilding Custom Transformers

Learn how to build custom transformers to process and shape data in BoxLang AI pipelines.

Create custom transformers to process, validate, and shape data as it flows through AI pipelines. Transformers sit between pipeline steps, allowing you to apply custom business logic, format conversions, and data validation.

🎯 Why Custom Transformers?

Build custom transformers when you need to:

  • Format conversion - Transform data between different formats (JSON, XML, custom)

  • Data validation - Validate and sanitize AI responses

  • Business logic - Apply domain-specific rules and processing

  • Content extraction - Parse and extract specific data from responses

  • Logging and monitoring - Track data as it flows through pipelines

🏗️ Transformer Architecture

spinner

📝 ITransformer Interface

All transformers should implement basic transformation methods:

interface {
    /**
     * Transform input data
     * @param input The data to transform
     * @return Transformed data
     */
    public any function transform( required any input );

    /**
     * Configure the transformer
     * @param config Configuration struct
     * @return this (for fluent API)
     */
    public any function configure( required struct config );
}

🚀 Quick Start: Simple Transformer

Here's a minimal transformer that cleans and formats text:

Usage:

🎨 Using Transformers in Pipelines

Inline Transformers

Use lambda functions for simple transformations:

Named Transformers with aiTransform()

Create reusable transformers:

Custom Transformer Classes

For complex logic, create classes:

💡 Advanced Example: JSON Schema Validator

Here's a transformer that validates AI responses against JSON schemas:

Usage:

🔄 Extending BaseTransformer

The BaseTransformer provides common functionality:

Core Methods

Chainable Configuration

Implement fluent methods:

Usage:

🎯 Built-In Transformers

BoxLang AI ships with several core transformers:

TextChunker

Splits text into chunks with overlap:

TextCleaner

Cleans and normalizes text:

AiTransformRunnable

Wraps functions as runnables:

💼 Real-World Examples

Code Extractor

Extract code blocks from AI responses:

Price Parser

Extract and format prices:

Sentiment Analyzer

Add sentiment analysis:

✅ Best Practices

1. Handle Multiple Input Types

2. Validate and Sanitize

3. Provide Meaningful Errors

4. Make Transformers Reusable

📚 Next Steps

🎓 Summary

Custom transformers enable you to:

  • ✅ Process and validate data between pipeline steps

  • ✅ Apply domain-specific business logic

  • ✅ Convert between data formats

  • ✅ Extract and parse specific content

  • ✅ Chain multiple transformations for complex workflows

Start with a simple function, wrap it with aiTransform(), or extend BaseTransformer for full control!

Last updated