/** * @file StreamedAnswerParser.ts * @description This file defines the StreamedAnswerParser class, which parses incoming character streams * to extract grounded or normal text based on the tags found in the input stream. It maintains state * between grounded text and normal text sections, handling buffered input and ensuring proper text formatting * for AI assistant responses. */ enum ParserState { Outside, InGroundedText, InNormalText, } export class StreamedAnswerParser { private state: ParserState = ParserState.Outside; private buffer: string = ''; private result: string = ''; private isStartOfLine: boolean = true; public parse(char: string): string { switch (this.state) { case ParserState.Outside: if (char === '<') { this.buffer = '<'; } else if (char === '>') { if (this.buffer.startsWith('') { this.state = ParserState.Outside; this.buffer = ''; } else if (this.buffer.startsWith('') { this.state = ParserState.Outside; this.buffer = ''; } else if (this.buffer.startsWith('<')) { this.buffer += char; } else { this.processChar(char); } break; } return this.result.trim(); } private processChar(char: string): void { if (this.isStartOfLine && char === ' ') { // Skip leading spaces return; } if (char === '\n') { this.result += char; this.isStartOfLine = true; } else { this.result += char; this.isStartOfLine = false; } } public reset(): void { this.state = ParserState.Outside; this.buffer = ''; this.result = ''; this.isStartOfLine = true; } }