|
|
import { BaseOutputParser, OutputParserException } from './base-parser.js';
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
export class RegexOutputParser extends BaseOutputParser {
|
|
|
constructor(options = {}) {
|
|
|
super();
|
|
|
this.regex = options.regex;
|
|
|
this.outputKeys = options.outputKeys || [];
|
|
|
this.dotAll = options.dotAll ?? false;
|
|
|
|
|
|
if (this.dotAll) {
|
|
|
|
|
|
const flags = this.regex.flags.includes('s')
|
|
|
? this.regex.flags
|
|
|
: this.regex.flags + 's';
|
|
|
this.regex = new RegExp(this.regex.source, flags);
|
|
|
}
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
async parse(text) {
|
|
|
const match = text.match(this.regex);
|
|
|
|
|
|
if (!match) {
|
|
|
throw new OutputParserException(
|
|
|
`Text does not match regex pattern: ${this.regex}`,
|
|
|
text
|
|
|
);
|
|
|
}
|
|
|
|
|
|
|
|
|
if (this.outputKeys.length === 0) {
|
|
|
return match.slice(1);
|
|
|
}
|
|
|
|
|
|
|
|
|
const result = {};
|
|
|
for (let i = 0; i < this.outputKeys.length; i++) {
|
|
|
result[this.outputKeys[i]] = match[i + 1];
|
|
|
}
|
|
|
|
|
|
return result;
|
|
|
}
|
|
|
|
|
|
getFormatInstructions() {
|
|
|
if (this.outputKeys.length > 0) {
|
|
|
return `Format your response to match: ${this.outputKeys.join(', ')}`;
|
|
|
}
|
|
|
return 'Follow the specified format exactly.';
|
|
|
}
|
|
|
} |