
    g3fi                       d Z ddlmZ ddlmZmZ ddlmZ ddlm	Z	 ddl
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mZmZmZmZmZm Z  dd
l!m"Z" ddl#m$Z$m%Z% ddl&m'Z' ddl(m)Z) ddl*m+Z+ ddl,m-Z- ddl.m/Z/ ddl0m1Z1m2Z2m3Z3 ddl4m5Z5 ddl6m7Z7  G d de-      Z8 edd      Z9	  G d de-e      Z: G d de:      Z; G d ded      Z< G d  d!ed      Z= G d" d#e-      Z> G d$ d%e>      Z? G d& d'e>      Z@ G d( d)e>      ZA G d* d+e'e      ZBe-ez  eBz  ZCeCeDeEeFz  eEeeG   z  eeH   z  f   z  eEz  eGeEef   z  ZI G d, d-eB      ZJ	 d1	 	 	 	 	 	 	 d2d.ZK	 d1	 	 	 	 	 d3d/ZLeLZMy0)4zChat prompt template.    )annotations)ABCabstractmethod)Sequence)Path)	AnnotatedAny	TypedDictTypeVarcastoverload)FieldPositiveIntSkipValidationmodel_validator)Selfoverride)	AIMessage
AnyMessageBaseMessageChatMessageHumanMessageSystemMessageconvert_to_messages)get_msg_title_repr)ChatPromptValueImageURL)BasePromptTemplate)DictPromptTemplate)ImagePromptTemplate)BaseMessagePromptTemplate)PromptTemplate)PromptTemplateFormatStringPromptTemplateget_template_variables)get_colored_text)is_interactive_envc                       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 )MessagesPlaceholdera0  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:

        ```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:

        ```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:

        ```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PositiveInt | None
n_messages)r-   c               *    t        |   d||d| y)aw  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.
        r+   r-   N )super__init__)selfr+   r-   kwargs	__class__s       Y/var/www/auto_recruiter/arenv/lib/python3.12/site-packages/langchain_core/prompts/chat.pyr3   zMessagesPlaceholder.__init__   s     	R}xR6R    c                4   | j                   r|j                  | 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)	r-   getr+   
isinstancelisttype
ValueErrorr   r.   )r4   r5   valuemsgs       r7   format_messagesz#MessagesPlaceholder.format_messages   s     }} JJt))2.**+ 	
 %&D../ 0gYtE{m5  S/!#E*??4??*,-Er8   c                8    | j                   s| j                  gS g S znInput variables for this prompt template.

        Returns:
            List of input variable names.
        )r-   r+   r4   s    r7   input_variablesz#MessagesPlaceholder.input_variables   s     ,0==""#@b@r8   c                    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.

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

)r+   r   r&   )r4   htmlvartitles       r7   pretty_reprzMessagesPlaceholder.pretty_repr   sQ     D&&&,&'=DIE"31C&'=>ESE""r8   )r+   r*   r-   r,   r5   r	   returnNoner5   r	   rR   zlist[BaseMessage]rR   	list[str]FrN   r,   rR   r*   )__name__
__module____qualname____doc____annotations__r-   r.   r3   rA   propertyrE   r   rQ   __classcell__r6   s   @r7   r)   r)   4   s    FP .Hd: &*J") 7<S S/3SGJS	S8 A A # #r8   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y)rb   zJBase class for message prompt templates that use a string prompt template.r$   promptdefault_factorydictadditional_kwargsNc                F    t        j                  |||      } | dd|i|S )af  Create a class from a string template.

        Args:
            template: a template.
            template_format: format of the template.
            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}"`.

            **kwargs: keyword arguments to pass to the constructor.

        Returns:
            A new instance of this class.
        template_formatpartial_variablesre   r1   )r"   from_template)clstemplaterl   rm   r5   re   s         r7   rn   z-BaseStringMessagePromptTemplate.from_template   s2    0  --+/

 +&+F++r8   c                @    t        j                  |      } | dd|i|S )a   Create a class from a template file.

        Args:
            template_file: path to a template file. String or Path.
            **kwargs: keyword arguments to pass to the constructor.

        Returns:
            A new instance of this class.
        re   r1   )r"   	from_file)ro   template_filer5   re   s       r7   from_template_filez2BaseStringMessagePromptTemplate.from_template_file   s'      ))-8+&+F++r8   c                     y)Format the prompt template.

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

        Returns:
            Formatted message.
        Nr1   r4   r5   s     r7   formatz&BaseStringMessagePromptTemplate.format      r8   c                .   K    | j                   di |S w)Async format the prompt template.

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

        Returns:
            Formatted message.
        r1   rx   rw   s     r7   aformatz'BaseStringMessagePromptTemplate.aformat  s      t{{$V$$   c                (     | j                   di |gS zFormat messages from kwargs.

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

        Returns:
            List of BaseMessages.
        r1   r|   rw   s     r7   rA   z/BaseStringMessagePromptTemplate.format_messages%       %f%&&r8   c                D   K    | j                   di | d{   gS 7 wzAsync format messages from kwargs.

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

        Returns:
            List of BaseMessages.
        Nr1   r}   rw   s     r7   aformat_messagesz0BaseStringMessagePromptTemplate.aformat_messages0  %      #dll,V,,--,     c                .    | j                   j                  S rC   )re   rE   rD   s    r7   rE   z/BaseStringMessagePromptTemplate.input_variables;  s     {{***r8   c                    | j                   j                  j                  dd      }t        ||      }| d| j                  j                  |       S )rG   MessagePromptTemplate MessagerJ   rM   rN   )r6   rY   replacer   re   rQ   )r4   rN   rP   s      r7   rQ   z+BaseStringMessagePromptTemplate.pretty_reprD  sQ     ''//0GT"5t4T[[44$4?@AAr8   )f-stringN)
