[docs]classOutputFixingParser(BaseOutputParser[T]):"""Wrap a parser and try to fix parsing errors."""@classmethoddefis_lc_serializable(cls)->bool:returnTrueparser:BaseOutputParser[T]"""The parser to use to parse the output."""# Should be an LLMChain but we want to avoid top-level imports from langchain.chainsretry_chain:Union[RunnableSerializable[OutputFixingParserRetryChainInput,str],Any]"""The RunnableSerializable to use to retry the completion (Legacy: LLMChain)."""max_retries:int=1"""The maximum number of times to retry the parse."""legacy:bool=True"""Whether to use the run or arun method of the retry_chain."""
[docs]@classmethoddeffrom_llm(cls,llm:Runnable,parser:BaseOutputParser[T],prompt:BasePromptTemplate=NAIVE_FIX_PROMPT,max_retries:int=1,)->OutputFixingParser[T]:"""Create an OutputFixingParser from a language model and a parser. Args: llm: llm to use for fixing parser: parser to use for parsing prompt: prompt to use for fixing max_retries: Maximum number of retries to parse. Returns: OutputFixingParser """chain=prompt|llm|StrOutputParser()returncls(parser=parser,retry_chain=chain,max_retries=max_retries)
[docs]defparse(self,completion:str)->T:retries=0whileretries<=self.max_retries:try:returnself.parser.parse(completion)exceptOutputParserExceptionase:ifretries==self.max_retries:raiseeelse:retries+=1ifself.legacyandhasattr(self.retry_chain,"run"):completion=self.retry_chain.run(instructions=self.parser.get_format_instructions(),completion=completion,error=repr(e),)else:try:completion=self.retry_chain.invoke(dict(instructions=self.parser.get_format_instructions(),completion=completion,error=repr(e),))except(NotImplementedError,AttributeError):# Case: self.parser does not have get_format_instructionscompletion=self.retry_chain.invoke(dict(completion=completion,error=repr(e),))raiseOutputParserException("Failed to parse")
[docs]asyncdefaparse(self,completion:str)->T:retries=0whileretries<=self.max_retries:try:returnawaitself.parser.aparse(completion)exceptOutputParserExceptionase:ifretries==self.max_retries:raiseeelse:retries+=1ifself.legacyandhasattr(self.retry_chain,"arun"):completion=awaitself.retry_chain.arun(instructions=self.parser.get_format_instructions(),completion=completion,error=repr(e),)else:try:completion=awaitself.retry_chain.ainvoke(dict(instructions=self.parser.get_format_instructions(),completion=completion,error=repr(e),))except(NotImplementedError,AttributeError):# Case: self.parser does not have get_format_instructionscompletion=awaitself.retry_chain.ainvoke(dict(completion=completion,error=repr(e),))raiseOutputParserException("Failed to parse")