
    gh>                       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 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-m.Z. ddl/m0Z0 erddl1m2Z2  ed          Z3 G d de,e4e(f         ee3         e          Z5d dZ6d!dZ7d!dZ8d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)	ErrorCodecreate_messagedumpd)BaseOutputParser)ChatPromptValueConcretePromptValueStringPromptValue)RunnableConfigRunnableSerializable)ensure_config)create_model_v2)DocumentFormatOutputTypec                  `    e Zd ZU dZded<   	  eg           Zded<   	  eed          Zded	<   	 d
Z	ded<   	  ee          Z
ded<   	 d
Zded<   	 d
Zded<   	  ed          d>d            Zed?d            Zed@d            Z ed          ZedAd            ZeedBd                         Ze	 dCdDd$            ZdEd'ZdFd)ZdFd*Ze	 dCdGd-            Ze	 dCdGd.            ZedHd/            Z dHd0Z!dId2Z"dJd3Z#edKd5            Z$dKd6Z%edLd8            Z&dM fd9ZdNd=Z' xZ(S )OBasePromptTemplatez8Base class for all prompt templates, returning a prompt.	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)modereturnr   c                   d| j         v r*d}t          t          |t          j                            d| j        v r*d}t          t          |t          j                            t          | j                                       | j                  }|r-d| }t          t          |t          j                            | S )z8Validate variable names do not include restricted names.stopzTCannot have an input variable named 'stop', as it is used internally, please rename.message
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msgoveralls      X/var/www/FlaskApp/flask-venv/lib/python3.11/site-packages/langchain_core/prompts/base.pyvalidate_variable_namesz*BasePromptTemplate.validate_variable_namesH   s     T)))"  sy7UVVV   T+++-  sy7UVVV   d*++889OPP 	MGMMCsy7UVVV       c                
    g dS )zpGet the namespace of the langchain object.

        Returns ["langchain", "schema", "prompt_template"].
        )	langchainschemaprompt_template clss    r@   get_lc_namespacez#BasePromptTemplate.get_lc_namespaced   s     :999rB   boolc                    dS )zJReturn whether this class is serializable.

        Returns True.
        TrG   rH   s    r@   is_lc_serializablez%BasePromptTemplate.is_lc_serializablel   s	     trB   )arbitrary_types_alloweddict[str, Any]c                     t          |           S Nr   r=   s    r@   _serializedzBasePromptTemplate._serializedx   s    T{{rB   r
   c                4    t           t          t          f         S )z%Return the output type of the prompt.)r   r   r   rR   s    r@   
OutputTypezBasePromptTemplate.OutputType|   s     &(??@@rB   configOptional[RunnableConfig]type[BaseModel]c                z      fd j         D             } fd j        D             }t          di ||          S )zGet the input schema for the prompt.

        Args:
            config: RunnableConfig, configuration for the prompt.

        Returns:
            Type[BaseModel]: The input schema for the prompt.
        c                V    i | ]%}|j                             |t                    d f&S ).r,   getstr.0kr=   s     r@   
<dictcomp>z7BasePromptTemplate.get_input_schema.<locals>.<dictcomp>   s@     $
 $
 $
78A $$Q,,c2$
 $
 $
rB   c                V    i | ]%}|j                             |t                    d f&S rQ   r[   r^   s     r@   ra   z7BasePromptTemplate.get_input_schema.<locals>.<dictcomp>   s@     $
 $
 $
89A $$Q,,d3$
 $
 $
rB   PromptInput)field_definitions)r'   r)   r!   )r=   rV   required_input_variablesoptional_input_variabless   `   r@   get_input_schemaz#BasePromptTemplate.get_input_schema   s    $
 $
 $
 $
<@<P$
 $
 $
 $
 $
 $
 $
=A=T$
 $
 $
  V!9V=UV
 
 
 	
rB   inner_inputdictc                n   t          |t                    srt          | j                  dk    r| j        d         }||i}nHd| j        j         dt          |           d}t          t          |t          j
                            t          | j                                      |          }|rd| j        j         d| d	| j         d
t          |                                           }|                                }|d| d| dz  }t!          t          |t          j
                            |S )N   r   z"Expected mapping type as input to z. Received .r6   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}}'.)
