
    D_i                       S r SSKJr  SSKJrJr  SSKJr  SSKJ	r	  SSK
JrJrJrJrJrJr  SSKJrJrJrJr  SSKJrJr  SS	KJrJrJrJrJrJrJ r   SS
K!J"r"  SSK#J$r$J%r%  SSK&J'r'  SSK(J)r)  SSK*J+r+  SSK,J-r-  SSK.J/r/  SSK0J1r1J2r2J3r3  SSK4J5r5  SSK6J7r7   " S S\-5      r8\" SSS9r9  " S S\-\5      r: " S S\:5      r; " S S\SS9r< " S  S!\SS9r= " S" S#\-5      r> " S$ S%\>5      r? " S& S'\>5      r@ " S( S)\>5      rA " S* S+\'\5      rB\-\-  \B-  rC\C\D\E\F-  \E\\G   -  \\H   -  4   -  \E-  \G\E\4   -  rI " S, S-\B5      rJ S1       S2S. jjrK S1     S3S/ jjrL\LrMg0)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                     ^  \ rS rSr% SrS\S'    SrS\S'    SrS	\S
'    SS.       SU 4S jjjrSS jr	\
SS j5       r\SSS jj5       rSrU =r$ )MessagesPlaceholder4   aL  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U ]  " SXS.UD6  g)aG  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       U/home/james-whalen/.local/lib/python3.13/site-packages/langchain_core/prompts/chat.pyr4   MessagesPlaceholder.__init__   s     	R}R6R    c                N   U R                   (       a  UR                  U R                  / 5      OXR                     n[        U[        5      (       d)  SU R                   SU S[        U5       3n[        U5      e[        U5      nU R                  (       a  X R                  * S nU$ )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/   )r5   r6   valuemsgs       r8   format_messages#MessagesPlaceholder.format_messages   s     }} JJt))2.**+ 	
 %&&D../ 0gYtE{m5  S/!#E*????*,-Er:   c                B    U R                   (       d  U R                  /$ / $ zVInput variables for this prompt template.

Returns:
    List of input variable names.
)r.   r,   r5   s    r8   input_variables#MessagesPlaceholder.input_variables   s     ,0==""#@b@r:   c                    SU R                   -   S-   nU(       a  [        SSS9n[        US5      nO[        S5      nU SU 3$ )xHuman-readable representation.

Args:
    html: Whether to format as HTML.

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

)r,   r   r&   )r5   htmlvartitles       r8   pretty_reprMessagesPlaceholder.pretty_repr   sQ     D&&&,&'=DIE"31C&'=>ESE""r:   r2   )r,   r+   r.   r-   r6   r	   returnNoner6   r	   rW   zlist[BaseMessage]rW   	list[str]FrR   r-   rW   r+   )__name__
__module____qualname____firstlineno____doc____annotations__r.   r/   r4   rC   propertyrH   r   rU   __static_attributes____classcell__r7   s   @r8   r)   r)   4   s    FP .Hd: &*J") 7<S S/3SGJS	S S8 A A # #r:   r)   MessagePromptTemplateTBaseStringMessagePromptTemplate)boundc                      \ rS rSr% SrS\S'    \" \S9rS\S'    \	  S         SS	 jj5       r
\	      SS
 j5       r\SS j5       rSS jrSS jrSS jr\SS j5       r\SSS jj5       rSrg)ri      zJBase class for message prompt templates that use a string prompt template.r$   promptdefault_factorydictadditional_kwargsNc                B    [         R                  " UUUS9nU " SSU0UD6$ )a  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_variablesrm   r2   )r"   from_template)clstemplatert   ru   r6   rm   s         r8   rv   -BaseStringMessagePromptTemplate.from_template   s2    0  --+/

 +&+F++r:   c                B    [         R                  " U5      nU " SSU0UD6$ )zCreate 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.
rm   r2   )r"   	from_file)rw   template_filer6   rm   s       r8   from_template_file2BaseStringMessagePromptTemplate.from_template_file   s'      ))-8+&+F++r:   c                    g){Format the prompt template.

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

Returns:
    Formatted message.
Nr2   r5   r6   s     r8   format&BaseStringMessagePromptTemplate.format      r:   c                .   #    U R                   " S0 UD6$ 7f)Async format the prompt template.

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

Returns:
    Formatted message.
