
    g3fi ?                    ~   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 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-m.Z. erddl	m/Z/ ddl0m1Z1  ed      Z2 G d de*e3e&f   eee2         Z4ddZ5ddZ6ddZ7y)z Base class for prompt templates.    )annotationsN)ABCabstractmethod)Mapping)cached_property)Path)TYPE_CHECKINGAnyGenericTypeVarcast)	BaseModel
ConfigDictFieldmodel_validator)Selfoverride)	ErrorCodecreate_message)dumpd)BaseOutputParser)ChatPromptValueConcretePromptValueStringPromptValue)RunnableConfigRunnableSerializable)ensure_config)create_model_v2)Callable)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d.d       Zeed/d              Zed0d1d       Zd2dZd3dZ	 	 	 	 d3dZe	 d0	 	 	 	 	 	 	 d4d        Ze	 d0	 	 	 	 	 	 	 d4d!       Zed5d"       Z d5d#Z!d6d$Z"d7d%Z#ed8d&       Z$d8d'Z%ed9d(       Z&d: fd)Zd;d*Z' xZ(S )<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BaseOutputParser | Noneoutput_parser)r(   zMapping[str, Any]partial_variablesztyping.Dict[str, Any] | Nonemetadatazlist[str] | Nonetagsafter)modec                   d| j                   v r&d}t        t        |t        j                              d| j
                  v r&d}t        t        |t        j                              t        | j                         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      Y/var/www/auto_recruiter/arenv/lib/python3.12/site-packages/langchain_core/prompts/base.pyvalidate_variable_namesz*BasePromptTemplate.validate_variable_namesH   s     T)))"  sy7U7UV  T+++-  sy7U7UV  d**+889O9OPCG9MCsy7U7UV      c                
    g dS )z~Get 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
     :9r?   c                     y)z,Return `True` as this class is serializable.TrD   rE   s    r=   is_lc_serializablez%BasePromptTemplate.is_lc_serializablem   s     r?   )arbitrary_types_allowedc                ,    t        dt        |             S )Ndict[str, Any])r   r   r:   s    r=   _serializedzBasePromptTemplate._serializedv   s    
 $eDk22r?   c                    t         t        z  S )z%Return the output type of the prompt.)r   r   rM   s    r=   
OutputTypezBasePromptTemplate.OutputType}   s     !#:::r?   c                    | j                   D ci c]%  }|| j                  j                  |t              df' }}| j                  D ci c]%  }|| j                  j                  |t              df' }}t        di ||      S c c}w c c}w )zGet the input schema for the prompt.

        Args:
            config: Configuration for the prompt.

        Returns:
            The input schema for the prompt.
        .NPromptInput)field_definitions)r%   r*   getstrr'   r   )r:   configkrequired_input_variablesoptional_input_variabless        r=   get_input_schemaz#BasePromptTemplate.get_input_schema   s     =A<P<P$
78A  $$Q,c22$
  $
 >B=T=T$
89A  $$Q,d33$
  $
 V!9V=UV
 	
$
$
s   *B	*Bc                h   t        |t              svt        | j                        dk(  r| j                  d   }||i}nLd| j                  j
                   dt        |       d}t        t        |t        j                              |}t        | j                        j                  |      }|rd| j                  j
                   d| d	| j                   d
