Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

base validator #35

Merged
merged 10 commits into from
Feb 3, 2024
Merged

base validator #35

merged 10 commits into from
Feb 3, 2024

Conversation

AlveinTeng
Copy link
Collaborator

@AlveinTeng AlveinTeng commented Dec 29, 2023

Variable Validator

Overview

The variableValidator class is designed to provide a flexible and robust mechanism for validating input data against a set of predefined rules. It's particularly useful in contexts where inputs need to be dynamically validated, such as in template processing or API input validation.

Features

  • Customizable Validation Rules: Set specific validation functions for individual variables or define a default validation function applicable to all variables not explicitly covered.
  • Exclusion Mechanism: Specify variables that should be excluded from validation, offering flexibility for diverse input scenarios.
  • Dynamic Rule Management: Add or remove validation rules for variables on-the-fly, adapting to changing requirements.

Usage

To use variableValidator, initialize an instance with an array of variable names you intend to validate and an optional set of rules.

Initialization

import { variableValidator } from './path/to/variableValidator';

const validator = new variableValidator(['name', 'age'], {
    default: value => typeof value === 'string',  // Default rule
    specific: {
        age: value => typeof value === 'number' && value >= 18  // Specific rule for 'age'
    },
    exclude: ['nickname']  // Exclude 'nickname' from validation
});

Adding and Removing Rules

You can dynamically add or remove validation rules for specific variables or modify the exclusion list:

import { variableValidator } from './path/to/variableValidator';
// Add a specific rule
validator.addSpecificRule('email', (input) => /\S+@\S+\.\S+/.test(input));

// Remove a specific rule
validator.removeSpecificRule('username');

// Add a variable to the exclude list
validator.addExcludeVariable('token');

// Remove a variable from the exclude list
validator.removeExcludeVariable('password');

Validating Input

To validate an input object against the defined rules, use the validate method. It returns a ValidationResult object indicating whether the validation passed and an optional error message:

const input = { username: 'user1', password: 'pass', email: '[email protected]' };
const result = validator.validate(input);

if (!result.isValid) {
    console.error(result.errorMessage);
} else {
    console.log('Validation passed!');
}

@AlveinTeng AlveinTeng requested a review from VictorS67 December 29, 2023 00:13
yarn.lock Show resolved Hide resolved
@VictorS67
Copy link
Owner

Please add documentation of the BasePromptTemplate and Validator. It would be very helpful if use cases are included. Thanks!

@AlveinTeng
Copy link
Collaborator Author

AlveinTeng commented Feb 3, 2024

Base Prompt Template

Introduction

The basePromptTemplate is a core component designed to streamline the integration and manipulation of dynamic content within template strings. It serves as the foundation for creating customizable text outputs that adapt based on specific input variables, making it an essential tool for applications that require dynamic text generation, such as automated messaging, configurable email templates, or personalized user interfaces.

A base prompt template enables developers to define a template with placeholders that can be programmatically replaced with actual data at runtime. This approach allows for a high degree of flexibility and reusability in applications where the content needs to be tailored to individual users or contexts without hardcoding every possible variation.

Use Cases

  • Automated Email Generation: Automatically generate personalized email content for marketing campaigns, user notifications, or system alerts by populating predefined templates with user-specific data.
  • Content Management Systems (CMS): Enable non-technical users to define templates for various content types, such as blog posts or product descriptions, that can be dynamically filled with actual data from a database.
  • Chatbots and Virtual Assistants: Use templates to generate varied responses based on user input or conversation context, enhancing the natural language processing capabilities of the bot.
  • Configuration Files: Dynamically generate configuration files for software or hardware based on user inputs or environmental variables, ensuring that each deployment is correctly configured.
  • Code Generation Tools: Simplify the process of generating boilerplate code for new projects or modules by defining templates that include common patterns and structures, filled in with specific details for each use case.

The basePromptTemplate class facilitates these and many other use cases by providing a robust framework for working with template strings. It includes features for input validation, template manipulation (such as adding prefixes and suffixes), and error handling to ensure that templates are correctly processed and output as expected.

Features

  • Dynamic Template Processing: Easily define and manipulate template strings with dynamic variables.
  • Input Validation: Leverage the integrated variableValidator to ensure input variables meet specified validation rules.
  • Flexible Template Manipulation: Add prefixes or suffixes to your template strings for enhanced customization.
  • Error Handling: Rigorous checks and error messages for undeclared or unused variables in the template.

Operational Workflow

  • Initialization: An instance of the class is instantiated with a template that contains placeholders and an optional validator to enforce input variable rules.
  • Input Validation: If a variableValidator is associated, the input variables are validated against the specified rules to ensure compliance.
  • Template Processing: The template undergoes processing where placeholders are substituted with actual values from the input object. Additional modifications, such as adding prefixes or suffixes, are applied as required.
  • Output Generation: The final text output, now with all placeholders replaced and modifications applied, is generated and returned. This output is ready for use within the application, be it for displaying messages, generating emails, or any other form of dynamic content delivery.

Methods

Constructor

The constructor initializes the template with optional parameters, such as input variables, the template string itself, and a validator. It also verifies that all declared input variables are utilized within the template.

constructor(fields?: Partial<PromptTemplateParams>)

addPrefix and addSuffix

These methods facilitate the addition of predefined text to the beginning or end of the template, respectively, allowing for enhanced customization of the output.

public addPrefix(prefix: string): void
public addSuffix(suffix: string): void

invoke

The invoke method is the class's core functionality, where placeholders in the template are replaced with actual values from the input object. This method involves validating the input (if a validator is set), processing the template, and generating the final text output.

async invoke(input: CallInput, options?: Partial<CallOptions>): Promise<CallOutput>

@AlveinTeng AlveinTeng requested a review from VictorS67 February 3, 2024 14:18
@AlveinTeng AlveinTeng merged commit cd37675 into VictorS67:master Feb 3, 2024
4 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants