[docs]classChatGeneration(Generation):"""A single chat generation output. A subclass of Generation that represents the response from a chat model that generates chat messages. The `message` attribute is a structured representation of the chat message. Most of the time, the message will be of type `AIMessage`. Users working with chat models will usually access information via either `AIMessage` (returned from runnable interfaces) or `LLMResult` (available via callbacks). """text:str="""""*SHOULD NOT BE SET DIRECTLY* The text contents of the output message."""message:BaseMessage"""The message output by the chat model."""# Override type to be ChatGeneration, ignore mypy error as this is intentionaltype:Literal["ChatGeneration"]="ChatGeneration"# type: ignore[assignment]"""Type is used exclusively for serialization purposes."""@root_validator(pre=False,skip_on_failure=True)defset_text(cls,values:Dict[str,Any])->Dict[str,Any]:"""Set the text attribute to be the contents of the message. Args: values: The values of the object. Returns: The values of the object with the text attribute set. Raises: ValueError: If the message is not a string or a list. """try:text=""ifisinstance(values["message"].content,str):text=values["message"].content# HACK: Assumes text in content blocks in OpenAI format.# Uses first text block.elifisinstance(values["message"].content,list):forblockinvalues["message"].content:ifisinstance(block,str):text=blockbreakelifisinstance(block,dict)and"text"inblock:text=block["text"]breakelse:passelse:passvalues["text"]=textexcept(KeyError,AttributeError)ase:raiseValueError("Error while initializing ChatGeneration")fromereturnvalues@classmethoddefget_lc_namespace(cls)->List[str]:"""Get the namespace of the langchain object."""return["langchain","schema","output"]
[docs]classChatGenerationChunk(ChatGeneration):"""ChatGeneration chunk, which can be concatenated with other ChatGeneration chunks. """message:BaseMessageChunk"""The message chunk output by the chat model."""# Override type to be ChatGeneration, ignore mypy error as this is intentionaltype:Literal["ChatGenerationChunk"]="ChatGenerationChunk"# type: ignore[assignment]"""Type is used exclusively for serialization purposes."""@classmethoddefget_lc_namespace(cls)->List[str]:"""Get the namespace of the langchain object."""return["langchain","schema","output"]def__add__(self,other:Union[ChatGenerationChunk,List[ChatGenerationChunk]])->ChatGenerationChunk:ifisinstance(other,ChatGenerationChunk):generation_info=merge_dicts(self.generation_infoor{},other.generation_infoor{},)returnChatGenerationChunk(message=self.message+other.message,generation_info=generation_infoorNone,)elifisinstance(other,list)andall(isinstance(x,ChatGenerationChunk)forxinother):generation_info=merge_dicts(self.generation_infoor{},*[chunk.generation_infoforchunkinotherifchunk.generation_info],)returnChatGenerationChunk(message=self.message+[chunk.messageforchunkinother],generation_info=generation_infoorNone,)else:raiseTypeError(f"unsupported operand type(s) for +: '{type(self)}' and '{type(other)}'")