rp   r*   rl   r#   rm   dict[str, Any] | Noner5   r	   rR   r   )rs   
str | Pathr5   r	   rR   r   r5   r	   rR   r   rT   rU   rW   rX   )rY   rZ   r[   r\   r]   r   rh   ri   classmethodrn   rt   r   rx   r}   rA   r   r^   rE   r   rQ   r1   r8   r7   rb   rb      s    T  !#D9t9F 1;37	,, ., 1	,
 , 
, ,< ,!, , 
	, ,"  	%	'	. + + B Br8   c                  .    e Zd ZU dZded<   	 ddZddZy)ChatMessagePromptTemplatezChat message prompt template.r*   rolec                ~     | j                   j                  di |}t        || j                  | j                        S )rv   contentr   ri   r1   )re   rx   r   r   ri   r4   r5   texts      r7   rx   z ChatMessagePromptTemplate.formatZ  s;     "t{{!!+F+tyyD<R<R
 	
r8   c                   K    | j                   j                  di | d{   }t        || j                  | j                        S 7 &w)r{   Nr   r1   )re   r}   r   r   ri   r   s      r7   r}   z!ChatMessagePromptTemplate.aformath  sG      )T[[((2622tyyD<R<R
 	
 3s    AA	'ANr   )rY   rZ   r[   r\   r]   rx   r}   r1   r8   r7   r   r   T  s    '
I

r8   r   c                      e Zd ZU ded<   y)_TextTemplateParam
str | dictr   NrY   rZ   r[   r]   r1   r8   r7   r   r   w  s    
r8   r   F)totalc                      e Zd ZU ded<   y)_ImageTemplateParamr   	image_urlNr   r1   r8   r7   r   r   {  s    r8   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ddd       Zy	)!_StringImageMessagePromptTemplateDHuman message prompt template. This is a message sent from the user.z\StringPromptTemplate | list[StringPromptTemplate | ImagePromptTemplate | DictPromptTemplate]re   rf   rh   ri   type[BaseMessage]
_msg_classN)rm   c                  t        |t              r"t        j                  |||      } | dd|i|S t        |t              r*|t        |      dkD  rd}t        |      g }|D ]  }t        |t              s2t        |t              rkd|v rgt        |j                               ddhk  rIt        |t              r|}nt        d|      d   }|j                  t        j                  ||             t        |t              rd	|v rt        |j                               dd	hk  rt        d
|      d	   }	g }
t        |	t              rHt        |	|      }|r't        |      dkD  rd| d| }t        |      |d   g}
d|	i}	t        |
|	|      }ndt        |	t              rDt        |	      }	dD ]%  }||	v s|
j                  t        |	|   |             ' t        |
|	|      }nd| }t        |      |j                  |       t        |t              r<|dk(  rd}t        |      t        t        d|      |      }|j                  |       d| }t        |        | dd|i|S d| }t        |      )a  Create a class from a string template.

        Args:
            template: a template.
            template_format: format of the template.
                Options are: 'f-string', 'mustache', 'jinja2'.
            partial_variables: A dictionary of variables that can be used too partially.

            **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.
        rk   re   r   z:Partial variables are not supported for list of templates.r   r=   r   rl   r   r      z:Only one format variable allowed per image template.
Got: z
From: url)rE   rp   rl   )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])rp   rl   zInvalid template: r1   )r;   r*   r"   rn   r<   lenr>   rh   setkeysr   appendr%   r    extendr   )ro   rp   rl   rm   r5   re   r@   tmplr   img_templaterE   	variablesimg_template_objkeydata_template_objs                  r7   rn   z/_StringImageMessagePromptTemplate.from_template  s   4 h$2@2N2N /"33F
 /f///h%!-37H3IA3MR o%F  N*dC(tT*$DIIK(VV,<<!$,$(#$8$?GMM&44 / tT*#t+DIIK(# $((=t#D[#QL&(O!,4$:(/%	 %"9~1%88A{&.tf%6 !$
 '1o 5/8|nO(-|'<+>,;%1,;,(
 $L$7'+L'9#< "C"l2 / 6 6$:(4S(9?%&!"" ,?,;%1,;,( !9?(o-MM"23d+&(2& 
 )o-(:!%&6!=(7)% MM"34.tf5C$S/)]N*^ /f///"8*-or8   c                b    t        |      j                  d      } | j                  |fd|i|S )a6  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.
        zutf-8)encodingrE   )r   	read_textrn   )ro   rs   rE   r5   rp   s        r7   rt   z4_StringImageMessagePromptTemplate.from_template_file  s9    " &00'0B s  U?UfUUr8   c                (     | j                   di |gS r   r|   rw   s     r7   rA   z1_StringImageMessagePromptTemplate.format_messages  r   r8   c                D   K    | j                   di | d{   gS 7 wr   r   rw   s     r7   r   z2_StringImageMessagePromptTemplate.aformat_messages$  r   r   c                    t        | j                  t              r| j                  n| j                  g}|D cg c]  }|j                  D ]  }|  c}}S c c}}w rC   )r;   re   r<   rE   )r4   promptsre   ivs       r7   rE   z1_StringImageMessagePromptTemplate.input_variables/  sH     ",DKK!>$++T[[M!(Jv63I3IJRJJJJs   Ac                   t        | j                  t              r9 | j                  j                  di |}| j	                  || j
                        S g }| j                  D ]  }|j                  D ci c]  }|||   
 }}t        |t              r- |j                  di |}|dk7  sH|j                  d|d       ]t        |t              r' |j                  di |}|j                  d|d       t        |t              s |j                  di |}	|j                  |	        | j	                  || j
                        S c c}w )rv   r   ri    r   r=   r   r   r=   r   r1   )
r;   re   r$   rx   r   ri   rE   r   r    r   
r4   r5   r   r   re   rO   inputsformatted_textformatted_imageformatted_dicts
             r7   rx   z(_StringImageMessagePromptTemplate.format9  sB    dkk#78%4;;%%//D??0F0F #   kk 	/F282H2HI3c6#;&IFI&"67&3fmm&=f&=!R'NNFN#KLF$78,9FMM,CF,C/RSF$671>1H1H~.	/ t/E/E  
 	
 Js   3E	c                  K   t        | j                  t              rA | j                  j                  di | d{   }| j	                  || j
                        S g }| j                  D ]  }|j                  D ci c]  }|||   
 }}t        |t              r5 |j                  di | d{   }|dk7  sP|j                  d|d       et        |t              r/ |j                  di | d{   }|j                  d|d       t        |t              s |j                  di |}	|j                  |	        | j	                  || j
                        S 7 'c c}w 7 7 vw)	r{   Nr   r   r   r   r   r   r1   )r;   re   r$   r}   r   ri   rE   r   r    r   rx   r   s
             r7   r}   z)_StringImageMessagePromptTemplate.aformatX  s^     dkk#78,,,6v66D??0F0F #   kk 	/F282H2HI3c6#;&IFI&"67,:FNN,DV,D&D!R'NNFN#KLF$782@&..2J62J,J/RSF$671>1H1H~.	/ t/E/E  
 	
# 7 J&D -KsM   :E/E#A E/=E&
'E/1E+2	E/<:E/6E-7)E/!AE/&E/-E/c                   | j                   j                  j                  dd      }t        |      }t	        | j
                  t              r| j
                  n| j
                  g}dj                  fd|D              }| d| S )rG   r   r   rJ   rM   c              3  B   K   | ]  }|j                           ywr   NrQ   ).0re   rN   s     r7   	<genexpr>z@_StringImageMessagePromptTemplate.pretty_repr.<locals>.<genexpr>  s     "WV6#5#54#5#@"W   )r6   rY   r   r   r;   re   r<   join)r4   rN   rP   r   prompt_reprss    `   r7   rQ   z-_StringImageMessagePromptTemplate.pretty_reprw  sq     ''//0GT"5t4!+DKK!>$++T[[M{{"Ww"WW\N++r8   r   )ro   
type[Self]rp   zKstr | list[str | _TextTemplateParam | _ImageTemplateParam | dict[str, Any]]rl   r#   rm   r   r5   r	   rR   r   )
ro   r   rs   r   rE   rV   r5   r	   rR   r   rT   rU   r   rW   rX   )rY   rZ   r[   r\   r]   r   rh   ri   r   rn   rt   rA   r   r^   rE   rx   r}   r   rQ   r1   r8   r7   r   r     s   N	P #D9t9F!!
 1;	v 48vvPv .	v 1v v 
v vp VV!V #V 	V
 
V V&	'	. K K
>
> , ,r8   r   c                       e Zd ZU dZeZded<   y)HumanMessagePromptTemplater   r   r   N)rY   rZ   r[   r\   r   r   r]   r1   r8   r7   r   r     s    N$0J!0r8   r   c                       e Zd ZU dZeZded<   y)AIMessagePromptTemplatez?AI message prompt template. This is a message sent from the AI.r   r   N)rY   rZ   r[   r\   r   r   r]   r1   r8   r7   r   r     s    I$-J!-r8   r   c                       e Zd ZU dZeZded<   y)SystemMessagePromptTemplatezYSystem message prompt template.

    This is a message that is not sent to the user.
    r   r   N)rY   rZ   r[   r\   r   r   r]   r1   r8   r7   r   r     s    
 %2J!1r8   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y)BaseChatPromptTemplatez%Base class for chat prompt templates.c                    d| j                   iS )NrE   )rE   rD   s    r7   lc_attributesz$BaseChatPromptTemplate.lc_attributes  s     "4#7#788r8   c                B     | j                   di |j                         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.
        r1   )format_prompt	to_stringrw   s     r7   rx   zBaseChatPromptTemplate.format  s#     "t!!+F+5577r8   c                ^   K    | j                   di | d{   j                         S 7 w)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.
        Nr1   )aformat_promptr   rw   s     r7   r}   zBaseChatPromptTemplate.aformat  s-      *d))3F33>>@@3s   -+-c                >     | j                   di |}t        |      S )zFormat prompt. Should return a ChatPromptValue.

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

        Returns:
            ChatPromptValue.
        messagesr1   )rA   r   r4   r5   r   s      r7   r   z$BaseChatPromptTemplate.format_prompt  s$     (4''1&111r8   c                Z   K    | j                   di | d{   }t        |      S 7 w)zAsync format prompt. Should return a ChatPromptValue.

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

        Returns:
            PromptValue.
        Nr   r1   )r   r   r   s      r7   r   z%BaseChatPromptTemplate.aformat_prompt  s0      /..88811 9s   +)+c                     y)z_Format kwargs into a list of messages.

        Returns:
            List of messages.
        Nr1   rw   s     r7   rA   z&BaseChatPromptTemplate.format_messages  ry   r8   c                .   K    | j                   di |S w)zeAsync format kwargs into a list of messages.

        Returns:
            List of messages.
        r1   )rA   rw   s     r7   r   z'BaseChatPromptTemplate.aformat_messages  s      $t##-f--r~   c                    t         )rG   NotImplementedErrorr4   rN   s     r7   rQ   z"BaseChatPromptTemplate.pretty_repr  s
     "!r8   c                J    t        | j                  t                            y)z&Print a human-readable representation.r   N)printrQ   r'   rD   s    r7   pretty_printz#BaseChatPromptTemplate.pretty_print  s    d$6$89:r8   N)rR   rh   )r5   r	   rR   r*   )r5   r	   rR   r   rT   rW   rX   )rR   rS   )rY   rZ   r[   r\   r^   r   r   rx   r}   r   r   r   rA   r   rQ   r   r1   r8   r7   r   r     sn    /9  9
8
A
2
2  . "" 
";r8   r   c                  V    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ddZ	 e
d      ed d              Zed!d       Ze	 d"	 	 	 	 	 d#d       Zd$dZd$dZd%dZd&dZd'dZed(d       Zed)d       Zd*dZd+dZed,d       Zd-dZed.d/d       Z xZS )0ChatPromptTemplatea  Prompt template for chat models.

    Use to create flexible templated prompts for chat models.

    ```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?')
    #    ]
    # )
    ```

    !!! note "Messages Placeholder"

        ```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.'),
        #    ]
        # )
        ```

    !!! note "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.

        ```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   Fr,   validate_templater   r   c                  |D cg c]  }t        ||       }}t               }t               }i }|D ]{  }	t        |	t              r7|	j                  r+g ||	j
                  <   |j                  |	j
                         Jt        |	t        t        f      sa|j                  |	j                         } t        |      t        |      |d|} t        dt                     j                  dd|i| yc c}w )ax	  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.
            **kwargs: Additional keyword arguments passed to `BasePromptTemplate`,
                including (but not limited to):

                - `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.

        Examples:
            Instantiation from a list of message templates:

            ```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:

            ```python
            template = ChatPromptTemplate(
                [
                    SystemMessage(content="hello"),
                    ("human", "Hello, how are you?"),
                ]
            )
            ```
        )rE   optional_variablesrm   ztype[ChatPromptTemplate]r   Nr1   )_convert_to_message_templater   r;   r)   r-   r+   addr   r!   updaterE   sortedr   r2   r3   )r4   r   rl   r5   message	messages_
input_varsr   partial_vars_messager6   s             r7   r3   zChatPromptTemplate.__init__q  s   N $
 )/B
	 
  #u
