a
    ”˜ëjd?  ã                   @  s”  d Z ddlmZ ddlZddlZddl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mZmZmZmZmZmZ ddl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# ddl$m%Z% ddl&m'Z' ddl(m)Z)m*Z*m+Z+ ddl,m-Z-m.Z. ddl/m0Z0 ddl1m2Z2 e�r2ddl3m4Z4 edƒZ5G dd„ de.e6e*f eee5 ƒZ7ddddœdd„Z8ddddœdd„Z9ddddœd d!„Z:dS )"z Base class for prompt templates.é    )ÚannotationsN)ÚABCÚabstractmethod)ÚMapping)Úcached_property)ÚPath)ÚTYPE_CHECKINGÚAnyÚCallableÚGenericÚOptionalÚTypeVarÚUnion)Ú	BaseModelÚ
ConfigDictÚFieldÚmodel_validator)ÚSelfÚoverride)Ú
deprecated)Ú	ErrorCodeÚcreate_message©Údumpd)ÚBaseOutputParser)ÚChatPromptValueConcreteÚPromptValueÚStringPromptValue)ÚRunnableConfigÚRunnableSerializable)Úensure_config)Úcreate_model_v2)ÚDocumentÚFormatOutputTypec                      s  e Zd ZU dZded< eg d�Zded< eedd�Zded	< d
Z	ded< eed�Z
ded< d
Zded< d
Zded< edd�ddœdd„ƒZeddœdd„ƒZeddœdd„ƒZedd�Zed dœd!d"„ƒZeed#dœd$d%„ƒƒZedVd&d'd(œd)d*„ƒZd#d+d,œd-d.„Zd+d/d,œd0d1„Zd+d/d,œd2d3„ZedWd+d&d#d/d4œd5d6„ƒZedXd+d&d#d/d4œd7d8„ƒZed#d/d9œd:d;„ƒZ d#d/d9œd<d=„Z!d>d d9œd?d@„Z"d#d d9œdAdB„Z#ed#dCd9œdDdE„ƒZ$d#dCd9œdFdG„Z%edHdœdIdJ„ƒZ&d#d+d9œ‡ fdKdL„Ze'dMdNdOdP�dQdRdSœdTdU„ƒZ(‡  Z)S )YÚBasePromptTemplatez8Base class for all prompt templates, returning a prompt.z	list[str]Úinput_variables)ÚdefaultÚoptional_variablesT)Údefault_factoryÚexcludeztyping.Dict[str, Any]Úinput_typesNzOptional[BaseOutputParser]Úoutput_parser)r(   zMapping[str, Any]Úpartial_variableszOptional[typing.Dict[str, Any]]ÚmetadatazOptional[list[str]]ÚtagsÚafter)Úmoder   )Úreturnc                 C  sv   d| j v r d}tt|tjd�ƒ‚d| jv r@d}tt|tjd�ƒ‚t| j ƒ | j¡}|rrd|› �}tt|tjd�ƒ‚| S )z8Validate variable names do not include restricted names.ÚstopzTCannot have an input variable named 'stop', as it is used internally, please rename.©ÚmessageZ
error_codezVCannot have an partial variable named 'stop', as it is used internally, please rename.z/Found overlapping input and partial variables: )r%   Ú
ValueErrorr   r   ÚINVALID_PROMPT_INPUTr,   ÚsetÚintersection)ÚselfÚmsgZoverall© r;   úZ/mnt/bigstor/www/usecases/.venv/lib/python3.9/site-packages/langchain_core/prompts/base.pyÚvalidate_variable_namesI   s&    
ÿÿ
ÿÿ
ÿz*BasePromptTemplate.validate_variable_namesc                 C  s   g d¢S )z€Get the namespace of the langchain object.

        Returns:
            ``["langchain", "schema", "prompt_template"]``
        )Z	langchainZschemaZprompt_templater;   ©Úclsr;   r;   r<   Úget_lc_namespacee   s    z#BasePromptTemplate.get_lc_namespaceÚboolc                 C  s   dS )z*Return True as this class is serializable.Tr;   r>   r;   r;   r<   Úis_lc_serializablen   s    z%BasePromptTemplate.is_lc_serializable)Zarbitrary_types_allowedzdict[str, Any]c                 C  s   t | ƒS ©Nr   ©r9   r;   r;   r<   Ú_serializedw   s    zBasePromptTemplate._serializedr	   c                 C  s   t ttf S )z%Return the output type of the prompt.)r   r   r   rD   r;   r;   r<   Ú