r2   r   r   s     r8   aformat'BaseStringMessagePromptTemplate.aformat  s      {{$V$$   c                (    U R                   " S0 UD6/$ zFormat messages from kwargs.

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

Returns:
    List of BaseMessages.
r2   r   r   s     r8   rC   /BaseStringMessagePromptTemplate.format_messages%       %f%&&r:   c                D   #    U R                   " S0 UD6I Sh  vN /$  N7fzAsync format messages from kwargs.

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

Returns:
    List of BaseMessages.
Nr2   r   r   s     r8   aformat_messages0BaseStringMessagePromptTemplate.aformat_messages0  "      ll,V,,--,     c                .    U R                   R                  $ rF   )rm   rH   rG   s    r8   rH   /BaseStringMessagePromptTemplate.input_variables;  s     {{***r:   c                    U R                   R                  R                  SS5      n[        X!S9nU SU R                  R                  US9 3$ )rK   MessagePromptTemplate MessagerN   rQ   rR   )r7   r^   replacer   rm   rU   )r5   rR   rT   s      r8   rU   +BaseStringMessagePromptTemplate.pretty_reprD  sO     ''//0GT"54T[[44$4?@AAr:   r2   )f-stringN)
rx   r+   rt   r#   ru   dict[str, Any] | Noner6   r	   rW   r   )r|   
str | Pathr6   r	   rW   r   r6   r	   rW   r   rY   rZ   r\   r]   )r^   r_   r`   ra   rb   rc   r   rp   rq   classmethodrv   r}   r   r   r   rC   r   rd   rH   r   rU   re   r2   r:   r8   ri   ri      s    T  !#D9t9F 1;37	,, ., 1	,
 , 
, ,< ,!, , 
	, ,"  	%	'	. + + B Br:   c                  :    \ rS rSr% SrS\S'    S	S jrS	S jrSrg)
ChatMessagePromptTemplateiT  zChat message prompt template.r+   rolec                v    U R                   R                  " S0 UD6n[        X R                  U R                  S9$ )r   contentr   rq   r2   )rm   r   r   r   rq   r5   r6   texts      r8   r    ChatMessagePromptTemplate.formatZ  s7     {{!!+F+yyD<R<R
 	
r:   c                   #    U R                   R                  " S0 UD6I Sh  vN n[        X R                  U R                  S9$  N"7f)r   Nr   r2   )rm   r   r   r   rq   r   s      r8   r   !ChatMessagePromptTemplate.aformath  sB      [[((2622yyD<R<R
 	
 3s    AA#Ar2   Nr   )	r^   r_   r`   ra   rb   rc   r   r   re   r2   r:   r8   r   r   T  s    '
I