t        |j                                }|j                         }|d| d| dz  }t!        t        |t        j                              |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}}'.)
isinstancedictlenr%   	__class____name__type	TypeErrorr   r   r7   r8   
differencelistkeyspopKeyError)r:   inner_inputvar_nameinner_input_r;   missingexample_keys          r=   _validate_inputz"BasePromptTemplate._validate_input   sR   +t,4''(A-//2 (+6 99P9P8Q R  $[ 12!5   " #	0N0N  'Ld**+66|DDNN3344J7) T"223d<#4#4#678: 
 "++-K,[M :#}F,C
 sy7U7UV  r?   c                H    | j                  |      } | j                  di |S NrD   )ro   format_promptr:   rj   rl   s      r=   "_format_prompt_with_error_handlingz5BasePromptTemplate._format_prompt_with_error_handling   s(    ++K8!t!!1L11r?   c                d   K   | j                  |      } | j                  di | d {   S 7 wrq   )ro   aformat_promptrs   s      r=   #_aformat_prompt_with_error_handlingz6BasePromptTemplate._aformat_prompt_with_error_handling   s4      ++K8(T((8<8888s   '0.0c                    t        |      }| j                  ri |d   | j                  |d<   | j                  r|dxx   | j                  z  cc<   | j                  | j                  ||d| j
                        S )zInvoke the prompt.

        Args:
            input: Input to the prompt.
            config: Configuration for the prompt.

        Returns:
            The output of the prompt.
        r-   r.   promptrun_type
serialized)r   r-   r.   _call_with_configrt   rN   r:   inputrV   kwargss       r=   invokezBasePromptTemplate.invoke   s~     v&==!HF:$6!H$--!HF:996Ndii'N%%33'' & 
 	
r?   c                0  K   t        |      }| j                  r|d   j                  | j                         | j                  r|d   j	                  | j                         | j                  | j                  ||d| j                         d{   S 7 w)zAsync invoke the prompt.

        Args:
            input: Input to the prompt.
            config: Configuration for the prompt.

        Returns:
            The output of the prompt.
        r-   r.   ry   rz   N)r   r-   updater.   extend_acall_with_configrw   rN   r~   s       r=   ainvokezBasePromptTemplate.ainvoke   s      v&==:%%dmm4996N!!$)),,,44'' - 
 
 	
 
s   BBBBc                     y)zCreate `PromptValue`.

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

        Returns:
            The output of the prompt.
        NrD   r:   r   s     r=   rr   z BasePromptTemplate.format_prompt       r?   c                .   K    | j                   di |S w)zAsync create `PromptValue`.

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

        Returns:
            The output of the prompt.
        rD   )rr   r   s     r=   rv   z!BasePromptTemplate.aformat_prompt  s      "t!!+F++   c                    | j                   j                         }t        t        | j                        j                  |            |d<   i | j                  ||d<    t        |       di |S )zReturn a partial of the prompt template.

        Args:
            **kwargs: Partial variables to set.

        Returns:
            A partial of the prompt template.
        r%   r,   rD   )__dict__copyrf   r8   r%   re   r,   rc   )r:   r   prompt_dicts      r=   partialzBasePromptTemplate.partial  sq     mm((*)-$$%008*
%& ,Pd.D.D+O+O'(tDz(K((r?   c                    | j                   j                         D ci c]  \  }}|t        |      s|n |        }}}i ||S c c}}w N)r,   itemscallable)r:   r   rW   vpartial_kwargss        r=   !_merge_partial_and_user_variablesz4BasePromptTemplate._merge_partial_and_user_variables!  sW     :>9O9O9U9U9W
15AAq,
 
 ,.+F++
s   Ac                     y)a  Format the prompt with the inputs.

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

        Returns:
            A formatted string.

        Example:
            ```python
            prompt.format(variable1="foo")
            ```
        NrD   r   s     r=   formatzBasePromptTemplate.format(  r   r?   c                .   K    | j                   di |S w)a%  Async format the prompt with the inputs.

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

        Returns:
            A formatted string.

        Example:
            ```python
            await prompt.aformat(variable1="foo")
            ```
        rD   )r   r   s     r=   aformatzBasePromptTemplate.aformat8  s      t{{$V$$r   c                    t         )zReturn the prompt type key.)NotImplementedErrorrM   s    r=   _prompt_typezBasePromptTemplate._prompt_typeH  s
     "!r?   c                    t        |   di |}t        j                  t              5  | j
                  |d<   ddd       |S # 1 sw Y   |S xY w)zReturn dictionary representation of prompt.

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

        Returns:
            Dictionary representation of the prompt.
        _typeNrD   )super
