
    gh              	      N   d Z ddlmZ ddlmZmZ ddlmZ ddlm	Z	m
Z
mZmZmZmZmZmZmZ ddlmZmZmZmZ ddlmZmZ ddlmZ dd	lmZmZmZm Z m!Z!m"Z"m#Z# dd
l$m%Z% ddl&m'Z'm(Z(m)Z) ddl*m+Z+ ddl,m-Z- ddl.m/Z/ ddl0m1Z1 ddl2m3Z3 ddl4m5Z5m6Z6m7Z7 ddl8m9Z9 ddl:m;Z; e	rddl<m=Z=  G d de1          Z> edd          Z?	  G d de1e          Z@ G d de@          ZA G d ded           ZB G d! d"ed           ZC G d# d$e1          ZD G d% d&eD          ZE G d' d(eD          ZF G d) d*eD          ZG G d+ d,e+e          ZHee1eeHf         ZIeeIeJeeKeLf         eeKeMeN         eMeO         f         f         eKeNeKef         f         ZP G d- d.eH          ZQ	 d>d?d8ZR	 d>d@d<ZSeSZTd=S )AzChat prompt template.    )annotations)ABCabstractmethod)Path)	TYPE_CHECKING	AnnotatedAnyOptional	TypedDictTypeVarUnioncastoverload)FieldPositiveIntSkipValidationmodel_validator)Selfoverride)
deprecated)	AIMessage
AnyMessageBaseMessageChatMessageHumanMessageSystemMessageconvert_to_messages)get_msg_title_repr)ChatPromptValueImageURLPromptValue)BasePromptTemplate)DictPromptTemplate)ImagePromptTemplate)BaseMessagePromptTemplate)PromptTemplate)PromptTemplateFormatStringPromptTemplateget_template_variables)get_colored_text)is_interactive_env)Sequencec                       e Zd ZU dZded<   	 dZded<   	 dZded	<   	 dd
d fdZddZe	dd            Z
eddd            Z xZS )MessagesPlaceholdera  Prompt template that assumes variable is already list of messages.

    A placeholder which can be used to pass in a list of messages.

    Direct usage:

        .. code-block:: python

            from langchain_core.prompts import MessagesPlaceholder

            prompt = MessagesPlaceholder("history")
            prompt.format_messages() # raises KeyError

            prompt = MessagesPlaceholder("history", optional=True)
            prompt.format_messages() # returns empty list []

            prompt.format_messages(
                history=[
                    ("system", "You are an AI assistant."),
                    ("human", "Hello!"),
                ]
            )
            # -> [
            #     SystemMessage(content="You are an AI assistant."),
            #     HumanMessage(content="Hello!"),
            # ]

    Building a prompt with chat history:

        .. code-block:: python

            from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder

            prompt = ChatPromptTemplate.from_messages(
                [
                    ("system", "You are a helpful assistant."),
                    MessagesPlaceholder("history"),
                    ("human", "{question}")
                ]
            )
            prompt.invoke(
               {
                   "history": [("human", "what's 5 + 2"), ("ai", "5 + 2 is 7")],
                   "question": "now multiply that by 4"
               }
            )
            # -> ChatPromptValue(messages=[
            #     SystemMessage(content="You are a helpful assistant."),
            #     HumanMessage(content="what's 5 + 2"),
            #     AIMessage(content="5 + 2 is 7"),
            #     HumanMessage(content="now multiply that by 4"),
            # ])

    Limiting the number of messages:

        .. code-block:: python

            from langchain_core.prompts import MessagesPlaceholder

            prompt = MessagesPlaceholder("history", n_messages=1)

            prompt.format_messages(
                history=[
                    ("system", "You are an AI assistant."),
                    ("human", "Hello!"),
                ]
            )
            # -> [
            #     HumanMessage(content="Hello!"),
            # ]
    strvariable_nameFbooloptionalNzOptional[PositiveInt]
n_messages)r2   kwargsr	   returnNonec               @     t                      j        d||d| dS )a  Create a messages placeholder.

        Args:
            variable_name: Name of variable to use as messages.
            optional: If True format_messages can be called with no arguments and will
                return an empty list. If False then a named argument with name
                `variable_name` must be passed in, even if the value is an empty list.
                Defaults to False.]
        r0   r2   N )super__init__)selfr0   r2   r4   	__class__s       X/var/www/FlaskApp/flask-venv/lib/python3.11/site-packages/langchain_core/prompts/chat.pyr;   zMessagesPlaceholder.__init__   sA     	 	
'(	
 	
>D	
 	
 	
 	
 	
    list[BaseMessage]c                2   | j         r|                    | j        g           n|| j                 }t          |t                    s,d| j         d| dt          |           }t          |          t          |          }| j        r|| j         d         }|S )zFormat messages from kwargs.

        Args:
            **kwargs: Keyword arguments to use for formatting.

        Returns:
            List of BaseMessage.

        Raises:
            ValueError: If variable is not a list of messages.
        z	variable z( should be a list of base messages, got z	 of type N)	r2   getr0   