'*u')! 	<H($78X=N=N79X334"&&x'='=>13LM !!(":":;	<  &j1"();"<!-
 	
 	;'1::XIXQWX1
s   C2c                
    g dS )ztGet the namespace of the LangChain object.

        Returns:
            `["langchain", "prompts", "chat"]`
        )	langchainr   chatr1   )ro   s    r7   get_lc_namespacez#ChatPromptTemplate.get_lc_namespace  s
     0/r8   c                    i | j                   }t        |d      r'|j                   r|j                  |j                          t        |t              r3 t	        | j
                  |j
                  z         j                  di |S t        |t        t        t        f      r* t	        g | j
                  |      j                  di |S t        |t        t        f      rHt        j                  |      } t	        | j
                  |j
                  z         j                  di |S t        |t              r?t        j                  |      } t	        g | j
                  |      j                  di |S dt!        |       }t#        |      )zCombine two prompt templates.

        Args:
            other: Another prompt template.

        Returns:
            Combined prompt template.
        rm   r   z Unsupported operand type for +: r1   )rm   hasattrr   r;   r   r   partialr!   r   r   r<   tuplefrom_messagesr*   r   rn   r=   r   )r4   otherpartialsother_re   r@   s         r7   __add__zChatPromptTemplate.__add__  s    .d,,- 5-.53J3JOOE334 e/0V%t}}u~~/MNVV   -{<RS
 P%/F/F/FGOO   edE]+'55e<FW%t}}v/NOWW   eS!/==eDFP%/G/G/GHPP   1e>!#&&r8   before)modec                   |d   }t               }t               }|j                  di       }|D ]  }t        |t        t        f      r|j                  |j                         t        |t              sEd|vri |d<   |j                  r>|j                  |d   vr-g |d   |j                  <   |j                  |j                         |j                  |vst        t           ||j                  <    d|v r|t        |d         z  }|r||z  }d|v r8|j                  d      r'|t        |d         k7  r$d| d|d    }t        |      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_typesrm   rE   r   z*Got mismatched input_variables. Expected: z. Got: r   )r   r:   r;   r!   r   r   rE   r)   r-   r+   r   r<   r   r>   r   )ro   valuesr   r  r   r  r   r@   s           r7   validate_input_variablesz+ChatPromptTemplate.validate_input_variables  s   " *%%
 U&,jj&C 	JG'$=?U#VW!!'"9"9:'#67&f424F./$$--V<O5PPIKF./0E0EF&**7+@+@A((;9=j9IK 5 56	J &(#f%89::J,,J&6::6I+JS(9!:;;!!+ -"#4568 
 !o%(.z(:F$%+12D+EF'( +}r8   c                j    t        j                  |fi |}t        |      }| j                  |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.
        re   )r"   rn   r   r  )ro   rp   r5   prompt_templater   s        r7   rn   z ChatPromptTemplate.from_template7  s6     )66xJ6J,OD  '++r8   c                     | ||      S )aq  Create a chat prompt template from a variety of message formats.

        Examples:
            Instantiation from a list of message templates:

            ```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:

            ```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.

        Returns:
            a chat prompt template.

        r   r1   )ro   r   rl   s      r7   r  z ChatPromptTemplate.from_messagesI  s    b 8_==r8   c                (    | j                   di |}g }| j                  D ]n  }t        |t              r|j	                  |g       &t        |t
        t        f      r$ |j                  di |}|j	                  |       `d| }t        |       |S )ap  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.

        Raises:
            ValueError: if messages are of unexpected types.

        Returns:
            list of formatted messages.
        Unexpected input: r1   )	!_merge_partial_and_user_variablesr   r;   r   r   r!   r   rA   r>   r4   r5   resultmessage_templater   r@   s         r7   rA   z"ChatPromptTemplate.format_messages|  s     877A&A $ 
	&*K8/01 #<>T"U ;*::DVDg&*+;*<= o%
	& r8   c                D  K    | j                   di |}g }| j                  D ]v  }t        |t              r|j	                  |g       &t        |t
        t        f      r, |j                  di | d{   }|j	                  |       hd| }t        |       |S 7 )w)af  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.
        Nr  r1   )	r  r   r;   r   r   r!   r   r   r>   r  s         r7   r   z#ChatPromptTemplate.aformat_messages  s      877A&A $ 
	&*K8/01 #<>T"U !B 0 A A KF KKg&*+;*<= o%
	&  Ls   A2B 4B5*B c                    | j                   j                         }t        t        | j                        j                  |            |d<   i | j                  ||d<    t        |       di |S )ap  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:
            ```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")
            ```
        rE   rm   r1   )__dict__copyr<   r   rE   
differencerm   r=   )r4   r5   prompt_dicts      r7   r
  zChatPromptTemplate.partial  sq    8 mm((*)-$$%008*
%& ,Pd.D.D+O+O'(tDz(K((r8   c                L    | j                   j                  t        |             y)zAppend a message to the end of the chat template.

        Args:
            message: representation of a message to append.
        N)r   r   r   )r4   r   s     r7   r   zChatPromptTemplate.append  s     	9'BCr8   c                r    | j                   j                  |D cg c]  }t        |       c}       yc c}w )zExtend the chat template with a sequence of messages.

        Args:
            messages: Sequence of message representations to append.
        N)r   r   r   )r4   r   r   s      r7   r   zChatPromptTemplate.extend  s-     	BJKw)'2K	
Ks   4c                     y Nr1   r4   indexs     r7   __getitem__zChatPromptTemplate.__getitem__  s    69r8   c                     y r*  r1   r+  s     r7   r-  zChatPromptTemplate.__getitem__  s    ?Br8   c                    t        |t              rO|j                  t        | j                              \  }}}| j                  |||   }t
        j                  |      S | j                  |   S )zUse to index into the chat template.

        Returns:
            If index is an int, returns the message at that index.
            If index is a slice, returns a new `ChatPromptTemplate`
            containing the messages in that slice.
        )r;   sliceindicesr   r   r   r  )r4   r,  startstopstepr   s         r7   r-  zChatPromptTemplate.__getitem__  s`     eU# %c$--.@ AE4}}U4_5H%33H==}}U##r8   c                ,    t        | j                        S )z'Return the length of the chat template.)r   r   rD   s    r7   __len__zChatPromptTemplate.__len__  s    4==!!r8   c                     y)z,Name of prompt type. Used for serialization.r  r1   rD   s    r7   _prompt_typezChatPromptTemplate._prompt_type  s     r8   c                    t         )zQSave prompt to file.

        Args:
            file_path: path to file.
        r   )r4   	file_paths     r7   savezChatPromptTemplate.save  s
     "!r8   c                L    dj                  fd| j                  D              S )rG   rM   c              3  B   K   | ]  }|j                           ywr   r   )r   r@   rN   s     r7   r   z1ChatPromptTemplate.pretty_repr.<locals>.<genexpr>  s     O#3???5Or   )r   r   r   s    `r7   rQ   zChatPromptTemplate.pretty_repr  s     {{OOOOr8   )r   #Sequence[MessageLikeRepresentation]rl   r#   r5   r	   rR   rS   rU   )r  r	   rR   r   )r  rh   rR   r	   )rp   r*   r5   r	   rR   r   r   )r   r>  rl   r#   rR   r   rT   )r5   r	   rR   r   )r   MessageLikeRepresentationrR   rS   )r   r>  rR   rS   )r,  intrR   MessageLike)r,  r0  rR   r   )r,  zint | slicerR   z MessageLike | ChatPromptTemplate)rR   r@  )rR   r*   )r:  z