OutputType{   s    zBasePromptTemplate.OutputTypezOptional[RunnableConfig]ztype[BaseModel])Úconfigr1   c                   s<   ‡ fdd„ˆ j D ƒ}‡ fdd„ˆ jD ƒ}tdi |¥|¥d�S )zÎGet the input schema for the prompt.

        Args:
            config: RunnableConfig, configuration for the prompt.

        Returns:
            Type[BaseModel]: The input schema for the prompt.
        c                   s    i | ]}|ˆ j  |t¡d f“qS ).©r*   ÚgetÚstr©Ú.0ÚkrD   r;   r<   Ú
<dictcomp>Ž   s   z7BasePromptTemplate.get_input_schema.<locals>.<dictcomp>c                   s    i | ]}|ˆ j  |t¡d f“qS rC   rH   rK   rD   r;   r<   rN   ‘   s   ZPromptInput)Zfield_definitions)r%   r'   r!   )r9   rG   Zrequired_input_variablesZoptional_input_variablesr;   rD   r<   Úget_input_schema�   s    
ÿ
ÿ
þz#BasePromptTemplate.get_input_schemaÚdict)Úinner_inputr1   c              
   C  sÊ   t |tƒsXt| jƒdkr,| jd }||i}n,d| jj› dt|ƒ› d�}tt|t	j
d�ƒ‚t| jƒ |¡}|rÆd| jj› d|› d	| j› d
t| ¡ ƒ› �}| ¡ }|d|› d|› d�7 }tt|t	j
d�ƒ‚|S )Né   r   z"Expected mapping type as input to z. Received Ú.r3   z	Input to z is missing variables z.  Expected: z Received: z
Note: if you intended {zb} to be part of the string and not a variable, please escape it with double curly braces like: '{{z}}'.)Ú
isinstancerP   Úlenr%   Ú	__class__Ú__name__ÚtypeÚ	TypeErrorr   r   r6   r7   Ú
differenceÚlistÚkeysÚpopÚKeyError)r9   rQ   Úvar_namer:   ÚmissingZexample_keyr;   r;   r<   Ú_validate_input™   s>    


ÿÿÿÿÿ
þÿþÿÿz"BasePromptTemplate._validate_inputr   c                 C  s   |   |¡}| jf i |¤ŽS rC   )ra   Úformat_prompt©r9   rQ   Zinner_input_r;   r;   r<   Ú"_format_prompt_with_error_handling»   s    
z5BasePromptTemplate._format_prompt_with_error_handlingc                 Ã  s    |   |¡}| jf i |¤ŽI d H S rC   )ra   Úaformat_promptrc   r;   r;   r<   Ú#_aformat_prompt_with_error_handling¿   s    
z6BasePromptTemplate._aformat_prompt_with_error_handling)ÚinputrG   Úkwargsr1   c                 K  sT   t |ƒ}| jr$i |d ¥| j¥|d< | jr<|d  | j7  < | j| j||d| jd�S )zßInvoke the prompt.

        Args:
            input: Dict, input to the prompt.
            config: RunnableConfig, configuration for the prompt.

        Returns:
            PromptValue: The output of the prompt.
        r-   r.   Úprompt©Zrun_typeZ
