[docs]classBaseLLMOutputParser(Generic[T],ABC):"""Abstract base class for parsing the outputs of a model."""
[docs]@abstractmethoddefparse_result(self,result:list[Generation],*,partial:bool=False)->T:"""Parse a list of candidate model Generations into a specific format. Args: result: A list of Generations to be parsed. The Generations are assumed to be different candidate outputs for a single model input. partial: Whether to parse the output as a partial result. This is useful for parsers that can parse partial results. Default is False. Returns: Structured output. """
[docs]asyncdefaparse_result(self,result:list[Generation],*,partial:bool=False)->T:"""Async parse a list of candidate model Generations into a specific format. Args: result: A list of Generations to be parsed. The Generations are assumed to be different candidate outputs for a single model input. partial: Whether to parse the output as a partial result. This is useful for parsers that can parse partial results. Default is False. Returns: Structured output. """returnawaitrun_in_executor(None,self.parse_result,result)
[docs]classBaseGenerationOutputParser(BaseLLMOutputParser,RunnableSerializable[LanguageModelOutput,T]):"""Base class to parse the output of an LLM call."""@property@overridedefInputType(self)->Any:"""Return the input type for the parser."""returnUnion[str,AnyMessage]@property@overridedefOutputType(self)->type[T]:"""Return the output type for the parser."""# even though mypy complains this isn't valid,# it is good enough for pydantic to build the schema fromreturnT# type: ignore[misc]
[docs]classBaseOutputParser(BaseLLMOutputParser,RunnableSerializable[LanguageModelOutput,T]):"""Base class to parse the output of an LLM call. Output parsers help structure language model responses. Example: .. code-block:: python class BooleanOutputParser(BaseOutputParser[bool]): true_val: str = "YES" false_val: str = "NO" def parse(self, text: str) -> bool: cleaned_text = text.strip().upper() if cleaned_text not in (self.true_val.upper(), self.false_val.upper()): raise OutputParserException( f"BooleanOutputParser expected output value to either be " f"{self.true_val} or {self.false_val} (case-insensitive). " f"Received {cleaned_text}." ) return cleaned_text == self.true_val.upper() @property def _type(self) -> str: return "boolean_output_parser" """# noqa: E501@property@overridedefInputType(self)->Any:"""Return the input type for the parser."""returnUnion[str,AnyMessage]@property@overridedefOutputType(self)->type[T]:"""Return the output type for the parser. This property is inferred from the first type argument of the class. Raises: TypeError: If the class doesn't have an inferable OutputType. """forbaseinself.__class__.mro():ifhasattr(base,"__pydantic_generic_metadata__"):metadata=base.__pydantic_generic_metadata__if"args"inmetadataandlen(metadata["args"])>0:returnmetadata["args"][0]msg=(f"Runnable {self.__class__.__name__} doesn't have an inferable OutputType. ""Override the OutputType property to specify the output type.")raiseTypeError(msg)
[docs]defparse_result(self,result:list[Generation],*,partial:bool=False)->T:"""Parse a list of candidate model Generations into a specific format. The return value is parsed from only the first Generation in the result, which is assumed to be the highest-likelihood Generation. Args: result: A list of Generations to be parsed. The Generations are assumed to be different candidate outputs for a single model input. partial: Whether to parse the output as a partial result. This is useful for parsers that can parse partial results. Default is False. Returns: Structured output. """returnself.parse(result[0].text)
[docs]@abstractmethoddefparse(self,text:str)->T:"""Parse a single string model output into some structure. Args: text: String output of a language model. Returns: Structured output. """
[docs]asyncdefaparse_result(self,result:list[Generation],*,partial:bool=False)->T:"""Async parse a list of candidate model Generations into a specific format. The return value is parsed from only the first Generation in the result, which is assumed to be the highest-likelihood Generation. Args: result: A list of Generations to be parsed. The Generations are assumed to be different candidate outputs for a single model input. partial: Whether to parse the output as a partial result. This is useful for parsers that can parse partial results. Default is False. Returns: Structured output. """returnawaitrun_in_executor(None,self.parse_result,result,partial=partial)
[docs]asyncdefaparse(self,text:str)->T:"""Async parse a single string model output into some structure. Args: text: String output of a language model. Returns: Structured output. """returnawaitrun_in_executor(None,self.parse,text)
# TODO: rename 'completion' -> 'text'.
[docs]defparse_with_prompt(self,completion:str,prompt:PromptValue)->Any:"""Parse the output of an LLM call with the input prompt for context. The prompt is largely provided in the event the OutputParser wants to retry or fix the output in some way, and needs information from the prompt to do so. Args: completion: String output of a language model. prompt: Input PromptValue. Returns: Structured output. """returnself.parse(completion)
[docs]defget_format_instructions(self)->str:"""Instructions on how the LLM output should be formatted."""raiseNotImplementedError
@propertydef_type(self)->str:"""Return the output parser type for serialization."""msg=(f"_type property is not implemented in class {self.__class__.__name__}."" This is required for serialization.")raiseNotImplementedError(msg)defdict(self,**kwargs:Any)->dict:"""Return dictionary representation of output parser."""output_parser_dict=super().dict(**kwargs)withcontextlib.suppress(NotImplementedError):output_parser_dict["_type"]=self._typereturnoutput_parser_dict