model_dump
contextlibsuppressr   r   )r:   r   r   ra   s      r=   r_   zBasePromptTemplate.dictM  sR     g(262  !45 	5#'#4#4K 	5	5s   AAc                J   | j                   rd}t        |      | j                         }d|vrd|  d}t        |      t	        |      }|j
                  }|j                  dd       |j                  dk(  r5|j                  dd	
      5 }t        j                  ||d       ddd       y|j                  j                  d      r5|j                  dd	
      5 }t        j                  ||d       ddd       y| d}t        |      # 1 sw Y   yxY w# 1 sw Y   yxY w)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:
            ```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wzutf-8)encoding   )indentN)z.yamlz.ymlF)default_flow_stylez must be json or yaml)r,   r6   r_   r   r   parentmkdirsuffixopenjsondumpendswithyaml)r:   	file_pathr;   r   	save_pathdirectory_pathfs          r=   savezBasePromptTemplate.save[  s-     !!>CS/! iik+%D6!:;C%c** O	"))TD9w&g6 4!		+q34 4&&'89g6 D!		+qUCD D K45CS/!4 4D Ds   DDDD")returnr   )r   r$   )r   bool)r   rL   )r   r
   r   )rV   RunnableConfig | Noner   ztype[BaseModel])rj   r
   r   r_   )rj   r_   r   r   )r   r_   rV   r   r   r
   r   r   )r   r
   r   r   )r   zstr | Callable[[], str]r   r#   )r   r
   r   rL   )r   r
   r   r!   )r   rU   )r   r
   r   r_   )r   z
Path | strr   None))rb   
__module____qualname____doc____annotations__r   r'   r_   r*   r+   r,   r-   r.   r   r>   classmethodrG   rI   r   model_configr   rN   propertyr   rP   rZ   ro   rt   rw   r   r   r   rr   rv   r   r   r   r   r   r   __classcell__)ra   s   @r=   r#   r#   '   s    C %*"$5	5
 */tT)RK&R .2M*1M+0+F(F
 .2H*1*!D
!&'" #6 : :    $L 3 3 ;  ; 
 
*"H299	9 ;?

#8
KN
	
 
2 ;?

#8
KN
	
 
2  	,) ,  %  " "("r?   r#   c                   d| j                   i| j                  }t        |j                        j	                  |      }t        |      dkD  rU|j                  D cg c]
  }|dk7  s	| }}d| dt        |       d}t        t        |t        j                              |j                  D ci c]  }|||   
 c}S c c}w c c}w )Npage_contentr   z?Document prompt requires documents to have metadata variables: z+. Received document with missing metadata: r]   r3   )r   r-   r8   r%   re   r`   rf   r6   r   r   r7   )docry   	base_infomissing_metadataivrequired_metadatar;   rW   s           r=   _get_document_infor     s    !1!1BS\\BI6112==iH
q //
23GB
 
 N !!L$%&a) 	
 393Q3QR
 	
 &,%;%;<Ay|O<<
 =s   
C &C 0Cc                :     |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:
        ```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"
        ```
    rD   )r   r   r   ry   s     r=   format_documentr     s!    D 6==;-c6:;;r?   c                V   K    |j                   di t        | |       d{   S 7 w)a0  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.
    NrD   )r   r   r   s     r=   aformat_documentr     s*     .  B"4S&"ABBBBs    )'))r   r    ry   BasePromptTemplate[str]r   r_   )r   r    ry   r   r   rU   )8r   
__future__r   r   r   typingabcr   r   collections.abcr   	functoolsr   pathlibr   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   r   langchain_core.documentsr    r!   r_   r#   r   r   r   rD   r?   r=   <module>r      s    & "    # # %  = =  B B , ? % ? 
 J 9 9(1 -. \"{*+S':J2K\"~
=$"<JCr?   