r:   r   c                       \ rS rSr% S\S'   Srg)_TextTemplateParamiw  
str | dictr   r2   Nr^   r_   r`   ra   rc   re   r2   r:   r8   r   r   w  s    
r:   r   F)totalc                       \ rS rSr% S\S'   Srg)_ImageTemplateParami{  r   	image_urlr2   Nr   r2   r:   r8   r   r   {  s    r:   r   c                      \ rS rSr% SrS\S'    \" \S9rS\S'    S\S	'   \	 SS
S.           SS jjj5       r
\	          SS j5       rSS jrSS jr\SS j5       rSS jrSS jr\SSS jj5       rSrg
)!_StringImageMessagePromptTemplatei  DHuman message prompt template. This is a message sent from the user.z\StringPromptTemplate | list[StringPromptTemplate | ImagePromptTemplate | DictPromptTemplate]rm   rn   rp   rq   type[BaseMessage]
_msg_classN)ru   c               f   [        U[        5      (       a   [        R                  " UUUS9nU " SSU0UD6$ [        U[        5      (       GaW  Ub  [        U5      S:  a  Sn[        U5      e/ nU GH%  n[        U[        5      (       d:  [        U[        5      (       aq  SU;   ak  [        UR                  5       5      SS1::  aL  [        U[        5      (       a  UnO[        SU5      S   nUR                  [        R                  " XS95        M  [        U[        5      (       Ga  S	U;   Ga  [        UR                  5       5      SS	1::  a  [        S
U5      S	   n	/ n
[        U	[        5      (       aJ  [        X5      nU(       a(  [        U5      S:  a  SU SU 3n[        U5      eUS   /n
SU	0n	[        U
U	US9nOi[        U	[        5      (       aD  [        U	5      n	S H'  nX;   d  M
  U
R                  [        X   U5      5        M)     [        U
U	US9nOSU 3n[        U5      eUR                  U5        GM  [        U[        5      (       a;  US:X  a  Sn[        U5      e[        [        SU5      US9nUR                  U5        GM  SU 3n[        U5      e   U " SSU0UD6$ SU 3n[        U5      e)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.
rs   rm   r   z:Partial variables are not supported for list of templates.r   r?   r   rt   r   r      z:Only one format variable allowed per image template.
Got: z
From: url)rH   rx   rt   )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])rx   rt   zInvalid template: r2   )r=   r+   r"   rv   r>   lenr@   rp   setkeysr   appendr%   r    extendr   )rw   rx   rt   ru   r6   rm   rB   tmplr   img_templaterH   	variablesimg_template_objkeydata_template_objs                  r8   rv   /_StringImageMessagePromptTemplate.from_template  s   4 h$$2@2N2N /"33F
 /f///h%%!-37H3IA3MR o%F dC((tT**$DIIK(VV,<<!$,,$(#$8$?GMM&44  tT**#t+DIIK(# $((=t#D[#QL&(O!,44$:(%	 %"9~1%88A{&.tf%6 !$
 '1o 5/8|nO(-|'<+>,;%1,;,(
 $L$77'+L'9#<C"2 / 6 6$:(4(9?%&!" $= ,?,;%1,;,( !9?(o-MM"23d++&(2& 
 )o-(:!%&6!=(7)% MM"34.tf5C$S/)] !^ /f///"8*-or:   c                \    [        U5      R                  SS9nU R                  " U4SU0UD6$ )zCreate 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)encodingrH   )r   	read_textrv   )rw   r|   rH   r6   rx   s        r8   r}   4_StringImageMessagePromptTemplate.from_template_file  s7    " &00'0B  U?UfUUr:   c                (    U R                   " S0 UD6/$ r   r   r   s     r8   rC   1_StringImageMessagePromptTemplate.format_messages  r   r:   c                D   #    U R                   " S0 UD6I Sh  vN /$  N7fr   r   r   s     r8   r   2_StringImageMessagePromptTemplate.aformat_messages$  r   r   c                    [        U R                  [        5      (       a  U R                  OU R                  /nU VVs/ s H  o"R                    H  o3PM     M     snn$ s  snnf rF   )r=   rm   r>   rH   )r5   promptsrm   ivs       r8   rH   1_StringImageMessagePromptTemplate.input_variables/  sJ     ",DKK!>!>$++T[[M!(Jv3I3IR3IJJJs   A c                   [        U R                  [        5      (       a5  U R                  R                  " S0 UD6nU R	                  X R
                  S9$ / nU R                   H  nUR                   Vs0 s H  oUX   _M	     nn[        U[        5      (       a0  UR                  " S0 UD6nUS:w  a  UR                  SUS.5        Md  Mf  [        U[        5      (       a(  UR                  " S0 UD6nUR                  SUS.5        M  [        U[        5      (       d  M  UR                  " S0 UD6n	UR                  U	5        M     U R	                  X0R
                  S9$ s  snf )r   r   rq    r   r?   r   r   r?   r   r2   )
r=   rm   r$   r   r   rq   rH   r   r    r   
r5   r6   r   r   rm   rS   inputsformatted_textformatted_imageformatted_dicts
             r8   r   (_StringImageMessagePromptTemplate.format9  sA    dkk#788;;%%//D??0F0F #   kkF282H2HI2H36;&2HFI&"677&,mm&=f&=!R'NNFN#KL (F$788,2MM,CF,C/RSF$677171H1H~. " /E/E  
 	
 Js   4Ec                
  #    [        U R                  [        5      (       a=  U R                  R                  " S0 UD6I Sh  vN nU R	                  X R
                  S9$ / nU R                   H  nUR                   Vs0 s H  oUX   _M	     nn[        U[        5      (       a8  UR                  " S0 UD6I Sh  vN nUS:w  a  UR                  SUS.5        Ml  Mn  [        U[        5      (       a0  UR                  " S0 UD6I Sh  vN nUR                  SUS.5        M  [        U[        5      (       d  M  UR                  " S0 UD6n	UR                  U	5        M     U R	                  X0R
                  S9$  GN6s  snf  N N{7f)	r   Nr   r   r   r   r   r   r2   )r=   rm   r$   r   r   rq   rH   r   r    r   r   r   s
             r8   r   )_StringImageMessagePromptTemplate.aformatX  s[     dkk#788,,6v66D??0F0F #   kkF282H2HI2H36;&2HFI&"677,2NN,DV,D&D!R'NNFN#KL (F$78828..2J62J,J/RSF$677171H1H~. " /E/E  
 	
# 7 J&D -KsI   ?FE7<F>E:,F8E?9AFF-F7AF:FFc                  ^ U R                   R                  R                  SS5      n[        UTS9n[	        U R
                  [        5      (       a  U R
                  OU R
                  /nSR                  U4S jU 5       5      nU SU 3$ )rK   r   r   rN   rQ   c              3  @   >#    U  H  oR                  TS 9v   M     g7fr   NrU   ).0rm   rR   s     r8   	<genexpr>@_StringImageMessagePromptTemplate.pretty_repr.<locals>.<genexpr>  s     "WwV#5#54#5#@w   )r7   r^   r   r   r=   rm   r>   join)r5   rR   rT   r   prompt_reprss    `   r8   rU   -_StringImageMessagePromptTemplate.pretty_reprw  st     ''//0GT"5t4!+DKK!>!>$++T[[M{{"Ww"WW\N++r:   r2   r   )rw   
