UNPKG

crewai-ts

Version:

TypeScript port of crewAI for agent-based workflows

90 lines (89 loc) 2.79 kB
/** * StructuredTaskOutput * Implements type-safe structured output for tasks with optimized memory usage * Designed for: * - Zero-copy transformations where possible * - Minimal memory overhead for large outputs * - Efficient caching of formatted results * - Streaming support for incremental processing */ /** * Implementation of StructuredTaskOutput * Optimized for memory efficiency and minimal object creation */ export class StructuredTaskOutputImpl { result; metadata; formattedData; isStreaming; streamingComplete; // Cache for expensive computations jsonCache; constructor(output, formattedData, isStreaming = false) { this.result = output.result; this.metadata = { ...output.metadata, formatTime: formattedData ? Date.now() - (output.metadata.executionTime || 0) : undefined, }; this.formattedData = formattedData; this.isStreaming = isStreaming; this.streamingComplete = !isStreaming; } /** * Get formatted data with type casting if needed * Zero runtime cost for same type, safe casting for different types */ getFormatted() { // Cast to unknown first to avoid direct type conversion errors return this.formattedData; } /** * Convert output to JSON string * Uses caching for repeated calls */ asJSON() { if (!this.jsonCache) { // Cache the JSON string to avoid repeated stringification this.jsonCache = JSON.stringify({ result: this.result, metadata: this.metadata, formattedData: this.formattedData }); } return this.jsonCache; } /** * Get plain text representation * Returns the raw result without formatting */ asPlainText() { return this.result; } /** * Update streaming status * Used when receiving chunks in streaming mode */ updateStreamingStatus(complete, additionalResult) { this.streamingComplete = complete; if (additionalResult) { // Efficiently append to result this.result += additionalResult; // Invalidate JSON cache since result changed this.jsonCache = undefined; } } /** * Create from a standard TaskOutput * Factory method for convenient creation */ static fromTaskOutput(output, formattedData) { return new StructuredTaskOutputImpl(output, formattedData); } /** * Create a streaming output container * For handling incremental results */ static createStreaming(initialOutput) { return new StructuredTaskOutputImpl(initialOutput, undefined, true); } }