File size: 1,016 Bytes
e706de2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
import { BaseOutputParser } from './base-parser.js';

/**

 * Parser that returns cleaned string output

 * Strips whitespace and optionally removes markdown

 *

 * Example:

 *   const parser = new StringOutputParser();

 *   const result = await parser.parse("  Hello World  ");

 *   // "Hello World"

 */
export class StringOutputParser extends BaseOutputParser {
  constructor(options = {}) {
    super();
    this.stripMarkdown = options.stripMarkdown ?? true;
  }

  /**

   * Parse: clean the text

   */
  async parse(text) {
    let cleaned = text.trim();

    if (this.stripMarkdown) {
      cleaned = this._stripMarkdownCodeBlocks(cleaned);
    }

    return cleaned;
  }

  /**

   * Remove markdown code blocks (```code```)

   */
  _stripMarkdownCodeBlocks(text) {
    // Remove ```language\ncode\n```
    return text.replace(/```[\w]*\n([\s\S]*?)\n```/g, '$1').trim();
  }

  getFormatInstructions() {
    return 'Respond with plain text. No markdown formatting.';
  }
}