a
    ”˜ëj¹Î  ã                	   @  sˆ  d Z ddlmZ ddlmZmZ ddlmZ ddlm	Z	m
Z
mZmZmZmZmZmZmZ ddlmZmZmZmZ ddlmZmZ ddlmZ dd	lmZmZmZm Z m!Z!m"Z"m#Z# dd
l$m%Z% ddl&m'Z'm(Z( ddl)m*Z* ddl+m,Z, ddl-m.Z. ddl/m0Z0 ddl1m2Z2 ddl3m4Z4m5Z5m6Z6 ddl7m8Z8 ddl9m:Z: e	�rFddl;m<Z< G dd„ de0ƒZ=eddd�Z>G dd„ de0eƒZ?G dd„ de?ƒZ@G dd„ dedd �ZAG d!d"„ d"edd �ZBG d#d$„ d$e0ƒZCG d%d&„ d&eCƒZDG d'd(„ d(eCƒZEG d)d*„ d*eCƒZFG d+d,„ d,e*eƒZGee0eeGf ZHeeHeIeeJeKf eeJeLeM eLeN f f eJeMeJef f ZOG d-d.„ d.eGƒZPd=d0d1d2d3d4œd5d6„ZQd>d7d2d8d9œd:d;„ZReRZSd<S )?zChat prompt template.é    )Úannotations)ÚABCÚabstractmethod)ÚPath)	ÚTYPE_CHECKINGÚ	AnnotatedÚAnyÚOptionalÚ	TypedDictÚTypeVarÚUnionÚcastÚoverload)ÚFieldÚPositiveIntÚSkipValidationÚmodel_validator)ÚSelfÚoverride)Ú
deprecated)Ú	AIMessageÚ
AnyMessageÚBaseMessageÚChatMessageÚHumanMessageÚSystemMessageÚconvert_to_messages)Úget_msg_title_repr)ÚChatPromptValueÚImageURL)ÚBasePromptTemplate)ÚDictPromptTemplate)ÚImagePromptTemplate)ÚBaseMessagePromptTemplate)ÚPromptTemplate)ÚPromptTemplateFormatÚStringPromptTemplateÚget_template_variables)Úget_colored_text)Úis_interactive_env)ÚSequencec                      sŒ   e Zd ZU dZded< dZded< dZded	< dd
œdddddœ‡ fdd„Zdddœdd„Ze	ddœdd„ƒZ
eddddœdd„ƒZ‡  ZS )ÚMessagesPlaceholderaï  Prompt template that assumes variable is already list of messages.

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

    Direct usage:

        .. code-block:: python

            from langchain_core.prompts import MessagesPlaceholder

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

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

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

    Building a prompt with chat history:

        .. code-block:: python

            from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder

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

    Limiting the number of messages:

        .. code-block:: python

            from langchain_core.prompts import MessagesPlaceholder

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

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

    ÚstrÚvariable_nameFÚboolÚoptionalNzOptional[PositiveInt]Ú
n_messages)r/   r   ÚNone)r-   r/   ÚkwargsÚreturnc                  s   t ƒ jf ||dœ|¤Ž dS )a—  Create a messages placeholder.

        Args:
            variable_name: Name of variable to use as messages.
            optional: If True format_messages can be called with no arguments and will
                return an empty list. If False then a named argument with name
                `variable_name` must be passed in, even if the value is an empty list.
                Defaults to False.]
        ©r-   r/   N)ÚsuperÚ__init__)Úselfr-   r/   r2   ©Ú	__class__© úZ/mnt/bigstor/www/usecases/.venv/lib/python3.9/site-packages/langchain_core/prompts/chat.pyr6   �   s    zMessagesPlaceholder.__init__úlist[BaseMessage]©r2   r3   c                 K  sn   | j r| | jg ¡n|| j }t|tƒsLd| j› d|› dt|ƒ› �}t|ƒ‚t|ƒ}| jrj|| j d… }|S )zöFormat 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   r0   )r7   r2   ÚvalueÚmsgr:   r:   r;   Úformat_messages    s     ÿý

