[docs]classRegexDictParser(BaseOutputParser[Dict[str,str]]):"""Parse the output of an LLM call into a Dictionary using a regex."""regex_pattern:str=r"{}:\s?([^.'\n']*)\.?"# : :meta private:"""The regex pattern to use to parse the output."""output_key_to_format:Dict[str,str]"""The keys to use for the output."""no_update_value:Optional[str]=None"""The default key to use for the output."""@propertydef_type(self)->str:"""Return the type key."""return"regex_dict_parser"
[docs]defparse(self,text:str)->Dict[str,str]:"""Parse the output of an LLM call."""result={}foroutput_key,expected_formatinself.output_key_to_format.items():specific_regex=self.regex_pattern.format(re.escape(expected_format))matches=re.findall(specific_regex,text)ifnotmatches:raiseValueError(f"No match found for output key: {output_key} with expected format \{expected_format} on text {text}")eliflen(matches)>1:raiseValueError(f"Multiple matches found for output key: {output_key} with \ expected format {expected_format} on text {text}")elif(self.no_update_valueisnotNoneandmatches[0]==self.no_update_value):continueelse:result[output_key]=matches[0]returnresult