[docs]classOutputFunctionsParser(BaseGenerationOutputParser[Any]):"""Parse an output that is one of sets of values."""args_only:bool=True"""Whether to only return the arguments to the function call."""
[docs]defparse_result(self,result:List[Generation],*,partial:bool=False)->Any:generation=result[0]ifnotisinstance(generation,ChatGeneration):raiseOutputParserException("This output parser can only be used with a chat generation.")message=generation.messagetry:func_call=copy.deepcopy(message.additional_kwargs["function_call"])exceptKeyErrorasexc:raiseOutputParserException(f"Could not parse function call: {exc}")ifself.args_only:returnfunc_call["arguments"]returnfunc_call
[docs]classJsonOutputFunctionsParser(BaseCumulativeTransformOutputParser[Any]):"""Parse an output as the Json object."""strict:bool=False"""Whether to allow non-JSON-compliant strings. See: https://docs.python.org/3/library/json.html#encoders-and-decoders Useful when the parsed output may include unicode characters or new lines. """args_only:bool=True"""Whether to only return the arguments to the function call."""@propertydef_type(self)->str:return"json_functions"def_diff(self,prev:Optional[Any],next:Any)->Any:returnjsonpatch.make_patch(prev,next).patch
[docs]defparse_result(self,result:List[Generation],*,partial:bool=False)->Any:iflen(result)!=1:raiseOutputParserException(f"Expected exactly one result, but got {len(result)}")generation=result[0]ifnotisinstance(generation,ChatGeneration):raiseOutputParserException("This output parser can only be used with a chat generation.")message=generation.messageif"function_call"notinmessage.additional_kwargs:returnNonetry:function_call=message.additional_kwargs["function_call"]exceptKeyErrorasexc:ifpartial:returnNoneelse:raiseOutputParserException(f"Could not parse function call: {exc}")try:ifpartial:ifself.args_only:returnparse_partial_json(function_call["arguments"],strict=self.strict)else:return{**function_call,"arguments":parse_partial_json(function_call["arguments"],strict=self.strict),}else:ifself.args_only:try:returnjson.loads(function_call["arguments"],strict=self.strict)except(json.JSONDecodeError,TypeError)asexc:raiseOutputParserException(f"Could not parse function call data: {exc}")else:try:return{**function_call,"arguments":json.loads(function_call["arguments"],strict=self.strict),}except(json.JSONDecodeError,TypeError)asexc:raiseOutputParserException(f"Could not parse function call data: {exc}")exceptKeyError:returnNone
# This method would be called by the default implementation of `parse_result`# but we're overriding that method so it's not needed.
[docs]classJsonKeyOutputFunctionsParser(JsonOutputFunctionsParser):"""Parse an output as the element of the Json object."""key_name:str"""The name of the key to return."""
[docs]classPydanticOutputFunctionsParser(OutputFunctionsParser):"""Parse an output as a pydantic object."""pydantic_schema:Union[Type[BaseModel],Dict[str,Type[BaseModel]]]"""The pydantic schema to parse the output with."""@model_validator(mode="before")@classmethoddefvalidate_schema(cls,values:Dict)->Any:schema=values["pydantic_schema"]if"args_only"notinvalues:values["args_only"]=isinstance(schema,type)andissubclass(schema,BaseModel)elifvalues["args_only"]andisinstance(schema,Dict):raiseValueError("If multiple pydantic schemas are provided then args_only should be"" False.")returnvalues
[docs]classPydanticAttrOutputFunctionsParser(PydanticOutputFunctionsParser):"""Parse an output as an attribute of a pydantic object."""attr_name:str"""The name of the attribute to return."""