ÿÿÿz#MessagesPlaceholder.format_messagesú	list[str]©r3   c                 C  s   | j s| jgS g S ©únInput variables for this prompt template.

        Returns:
            List of input variable names.
        )r/   r-   ©r7   r:   r:   r;   Úinput_variables¼   s    z#MessagesPlaceholder.input_variables©Úhtmlr3   c                 C  s@   d| j  d }|r*tddd�}t|dƒ}ntdƒ}|› d|› �S )ú³Human-readable representation.

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

        Returns:
            Human-readable representation.
        Ú{Ú}zMessages PlaceholderT©ZboldZyellowú

)r-   r   r(   )r7   rM   ÚvarÚtitler:   r:   r;   Úpretty_reprÅ   s    
zMessagesPlaceholder.pretty_repr)F)Ú__name__Ú
__module__Ú__qualname__Ú__doc__Ú__annotations__r/   r0   r6   rE   ÚpropertyrK   r   rU   Ú__classcell__r:   r:   r8   r;   r+   :   s   
Iÿr+   ÚMessagePromptTemplateTÚBaseStringMessagePromptTemplate)Úboundc                   @  sÌ   e Zd ZU dZded< eed�Zded< ed)d	d
ddddœdd„ƒZ	edddddœdd„ƒZ
edddœdd„ƒZdddœdd„Zdddœdd„Zdddœdd „Zedd!œd"d#„ƒZed*d%d	d&œd'd(„ƒZdS )+r^   zJBase class for message prompt templates that use a string prompt template.r&   Úprompt©Údefault_factoryÚdictÚadditional_kwargsúf-stringNr,   r%   úOptional[dict[str, Any]]r   r   )ÚtemplateÚtemplate_formatÚpartial_variablesr2   r3   c                 K  s"   t j|||d�}| f d|i|¤ŽS )aæ  Create a class from a string template.

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

        Returns:
            A new instance of this class.
        ©rh   ri   r`   )r$   Úfrom_template)Úclsrg   rh   ri   r2   r`   r:   r:   r;   rk   æ   s    ýz-BaseStringMessagePromptTemplate.from_templateúUnion[str, Path]rF   )Útemplate_filerK   r2   r3   c                 K  s   t  |¡}| f d|i|¤ŽS )á6  Create a class from a template file.

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

        Returns:
            A new instance of this class.
        r`   )r$   Ú	from_file)rl   rn   rK   r2   r`   r:   r:   r;   Úfrom_template_file  s    
z2BaseStringMessagePromptTemplate.from_template_filer   r=   c                 K  s   dS )ú£Format the prompt template.

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

        Returns:
            Formatted message.
        Nr:   ©r7   r2   r:   r:   r;   Úformat  s    z&BaseStringMessagePromptTemplate.formatc                 Ë  s   | j f i |¤ŽS )ú©Async format the prompt template.

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

        Returns:
            Formatted message.
        ©rt   rs   r:   r:   r;   Úaformat$  s    	z'BaseStringMessagePromptTemplate.aformatr<   c                 K  s   | j f i |¤ŽgS ©z§Format messages from kwargs.

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

        Returns:
            List of BaseMessages.
        rv   rs   r:   r:   r;   rE   /  s    	z/BaseStringMessagePromptTemplate.format_messagesc                 Ë  s   | j f i |¤ŽI dH gS ©z­Async format messages from kwargs.

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

        Returns:
            List of BaseMessages.
        N©rw   rs   r:   r:   r;   Úaformat_messages:  s    	z0BaseStringMessagePromptTemplate.aformat_messagesrG   c                 C  s   | j jS rH   )r`   rK   rJ   r:   r:   r;   rK   E  s    z/BaseStringMessagePromptTemplate.input_variablesFr.   rL   c                 C  s4   | j j dd¡}t||d�}|› d| jj|d�› �S )rN   ÚMessagePromptTemplateú MessagerQ   rR   ©rM   )r9   rV   Úreplacer   r`   rU   )r7   rM   rT   r:   r:   r;   rU   N  s    z+BaseStringMessagePromptTemplate.pretty_repr)re   N)F)rV   rW   rX   rY   rZ   r   rc   rd   Úclassmethodrk   rq   r   rt   rw   rE   r{   r[   rK   r   rU   r:   r:   r:   r;   r^   Þ   s$   
  ü
c                   @  s:   e Zd ZU dZded< dddœdd„Zdddœd	d
„ZdS )ÚChatMessagePromptTemplatezChat message prompt template.r,   Úroler   r   r=   c                 K  s$   | j jf i |¤Ž}t|| j| jd�S )rr   ©Úcontentr‚   rd   )r`   rt   r   r‚   rd   ©r7   r2   Útextr:   r:   r;   rt   d  s    	
ÿz ChatMessagePromptTemplate.formatc                 Ë  s*   | j jf i |¤ŽI dH }t|| j| jd�S )ru   Nrƒ   )r`   rw   r   r‚   rd   r…   r:   r:   r;   rw   r  s    	
ÿz!ChatMessagePromptTemplate.aformatN)rV   rW   rX   rY   rZ   rt   rw   r:   r:   r:   r;   r�   ^  s   
r�   c                   @  s   e Zd ZU ded< dS )Ú_TextTemplateParamúUnion[str, dict]r†   N©rV   rW   rX   rZ   r:   r:   r:   r;   r‡   �  s   
r‡   F)Útotalc                   @  s   e Zd ZU ded< dS )Ú_ImageTemplateParamrˆ   Ú	image_urlNr‰   r:   r:   r:   r;   r‹   …  s   
r‹   c                
   @  sÚ   e Zd ZU dZded< eed�Zded< ded< ed.d
