crewai-ts
Version:
TypeScript port of crewAI for agent-based workflows
117 lines (116 loc) • 3.24 kB
JavaScript
/**
* TaskOutputFormatter
* Implements structured output format controls with schema validation
* Optimized for:
* - Minimal memory overhead
* - Efficient schema validation
* - Reusable data transformations
* - Zero runtime validation cost for known schemas
*/
/**
* ZodOutputSchema - Zod-based schema implementation
* Provides efficient schema validation with minimal runtime overhead
*/
export class ZodOutputSchema {
schema;
constructor(schema) {
this.schema = schema;
}
validate(data) {
return this.schema.parse(data);
}
parse(data) {
return this.schema.parse(data);
}
safeParse(data) {
const result = this.schema.safeParse(data);
if (result.success) {
return { success: true, data: result.data };
}
else {
return { success: false, error: new Error(result.error.message) };
}
}
}
/**
* InterfaceOutputSchema - Interface-based schema implementation
* Uses TypeScript interfaces for zero runtime validation overhead
* Only provides type checking at compile time
*/
export class InterfaceOutputSchema {
// This is intentionally minimal to avoid runtime overhead
validate(data) {
return data;
}
parse(data) {
return data;
}
safeParse(data) {
try {
return { success: true, data: data };
}
catch (error) {
return { success: false, error: error };
}
}
}
/**
* TaskOutputFormatter - Main class to format task outputs
* Provides methods to validate, transform, and format task outputs
*/
export class TaskOutputFormatter {
schema;
constructor(schema) {
this.schema = schema;
}
/**
* Format raw output to structured data
* Optimized for minimal object creation and memory usage
*/
format(rawOutput) {
let parsed;
try {
// Try to parse as JSON first
parsed = JSON.parse(rawOutput);
}
catch {
// If not valid JSON, treat as plain text
parsed = rawOutput;
}
return this.schema.parse(parsed);
}
/**
* Safely format output with error handling
* Returns either the formatted output or null with error information
*/
safeFormat(rawOutput) {
try {
const data = this.format(rawOutput);
return { success: true, data };
}
catch (error) {
return { success: false, error: error };
}
}
/**
* Create a formatter with a Zod schema
* Provides full validation but has runtime overhead
*/
static fromZodSchema(schema) {
return new TaskOutputFormatter(new ZodOutputSchema(schema));
}
/**
* Create a formatter with a TypeScript interface
* Zero runtime validation overhead but no runtime type checking
*/
static fromInterface() {
return new TaskOutputFormatter(new InterfaceOutputSchema());
}
}
/**
* Function to create a output formatter with a specific schema
* Convenience function for common use cases
*/
export function createOutputFormatter(schema) {
return TaskOutputFormatter.fromZodSchema(schema);
}