isinstanceri   lenr'   	__class____name__type	TypeErrorr   r   r:   r;   
differencelistkeyspopKeyError)r=   rh   var_namer>   missingexample_keys         r@   _validate_inputz"BasePromptTemplate._validate_input   s   +t,, 	4'((A--/2'559P 5 5 $[ 1 15 5 5   " #	0N    
 d*++66{CC 	9DN3 9 97 9 9"29 9";#3#3#5#5669 9 
 "++--K,[ , ,#, , ,C
 sy7UVVV   rB   r   c                F    |                      |          } | j        di |S NrG   )r{   format_promptr=   rh   _inner_inputs      r@   "_format_prompt_with_error_handlingz5BasePromptTemplate._format_prompt_with_error_handling   s.    ++K88!t!11L111rB   c                V   K   |                      |          } | j        di | d {V S r}   )r{   aformat_promptr   s      r@   #_aformat_prompt_with_error_handlingz6BasePromptTemplate._aformat_prompt_with_error_handling   sF       ++K88(T(88<888888888rB   inputkwargsc                    t          |          }| j        ri |d         | j        |d<   | j        r|d         | j        z   |d<   |                     | j        ||d| j                  S )zInvoke the prompt.

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

        Returns:
            PromptValue: The output of the prompt.
        r/   r0   promptrun_type
serialized)r    r/   r0   _call_with_configr   rS   r=   r   rV   r   s       r@   invokezBasePromptTemplate.invoke   s     v&&= 	I!HF:$6!H$-!HF:9 	8#F^di7F6N%%3' & 
 
 	
rB   c                  K   t          |          }| j        r |d                             | j                   | j        r |d                             | j                   |                     | j        ||d| j                   d{V S )zAsync invoke the prompt.

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

        Returns:
            PromptValue: The output of the prompt.
        r/   r0   r   r   N)r    r/   updater0   extend_acall_with_configr   rS   r   s       r@   ainvokezBasePromptTemplate.ainvoke   s       v&&= 	5:%%dm4449 	-6N!!$),,,,,4' - 
 
 
 
 
 
 
 
 	
rB   c                    dS )zCreate Prompt Value.

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

        Returns:
            PromptValue: The output of the prompt.
        NrG   r=   r   s     r@   r~   z BasePromptTemplate.format_prompt         rB   c                    K    | j         di |S )zAsync create Prompt Value.

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

        Returns:
            PromptValue: The output of the prompt.
        rG   )r~   r   s     r@   r   z!BasePromptTemplate.aformat_prompt  s!       "t!++F+++rB   Union[str, Callable[[], str]]c                    | j                                         }t          t          | j                                      |                    |d<   i | j        ||d<    t          |           di |S )zReturn 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.   rG   )__dict__copyrt   r;   r'   rs   r.   rq   )r=   r   prompt_dicts      r@   partialzBasePromptTemplate.partial  s     m((**)-$%%0088*
 *
%& ,Pd.D+O+O'(tDzz((K(((rB   c                T    d | j                                         D             }i ||S )Nc                L    i | ]!\  }}|t          |          s|n	 |            "S rG   )callable)r_   r`   vs      r@   ra   zHBasePromptTemplate._merge_partial_and_user_variables.<locals>.<dictcomp>"  s@     
 
 
15AA,qq
 
 
rB   )r.   items)r=   r   partial_kwargss      r@   !_merge_partial_and_user_variablesz4BasePromptTemplate._merge_partial_and_user_variables   sA    
 
9=9O9U9U9W9W
 
 
 ,.+F++rB   r#   c                    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")
        NrG   r   s     r@   formatzBasePromptTemplate.format'  r   rB   c                    K    | j         d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")
        rG   )r   r   s     r@   aformatzBasePromptTemplate.aformat8  s        t{$$V$$$rB   r]   c                    t           )zReturn the prompt type key.)NotImplementedErrorrR   s    r@   _prompt_typezBasePromptTemplate._prompt_typeI  s
     "!rB   c                     t                      j        di |}t          j        t                    5  | j        |d<   ddd           n# 1 swxY w Y   |S )a1  Return dictionary representation of prompt.

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

        Returns:
            Dict: Dictionary representation of the prompt.

        Raises:
            NotImplementedError: If the prompt type is not implemented.
        _typeNrG   )super