Path | strrR   rS   rW   rX   )rY   rZ   r[   r\   r]   r   r3   r   r  r  r   r  rn   r  rA   r   r
  r   r   r   r-  r6  r^   r8  r;  r   rQ   r_   r`   s   @r7   r   r     sV   fP =<U#t#8 1;	]Y5]Y .	]Y
 ]Y 
]Y~ 0 0&'P (#2  $2h , ,"  1;0>50> .0> 
	0> 0>d88!)FD
 9 9B B$"  " 
P 
Pr8   r   c                   | dv rt         j                  ||      }|S | dv r#t        j                  t        d|      |      }|S | dk(  r#t        j                  t        d|      |      }|S | dk(  rt        |t              r5|d   dk7  s|d	   d
k7  rd| d}t        |      |dd	 }t        |d      }|S 	 |\  }}t        |t              sd| }t        |      t        |t              sd| }t        |      |d   dk7  s|d	   d
k7  rd| d}t        |      |dd	 }t        ||      }|S d|  d}t        |      # t        $ r}d| }t        |      |d}~ww xY w)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.

    Returns:
        a message prompt template of the appropriate type.

    Raises:
        ValueError: If unexpected message type.
    >   userhumanr   >   ai	assistantr*   systemplaceholderr   rH   rI   zInvalid placeholder template: z6. Expected a variable name surrounded by curly braces.r   Tr0   zUnexpected arguments for placeholder message type. Expected either a single string variable name or a list of [variable_name: str, is_optional: bool]. Got: Nz+Expected is_optional to be a boolean. Got: z,Expected variable name to be a string. Got: zUnexpected message type: z=. Use one of 'human', 'user', 'ai', 'assistant', or 'system'.)
r   rn   r   r   r   r;   r*   r>   r)   r,   )	message_typerp   rl   r   r@   var_namevar_name_wrappedis_optionales	            r7   "_create_template_from_message_typerO    s   $ ((-G-U-Uo .V .
n Ni 
,	,)77!? 8 
f Na 
	!-;;!? < 
^ NY 
	&h${c!Xb\S%84XJ ?L L  !o%"~H)4PGF NC	-08- + k40CK=Q o%.4DEUDVW o%"c)-=b-AS-H45E4F GL L  !o%'"-H);WG N	 (~ 67 8 	 o=  - &J(  !o1,-s   8E 	E"EE"c                   t        | t        t        f      r| }|S t        | t              r| }|S t        | t              rt        d| |      }|S t        | t        t        f      rt        | t              r9t        | j                               ddhk7  rd|  }t        |      | d   }| d   }n#t        |       dk7  rd|  }t        |      | \  }}t        |t              rt        |||      }|S t        |d      r7d	|j                  v r)|j                  d	   j                  }t        |||      }|S  |t        j                   t#        d
|      |            }|S dt%        |        }t'        |      )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.

    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.
    rD  r   r   r   z<Expected dict to have exact keys 'role' and 'content'. Got:    z*Expected 2-tuple of (role, template), got model_fieldsr=   r*   r  zUnsupported message type: )r;   r!   r   r   r*   rO  r  rh   r   r   r>   r   r	  rR  defaultr"   rn   r   r=   r   )r   rl   message_r@   message_type_strrp   rJ  s          r7   r   r   i  s   2 '57MNO 	^ OY 
G[	)V OU 
GS	!5Wo
R OM 
GeT]	+gt$7<<>"y&&99$I'  !o%&vy)H7|q B7)L o%)0&h&,9 (OH* O# $n5*777+88@HHL9hH O (%33)?H O +4=/:!#&&r8   Nr   )rJ  r*   rp   z
str | listrl   r#   rR   r!   )r   r?  rl   r#   rR   z@BaseMessage | BaseMessagePromptTemplate | BaseChatPromptTemplate)Nr\   
__future__r   abcr   r   collections.abcr   pathlibr   typingr   r	   r
   r   r   r   pydanticr   r   r   r   typing_extensionsr   r   langchain_core.messagesr   r   r   r   r   r   r   langchain_core.messages.baser   langchain_core.prompt_valuesr   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'   r)   ra   rb   r   r   r   r   r   r   r   r   rA  r  r*   r=   rh   objectr?  r   rO  r   _convert_to_messager1   r8   r7   <module>rj     s    " # $    -   < B : : < 9 
 2 CY#3 Y#x !$E  2{B&? {B| 
 ?  
F% )5 G,(A G,T1!B 1.? .2"C 2X;/ X;v (+58NN C$Jhtn,x/???@A	
 38n VP/ VPx -7JJJ *J 	J^ -7I&I)I FIZ 3 r8   