dœdddddddœdd„ƒZ	eddddddœdd„ƒZ
dddœdd„Zdddœdd„Zedd œd!d"„ƒZdd#dœd$d%„Zdd#dœd&d'„Zed/d)d*d+œd,d-„ƒZd
S )0Ú!_StringImageMessagePromptTemplateúDHuman message prompt template. This is a message sent from the user.zgUnion[StringPromptTemplate, list[Union[StringPromptTemplate, ImagePromptTemplate, DictPromptTemplate]]]r`   ra   rc   rd   útype[BaseMessage]Ú
_msg_classre   N)ri   z
type[Self]zUUnion[str, list[Union[str, _TextTemplateParam, _ImageTemplateParam, dict[str, Any]]]]r%   rf   r   r   )rl   rg   rh   ri   r2   r3   c                K  sT  t |tƒr,tj|||d�}| f d|i|¤ŽS t |tƒ�r>|durXt|ƒdkrXd}t|ƒ‚g }|D �]È}t |tƒs–t |tƒrÊd|v rÊt| 	¡ ƒddhkrÊt |tƒr¦|}nt
d|ƒd }| tj||d	�¡ q`t |tƒ�rØd
|v �rØt| 	¡ ƒdd
hk�rØt
d|ƒd
 }	g }
t |	tƒ�rlt|	|ƒ}|�rTt|ƒdk�rJd|› d|› �}t|ƒ‚|d g}
d|	i}	t|
|	|d�}n`t |	tƒ�rºt|	ƒ}	dD ]$}||	v �r„|
 t|	| |ƒ¡ �q„t|
|	|d�}nd|› �}t|ƒ‚| |¡ q`t |tƒ�r|dk�rúd}t|ƒ‚tt
d|ƒ|d�}| |¡ q`d|› �}t|ƒ‚q`| f d|i|¤ŽS d|› �}t|ƒ‚dS )aD  Create a class from a string template.

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

        Returns:
            A new instance of this class.

        Raises:
            ValueError: If the template is not a string or list of strings.
        rj   r`   Nr   z:Partial variables are not supported for list of templates.r†   rA   r‡   ©rh   rŒ   r‹   é   z:Only one format variable allowed per image template.
Got: z
From: Úurl)rK   rg   rh   )r“   ÚpathZdetailzInvalid image template: Zjinja2zsjinja2 is unsafe and is not supported for templates expressed as dicts. Please use 'f-string' or 'mustache' format.zdict[str, Any])rg   rh   zInvalid template: )r?   r,   r$   rk   r@   ÚlenrB   rc   ÚsetÚkeysr   Úappendr'   r"   Úextendr!   )rl   rg   rh   ri   r2   r`   rD   Útmplr†   Zimg_templaterK   Ú	variablesZimg_template_objÚkeyZdata_template_objr:   r:   r;   rk   –  s¸    
ý

ÿþý
ÿÿÿþ
þÿý	ÿÿþÿ
ý
ÿÿý

ÿþ


z/_StringImageMessagePromptTemplate.from_templaterm   rF   )rl   rn   rK   r2   r3   c                 K  s"   t |ƒ ¡ }| j|fd|i|¤ŽS )ro   rK   )r   Ú	read_textrk   )rl   rn   rK   r2   rg   r:   r:   r;   rq     s    z4_StringImageMessagePromptTemplate.from_template_filer<   r=   c                 K  s   | j f i |¤ŽgS rx   rv   rs   r:   r:   r;   rE   &  s    	z1_StringImageMessagePromptTemplate.format_messagesc                 Ë  s   | j f i |¤ŽI dH gS ry   rz   rs   r:   r:   r;   r{   1  s    	z2_StringImageMessagePromptTemplate.aformat_messagesrG   c                 C  s(   t | jtƒr| jn| jg}dd„ |D ƒS )rI   c                 S  s   g | ]}|j D ]}|‘qqS r:   ©rK   )Ú.0r`   Zivr:   r:   r;   Ú
<listcomp>D  ó    zE_StringImageMessagePromptTemplate.input_variables.<locals>.<listcomp>)r?   r`   r@   )r7   Úpromptsr:   r:   r;   rK   <  s    z1_StringImageMessagePromptTemplate.input_variablesr   c                   sÞ   t | jtƒr.| jjf i ˆ ¤Ž}| j|| jd�S g }| jD ]”}‡ fdd„|jD ƒ}t |tƒr||jf i |¤Ž}| d|dœ¡ q8t |tƒr¨|jf i |¤Ž}| d|dœ¡ q8t |t	ƒr8|jf i |¤Ž}| |¡ q8| j|| jd�S )rr   ©r„   rd   c                   s   i | ]}|ˆ | “qS r:   r:   ©rŸ   rS   ©r2   r:   r;   Ú
<dictcomp>V  r¡   z<_StringImageMessagePromptTemplate.format.<locals>.<dictcomp>r†   ©rA   r†   rŒ   ©rA   rŒ   )
r?   r`   r&   rt   r�   rd   rK   r˜   r"   r!   ©r7   r2   r†   r„   r`   ÚinputsÚ	formattedr:   r¥   r;   rt   F  s,    	ÿ