model_dump
contextlibsuppressr   r   )r=   r   r   ro   s      r@   ri   zBasePromptTemplate.dictN  s     )egg(22622 !455 	5 	5#'#4K 	5 	5 	5 	5 	5 	5 	5 	5 	5 	5 	5 	5 	5 	5 	5s   AAA	file_pathUnion[Path, str]Nonec                t   | j         rd}t          |          |                                 }d|vrd|  d}t          |          t	          |          }|j        }|                    dd           |j        dk    rG|                    d          5 }t          j
        ||d	
           ddd           dS # 1 swxY w Y   dS |j                            d          rG|                    d          5 }t          j
        ||d           ddd           dS # 1 swxY w Y   dS | d}t          |          )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)default_flow_stylez must be json or yaml)r.   r9   ri   r   r   parentmkdirsuffixopenjsondumpendswithyaml)r=   r   r>   r   	save_pathdirectory_pathfs          r@   savezBasePromptTemplate.save_  s     ! 	">CS//! iikk+%%;D;;;C%c*** OO	")TD999w&&$$ 4	+q33334 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4 4&&'899 	"$$ D	+qUCCCCD D D D D D D D D D D D D D D D D D 555CS//!s$   B88B<?B<4DD D)r3   r   )r3   r&   )r3   rK   )r3   rO   )r3   r
   rQ   )rV   rW   r3   rX   )rh   r
   r3   ri   )rh   ri   r3   r   )r   ri   rV   rW   r   r
   r3   r   )r   r
   r3   r   )r   r   r3   r%   )r   r
   r3   rO   )r   r
   r3   r#   )r3   r]   )r   r
   r3   ri   )r   r   r3   r   ))rp   
__module____qualname____doc____annotations__r   r)   ri   r,   r-   r.   r/   r0   r   rA   classmethodrJ   rM   r   model_configr   rS   propertyr   rU   rg   r{   r   r   r   r   r   r~   r   r   r   r   r   r   r   __classcell__)ro   s   @r@   r%   r%   -   sU         CB$)E"$5$5$55555: */tT)R)R)RKRRRRA04M4444M+05+F+F+FFFFF4 15H4444* $D$$$$&_'"""   #"6 : : : [:    [ : $  L    _ A A A X XA 15
 
 
 
 X
.       D2 2 2 29 9 9 9 >B
 
 
 
 X
2 >B
 
 
 
 X
2    ^	, 	, 	, 	,) ) ) ) , , , ,    ^ % % % %" " " " X"     "(" (" (" (" (" (" (" ("rB   r%   docr"   r   BasePromptTemplate[str]r3   ri   c                \   d| j         i| j        t          |j                                                }t          |          dk    rOd |j        D             }d| dt          |           d}t          t          |t          j
                            fd|j        D             S )	Npage_contentr   c                    g | ]
}|d k    |S )r   rG   )r_   ivs     r@   
<listcomp>z&_get_document_info.<locals>.<listcomp>  s)     
 
 
23G3GB3G3G3GrB   z?Document prompt requires documents to have metadata variables: z+. Received document with missing metadata: rl   r6   c                "    i | ]}||         S rG   rG   )r_   r`   	base_infos     r@   ra   z&_get_document_info.<locals>.<dictcomp>  s    <<<Ay|<<<rB   )r   r/   r;   r'   rs   rn   rt   r9   r   r   r:   )r   r   missing_metadatarequired_metadatar>   r   s        @r@   _get_document_infor     s    !1BS\BI6122==iHH
q  
 
/
 
 
) ) )$%%) ) ) 	
 393QRRR
 
 	
 =<<<V%;<<<<rB   r]   c                8     |j         d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"
    rG   )r   r   r   r   s     r@   format_documentr     s(    D 6=;;-c6::;;;rB   c                H   K    |j         di t          | |           d{V 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.
    NrG   )r   r   r   s     r@   aformat_documentr     s=      .  BB"4S&"A"ABBBBBBBBBrB   )r   r"   r   r   r3   ri   )r   r"   r   r   r3   r]   )9r   
__future__r   r   r   typingabcr   r   collections.abcr   	functoolsr   pathlibr   r	   r
   r   r   r   r   r   r   pydanticr   r   r   r   typing_extensionsr   r   langchain_core.exceptionsr   r   langchain_core.loadr   "langchain_core.output_parsers.baser   langchain_core.prompt_valuesr   r   r   langchain_core.runnablesr   r   langchain_core.runnables.configr    langchain_core.utils.pydanticr!   langchain_core.documentsr"   r#   ri   r%   r   r   r   rG   rB   r@   <module>r      s   & & " " " " " "       # # # # # # # # # # # # # # % % % % % %                         B B B B B B B B B B B B , , , , , , , , ? ? ? ? ? ? ? ? % % % % % % ? ? ? ? ? ?         
 J I I I I I I I 9 9 9 9 9 9 9 9 9 9 9 9 2111111 7-.. Z" Z" Z" Z" Z"{*+W5E-FZ" Z" Z"z
= = = =$"< "< "< "<JC C C C C CrB   