isinstancelisttype
ValueErrorr   r3   )r<   r4   valuemsgs       r>   format_messagesz#MessagesPlaceholder.format_messages   s     },FJJt)2...*+ 	
 %&& 	"5D. 5 55 5'+E{{5 5  S//!#E**? 	.4?*,,-Er?   	list[str]c                $    | j         s| j        gng S nInput variables for this prompt template.

        Returns:
            List of input variable names.
        )r2   r0   r<   s    r>   input_variablesz#MessagesPlaceholder.input_variables   s     ,0=@"##b@r?   htmlc                    d| j         z   dz   }|r"t          dd          }t          |d          }nt          d          }| d| S )Human-readable representation.

        Args:
            html: Whether to format as HTML. Defaults to False.

        Returns:
            Human-readable representation.
        {}zMessages PlaceholderTboldyellow

)r0   r   r*   )r<   rP   vartitles       r>   pretty_reprzMessagesPlaceholder.pretty_repr   sd     D&&, 	?&'=DIIIE"311CC&'=>>E""S"""r?   )r0   r/   r2   r1   r4   r	   r5   r6   r4   r	   r5   r@   r5   rJ   FrP   r1   r5   r/   )__name__
__module____qualname____doc____annotations__r2   r3   r;   rI   propertyrO   r   r[   __classcell__r=   s   @r>   r.   r.   :   s         F FP .H3 )-J,,,, 7<
 
 
 
 
 
 
 
$   8 A A A XA # # # # X# # # # #r?   r.   MessagePromptTemplateTBaseStringMessagePromptTemplate)boundc                      e Zd ZU dZded<   	  ee          Zded<   	 e	 	 d$d%d            Z	ed&d            Z
ed'd            Zd'dZd(dZd(dZed)d            Zed*d+d#            ZdS ),ri   zJBase class for message prompt templates that use a string prompt template.r(   promptdefault_factorydictadditional_kwargsf-stringNtemplater/   template_formatr'   partial_variablesOptional[dict[str, Any]]r4   r	   r5   r   c                D    t          j        |||          } | dd|i|S )a  Create a class from a string template.

        Args:
            template: a template.
            template_format: format of the template. Defaults to "f-string".
            partial_variables: A dictionary of variables that can be used to partially
                               fill in the template. For example, if the template is
                              `"{variable1} {variable2}"`, and `partial_variables` is
                              `{"variable1": "foo"}`, then the final prompt will be
                              `"foo {variable2}"`.
                              Defaults to None.
            **kwargs: keyword arguments to pass to the constructor.

        Returns:
            A new instance of this class.
        rs   rt   rl   r9   )r&   from_template)clsrr   rs   rt   r4   rl   s         r>   rx   z-BaseStringMessagePromptTemplate.from_template   sA    0  -+/
 
 

 s++&+F+++r?   template_fileUnion[str, Path]rO   rJ   c                @    t          j        ||          } | dd|i|S )6  Create a class from a template file.

        Args:
            template_file: path to a template file. String or Path.
            input_variables: list of input variables.
            **kwargs: keyword arguments to pass to the constructor.

        Returns:
            A new instance of this class.
        rl   r9   )r&   	from_file)ry   rz   rO   r4   rl   s        r>   from_template_filez2BaseStringMessagePromptTemplate.from_template_file  s1    "  )-IIs++&+F+++r?   r   c                    dS )Format the prompt template.

        Args:
            **kwargs: Keyword arguments to use for formatting.

        Returns:
            Formatted message.
        Nr9   r<   r4   s     r>   formatz&BaseStringMessagePromptTemplate.format        r?   c                    K    | j         di |S )Async format the prompt template.

        Args:
            **kwargs: Keyword arguments to use for formatting.

        Returns:
            Formatted message.
        r9   r   r   s     r>   aformatz'BaseStringMessagePromptTemplate.aformat%  s        t{$$V$$$r?   r@   c                     | j         di |gS zFormat messages from kwargs.

        Args:
            **kwargs: Keyword arguments to use for formatting.

        Returns:
            List of BaseMessages.
        r9   r   r   s     r>   rI   z/BaseStringMessagePromptTemplate.format_messages0       %%f%%&&r?   c                .   K    | j         di | d{V gS zAsync format messages from kwargs.

        Args:
            **kwargs: Keyword arguments to use for formatting.

        Returns:
            List of BaseMessages.
        Nr9   r   r   s     r>   aformat_messagesz0BaseStringMessagePromptTemplate.aformat_messages;  5       #dl,,V,,,,,,,,--r?   c                    | j         j        S rL   )rl   rO   rN   s    r>   rO   z/BaseStringMessagePromptTemplate.input_variablesF  s     {**r?   FrP   r1   c                    | j         j                            dd          }t          ||          }| d| j                            |           S )rR   MessagePromptTemplate MessagerU   rX   rP   )r=   r`   replacer   rl   r[   )r<   rP   rZ   s      r>   r[   z+BaseStringMessagePromptTemplate.pretty_reprO  sX     '//0GTT"5t444AAT[44$4??AAAr?   )rq   N)
rr   r/   rs   r'   rt   ru   r4   r	   r5   r   )rz   r{   rO   rJ   r4   r	   r5   r   r4   r	   r5   r   r\   r]   r^   r_   )r`   ra   rb   rc   rd   r   ro   rp   classmethodrx   r   r   r   r   rI   r   re   rO   r   r[   r9   r?   r>   ri   ri      s@        TT    !#eD9999999F 1;6:	, , , , [,< , , , [,&    ^	% 	% 	% 	%	' 	' 	' 	'	. 	. 	. 	. + + + X+ B B B B XB B Br?   c                  0    e Zd ZU dZded<   	 ddZdd	Zd
S )ChatMessagePromptTemplatezChat message prompt template.r/   roler4   r	   r5   r   c                ^     | j         j        di |}t          || j        | j                  S )r   contentr   rp   r9   )rl   r   r   r   rp   r<   r4   texts      r>   r   z ChatMessagePromptTemplate.formate  sA     "t{!++F++tyD<R
 
 
 	
r?   c                n   K    | j         j        di | d{V }t          || j        | j                  S )r   Nr   r9   )rl   r   r   r   rp   r   s      r>   r   z!ChatMessagePromptTemplate.aformats  sW       )T[(22622222222tyD<R
 
 
 	
r?   Nr   )r`   ra   rb   rc   rd   r   r   r9   r?   r>   r   r   _  sP         ''III
 
 
 

 
 
 
 
 
r?   r   c                      e Zd ZU ded<   dS )_TextTemplateParamUnion[str, dict]r   Nr`   ra   rb   rd   r9   r?   r>   r   r     s         r?   r   F)totalc                      e Zd ZU ded<   dS )_ImageTemplateParamr   	image_urlNr   r9   r?   r>   r   r     s         r?   r   c                      e Zd ZU dZded<   	  ee          Zded<   	 ded<   e	 d*d
dd+d            Z	ed,d            Z
d-dZd-d Zed.d!            Zd/d#Zd/d$Zed0d1d)            Zd
S )2!_StringImageMessagePromptTemplateDHuman message prompt template. This is a message sent from the user.zgUnion[StringPromptTemplate, list[Union[StringPromptTemplate, ImagePromptTemplate, DictPromptTemplate]]]rl   rm   ro   rp   type[BaseMessage]
_msg_classrq   N)rt   ry   
type[Self]rr   UUnion[str, list[Union[str, _TextTemplateParam, _ImageTemplateParam, dict[str, Any]]]]rs   r'   rt   ru   r4   r	   r5   r   c               6   t          |t                    r!t          j        |||          } | dd|i|S t          |t                    r|$t          |          dk    rd}t          |          g }|D ]}t          |t                    s@t          |t                    rd|v rt          |	                                          ddhk    rXt          |t                    r|}nt          d|          d         }|                    t          j        ||	                     t          |t                    rJd
|v rEt          |	                                          dd
hk    rt          d|          d
         }	g }
t          |	t                    r\t          |	|          }|r3t          |          dk    rd| d| }t          |          |d         g}
d|	i}	t          |
|	|          }n}t          |	t                    rTt          |	          }	dD ]/}||	v r)|
                    t          |	|         |                     0t          |
|	|          }nd| }t          |          |                    |           t          |t                    rM|dk    rd}t          |          t          t          d|          |          }|                    |           rd| }t          |           | dd|i|S d| }t          |          )aD  Create a class from a string template.

        Args:
            template: a template.
            template_format: format of the template.
                Options are: 'f-string', 'mustache', 'jinja2'. Defaults to "f-string".
            partial_variables: A dictionary of variables that can be used too partially.
                Defaults to None.
            **kwargs: keyword arguments to pass to the constructor.

        Returns:
            A new instance of this class.

        Raises:
            ValueError: If the template is not a string or list of strings.
        rw   rl   Nr   z:Partial variables are not supported for list of templates.r   rE   r   rs   r   r      z:Only one format variable allowed per image template.
Got: z
From: url)rO   rr   rs   )r   pathdetailzInvalid image template: jinja2zsjinja2 is unsafe and is not supported for templates expressed as dicts. Please use 'f-string' or 'mustache' format.zdict[str, Any])rr   rs   zInvalid template: r9   )rC   r/   r&   rx   rD   lenrF   ro   setkeysr   appendr)   r$   extendr#   )ry   rr   rs   rt   r4   rl   rH   tmplr   img_templaterO   varsimg_template_objkeydata_template_objs                  r>   rx   z/_StringImageMessagePromptTemplate.from_template  s   8 h$$ 	08F8T /"39 9 9F
 3//f////h%% S	0!-37H3I3IA3M3MR oo%F  M* M*tS))L*!$--L* $DIIKK((VV,<<<!$,, H$(#$8$??GMM&4 /      tT**=*#t++DIIKK((#  $((=t#D#D[#QL&(O!,44 !.5lOTT 8"4yy1}}%68<%6 %6/3%6 %6 !$
 '1oo 5/3AwiO(-|'<+>,;%1,;, , ,((
 $L$77 .'+L'9'9#< " "C"l22 / 6 6$:(4S(9?%& %&!" !" !"
 ,?,;%1,;, , ,(( @??(oo-MM"23333d++ *&(22& 
 )oo-(:!%&6!=!=(7) ) )% MM"344445t55C$S//)3//f////-8--oor?   rz   r{   rO   rJ   c                d    t          |                                          } | j        |fd|i|S )r}   rO   )r   	read_textrx   )ry   rz   rO   r4   rr   s        r>   r   z4_StringImageMessagePromptTemplate.from_template_file  s=    " &&0022 s UU?UfUUUr?   r@   c                     | j         di |gS r   r   r   s     r>   rI   z1_StringImageMessagePromptTemplate.format_messages%  r   r?   c                .   K    | j         di | d{V gS r   r   r   s     r>   r   z2_StringImageMessagePromptTemplate.aformat_messages0  r   r?   c                l    t          | j        t                    r| j        n| j        g}d |D             S )rM   c                &    g | ]}|j         D ]}|S r9   rO   ).0rl   ivs      r>   
<listcomp>zE_StringImageMessagePromptTemplate.input_variables.<locals>.<listcomp>C  s(    JJJv63IJJRJJJJr?   )rC   rl   rD   )r<   promptss     r>   rO   z1_StringImageMessagePromptTemplate.input_variables;  s8     ",DK!>!>Q$++T[MJJJJJJr?   r   c                d   t          | j        t                    r. | j        j        di }|                     || j                  S g }| j        D ]}fd|j        D             }t          |t                    r& |j        di |}|                    d|d           Pt          |t                    r& |j        di |}|                    d|d           t          |t                    r" |j        di |}|                    |           |                     || j                  S )r   r   rp   c                "    i | ]}||         S r9   r9   r   rY   r4   s     r>   
<dictcomp>z<_StringImageMessagePromptTemplate.format.<locals>.<dictcomp>U      III3c6#;IIIr?   r   rE   r   r   rE   r   r9   )
rC   rl   r(   r   r   rp   rO   r   r$   r#   r<   r4   r   r   rl   inputs	formatteds    `     r>   r   z(_StringImageMessagePromptTemplate.formatE  s    dk#788 	%4;%////D??0F #    k 	* 	*FIIII&2HIIIF&"677 
*BO&- C CC C	 	BBCCCCF$788 *)FM33F33	)LLMMMMF$677 *)FM33F33	y)))t/E  
 
 	
r?   c                  K   t          | j        t                    r4 | j        j        di  d{V }|                     || j                  S g }| j        D ]}fd|j        D             }t          |t                    r, |j        di | d{V }|                    d|d           Vt          |t                    r, |j        di | d{V }|                    d|d           t          |t                    r" |j
        di |}|                    |           |                     || j                  S )	r   Nr   c                "    i | ]}||         S r9   r9   r   s     r>   r   z=_StringImageMessagePromptTemplate.aformat.<locals>.<dictcomp>u  r   r?   r   r   r   r   r9   )rC   rl   r(   r   r   rp   rO   r   r$   r#   r   r   s    `     r>   r   z)_StringImageMessagePromptTemplate.aformate  s      dk#788 	,,66v66666666D??0F #    k 	* 	*FIIII&2HIIIF&"677 
*HV I II I C C C C C C	 	BBCCCCF$788 *"0&.":":6":":::::::	)LLMMMMF$677 *)FM33F33	y)))t/E  
 
 	
r?   FrP   r1   r/   c                   | j         j                            dd          }t          |          }t	          | j        t                    r| j        n| j        g}d                    fd|D                       }| d| S )rR   r   r   rU   rX   c              3  D   K   | ]}|                                V  dS r   Nr[   )r   rl   rP   s     r>   	<genexpr>z@_StringImageMessagePromptTemplate.pretty_repr.<locals>.<genexpr>  s4      "W"WV6#5#54#5#@#@"W"W"W"W"W"Wr?   )r=   r`   r   r   rC   rl   rD   join)r<   rP   rZ   r   prompt_reprss    `   r>   r[   z-_StringImageMessagePromptTemplate.pretty_repr  s     '//0GTT"5t444!+DK!>!>Q$++T[M{{"W"W"W"Ww"W"W"WWW++\+++r?   rq   )ry   r   rr   r   rs   r'   rt   ru   r4   r	   r5   r   )
ry   r   rz   r{   rO   rJ   r4   r	   r5   r   r\   r]   r   r^   r_   )r`   ra   rb   rc   rd   r   ro   rp   r   rx   r   rI   r   re   rO   r   r   r   r[   r9   r?   r>   r   r     sa        NN    #eD9999999F!!!! 1;w 7;w w w w w [wr V V V [V&	' 	' 	' 	'	. 	. 	. 	. K K K XK
 
 
 
@
 
 
 
@ , , , , X, , ,r?   r   c                  "    e Zd ZU dZeZded<   dS )HumanMessagePromptTemplater   r   r   N)r`   ra   rb   rc   r   r   rd   r9   r?   r>   r   r     s)         NN$0J000000r?   r   c                  "    e Zd ZU dZeZded<   dS )AIMessagePromptTemplatez?AI message prompt template. This is a message sent from the AI.r   r   N)r`   ra   rb   rc   r   r   rd   r9   r?   r>   r   r     s)         II$-J------r?   r   c                  "    e Zd ZU dZeZded<   dS )SystemMessagePromptTemplatezYSystem message prompt template.

    This is a message that is not sent to the user.
    r   r   N)r`   ra   rb   rc   r   r   rd   r9   r?   r>   r   r     s/          
 %2J111111r?   r   c                      e Zd ZdZeedd                        ZddZdd	ZddZ	ddZ
edd            ZddZ	 dddZddZdS )BaseChatPromptTemplatez%Base class for chat prompt templates.r5   ro   c                    d| j         iS )NrO   r   rN   s    r>   lc_attributesz$BaseChatPromptTemplate.lc_attributes  s     "4#788r?   r4   r	   r/   c                @     | j         di |                                S )a
  Format the chat template into a string.

        Args:
            **kwargs: keyword arguments to use for filling in template variables
                      in all the template messages in this chat template.

        Returns:
            formatted string.
        r9   )format_prompt	to_stringr   s     r>   r   zBaseChatPromptTemplate.format  s)     "t!++F++55777r?   c                P   K    | j         di | d{V                                 S )a  Async format the chat template into a string.

        Args:
            **kwargs: keyword arguments to use for filling in template variables
                      in all the template messages in this chat template.

        Returns:
            formatted string.
        Nr9   )aformat_promptr   r   s     r>   r   zBaseChatPromptTemplate.aformat  s?       *d)33F33333333>>@@@r?   r!   c                <     | j         di |}t          |          S )zFormat prompt. Should return a PromptValue.

        Args:
            **kwargs: Keyword arguments to use for formatting.

        Returns:
            PromptValue.
        messagesr9   )rI   r   r<   r4   r   s      r>   r   z$BaseChatPromptTemplate.format_prompt  s-     (4'11&111111r?   c                L   K    | j         di | d{V }t          |          S )zAsync format prompt. Should return a PromptValue.

        Args:
            **kwargs: Keyword arguments to use for formatting.

        Returns:
            PromptValue.
        Nr   r9   )r   r   r   s      r>   r   z%BaseChatPromptTemplate.aformat_prompt  sC       /.88888888881111r?   r@   c                    dS )z&Format kwargs into a list of messages.Nr9   r   s     r>   rI   z&BaseChatPromptTemplate.format_messages  r   r?   c                    K    | j         di |S )z,Async format kwargs into a list of messages.r9   )rI   r   s     r>   r   z'BaseChatPromptTemplate.aformat_messages  s      #t#--f---r?   FrP   r1   c                    t           )rR   NotImplementedErrorr<   rP   s     r>   r[   z"BaseChatPromptTemplate.pretty_repr  s
     "!r?   r6   c                d    t          |                     t                                           dS )z&Print a human-readable representation.r   N)printr[   r+   rN   s    r>   pretty_printz#BaseChatPromptTemplate.pretty_print  s.    d$6$8$899:::::r?   N)r5   ro   )r4   r	   r5   r/   )r4   r	   r5   r!   r\   r^   r_   )r5   r6   )r`   ra   rb   rc   re   r   r   r   r   r   r   r   rI   r   r[   r   r9   r?   r>   r   r     s        //9 9 9 X X9
8 
8 
8 
8
A 
A 
A 
A
2 
2 
2 
2
2 
2 
2 
2 5 5 5 ^5. . . . " " " " "; ; ; ; ; ;r?   r   c                      e Zd ZU dZded<   	 dZded<   	 ddd? fdZed@d            ZdAdZ	 e
d          edBd                        ZedCd            Ze eddd           dDd#                        Ze eddd           dEd%                        Ze	 dFdGd&            ZdHd(ZdHd)ZdId*ZdJd-ZdKd.ZedLd2            ZedMd4            ZdNd7ZdOd8ZedPd9            ZdQd<ZedRdSd>            Z xZS )TChatPromptTemplatea  Prompt template for chat models.

    Use to create flexible templated prompts for chat models.

    Examples:

        .. versionchanged:: 0.2.24

            You can pass any Message-like formats supported by
            ``ChatPromptTemplate.from_messages()`` directly to ``ChatPromptTemplate()``
            init.

        .. code-block:: python

            from langchain_core.prompts import ChatPromptTemplate

            template = ChatPromptTemplate([
                ("system", "You are a helpful AI bot. Your name is {name}."),
                ("human", "Hello, how are you doing?"),
                ("ai", "I'm doing well, thanks!"),
                ("human", "{user_input}"),
            ])

            prompt_value = template.invoke(
                {
                    "name": "Bob",
                    "user_input": "What is your name?"
                }
            )
            # Output:
            # ChatPromptValue(
            #    messages=[
            #        SystemMessage(content='You are a helpful AI bot. Your name is Bob.'),
            #        HumanMessage(content='Hello, how are you doing?'),
            #        AIMessage(content="I'm doing well, thanks!"),
            #        HumanMessage(content='What is your name?')
            #    ]
            #)

    Messages Placeholder:

        .. code-block:: python

            # In addition to Human/AI/Tool/Function messages,
            # you can initialize the template with a MessagesPlaceholder
            # either using the class directly or with the shorthand tuple syntax:

            template = ChatPromptTemplate([
                ("system", "You are a helpful AI bot."),
                # Means the template will receive an optional list of messages under
                # the "conversation" key
                ("placeholder", "{conversation}")
                # Equivalently:
                # MessagesPlaceholder(variable_name="conversation", optional=True)
            ])

            prompt_value = template.invoke(
                {
                    "conversation": [
                        ("human", "Hi!"),
                        ("ai", "How can I assist you today?"),
                        ("human", "Can you make me an ice cream sundae?"),
                        ("ai", "No.")
                    ]
                }
            )

            # Output:
            # ChatPromptValue(
            #    messages=[
            #        SystemMessage(content='You are a helpful AI bot.'),
            #        HumanMessage(content='Hi!'),
            #        AIMessage(content='How can I assist you today?'),
            #        HumanMessage(content='Can you make me an ice cream sundae?'),
            #        AIMessage(content='No.'),
            #    ]
            #)

    Single-variable template:

        If your prompt has only a single input variable (i.e., 1 instance of "{variable_nams}"),
        and you invoke the template with a non-dict object, the prompt template will
        inject the provided argument into that variable location.


        .. code-block:: python

            from langchain_core.prompts import ChatPromptTemplate

            template = ChatPromptTemplate([
                ("system", "You are a helpful AI bot. Your name is Carl."),
                ("human", "{user_input}"),
            ])

            prompt_value = template.invoke("Hello, there!")
            # Equivalent to
            # prompt_value = template.invoke({"user_input": "Hello, there!"})

            # Output:
            #  ChatPromptValue(
            #     messages=[
            #         SystemMessage(content='You are a helpful AI bot. Your name is Carl.'),
            #         HumanMessage(content='Hello, there!'),
            #     ]
            # )

    z.Annotated[list[MessageLike], SkipValidation()]r   Fr1   validate_templaterq   r   #Sequence[MessageLikeRepresentation]rs   r'   r4   r	   r5   r6   c                  fd|D             }t                      }t                      }i }|D ]y}t          |t                    r,|j        r%g ||j        <   |                    |j                   Ct          |t          t          f          r|                    |j	                   zt          |          t          |          |d|} t          dt                                j        dd|i| dS )ad  Create a chat prompt template from a variety of message formats.

        Args:
            messages: sequence of message representations.
                  A message can be represented using the following formats:
                  (1) BaseMessagePromptTemplate, (2) BaseMessage, (3) 2-tuple of
                  (message type, template); e.g., ("human", "{user_input}"),
                  (4) 2-tuple of (message class, template), (5) a string which is
                  shorthand for ("human", template); e.g., "{user_input}".
            template_format: format of the template. Defaults to "f-string".
            input_variables: A list of the names of the variables whose values are
                required as inputs to the prompt.
            optional_variables: A list of the names of the variables for placeholder
                or MessagePlaceholder that are optional.
                These variables are auto inferred from the prompt and user need not
                provide them.
            partial_variables: A dictionary of the partial variables the prompt
                template carries. Partial variables populate the template so that you
                don't need to pass them in every time you call the prompt.
            validate_template: Whether to validate the template.
            input_types: A dictionary of the types of the variables the prompt template
                expects. If not provided, all variables are assumed to be strings.

        Returns:
            A chat prompt template.

        Examples:
            Instantiation from a list of message templates:

            .. code-block:: python

                template = ChatPromptTemplate([
                    ("human", "Hello, how are you?"),
                    ("ai", "I'm doing well, thanks!"),
                    ("human", "That's good to hear."),
                ])

            Instantiation from mixed message formats:

            .. code-block:: python

                template = ChatPromptTemplate([
                    SystemMessage(content="hello"),
                    ("human", "Hello, how are you?"),
                ])

        c                0    g | ]}t          |          S r9   _convert_to_message_template)r   messagers   s     r>   r   z/ChatPromptTemplate.__init__.<locals>.<listcomp>  s3     
 
 
 )/BB
 
 
r?   )rO   optional_variablesrt   ztype[ChatPromptTemplate]r   Nr9   )r   rC   r.   r2   r0   addr   r%   updaterO   sortedr   r:   r;   )
r<   r   rs   r4   	_messages
input_varsr	  partial_vars_messager=   s
     `      r>   r;   zChatPromptTemplate.__init__~  s:   l
 
 
 
#
 
 
	  #uu
'*uu')! 	< 	<H($788 <X=N <79X34"&&x'=>>>>13LM  < !!(":;;;  &j11"();"<"<!-
 
 	
 	;'11:XXIXQWXXXXXr?   rJ   c                
    g dS )z*Get the namespace of the langchain object.)	langchainr   chatr9   )ry   s    r>   get_lc_namespacez#ChatPromptTemplate.get_lc_namespace  s     0///r?   otherc                    i | j         }t          |d          r!|j         r|                    |j                    t          |t                    r( t	          | j        |j        z             j        di |S t          |t          t          t          f          r$ t	          | j        |gz             j        di |S t          |t          t          f          rBt                              |          } t	          | j        |j        z             j        di |S t          |t                    r>t                              |          } t	          | j        |gz             j        di |S dt!          |           }t#          |          )zCombine two prompt templates.

        Args:
            other: Another prompt template.

        Returns:
            Combined prompt template.
        rt   r   z Unsupported operand type for +: Nr9   )rt   hasattrr  rC   r  r   partialr%   r   r   rD   tuplefrom_messagesr/   r   rx   rE   r   )r<   r  partials_otherrl   rH   s         r>   __add__zChatPromptTemplate.__add__  s    .d,- 5-.. 	553J 	5OOE3444 e/00 	V%t}u~/MNNNV     -{<RS
 
 	 P%t}w/FGGGO     edE]++ 	'55e<<FW%t}v/NOOOW     eS!! 	/==eDDFP%t}x/GHHHP     ?e>>!#&&&r?   before)modevaluesro   c                .   |d         }t                      }t                      }|                    di           }|D ]}t          |t          t          f          r|                    |j                   t          |t                    rld|vri |d<   |j        r9|j	        |d         vr*g |d         |j	        <   |
                    |j	                   |j	        |vrt          t                   ||j	        <   d|v r|t          |d                   z
  }|r||z
  }d|v rL|                    d          r7|t          |d                   k    rd| d|d          }t          |          nt          |          |d<   |rt          |          |d<   ||d<   |S )	aG  Validate input variables.

        If input_variables is not set, it will be set to the union of
        all input variables in the messages.

        Args:
            values: values to validate.

        Returns:
            Validated values.

        Raises:
            ValueError: If input variables do not match.
        r   input_typesrt   rO   r  z*Got mismatched input_variables. Expected: z. Got: r	  )r   rB   rC   r%   r   r  rO   r.   r2   r0   r
  rD   r   rF   r  )ry   r   r   r  r	  r"  r  rH   s           r>   validate_input_variablesz+ChatPromptTemplate.validate_input_variables  s   " *%%%
 UU&,jj&C&C 	J 	JG'$=?U#VWW ;!!'"9:::'#677 
J&f4424F./$B-V<O5PPPIKF./0EF&**7+@AAA(;;9=j9IK 56&((#c&1D*E&F&FFJ 	9#&88J&&6::6I+J+J&S(9!:;;;;8!+8 8"#458 8 
 !oo% < )/z(:(:F$% 	F+12D+E+EF'( +}r?   rr   r/   c                r    t          j        |fi |}t          |          }|                     |g          S )aY  Create a chat prompt template from a template string.

        Creates a chat template consisting of a single message assumed to be from
        the human.

        Args:
            template: template string
            **kwargs: keyword arguments to pass to the constructor.

        Returns:
            A new instance of this class.
        rl   )r&   rx   r   r  )ry   rr   r4   prompt_templater  s        r>   rx   z ChatPromptTemplate.from_template1  sB     )6xJJ6JJ,ODDD  '+++r?   z0.0.1r  T)alternativependingstring_messageslist[tuple[str, str]]c                .     | d |D                       S )zCreate a chat prompt template from a list of (role, template) tuples.

        Args:
            string_messages: list of (role, template) tuples.

        Returns:
            a chat prompt template.
        c                L    g | ]!\  }}t                               ||           "S ))r   )r   rx   )r   r   rr   s      r>   r   z8ChatPromptTemplate.from_role_strings.<locals>.<listcomp>Q  s?       "D( *77t7LL  r?   r   r9   ry   r)  s     r>   from_role_stringsz$ChatPromptTemplate.from_role_stringsC  s9     s &5  
 
 
 	
r?   1list[tuple[type[BaseMessagePromptTemplate], str]]c                ,    |                      |          S )zCreate a chat prompt template from a list of (role class, template) tuples.

        Args:
            string_messages: list of (role class, template) tuples.

        Returns:
            a chat prompt template.
        )r  r-  s     r>   from_stringszChatPromptTemplate.from_stringsW  s       111r?   c                     | ||          S )a  Create a chat prompt template from a variety of message formats.

        Examples:
            Instantiation from a list of message templates:

            .. code-block:: python

                template = ChatPromptTemplate.from_messages([
                    ("human", "Hello, how are you?"),
                    ("ai", "I'm doing well, thanks!"),
                    ("human", "That's good to hear."),
                ])

            Instantiation from mixed message formats:

            .. code-block:: python

                template = ChatPromptTemplate.from_messages([
                    SystemMessage(content="hello"),
                    ("human", "Hello, how are you?"),
                ])

        Args:
            messages: sequence of message representations.
                  A message can be represented using the following formats:
                  (1) BaseMessagePromptTemplate, (2) BaseMessage, (3) 2-tuple of
                  (message type, template); e.g., ("human", "{user_input}"),
                  (4) 2-tuple of (message class, template), (5) a string which is
                  shorthand for ("human", template); e.g., "{user_input}".
            template_format: format of the template. Defaults to "f-string".

        Returns:
            a chat prompt template.
        r   r9   )ry   r   rs   s      r>   r  z ChatPromptTemplate.from_messagesf  s    P s8_====r?   r@   c                4    | j         di |}g }| j        D ]}t          |t                    r|                    |g           .t          |t
          t          f          r# |j        di |}|                    |           md| }t          |          |S )a(  Format the chat template into a list of finalized messages.

        Args:
            **kwargs: keyword arguments to use for filling in template variables
                      in all the template messages in this chat template.

        Returns:
            list of formatted messages.
        Unexpected input: r9   )	!_merge_partial_and_user_variablesr   rC   r   r   r%   r   rI   rF   r<   r4   resultmessage_templater  rH   s         r>   rI   z"ChatPromptTemplate.format_messages  s     87AA&AA $ 
	& 
	&*K88 	&/01111 #<>T"U  & ;*:DDVDDg&&&&=+;== oo%r?   c                D  K    | j         di |}g }| j        D ]}t          |t                    r|                    |g           .t          |t
          t          f          r) |j        di | d{V }|                    |           sd| }t          |          |S )al  Async format the chat template into a list of finalized messages.

        Args:
            **kwargs: keyword arguments to use for filling in template variables
                      in all the template messages in this chat template.

        Returns:
            list of formatted messages.

        Raises:
            ValueError: If unexpected input.
        Nr4  r9   )	r5  r   rC   r   r   r%   r   r   rF   r6  s         r>   r   z#ChatPromptTemplate.aformat_messages  s       87AA&AA $ 
	& 
	&*K88 	&/01111 #<>T"U  & !B 0 A K KF K KKKKKKKg&&&&=+;== oo%r?   c                    | j                                         }t          t          | j                                      |                    |d<   i | j        ||d<    t          |           di |S )a  Get a new ChatPromptTemplate with some input variables already filled in.

        Args:
            **kwargs: keyword arguments to use for filling in template variables. Ought
                        to be a subset of the input variables.

        Returns:
            A new ChatPromptTemplate.


        Example:

            .. code-block:: python

                from langchain_core.prompts import ChatPromptTemplate

                template = ChatPromptTemplate.from_messages(
                    [
                        ("system", "You are an AI assistant named {name}."),
                        ("human", "Hi I'm {user}"),
                        ("ai", "Hi there, {user}, I'm {name}."),
                        ("human", "{input}"),
                    ]
                )
                template2 = template.partial(user="Lucy", name="R2D2")

                template2.format_messages(input="hello")
        rO   rt   r9   )__dict__copyrD   r   rO   
differencert   rE   )r<   r4   prompt_dicts      r>   r  zChatPromptTemplate.partial  s    : m((**)-$%%0088*
 *
%& ,Pd.D+O+O'(tDzz((K(((r?   r  MessageLikeRepresentationc                T    | j                             t          |                     dS )zAppend a message to the end of the chat template.

        Args:
            message: representation of a message to append.
        N)r   r   r  )r<   r  s     r>   r   zChatPromptTemplate.append  s)     	9'BBCCCCCr?   c                N    | j                             d |D                        dS )zExtend the chat template with a sequence of messages.

        Args:
            messages: sequence of message representations to append.
        c                ,    g | ]}t          |          S r9   r  )r   r  s     r>   r   z-ChatPromptTemplate.extend.<locals>.<listcomp>  s!    KKKw)'22KKKr?   N)r   r   )r<   r   s     r>   r   zChatPromptTemplate.extend  s9     	KK(KKK	
 	
 	
 	
 	
r?   indexintMessageLikec                    d S Nr9   r<   rC  s     r>   __getitem__zChatPromptTemplate.__getitem__  s    69cr?   slicec                    d S rG  r9   rH  s     r>   rI  zChatPromptTemplate.__getitem__  s    ?Bsr?   Union[int, slice]&Union[MessageLike, ChatPromptTemplate]c                    t          |t                    rU|                    t          | j                            \  }}}| j        |||         }t
                              |          S | j        |         S )z$Use to index into the chat template.)rC   rJ  indicesr   r   r  r  )r<   rC  startstopstepr   s         r>   rI  zChatPromptTemplate.__getitem__  sk     eU## 	> %c$-.@.@ A AE4}U4_5H%33H===}U##r?   c                *    t          | j                  S )z$Get the length of the chat template.)r   r   rN   s    r>   __len__zChatPromptTemplate.__len__  s    4=!!!r?   c                    dS )z,Name of prompt type. Used for serialization.r  r9   rN   s    r>   _prompt_typezChatPromptTemplate._prompt_type  s	     vr?   	file_pathUnion[Path, str]c                    t           )zQSave prompt to file.

        Args:
            file_path: path to file.
        r   )r<   rW  s     r>   savezChatPromptTemplate.save  s
     "!r?   rP   c                P    d                     fd| j        D                       S )rR   rX   c              3  D   K   | ]}|                                V  dS r   r   )r   rH   rP   s     r>   r   z1ChatPromptTemplate.pretty_repr.<locals>.<genexpr>'  s1      OO#3???55OOOOOOr?   )r   r   r   s    `r>   r[   zChatPromptTemplate.pretty_repr  s.     {{OOOOOOOOOOr?   )r   r  rs   r'   r4   r	   r5   r6   r]   )r  r	   r5   r  )r   ro   r5   r	   )rr   r/   r4   r	   r5   r  )r)  r*  r5   r  )r)  r/  r5   r  r   )r   r  rs   r'   r5   r  r\   )r4   r	   r5   r  )r  r?  r5   r6   )r   r  r5   r6   )rC  rD  r5   rE  )rC  rJ  r5   r  )rC  rL  r5   rM  )r5   rD  )r5   r/   )rW  rX  r5   r6   r^   r_   )r`   ra   rb   rc   rd   r  r;   r   r  r  r   r#  rx   r   r.  r1  r  rI   r   r  r   r   r   rI  rT  re   rV  rZ  r   r[   rf   rg   s   @r>   r  r    s        j jX =<<<U#####8 1;	NY NY NY NY NY NY NY NY` 0 0 0 [0&' &' &' &'P _(###2 2 2 [ $#2h , , , [," Z_dCCC
 
 
 DC [
$ Z_dCCC2 2 2 DC [2  1;'> '> '> '> ['>R   2   8") ") ") ")HD D D D
 
 
 
 999 X9BBB XB$ $ $ $" " " "    X" " " " 
P 
P 
P 
P X
P 
P 
P 
P 
Pr?   r  rq   message_typer/   rr   Union[str, list]rs   r'   r5   r%   c                t   | dv rt                               ||          }n| dv r,t                              t          d|          |          }ne| dk    r,t                              t          d|          |          }n3| dk    rt          |t                    rI|d         dk    s|d	         d
k    rd| d}t          |          |dd	         }t          |d          }nt          |          dk    rt          |d         t                    rw|\  }}t          |t                    sd| }t          |          |d         dk    s|d	         d
k    rd| d}t          |          |dd	         }t          ||          }n)d| }t          |          d|  d}t          |          |S )a  Create a message prompt template from a message type and template string.

    Args:
        message_type: str the type of the message template (e.g., "human", "ai", etc.)
        template: str the template string.
        template_format: format of the template. Defaults to "f-string".

    Returns:
        a message prompt template of the appropriate type.

    Raises:
        ValueError: If unexpected message type.
    )humanuserr   )ai	assistantr/   systemplaceholderr   rS   rT   zInvalid placeholder template: z6. Expected a variable name surrounded by curly braces.r   Tr8      z,Expected variable name to be a string. Got: zUnexpected arguments for placeholder message type. Expected either a single string variable name or a list of [variable_name: str, is_optional: bool]. Got: zUnexpected message type: z=. Use one of 'human', 'user', 'ai', 'assistant', or 'system'.)r   rx   r   r   r   rC   r/   rF   r.   r   r1   )r]  rr   rs   r  rH   var_namevar_name_wrappedis_optionals           r>   "_create_template_from_message_typerk  *  sN   $ (((-G-U-Uo .V .
 .
 
,	,	,)77!!? 8 
 
 
	!	!-;;!!? < 
 
 
	&	&h$$ 	"{c!!Xb\S%8%8LX L L L  !oo%"~H)4PPPGG]]aJx{D$A$A,4)k.44 &WEUWW oo%"c))-=b-AS-H-HL5E L L L  !oo%'"-H);WWWGG$ "$ $  S//!8 8 8 8 	 ooNr?   r  r?  EUnion[BaseMessage, BaseMessagePromptTemplate, BaseChatPromptTemplate]c                
   t          | t          t          f          r| }nbt          | t                    r| }nIt          | t                    rt          d| |          }n t          | t          t          f          rt          | t                    rKt          | 	                                          ddhk    rd|  }t          |          | d         | d         f} t          |           dk    rd|  }t          |          | \  }}t          |t                    rt          |||          }nP |t          j        t          d|          |          	          }n!d
t          |            }t!          |          |S )a  Instantiate a message from a variety of message formats.

    The message format can be one of the following:

    - BaseMessagePromptTemplate
    - BaseMessage
    - 2-tuple of (role string, template); e.g., ("human", "{user_input}")
    - 2-tuple of (message class, template)
    - string: shorthand for ("human", template); e.g., "{user_input}"

    Args:
        message: a representation of a message in one of the supported formats.
        template_format: format of the template. Defaults to "f-string".

    Returns:
        an instance of a message or a message template.

    Raises:
        ValueError: If unexpected message type.
        ValueError: If 2-tuple does not have 2 elements.
    r`  r   r   r   z<Expected dict to have exact keys 'role' and 'content'. Got: rg  z*Expected 2-tuple of (role, template), got r/   r%  zUnsupported message type: )rC   r%   r   r   r/   rk  r  ro   r   r   rF   r   r&   rx   r   rE   r   )r  rs   r  rH   message_type_strrr   s         r>   r  r  q  s   2 '57MNOO #'  	 
G[	)	) '	GS	!	! '5Wo
 
 
 
GeT]	+	+ 'gt$$ 	<7<<>>""y&&999'$' '  !oo%v	(:;Gw<<1HwHHCS//!%,"(&,, 		9 (O  HH ('%3))?    HH ;4==::!#&&&Or?   Nr   )r]  r/   rr   r^  rs   r'   r5   r%   )r  r?  rs   r'   r5   rl  )Urc   
__future__r   abcr   r   pathlibr   typingr   r   r	   r
   r   r   r   r   r   pydanticr   r   r   r   typing_extensionsr   r   langchain_core._apir   langchain_core.messagesr   r   r   r   r   r   r   langchain_core.messages.baser   langchain_core.prompt_valuesr   r    r!   langchain_core.prompts.baser"   langchain_core.prompts.dictr#   langchain_core.prompts.imager$   langchain_core.prompts.messager%   langchain_core.prompts.promptr&   langchain_core.prompts.stringr'   r(   r)   langchain_core.utilsr*   $langchain_core.utils.interactive_envr+   collections.abcr,   r.   rh   ri   r   r   r   r   r   r   r   r   rE  r  r/   rE   rD   ro   objectr?  r  rk  r  _convert_to_messager9   r?   r>   <module>r     s     " " " " " " # # # # # # # #      
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
            - , , , , , , , * * * * * *                  < ; ; ; ; ; O O O O O O O O O O : : : : : : : : : : : : < < < < < <      9 8 8 8 8 8         
 2 1 1 1 1 1 C C C C C C )((((((\# \# \# \# \#3 \# \# \#~ !$E    2}B }B }B }B }B&? }B }B }B@ 
  
  
  
  
 ?  
  
  
F    %             )5        J, J, J, J, J,(A J, J, J,Z1 1 1 1 1!B 1 1 1. . . . .? . . .2 2 2 2 2"C 2 2 2P; P; P; P; P;/ P; P; P;f -{<RRS!	c4ic4:tF|+,	. cN [P [P [P [P [P/ [P [P [PB -7D D D D DR -7> > > > >D 3   r?   