ÿ

ÿz(_StringImageMessagePromptTemplate.formatc                 ‹  sð   t | jtƒr4| jjf i ˆ ¤ŽI dH }| j|| jd�S g }| jD ] }‡ fdd„|jD ƒ}t |tƒrˆ|jf i |¤ŽI dH }| d|dœ¡ q>t |tƒrº|jf i |¤ŽI dH }| d|dœ¡ q>t |t	ƒr>|j
f i |¤Ž}| |¡ q>| j|| jd�S )	ru   Nr£   c                   s   i | ]}|ˆ | “qS r:   r:   r¤   r¥   r:   r;   r¦   v  r¡   z=_StringImageMessagePromptTemplate.aformat.<locals>.<dictcomp>r†   r§   rŒ   r¨   )r?   r`   r&   rw   r�   rd   rK   r˜   r"   r!   rt   r©   r:   r¥   r;   rw   f  s,    	ÿ

ÿ

ÿz)_StringImageMessagePromptTemplate.aformatFr.   r,   rL   c                   s\   | j j dd¡}t|ˆ d�}t| jtƒr.| jn| jg}d ‡ fdd„|D ƒ¡}|› d|› �S )rN   r|   r}   rQ   rR   c                 3  s   | ]}|j ˆ d �V  qdS ©r~   N©rU   )rŸ   r`   r~   r:   r;   Ú	<genexpr>”  r¡   z@_StringImageMessagePromptTemplate.pretty_repr.<locals>.<genexpr>)r9   rV   r   r   r?   r`   r@   Újoin)r7   rM   rT   r¢   Zprompt_reprsr:   r~   r;   rU   †  s
    z-_StringImageMessagePromptTemplate.pretty_repr)re   )F)rV   rW   rX   rY   rZ   r   rc   rd   r€   rk   rq   rE   r{   r[   rK   rt   rw   r   rU   r:   r:   r:   r;   r�   ‰  s&   
 úøz	  r�   c                   @  s   e Zd ZU dZeZded< dS )ÚHumanMessagePromptTemplaterŽ   r�   r�   N)rV   rW   rX   rY   r   r�   rZ   r:   r:   r:   r;   r°   ˜  s   
r°   c                   @  s   e Zd ZU dZeZded< dS )ÚAIMessagePromptTemplatez?AI message prompt template. This is a message sent from the AI.r�   r�   N)rV   rW   rX   rY   r   r�   rZ   r:   r:   r:   r;   r±   ž  s   
r±   c                   @  s   e Zd ZU dZeZded< dS )ÚSystemMessagePromptTemplatezYSystem message prompt template.

    This is a message that is not sent to the user.
    r�   r�   N)rV   rW   rX   rY   r   r�   rZ   r:   r:   r:   r;   r²   ¤  s   
r²   c                   @  sª   e Zd ZdZeeddœdd„ƒƒZdddœd	d
„Zdddœdd„Zdddœdd„Z	dddœdd„Z
edddœdd„ƒZdddœdd„Zd dddœdd„Zddœdd„ZdS )!ÚBaseChatPromptTemplatez%Base class for chat prompt templates.rc   rG   c                 C  s
   d| j iS )NrK   rž   rJ   r:   r:   r;   Úlc_attributes°  s    z$BaseChatPromptTemplate.lc_attributesr   r,   r=   c                 K  s   | j f i |¤Ž ¡ S )a
  Format the chat template into a string.

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

        Returns:
            formatted string.
        )Úformat_promptÚ	to_stringrs   r:   r:   r;   rt   µ  s    
zBaseChatPromptTemplate.formatc                 Ë  s   | j f i |¤ŽI dH  ¡ S )a  Async format the chat template into a string.

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

        Returns:
            formatted string.
        N)Úaformat_promptr¶   rs   r:   r:   r;   rw   Á  s    
zBaseChatPromptTemplate.aformatr   c                 K  s   | j f i |¤Ž}t|d�S )zµFormat prompt. Should return a ChatPromptValue.

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

        Returns:
            ChatPromptValue.
        ©Úmessages)rE   r   ©r7   r2   r¹   r:   r:   r;   rµ   Í  s    	z$BaseChatPromptTemplate.format_promptc                 Ë  s    | j f i |¤ŽI dH }t|d�S )z·Async format prompt. Should return a ChatPromptValue.

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

        Returns:
            PromptValue.
        Nr¸   )r{   r   rº   r:   r:   r;   r·   Ù  s    	z%BaseChatPromptTemplate.aformat_promptr<   c                 K  s   dS )z_Format kwargs into a list of messages.

        Returns:
            List of messages.
        Nr:   rs   r:   r:   r;   rE   å  s    z&BaseChatPromptTemplate.format_messagesc                 Ë  s   | j f i |¤ŽS )zeAsync format kwargs into a list of messages.

        Returns:
            List of messages.
        )rE   rs   r:   r:   r;   r{   í  s    z'BaseChatPromptTemplate.aformat_messagesFr.   rL   c                 C  s   t ‚dS )rN   N©ÚNotImplementedError©r7   rM   r:   r:   r;   rU   õ  s    z"BaseChatPromptTemplate.pretty_reprr1   c                 C  s   t | jtƒ d�ƒ dS )z&Print a human-readable representation.r~   N)ÚprintrU   r)   rJ   r:   r:   r;   Úpretty_print  s    z#BaseChatPromptTemplate.pretty_printN)F)rV   rW   rX   rY   r[   r   r´   rt   rw   rµ   r·   r   rE   r{   rU   r¿   r:   r:   r:   r;   r³   ­  s   
 þr³   c                      sÖ  e Zd ZU dZded< dZded< ddœd	d
dddœ‡ fdd„Zeddœdd„ƒZdd dœdd„Z	e
dd�edddœdd„ƒƒZeddd dœdd „ƒZeed!d"d#d$�d%d d&œd'd(„ƒƒZeed!d"d#d$�d)d d&œd*d+„ƒƒZedWd	d
d d,œd-d.„ƒZdd/d0œd1d2„Zdd/d0œd3d4„Zdd d0œd5d6„Zd7dd8œd9d:„Zd	dd;œd<d=„Zed>d?d@œdAdB„ƒZedCd d@œdDdB„ƒZdEdFd@œdGdB„Zd>dœdHdI„ZeddœdJdK„ƒZedLdMdNdO�dPddQœdRdS„ƒZedXdddTœdUdV„ƒZ‡  ZS )YÚChatPromptTemplateat  Prompt template for chat models.

    Use to create flexible templated prompts for chat models.

    Examples:

        .. versionchanged:: 0.2.24

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

        .. code-block:: python

            from langchain_core.prompts import ChatPromptTemplate

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

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

    Messages Placeholder:

        .. code-block:: python

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

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

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

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

    Single-variable template:

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


        .. code-block:: python

            from langchain_core.prompts import ChatPromptTemplate

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

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

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

    z.Annotated[list[MessageLike], SkipValidation()]r¹   Fr.   Úvalidate_templatere   r‘   z#Sequence[MessageLikeRepresentation]r%   r   r1   )r¹   rh   r2   r3   c          	        s¦   ‡ fdd„|D ƒ}t ƒ }t ƒ }i }|D ]F}t|tƒrR|jrRg ||j< | |j¡ q&t|ttfƒr&| |j	¡ q&t
|ƒt
|ƒ|dœ|¥}tdtƒ ƒjf d|i|¤Ž dS )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. Defaults to "f-string".
            input_variables: A list of the names of the variables whose values are
                required as inputs to the prompt.
            optional_variables: A list of the names of the variables for placeholder
                or MessagePlaceholder that are optional.
                These variables are auto inferred from the prompt and user need not
                provide them.
            partial_variables: A dictionary of the partial variables the prompt
                template carries. Partial variables populate the template so that you
                don't need to pass them in every time you call the prompt.
            validate_template: Whether to validate the template.
            input_types: A dictionary of the types of the variables the prompt template
                expects. If not provided, all variables are assumed to be strings.

        Examples:
            Instantiation from a list of message templates:

            .. code-block:: python

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

            Instantiation from mixed message formats:

            .. code-block:: python

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

        c                   s   g | ]}t |ˆ ƒ‘qS r:   ©Ú_convert_to_message_template©rŸ   Úmessager‘   r:   r;   r    Ä  s   ÿz/ChatPromptTemplate.__init__.<locals>.<listcomp>)rK   Úoptional_variablesri   ztype[ChatPromptTemplate]r¹   N)r–   r?   r+   r/   r-   Úaddr³   r#   ÚupdaterK   Úsortedr   r5   r6   )	r7   r¹   rh   r2   Z	messages_Ú
input_varsrÆ   Zpartial_varsÚ_messager8   r‘   r;   r6   �  s*    7
þ
ÿýüzChatPromptTemplate.__init__rF   rG   c                 C  s   g d¢S )zvGet the namespace of the langchain object.

        Returns:
            ``["langchain", "prompts", "chat"]``
        )Z	langchainr¢   Úchatr:   )rl   r:   r:   r;   Úget_lc_namespaceÞ  s    z#ChatPromptTemplate.get_lc_namespace)Úotherr3   c                 C  s  i | j ¥}t|dƒr&|j r&| |j ¡ t|tƒrNt| j|j d�jf i |¤ŽS t|ttt	fƒr~tg | j¢|‘d�jf i |¤ŽS t|t
tfƒr´t |¡}t| j|j d�jf i |¤ŽS t|tƒrèt |¡}tg | j¢|‘d�jf i |¤ŽS dt|ƒ› �}t|ƒ‚dS )z™Combine two prompt templates.

        Args:
            other: Another prompt template.

        Returns:
            Combined prompt template.
        ri   r¸   z Unsupported operand type for +: N)ri   ÚhasattrrÈ   r?   rÀ   r¹   Úpartialr#   r   r³   r@   ÚtupleÚfrom_messagesr,   r°   rk   rA   r¼   )r7   rÎ   ZpartialsZother_r`   rD   r:   r:   r;   Ú__add__ç  s2    	