type[Self]rx   zKstr | list[str | _TextTemplateParam | _ImageTemplateParam | dict[str, Any]]rt   r#   ru   r   r6   r	   rW   r   )
rw   r   r|   r   rH   r[   r6   r	   rW   r   rY   rZ   r   r\   r]   )r^   r_   r`   ra   rb   rc   r   rp   rq   r   rv   r}   rC   r   rd   rH   r   r   r   rU   re   r2   r:   r8   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
>
> , ,r:   r   c                  (    \ rS rSr% Sr\rS\S'   Srg)HumanMessagePromptTemplatei  r   r   r   r2   N)	r^   r_   r`   ra   rb   r   r   rc   re   r2   r:   r8   r   r     s    N$0J!0r:   r   c                  (    \ rS rSr% Sr\rS\S'   Srg)AIMessagePromptTemplatei  z?AI message prompt template. This is a message sent from the AI.r   r   r2   N)	r^   r_   r`   ra   rb   r   r   rc   re   r2   r:   r8   r   r     s    I$-J!-r:   r   c                  (    \ rS rSr% Sr\rS\S'   Srg)SystemMessagePromptTemplatei  zQSystem message prompt template.

This is a message that is not sent to the user.
r   r   r2   N)	r^   r_   r`   ra   rb   r   r   rc   re   r2   r:   r8   r   r     s    
 %2J!1r:   r   c                      \ rS rSrSr\\SS j5       5       rSS jrSS jr	SS jr
SS jr\SS j5       rSS	 jr S   SS
 jjrSS jrSrg)BaseChatPromptTemplatei  z%Base class for chat prompt templates.c                    SU R                   0$ )NrH   )rH   rG   s    r8   lc_attributes$BaseChatPromptTemplate.lc_attributes  s     "4#7#788r:   c                B    U R                   " S0 UD6R                  5       $ )zFormat 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.
r2   )format_prompt	to_stringr   s     r8   r   BaseChatPromptTemplate.format  s!     !!+F+5577r:   c                ^   #    U R                   " S0 UD6I Sh  vN R                  5       $  N7f)zAsync 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.
Nr2   )aformat_promptr  r   s     r8   r   BaseChatPromptTemplate.aformat  s*      ))3F33>>@@3s   -+-c                8    U R                   " S0 UD6n[        US9$ )zFormat prompt. Should return a ChatPromptValue.

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

Returns:
    ChatPromptValue.
messagesr2   )rC   r   r5   r6   r  s      r8   r   $BaseChatPromptTemplate.format_prompt  s"     ''1&111r:   c                T   #    U R                   " S0 UD6I Sh  vN n[        US9$  N7f)zAsync format prompt. Should return a ChatPromptValue.

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

Returns:
    PromptValue.
Nr  r2   )r   r   r	  s      r8   r  %BaseChatPromptTemplate.aformat_prompt  s-      ..88811 9s   (&(c                    g)zGFormat kwargs into a list of messages.

Returns:
    List of messages.
Nr2   r   s     r8   rC   &BaseChatPromptTemplate.format_messages  r   r:   c                .   #    U R                   " S0 UD6$ 7f)zMAsync format kwargs into a list of messages.

Returns:
    List of messages.
r2   )rC   r   s     r8   r   'BaseChatPromptTemplate.aformat_messages  s      ##-f--r   c                    [         e)rK   NotImplementedErrorr5   rR   s     r8   rU   "BaseChatPromptTemplate.pretty_repr  s
     "!r:   c                D    [        U R                  [        5       S95        g)z&Print a human-readable representation.r   N)printrU   r'   rG   s    r8   pretty_print#BaseChatPromptTemplate.pretty_print  s    d$6$89:r:   r2   N)rW   rp   )r6   r	   rW   r+   )r6   r	   rW   r   rY   r\   r]   )rW   rX   )r^   r_   r`   ra   rb   rd   r   r   r   r   r   r  r   rC   r   rU   r  re   r2   r:   r8   r   r     sn    /9  9