serialized)r    r-   r.   Z_call_with_configrd   rE   ©r9   rg   rG   rh   r;   r;   r<   ÚinvokeÅ   s    ûzBasePromptTemplate.invokec                 Ë  sR   t |ƒ}| jr|d  | j¡ | jr4|d  | j¡ | j| j||d| jd�I dH S )zåAsync invoke the prompt.

        Args:
            input: Dict, input to the prompt.
            config: RunnableConfig, configuration for the prompt.

        Returns:
            PromptValue: The output of the prompt.
        r-   r.   ri   rj   N)r    r-   Úupdater.   ÚextendZ_acall_with_configrf   rE   rk   r;   r;   r<   Úainvokeß   s    ûzBasePromptTemplate.ainvoke)rh   r1   c                 K  s   dS )z¸Create Prompt Value.

        Args:
            kwargs: Any arguments to be passed to the prompt template.

        Returns:
            PromptValue: The output of the prompt.
        Nr;   ©r9   rh   r;   r;   r<   rb   ù   s    z BasePromptTemplate.format_promptc                 Ë  s   | j f i |¤ŽS )z¾Async create Prompt Value.

        Args:
            kwargs: Any arguments to be passed to the prompt template.

        Returns:
            PromptValue: The output of the prompt.
        )rb   rp   r;   r;   r<   re     s    	z!BasePromptTemplate.aformat_promptzUnion[str, Callable[[], str]]c                 K  sF   | j  ¡ }tt| jƒ |¡ƒ|d< i | j¥|¥|d< t| ƒf i |¤ŽS )záReturn a partial of the prompt template.

        Args:
            kwargs: Union[str, Callable[[], str]], partial variables to set.

        Returns:
            BasePromptTemplate: A partial of the prompt template.
        r%   r,   )Ú__dict__Úcopyr[   r7   r%   rZ   r,   rX   ©r9   rh   Úprompt_dictr;   r;   r<   Úpartial  s    	
ÿzBasePromptTemplate.partialc                 K  s    dd„ | j  ¡ D ƒ}i |¥|¥S )Nc                 S  s$   i | ]\}}|t |ƒs|n|ƒ “qS r;   )Úcallable)rL   rM   Úvr;   r;   r<   rN   !  s   zHBasePromptTemplate._merge_partial_and_user_variables.<locals>.<dictcomp>)r,   Úitems)r9   rh   Zpartial_kwargsr;   r;   r<   Ú!_merge_partial_and_user_variables  s    ÿz4BasePromptTemplate._merge_partial_and_user_variablesr#   c                 K  s   dS )a  Format the prompt with the inputs.

        Args:
            kwargs: Any arguments to be passed to the prompt template.

        Returns:
            A formatted string.

        Example:

        .. code-block:: python

            prompt.format(variable1="foo")

        Nr;   rp   r;   r;   r<   Úformat&  s    zBasePromptTemplate.formatc                 Ë  s   | j f i |¤ŽS )a  Async format the prompt with the inputs.

        Args:
            kwargs: Any arguments to be passed to the prompt template.

        Returns:
            A formatted string.

        Example:

        .. code-block:: python

            await prompt.aformat(variable1="foo")

        )rz   rp   r;   r;   r<   Úaformat8  s    zBasePromptTemplate.aformatrJ   c                 C  s   t ‚dS )zReturn the prompt type key.N)ÚNotImplementedErrorrD   r;   r;   r<   Ú_prompt_typeJ  s    zBasePromptTemplate._prompt_typec                   sJ   t ƒ jf i |¤Ž}t t¡� | j|d< W d  ƒ n1 s<0    Y  |S )zØReturn dictionary representation of prompt.

        Args:
            kwargs: Any additional arguments to pass to the dictionary.

        Returns:
            Dict: Dictionary representation of the prompt.
        Ú_typeN)ÚsuperZ
model_dumpÚ
contextlibÚsuppressr|   r}   rs   ©rV   r;   r<   rP   O  s    	(zBasePromptTemplate.dictz0.3.86z1.0.0zkUse `dumpd`/`dumps` from `langchain_core.load` to serialize prompts and `load`/`loads` to deserialize them.)ZsinceZremovalÚalternativezUnion[Path, str]ÚNone)Ú	file_pathr1   c                 C  sö   | j rd}t|ƒ‚|  ¡ }d|vr6d| › d�}t|ƒ‚t|ƒ}|j}|jddd� |jdkr˜| d¡� }t	j
||d	d
� W d  ƒ qò1 sŒ0    Y  nZ|j d¡rà| d¡� }tj
||dd� W d  ƒ qò1 sÔ0    Y  n|› d�}t|ƒ‚dS )a¡  Save the prompt.

        Args:
            file_path: Path to directory to save prompt to.

        Raises:
            ValueError: If the prompt has partial variables.
            ValueError: If the file path is not json or yaml.
            NotImplementedError: If the prompt type is not implemented.

        Example:
        .. code-block:: python

            prompt.save(file_path="path/prompt.yaml")

        z*Cannot save prompt with partial variables.r~   zPrompt z does not support saving.T)ÚparentsÚexist_okz.jsonÚwé   )ÚindentN)z.yamlz.ymlF)Zdefault_flow_stylez must be json or yaml)r,   r5   rP   r|   r   ÚparentÚmkdirÚsuffixÚopenÚjsonÚdumpÚendswithÚyaml)r9   r…   r:   rt   Z	save_pathZdirectory_pathÚfr;   r;   r<   Úsave]  s$    