ÿ
ÿÿ
ÿ

ÿzChatPromptTemplate.__add__Úbefore)Úmoderc   )Úvaluesr3   c                 C  s8  |d }t ƒ }t ƒ }| di ¡}|D ]~}t|ttfƒrB| |j¡ t|tƒr$d|vr\i |d< |jrŠ|j	|d vrŠg |d |j	< | 
|j	¡ |j	|vr$tt ||j	< q$d|v r¼|t |d ƒ8 }|rÈ||8 }d|v �r| d¡�r|t |d ƒk�rd|› d|d › �}t|ƒ‚nt|ƒ|d< |�r,t|ƒ|d< ||d< |S )	aG  Validate input variables.

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

        Args:
            values: values to validate.

        Returns:
            Validated values.

        Raises:
            ValueError: If input variables do not match.
        r¹   Úinput_typesri   rK   rÁ   z*Got mismatched input_variables. Expected: z. Got: rÆ   )r–   r>   r?   r#   r³   rÈ   rK   r+   r/   r-   rÇ   r@   r   rB   rÉ   )rl   rÖ   r¹   rÊ   rÆ   r×   rÅ   rD   r:   r:   r;   Úvalidate_input_variables  sH    
ÿþ
ÿþÿ
z+ChatPromptTemplate.validate_input_variablesr,   )rg   r2   r3   c                 K  s(   t j|fi |¤Ž}t|d�}|  |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.
        ©r`   )r$   rk   r°   rÒ   )rl   rg   r2   Zprompt_templaterÅ   r:   r:   r;   rk   E  s    
z ChatPromptTemplate.from_templatez0.0.1rÒ   T)ÚalternativeÚpendingzlist[tuple[str, str]])Ústring_messagesr3   c                 C  s   | dd„ |D ƒd�S )zÑCreate a chat prompt template from a list of (role, template) tuples.

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

        Returns:
            a chat prompt template.
        c                 S  s   g | ]\}}t j||d �‘qS ))r‚   )r�   rk   )rŸ   r‚   rg   r:   r:   r;   r    e  s   ÿz8ChatPromptTemplate.from_role_strings.<locals>.<listcomp>r¸   r:   ©rl   rÜ   r:   r:   r;   Úfrom_role_stringsW  s
    þÿz$ChatPromptTemplate.from_role_stringsz1list[tuple[type[BaseMessagePromptTemplate], str]]c                 C  s
   |   |¡S )zÝCreate a chat prompt template from a list of (role class, template) tuples.

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

        Returns:
            a chat prompt template.
        )rÒ   rÝ   r:   r:   r;   Úfrom_stringsk  s    zChatPromptTemplate.from_strings)r¹   rh   r3   c                 C  s   | ||d�S )a†  Create a chat prompt template from a variety of message formats.

        Examples:
            Instantiation from a list of message templates:

            .. code-block:: python

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

            Instantiation from mixed message formats:

            .. code-block:: python

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

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

        Returns:
            a chat prompt template.

        r‘   r:   )rl   r¹   rh   r:   r:   r;   rÒ   z  s    -z ChatPromptTemplate.from_messagesr<   r=   c                 K  sx   | j f i |¤Ž}g }| jD ]X}t|tƒr6| |g¡ qt|ttfƒr`|jf i |¤Ž}| |¡ qd|› �}t|ƒ‚q|S )av  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: )	Ú!_merge_partial_and_user_variablesr¹   r?   r   r™   r#   r³   rE   rB   ©r7   r2   ÚresultZmessage_templaterÅ   rD   r:   r:   r;   rE   ©  s    