8
A
2
2  . "" 
";r:   r   c                    ^  \ rS rSr% SrS\S'    SrS\S'    SS	.       SU 4S
 jjjr\S S j5       r	S!S jr
\" SS9\S"S j5       5       r\S#S j5       r\ S$     S%S jj5       rS&S jrS&S jrS'S jrS(S jrS)S jr\S*S j5       r\S+S j5       rS,S jrS-S jr\S.S j5       rS/S jr\S0S1S jj5       rSrU =r$ )2ChatPromptTemplatei  a  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                 > U Vs/ s H  n[        XB5      PM     nn[        5       n[        5       n0 nU H  n	[        U	[        5      (       a<  U	R                  (       a+  / XR
                  '   UR                  U	R
                  5        MT  [        U	[        [        45      (       d  Mq  UR                  U	R                  5        M     [        U5      [        U5      US.UEn[        S[        5       5      R                  " SSU0UD6  gs  snf )a  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?"),
        ]
    )
    ```
)rH   optional_variablesru   ztype[ChatPromptTemplate]r  Nr2   )_convert_to_message_templater   r=   r)   r.   r,   addr   r!   updaterH   sortedr   r3   r4   )r5   r  rt   r6   message	messages_
input_varsr  partial_vars_messager7   s             r8   r4   ChatPromptTemplate.__init__q  s   N $
# )B# 	 
  #u
'*u')!H($788X=N=N79334"&&x'='=>13LM  !!(":":; "  &j1"();"<!-
 	
 	'1::XIXQWX1
s   Dc                
    / SQ$ )z\Get the namespace of the LangChain object.

Returns:
    `["langchain", "prompts", "chat"]`
)	langchainr   chatr2   )rw   s    r8   get_lc_namespace#ChatPromptTemplate.get_lc_namespace  s
     0/r:   c                D   0 U R                   En[        US5      (       a,  UR                   (       a  UR                  UR                   5        [        U[        5      (       a0  [	        U R
                  UR
                  -   S9R                  " S0 UD6$ [        U[        [        [        45      (       a'  [	        / U R
                  QUPS9R                  " S0 UD6$ [        U[        [        45      (       aE  [        R                  U5      n[	        U R
                  UR
                  -   S9R                  " S0 UD6$ [        U[        5      (       a<  [        R                  U5      n[	        / U R
                  QUPS9R                  " S0 UD6$ S[!        U5       3n[#        U5      e)zqCombine two prompt templates.

Args:
    other: Another prompt template.

Returns:
    Combined prompt template.
ru   r  z Unsupported operand type for +: r2   )ru   hasattrr!  r=   r  r  partialr!   r   r   r>   tuplefrom_messagesr+   r   rv   r?   r  )r5   otherpartialsother_rm   rB   s         r8   __add__ChatPromptTemplate.__add__  s    .d,,- 5-..53J3JOOE334 e/00%t}}u~~/MNVV   -{<RS
 
 &/F/F/FGOO   edE]++'55e<F%t}}v/NOWW   eS!!/==eDF%/G/G/GHPP   1e>!#&&r:   before)modec                2   US   n[        5       n[        5       nUR                  S0 5      nU H  n[        U[        [        45      (       a  UR                  UR                  5        [        U[        5      (       d  MP  SU;  a  0 US'   UR                  (       a@  UR                  US   ;  a-  / US   UR                  '   UR                  UR                  5        UR                  U;  d  M  [        [           XVR                  '   M     SU;   a  U[        US   5      -  nU(       a  X4-  nSU;   a?  UR                  S5      (       a)  U[        US   5      :w  a  SU SUS    3n[        U5      eO[        U5      US'   U(       a  [        U5      US'   XQS'   U$ )	zValidate 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_typesru   rH   r  z*Got mismatched input_variables. Expected: z. Got: r  )r   r<   r=   r!   r   r!  rH   r)   r.   r,   r   r>   r   r@   r"  )rw   valuesr  r%  r  r;  r#  rB   s           r8   validate_input_variables+ChatPromptTemplate.validate_input_variables  s   " *%%
 U&,jj&CG'$=?U#VWW!!'"9"9:'#677&f424F./$$--V<O5PPIKF./0E0EF&**7+@+@A((;9=j9IK 5 56   &(#f%89::J,J&6::6I+J+JS(9!:;;!!+ -"#4568 
 !o% < )/z(:F$%+12D+EF'( +}r:   c                f    [         R                  " U40 UD6n[        US9nU R                  U/5      $ )a  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.
rm   )r"   rv   r   r2  )rw   rx   r6   prompt_templater#  s        r8   rv    ChatPromptTemplate.from_template7  s6     )66xJ6J,OD  '++r:   c                    U " XS9$ )aa  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   r2   )rw   r  rt   s      r8   r2   ChatPromptTemplate.from_messagesI  s    b 8==r:   c                B   U R                   " S0 UD6n/ nU R                   Hz  n[        U[        5      (       a  UR	                  U/5        M,  [        U[
        [        45      (       a%  UR                  " S0 UD6nUR	                  U5        Ml  SU 3n[        U5      e   U$ )a0  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: r2   )	!_merge_partial_and_user_variablesr  r=   r   r   r!   r   rC   r@   r5   r6   resultmessage_templater#  rB   s         r8   rC   "ChatPromptTemplate.format_messages|  s     77A&A $*K88/01 #<>T"U  +::DVDg&*+;*<= o% !. r:   c                ^  #    U R                   " S0 UD6n/ nU R                   H  n[        U[        5      (       a  UR	                  U/5        M,  [        U[
        [        45      (       a-  UR                  " S0 UD6I Sh  vN nUR	                  U5        Mt  SU 3n[        U5      e   U$  N+7f)a&  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.
NrF  r2   )	rG  r  r=   r   r   r!   r   r   r@   rH  s         r8   r   #ChatPromptTemplate.aformat_messages  s      77A&A $*K88/01 #<>T"U  !1 A A KF KKg&*+;*<= o% !.  Ls   A=B-?B+ ,B-c                    U R                   R                  5       n[        [        U R                  5      R                  U5      5      US'   0 U R                  EUEUS'   [        U 5      " S0 UD6$ )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:
    ```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")
    ```
rH   ru   r2   )__dict__copyr>   r   rH   
differenceru   r?   )r5   r6   prompt_dicts      r8   r0  ChatPromptTemplate.partial  so    8 mm((*)-$$%008*
%& ,Pd.D.D+O+O'(Dz(K((r:   c                L    U R                   R                  [        U5      5        g)zmAppend a message to the end of the chat template.

Args:
    message: representation of a message to append.
N)r  r   r  )r5   r#  s     r8   r   ChatPromptTemplate.append  s     	9'BCr:   c                x    U R                   R                  U Vs/ s H  n[        U5      PM     sn5        gs  snf )zzExtend the chat template with a sequence of messages.

Args:
    messages: Sequence of message representations to append.
N)r  r   r  )r5   r  r#  s      r8   r   ChatPromptTemplate.extend  s1     	BJK(w)'2(K	
Ks   7c                    g Nr2   r5   indexs     r8   __getitem__ChatPromptTemplate.__getitem__  s    69r:   c                    g rY  r2   rZ  s     r8   r\  r]    s    ?Br:   c                    [        U[        5      (       aM  UR                  [        U R                  5      5      u  p#nU R                  X#U2   n[
        R                  U5      $ U R                  U   $ )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  r2  )r5   r[  startstopstepr  s         r8   r\  r]    s_     eU## %c$--.@ AE}}U_5H%33H==}}U##r:   c                ,    [        U R                  5      $ )z'Return the length of the chat template.)r   r  rG   s    r8   __len__ChatPromptTemplate.__len__  s    4==!!r:   c                    g)z,Name of prompt type. Used for serialization.r+  r2   rG   s    r8   _prompt_typeChatPromptTemplate._prompt_type  s     r:   c                    [         e)z9Save prompt to file.

Args:
    file_path: path to file.
r  )r5   	file_paths     r8   saveChatPromptTemplate.save  s
     "!r:   c                N   ^ SR                  U4S jU R                   5       5      $ )rK   rQ   c              3  @   >#    U  H  oR                  TS 9v   M     g7fr   r   )r   rB   rR   s     r8   r   1ChatPromptTemplate.pretty_repr.<locals>.<genexpr>  s     O#???5r   )r   r  r  s    `r8   rU   ChatPromptTemplate.pretty_repr  s     {{OOOOr:   r2   )r  #Sequence[MessageLikeRepresentation]rt   r#   r6   r	   rW   rX   rZ   )r3  r	   rW   r  )r<  rp   rW   r	   )rx   r+   r6   r	   rW   r  r   )r  rs  rt   r#   rW   r  rY   )r6   r	   rW   r  )r#  MessageLikeRepresentationrW   rX   )r  rs  rW   rX   )r[  intrW   MessageLike)r[  r`  rW   r  )r[  zint | slicerW   z MessageLike | ChatPromptTemplate)rW   ru  )rW   r+   )rl  z
Path | strrW   rX   r\   r]   )r^   r_   r`   ra   rb   rc   r  r4   r   r,  r6  r   r=  rv   r2  rC   r   r0  r   r   r   r\  rf  rd   ri  rm  r   rU   re   rf   rg   s   @r8   r  r    s]   fP =<U#t#8 1;	]Y5]Y .	]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r:   r  c                   U S;   a  [         R                  XS9nU$ U S;   a   [        R                  [        SU5      US9nU$ U S:X  a   [        R                  [        SU5      US9nU$ U S:X  a  [        U[        5      (       a4  US   S:w  d	  US	   S
:w  a  SU S3n[        U5      eUSS	 n[        USS9nU$  Uu  pg[        U[        5      (       d  SU 3n[        U5      e[        U[        5      (       d  SU 3n[        U5      eUS   S:w  d	  US	   S
:w  a  SU S3n[        U5      eUSS	 n[        XWS9n U$ SU  S3n[        U5      e! [         a  nSU 3n[        U5      UeSnAff = f)an  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   rL   rM   zInvalid placeholder template: z6. Expected a variable name surrounded by curly braces.r   Tr1   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   rv   r   r   r   r=   r+   r@   r)   r-   )	message_typerx   rt   r#  rB   var_namevar_name_wrappedis_optionales	            r8   "_create_template_from_message_typer    s   $ ((-G-U-U .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0CK=Q o%.4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                   [        U [        [        45      (       a  U nU$ [        U [        5      (       a  U nU$ [        U [        5      (       a  [        SXS9nU$ [        U [        [        45      (       a  [        U [        5      (       a:  [        U R                  5       5      SS1:w  a  SU  3n[        U5      eU S   nU S   nO#[        U 5      S:w  a  SU  3n[        U5      eU u  pE[        U[        5      (       a  [        XEUS9nU$ [        US5      (       a5  S	UR                  ;   a%  UR                  S	   R                  n[        XeUS9nU$ U" [        R                   " [#        S
U5      US9S9n U$ S[%        U 5       3n['        U5      e)al  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.
ry  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+   r  r1  rp   r   r   r@   r   r/  r  defaultr"   rv   r   r?   r  )r#  rt   message_rB   message_type_strrx   r  s          r8   r  r  i  s   2 '57MNOO 	^ OY 
G[	)	)V OU 
GS	!	!5W
R OM 
GeT]	+	+gt$$7<<>"y&&99$I'  !o%&vy)H7|q B7)L o%)0&&,,9 OH* O# $n55*777+88@HHL9H O (%33)?H O +4=/:!#&&r:   Nr   )r  r+   rx   z
str | listrt   r#   rW   r!   )r#  rt  rt   r#   rW   z@BaseMessage | BaseMessagePromptTemplate | BaseChatPromptTemplate)Nrb   
__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)   rh   ri   r   r   r   r   r   r   r   r   rv  r1  r+   r?   rp   objectrt  r  r  r  _convert_to_messager2   r:   r8   <module>r     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 r:   