UNPKG

@mastra/core

Version:
184 lines • 9.32 kB
import { TransformStream } from 'node:stream/web'; import type { StructuredOutputOptions } from '../../agent/types.js'; import type { IMastraLogger } from '../../logger/index.js'; import type { ZodType, PublicSchema, StandardSchemaWithJSON } from '../../schema/index.js'; import type { ValidationResult } from '../aisdk/v5/compat/index.js'; import type { ChunkType } from '../types.js'; import type { ZodLikePartialSchema } from './schema.js'; type StreamTransformerStructuredOutput<OUTPUT> = Omit<StructuredOutputOptions<OUTPUT>, 'schema'> & { schema: PublicSchema<OUTPUT>; }; /** * Escapes unescaped newlines, carriage returns, and tabs within JSON string values. * * LLMs often output actual newline characters inside JSON strings instead of properly * escaped \n sequences, which breaks JSON parsing. This function fixes that by: * 1. Tracking whether we're inside a JSON string (after an unescaped quote) * 2. Replacing literal newlines/tabs with their escape sequences only inside strings * 3. Preserving already-escaped sequences like \\n * * @param text - Raw JSON text that may contain unescaped control characters in strings * @returns JSON text with control characters properly escaped inside string values */ export declare function escapeUnescapedControlCharsInJsonStrings(text: string): string; interface ProcessPartialChunkParams { /** Text accumulated from streaming so far */ accumulatedText: string; /** Previously parsed object from last emission */ previousObject: unknown; /** Previous processing result (handler-specific state) */ previousResult?: unknown; } interface ProcessPartialChunkResult { /** Whether a new value should be emitted */ shouldEmit: boolean; /** The value to emit if shouldEmit is true */ emitValue?: unknown; /** New previous result state for next iteration */ newPreviousResult?: unknown; } type ValidateAndTransformFinalResult<OUTPUT = undefined> = { /** Whether validation succeeded */ success: true; /** * The validated and transformed value if successful */ value: OUTPUT; } | { /** Whether validation succeeded */ success: false; /** * Error if validation failed */ error: Error; }; /** * Base class for all output format handlers. * Each handler implements format-specific logic for processing partial chunks * and validating final results. */ declare abstract class BaseFormatHandler<OUTPUT = undefined> { abstract readonly type: 'object' | 'array' | 'enum'; /** * The original user-provided schema (Zod, JSON Schema, or AI SDK Schema). */ readonly schema: StandardSchemaWithJSON<OUTPUT> | undefined; /** * Validate partial chunks as they are streamed. @planned */ readonly validatePartialChunks: boolean; readonly partialSchema?: ZodLikePartialSchema<OUTPUT> | undefined; constructor(schema?: StandardSchemaWithJSON<OUTPUT>, options?: { validatePartialChunks?: boolean; }); /** * Checks if the original schema is a Zod schema with safeParse method. */ protected isZodSchema(schema: unknown): schema is ZodType; /** * Validates a value against the schema using StandardSchemaWithJSON's validate method. */ protected validateValue(value: unknown, diagnosticValue?: unknown): Promise<ValidationResult<OUTPUT>>; /** * Processes a partial chunk of accumulated text and determines if a new value should be emitted. * @param params - Processing parameters * @param params.accumulatedText - Text accumulated from streaming so far * @param params.previousObject - Previously parsed object from last emission * @param params.previousResult - Previous processing result (handler-specific state) * @returns Promise resolving to processing result with emission decision */ abstract processPartialChunk(params: ProcessPartialChunkParams): Promise<ProcessPartialChunkResult>; /** * Validates and transforms the final parsed value when streaming completes. * @param finalValue - The final parsed value to validate * @returns Promise resolving to validation result */ abstract validateAndTransformFinal(finalValue: string): Promise<ValidateAndTransformFinalResult<OUTPUT>>; /** * Preprocesses accumulated text to handle LLMs that wrap JSON in code blocks * and fix common JSON formatting issues like unescaped newlines in strings. * Extracts content from the first complete valid ```json...``` code block or removes opening ```json prefix if no complete code block is found (streaming chunks). * @param accumulatedText - Raw accumulated text from streaming * @returns Processed text ready for JSON parsing */ protected preprocessText(accumulatedText: string): string; } /** * Handles object format streaming. Emits parsed objects when they change during streaming. * This is the simplest format - objects are parsed and emitted directly without wrapping. */ declare class ObjectFormatHandler<OUTPUT = undefined> extends BaseFormatHandler<OUTPUT> { readonly type: 'object'; processPartialChunk({ accumulatedText, previousObject, }: ProcessPartialChunkParams): Promise<ProcessPartialChunkResult>; validateAndTransformFinal(finalRawValue: string): Promise<ValidateAndTransformFinalResult<OUTPUT>>; } /** * Handles array format streaming. Arrays are wrapped in {elements: [...]} objects by the LLM * for better generation reliability. This handler unwraps them and filters incomplete elements. * Emits progressive array states as elements are completed. */ declare class ArrayFormatHandler<OUTPUT = undefined> extends BaseFormatHandler<OUTPUT> { readonly type: 'array'; /** Previously filtered array to track changes */ private textPreviousFilteredArray; /** Whether we've emitted the initial empty array */ private hasEmittedInitialArray; processPartialChunk({ accumulatedText, previousObject, }: ProcessPartialChunkParams): Promise<ProcessPartialChunkResult>; validateAndTransformFinal(finalRawValue: string): Promise<ValidateAndTransformFinalResult<OUTPUT>>; } /** * Handles enum format streaming. Enums are wrapped in {result: ""} objects by the LLM * for better generation reliability. This handler unwraps them and provides partial matching. * Emits progressive enum states as they are completed. * Validates the final result against the user-provided schema. */ declare class EnumFormatHandler<OUTPUT = undefined> extends BaseFormatHandler<OUTPUT> { readonly type: 'enum'; /** Previously emitted enum result to avoid duplicate emissions */ private textPreviousEnumResult?; /** * Finds the best matching enum value for a partial result string. * If multiple values match, returns the partial string. If only one matches, returns that value. * @param partialResult - Partial enum string from streaming * @returns Best matching enum value or undefined if no matches */ private findBestEnumMatch; processPartialChunk({ accumulatedText, previousObject, }: ProcessPartialChunkParams): Promise<ProcessPartialChunkResult>; validateAndTransformFinal(rawFinalValue: string): Promise<ValidateAndTransformFinalResult<OUTPUT>>; } /** * Factory function to create the appropriate output format handler based on schema. * Analyzes the transformed schema format and returns the corresponding handler instance. * @param schema - Original user-provided schema (e.g., Zod schema from agent.stream({output: z.object({})})) * @param transformedSchema - Wrapped/transformed schema used for LLM generation (arrays wrapped in {elements: []}, enums in {result: ""}) * @returns Handler instance for the detected format type */ export declare function createOutputHandler<OUTPUT = undefined>({ schema }: { schema?: PublicSchema<OUTPUT>; }): ArrayFormatHandler<OUTPUT> | EnumFormatHandler<OUTPUT> | ObjectFormatHandler<OUTPUT>; export declare function isStructuredOutputError(error: unknown): boolean; /** * Transforms raw text-delta chunks into structured object chunks for JSON mode streaming. * * For JSON response formats, this transformer: * - Accumulates text deltas and parses them as partial JSON * - Emits 'object' chunks when the parsed structure changes * - For arrays: filters incomplete elements and unwraps from {elements: [...]} wrapper * - For objects: emits the parsed object directly * - For enums: unwraps from {result: ""} wrapper and provides partial matching * - Always passes through original chunks for downstream processing */ export declare function createObjectStreamTransformer<OUTPUT = undefined>({ structuredOutput, logger, }: { structuredOutput?: StreamTransformerStructuredOutput<OUTPUT>; logger?: IMastraLogger; }): TransformStream<ChunkType<OUTPUT>, ChunkType<OUTPUT>>; /** * Transforms object chunks into JSON text chunks for streaming. * * This transformer: * - For arrays: emits opening bracket, new elements, and closing bracket * - For objects/no-schema: emits the object as JSON */ export declare function createJsonTextStreamTransformer<OUTPUT = undefined>(schema?: StandardSchemaWithJSON<OUTPUT>): TransformStream<ChunkType<OUTPUT>, string>; export {}; //# sourceMappingURL=output-format-handlers.d.ts.map