ÿ

z"ChatPromptTemplate.format_messagesc                 Ë  s~   | j f i |¤Ž}g }| jD ]^}t|tƒr6| |g¡ qt|ttfƒrf|jf i |¤ŽI dH }| |¡ qd|› �}t|ƒ‚q|S )al  Async format the chat template into a list of finalized messages.

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

        Returns:
            list of formatted messages.

        Raises:
            ValueError: If unexpected input.
        Nrà   )	rá   r¹   r?   r   r™   r#   r³   r{   rB   râ   r:   r:   r;   r{   Å  s    

ÿ

z#ChatPromptTemplate.aformat_messagesc                 K  sF   | j  ¡ }tt| jƒ |¡ƒ|d< i | j¥|¥|d< t| ƒf i |¤ŽS )aœ  Get a new ChatPromptTemplate with some input variables already filled in.

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

        Returns:
            A new ChatPromptTemplate.


        Example:

            .. code-block:: python

                from langchain_core.prompts import ChatPromptTemplate

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

                template2.format_messages(input="hello")

        rK   ri   )Ú__dict__Úcopyr@   r–   rK   Ú
differenceri   rA   )r7   r2   Zprompt_dictr:   r:   r;   rÐ   á  s    
ÿzChatPromptTemplate.partialÚMessageLikeRepresentation)rÅ   r3   c                 C  s   | j  t|ƒ¡ dS )z…Append a message to the end of the chat template.

        Args:
            message: representation of a message to append.
        N)r¹   r˜   rÃ   )r7   rÅ   r:   r:   r;   r˜     s    zChatPromptTemplate.append)r¹   r3   c                 C  s   | j  dd„ |D ƒ¡ dS )z’Extend the chat template with a sequence of messages.

        Args:
            messages: sequence of message representations to append.
        c                 S  s   g | ]}t |ƒ‘qS r:   rÂ   rÄ   r:   r:   r;   r      r¡   z-ChatPromptTemplate.extend.<locals>.<listcomp>N)r¹   r™   )r7   r¹   r:   r:   r;   r™     s    ÿzChatPromptTemplate.extendÚintÚMessageLike)Úindexr3   c                 C  s   d S ©Nr:   ©r7   rê   r:   r:   r;   Ú__getitem__  s    zChatPromptTemplate.__getitem__Úslicec                 C  s   d S rë   r:   rì   r:   r:   r;   rí     s    zUnion[int, slice]z&Union[MessageLike, ChatPromptTemplate]c                 C  sD   t |tƒr:| t| jƒ¡\}}}| j|||… }t |¡S | j| S )zûUse 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?   rî   Úindicesr•   r¹   rÀ   rÒ   )r7   rê   ÚstartÚstopÚstepr¹   r:   r:   r;   rí     s
    


