[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="""""The text contents of the output message. .. warning:: SHOULD NOT BE SET DIRECTLY! """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."""@model_validator(mode="after")defset_text(self)->Self:"""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. """text=""ifisinstance(self.message.content,str):text=self.message.content# Assumes text in content blocks in OpenAI format.# Uses first text block.elifisinstance(self.message.content,list):forblockinself.message.content:ifisinstance(block,str):text=blockbreakifisinstance(block,dict)and"text"inblock:text=block["text"]breakself.text=textreturnself
[docs]classChatGenerationChunk(ChatGeneration):"""``ChatGeneration`` chunk. ``ChatGeneration`` chunks 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."""def__add__(self,other:Union[ChatGenerationChunk,list[ChatGenerationChunk]])->ChatGenerationChunk:"""Concatenate two ``ChatGenerationChunk``s. Args: other: The other ``ChatGenerationChunk`` or list of ``ChatGenerationChunk`` to concatenate. Raises: TypeError: If other is not a ``ChatGenerationChunk`` or list of ``ChatGenerationChunk``. Returns: A new ``ChatGenerationChunk`` concatenated from self and other. """ifisinstance(other,ChatGenerationChunk):generation_info=merge_dicts(self.generation_infoor{},other.generation_infoor{},)returnChatGenerationChunk(message=self.message+other.message,generation_info=generation_infoorNone,)ifisinstance(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,)msg=f"unsupported operand type(s) for +: '{type(self)}' and '{type(other)}'"raiseTypeError(msg)
[docs]defmerge_chat_generation_chunks(chunks:list[ChatGenerationChunk],)->Union[ChatGenerationChunk,None]:"""Merge a list of ``ChatGenerationChunk``s into a single ``ChatGenerationChunk``. Args: chunks: A list of ``ChatGenerationChunk`` to merge. Returns: A merged ``ChatGenerationChunk``, or None if the input list is empty. """ifnotchunks:returnNoneiflen(chunks)==1:returnchunks[0]returnchunks[0]+chunks[1:]