00
zBasePromptTemplate.save)N)N)N)*rW   Ú
__module__Ú__qualname__Ú__doc__Ú__annotations__r   r'   rP   r*   r+   r,   r-   r.   r   r=   Úclassmethodr@   rB   r   Zmodel_configr   rE   Úpropertyr   rF   rO   ra   rd   rf   rl   ro   r   rb   re   ru   ry   rz   r{   r}   r   r”   Ú__classcell__r;   r;   r‚   r<   r$   .   sf   
ÿ ÿ" ÿ ÿ
ýr$   r"   zBasePromptTemplate[str]rP   )Údocri   r1   c                   sx   d| j i| j¥‰ t|jƒ ˆ ¡}t|ƒdkrddd„ |jD ƒ}d|› dt|ƒ› d�}tt|t	j
d�ƒ‚‡ fd	d
„|jD ƒS )NÚpage_contentr   c                 S  s   g | ]}|d kr|‘qS )r�   r;   )rL   Zivr;   r;   r<   Ú
<listcomp>“  s   z&_get_document_info.<locals>.<listcomp>z?Document prompt requires documents to have metadata variables: z+. Received document with missing metadata: rS   r3   c                   s   i | ]}|ˆ | “qS r;   r;   rK   ©Z	base_infor;   r<   rN   ž  ó    z&_get_document_info.<locals>.<dictcomp>)r�   r-   r7   r%   rZ   rU   r[   r5   r   r   r6   )rœ   ri   Zmissing_metadataZrequired_metadatar:   r;   rŸ   r<   Ú_get_document_info�  s     ÿÿþÿÿr¡   rJ   c                 C  s   |j f i t| |ƒ¤ŽS )a·  Format a document into a string based on a prompt template.

    First, this pulls information from the document from two sources:

    1. page_content:
        This takes the information from the `document.page_content`
        and assigns it to a variable named `page_content`.
    2. metadata:
        This takes information from `document.metadata` and assigns
        it to variables of the same name.

    Those variables are then passed into the `prompt` to produce a formatted string.

    Args:
        doc: Document, the page_content and metadata will be used to create
            the final string.
        prompt: BasePromptTemplate, will be used to format the page_content
            and metadata into the final string.

    Returns:
        string of the document formatted.

    Example:
        .. code-block:: python

            from langchain_core.documents import Document
            from langchain_core.prompts import PromptTemplate

            doc = Document(page_content="This is a joke", metadata={"page": "1"})
            prompt = PromptTemplate.from_template("Page {page}: {page_content}")
            format_document(doc, prompt)
            >>> "Page 1: This is a joke"

    )rz   r¡   ©rœ   ri   r;   r;   r<   Úformat_document¡  s    #r£   c                 Ã  s   |j f i t| |ƒ¤ŽI dH S )a   Async format a document into a string based on a prompt template.

    First, this pulls information from the document from two sources:

    1. page_content:
        This takes the information from the `document.page_content`
        and assigns it to a variable named `page_content`.
    2. metadata:
        This takes information from `document.metadata` and assigns
        it to variables of the same name.

    Those variables are then passed into the `prompt` to produce a formatted string.

    Args:
        doc: Document, the page_content and metadata will be used to create
            the final string.
        prompt: BasePromptTemplate, will be used to format the page_content
            and metadata into the final string.

    Returns:
        string of the document formatted.
    N)r{   r¡   r¢   r;   r;   r<   Úaformat_documentÇ  s    r¤   );r—   Ú
__future__r   r€   r�   ÚtypingÚabcr   r   Úcollections.abcr   Ú	functoolsr   Úpathlibr   r   r	   r
   r   r   r   r   r’   Zpydanticr   r   r   r   Ztyping_extensionsr   r   Zlangchain_core._apir   Zlangchain_core.exceptionsr   r   Zlangchain_core.loadr   Z"langchain_core.output_parsers.baser   Zlangchain_core.prompt_valuesr   r   r   Zlangchain_core.runnablesr   r   Zlangchain_core.runnables.configr    Zlangchain_core.utils.pydanticr!   Zlangchain_core.documentsr"   r#   rP   r$   r¡   r£   r¤   r;   r;   r;   r<   Ú<module>   s>   $

ÿ  c&