c                 C  s
   t | jƒS )z'Return the length of the chat template.)r•   r¹   rJ   r:   r:   r;   Ú__len__.  s    zChatPromptTemplate.__len__c                 C  s   dS )z,Name of prompt type. Used for serialization.rÌ   r:   rJ   r:   r:   r;   Ú_prompt_type2  s    zChatPromptTemplate._prompt_typez0.3.86z1.0.0zkUse `dumpd`/`dumps` from `langchain_core.load` to serialize prompts and `load`/`loads` to deserialize them.)ZsinceZremovalrÚ   zUnion[Path, str])Ú	file_pathr3   c                 C  s   t ‚dS )zQSave prompt to file.

        Args:
            file_path: path to file.
        Nr»   )r7   rõ   r:   r:   r;   Úsave7  s    zChatPromptTemplate.saverL   c                   s   d  ‡ fdd„| jD ƒ¡S )rN   rR   c                 3  s   | ]}|j ˆ d �V  qdS r¬   r­   )rŸ   rD   r~   r:   r;   r®   P  r¡   z1ChatPromptTemplate.pretty_repr.<locals>.<genexpr>)r¯   r¹   r½   r:   r~   r;   rU   E  s    zChatPromptTemplate.pretty_repr)re   )F)rV   rW   rX   rY   rZ   rÁ   r6   r€   rÍ   rÓ   r   rØ   rk   r   rÞ   rß   rÒ   rE   r{   rÐ   r˜   r™   r   rí   ró   r[   rô   rö   r   rU   r\   r:   r:   r8   r;   rÀ     sV   
rüQ(4 ý.%
ýrÀ   re   r,   zUnion[str, list]r%   r#   )Úmessage_typerg   rh   r3   c                 C  sl  | dv rt j||d�}�nN| dv r:tjtd|ƒ|d�}�n.| dkrZtjtd|ƒ|d�}�n| dk�rTt|tƒr´|d dks†|d	 d
kršd|› d�}t|ƒ‚|dd	… }t|dd�}nžt	|ƒdk�r@t|d t
ƒ�r@|\}}t|tƒsöd|› �}t|ƒ‚|d dk�s|d	 d
k�r&d|› d�}t|ƒ‚|dd	… }t||d�}nd|› �}t|ƒ‚nd| › d�}t|ƒ‚|S )aª  Create a message prompt template from a message type and template string.

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

    Returns:
        a message prompt template of the appropriate type.

    Raises:
        ValueError: If unexpected message type.
    >   ÚuserÚhumanr‘   >   ZaiZ	assistantr,   ÚsystemÚplaceholderr   rO   éÿÿÿÿrP   zInvalid placeholder template: z6. Expected a variable name surrounded by curly braces.r’   Tr4   é   z,Expected variable name to be a string. Got: zœUnexpected arguments for placeholder message type. Expected either a single string variable name or a list of [variable_name: str, is_optional: bool]. Got: zUnexpected message type: z=. Use one of 'human', 'user', 'ai', 'assistant', or 'system'.)r°   rk   r±   r   r²   r?   r,   rB   r+   r•   r.   )r÷   rg   rh   rÅ   rD   Úvar_nameZvar_name_wrappedZis_optionalr:   r:   r;   Ú"_create_template_from_message_typeS  sP    ÿ

ÿ

ÿ



ÿ


ÿýÿ

ÿrÿ   rç   zEUnion[BaseMessage, BaseMessagePromptTemplate, BaseChatPromptTemplate])rÅ   rh   r3   c                 C  s  t | ttfƒr| }nêt | tƒr$| }nÚt | tƒr>td| |d�}nÀt | ttfƒrèt | tƒrŒt|  	¡ ƒddhkr|d| › �}t
|ƒ‚| d | d f} t| ƒdkrªd| › �}t
|ƒ‚| \}}t |tƒrÌt|||d�}qþ|tjtd|ƒ|d�d	�}nd
t| ƒ› �}t|ƒ‚|S )aÀ  Instantiate a message from a variety of message formats.

    The message format can be one of the following:

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

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

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

    Raises:
        ValueError: If unexpected message type.
        ValueError: If 2-tuple does not have 2 elements.
    rù   r‘   r„   r‚   z<Expected dict to have exact keys 'role' and 'content'. Got: rý   z*Expected 2-tuple of (role, template), got r,   rÙ   zUnsupported message type: )r?   r#   r³   r   r,   rÿ   rÑ   rc   r–   r—   rB   r•   r$   rk   r   rA   r¼   )rÅ   rh   Zmessage_rD   Zmessage_type_strrg   r:   r:   r;   rÃ   š  sD    þ

ÿ
ÿÿ

ÿ
ÿÿrÃ   N)re   )re   )TrY   Ú
__future__r   Úabcr   r   Úpathlibr   Útypingr   r   r   r	   r
   r   r   r   r   Zpydanticr   r   r   r   Ztyping_extensionsr   r   Zlangchain_core._apir   Zlangchain_core.messagesr   r   r   r   r   r   r   Zlangchain_core.messages.baser   Zlangchain_core.prompt_valuesr   r   Zlangchain_core.prompts.baser    Zlangchain_core.prompts.dictr!   Zlangchain_core.prompts.imager"   Zlangchain_core.prompts.messager#   Zlangchain_core.prompts.promptr$   Zlangchain_core.prompts.stringr%   r&   r'   Zlangchain_core.utilsr(   Z$langchain_core.utils.interactive_envr)   Úcollections.abcr*   r+   r]   r^   r�   r‡   r‹   r�   r°   r±   r²   r³   ré   rÑ   r,   rA   r@   rc   Úobjectrç   rÀ   rÿ   rÃ   Z_convert_to_messager:   r:   r:   r;   Ú<module>   sv   ,$	 ÿ #  	[
ÿÿ
úÿ    E ýI þB