a
    ”˜ëj¢7  ã                   @  s  U d Z ddlmZ ddl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 ddl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 z<ddlmZ ddlm Z  ddl!m"Z" G dd„ de"ƒZ#dZ$W n e%yø   dZ$Y n0 ed Z&ddddœdd„Z'ddddœdd„Z(dd d!œd"d#„Z)ddddœd$d%„Z*dd d!œd&d'„Z+e,e-d(f Z.dd)d!œd*d+„Z/dd(d,d-œd.d/„Z0ej1e*e'dœZ2d0e3d1< ej4e(d2œZ5d0e3d3< dd4d!œd5d6„Z6ddd!œd7d8„Z7ddddd9œd:d;„Z8dddd<œd=d>„Z9G d?d@„ d@eeƒZ:dAdAdBdCœdDdE„Z;dS )FzBasePrompt schema definition.é    )ÚannotationsN)ÚABC)ÚCallableÚSequence)Ú	Formatter)ÚAnyÚLiteral)Ú	BaseModelÚcreate_model)ÚPromptValueÚStringPromptValue)ÚBasePromptTemplate)Úget_colored_textÚmustache)Ú	formatter)Úis_interactive_env)Úmeta)ÚSecurityError)ÚSandboxedEnvironmentc                   @  sF   e Zd ZdZdddddœdd„Zdddœd	d
„Zddddœdd„ZdS )Ú_RestrictedSandboxedEnvironmentzüA more restrictive Jinja2 sandbox that blocks all attribute/method access.

        This sandbox only allows simple variable lookups, no attribute or method access.
        This prevents template injection attacks via methods like parse_raw().
        r   ÚstrÚbool)Ú_objÚ_attrÚ_valueÚreturnc                 C  s   dS )aé  Block ALL attribute access for security.

            Only allow accessing variables directly from the context dict,
            no attribute access on those objects.

            Args:
                _obj: The object being accessed (unused, always blocked).
                _attr: The attribute name (unused, always blocked).
                _value: The attribute value (unused, always blocked).

            Returns:
                False - all attribute access is blocked.
            F© )Úselfr   r   r   r   r   ú\/mnt/bigstor/www/usecases/.venv/lib/python3.9/site-packages/langchain_core/prompts/string.pyÚis_safe_attribute   s    z1_RestrictedSandboxedEnvironment.is_safe_attribute)r   r   c                 C  s   dS )zÖBlock all method calls for security.

            Args:
                _obj: The object being checked (unused, always blocked).

            Returns:
                False - all callables are blocked.
            Fr   )r   r   r   r   r   Úis_safe_callable0   s    	z0_RestrictedSandboxedEnvironment.is_safe_callable)ÚobjÚ	attributer   c                 C  s$   d|› dt |ƒj› d�}t|ƒ‚dS )a+  Override getattr to block all attribute access.

            Args:
                obj: The object.
                attribute: The attribute name.

            Returns:
                Never returns.

            Raises:
                SecurityError: Always, to block attribute access.
            zGAccess to attributes is not allowed in templates. Attempted to access 'z' on zK. Use only simple variable names like {{variable}} without dots or methods.N)ÚtypeÚ__name__r   )r   r!   r"   Úmsgr   r   r   Úgetattr;   s    ÿÿÿz'_RestrictedSandboxedEnvironment.getattrN)r$   Ú
__module__Ú__qualname__Ú__doc__r   r    r&   r   r   r   r   r      s   r   TF)úf-stringr   Újinja2r   r   )ÚtemplateÚkwargsr   c                K  s(   t sd}t|ƒ‚tƒ  | ¡jf i |¤ŽS )a¥  Format a template using jinja2.

    *Security warning*:
        As of LangChain 0.0.329, this method uses Jinja2's
        SandboxedEnvironment by default. However, this sand-boxing should
        be treated as a best-effort approach rather than a guarantee of security.
        Do not accept jinja2 templates from untrusted sources as they may lead
        to arbitrary Python code execution.

        https://jinja.palletsprojects.com/en/3.1.x/sandbox/

    Args:
        template: The template string.
        **kwargs: The variables to format the template with.

    Returns:
        The formatted string.

    Raises:
        ImportError: If jinja2 is not installed.
    a  jinja2 not installed, which is needed to use the jinja2_formatter. Please install it with `pip install jinja2`.Please be cautious when using jinja2 templates. Do not expand jinja2 templates using unverified or user-controlled inputs as that can result in arbitrary Python code execution.)Ú_HAS_JINJA2ÚImportErrorr   Zfrom_stringÚrender)r,   r-   r%   r   r   r   Újinja2_formatterW   s
    ÿr1   ú	list[str]ÚNone)r,   Úinput_variablesr   c                 C  sd   t |ƒ}t| ƒ}|| }|| }d}|r8|d|› d�7 }|rJ|d|› �7 }|r`tj| ¡ dd� dS )záValidate that the input variables are valid for the template.

    Issues a warning if missing or extra variables are found.

    Args:
        template: The template string.
        input_variables: The input variables.
    Ú zMissing variables: ú zExtra variables: é   )Ú
stacklevelN)ÚsetÚ#_get_jinja2_variables_from_templateÚwarningsÚwarnÚstrip)r,   r4   Zinput_variables_setZvalid_variablesZmissing_variablesZextra_variablesZwarning_messager   r   r   Úvalidate_jinja2}   s    	r>   zset[str])r,   r   c                 C  s*   t sd}t|ƒ‚tƒ }| | ¡}t |¡S )Nzojinja2 not installed, which is needed to use the jinja2_formatter. Please install it with `pip install jinja2`.)r.   r/   r   Úparser   Zfind_undeclared_variables)r,   r%   ÚenvÚastr   r   r   r:   –   s    ÿ
r:   c                K  s   t  | |¡S )zÁFormat a template using mustache.

    Args:
        template: The template string.
        **kwargs: The variables to format the template with.

    Returns:
        The formatted string.
    )r   r0   )r,   r-   r   r   r   Úmustache_formatter¢   s    
rB   c                 C  sp   t ƒ }d}t | ¡D ]V\}}|dkr.|d8 }n,|dv rZ|dkrZ|dkrZ| | d¡d ¡ |dv r|d7 }q|S )z™Get the variables from a mustache template.

    Args:
        template: The template string.

    Returns:
        The variables from the template.
    r   Úendé   >   úinverted sectionÚvariableú	no escapeÚsectionÚ.>   rE   rH   )r9   r   ÚtokenizeÚaddÚsplit)r,   Ú	variablesZsection_depthÚtype_Úkeyr   r   r   Úmustache_template_vars¯   s    
ÿþý
rP   ÚDefsztype[BaseModel]c                   s  i }d}g }t  | ¡D ]t\}}|dkr(q|dkr>|rŠ| ¡ }q|dv rl| |¡ |t| d¡ƒ7 }d||< q|dv rd||t| d¡ƒ < q| ¡ D ](\‰ }|o¶t‡ fdd	„|D ƒƒ |ˆ < q”i }|�r| ¡ \}}	|}
|d
d… D ]}|
 	|i ¡}
qä|
 	|d |	�r
dni ¡ qÂt
d|ƒS )z­Get the variables from a mustache template.

    Args:
        template: The template string.

    Returns:
        The variables from the template as a Pydantic model.
    r   rI   rC   >   rE   rH   F>   rF   rG   Tc                 3  s    | ]}|ˆ krt ˆ |ƒV  qd S ©N)Úis_subsequence)Ú.0Úk©Zfkeyr   r   Ú	<genexpr>ç   s   z"mustache_schema.<locals>.<genexpr>Néÿÿÿÿr5   ZPromptInput)r   rJ   ÚpopÚappendÚtuplerL   ÚitemsÚanyÚpopitemÚ
setdefaultÚ_create_model_recursive)r,   ÚfieldsÚprefixZsection_stackrN   rO   ZfvalÚdefsÚfieldZis_leafÚcurrentÚpartr   rV   r   Úmustache_schemaÍ   s6    	


ÿrg   r#   )Únamerc   r   c                 C  s   t | fi dd„ | ¡ D ƒ¤ŽS )Nc                 S  s0   i | ](\}}||r t ||ƒd fn
t|ƒd f“qS rR   )r`   r#   ©rT   rU   Úvr   r   r   Ú
<dictcomp>÷   s   ÿz+_create_model_recursive.<locals>.<dictcomp>)r
   r\   )rh   rc   r   r   r   r`   ô   s    ÿþþr`   zdict[str, Callable]ÚDEFAULT_FORMATTER_MAPPING)r*   r+   ÚDEFAULT_VALIDATOR_MAPPINGzlist[tuple[str, str | None]]c                 C  s8   g }t ƒ  | ¡D ]"\}}}}|d ur| ||f¡ q|S rR   )r   r?   rZ   )r,   ra   Ú_Ú
field_nameÚformat_specr   r   r   Ú_parse_f_string_fields
  s
    rq   c                 C  s’   t ƒ }t| ƒD ]z\}}d|v s.d|v s.d|v rBd|›d�}t|ƒ‚| ¡ r^d|›d�}t|ƒ‚|r~d|v srd|v r~d	}t|ƒ‚| |¡ qt|ƒS )
z=Validate an f-string template and return its input variables.rI   ú[ú]zInvalid variable name z[ in f-string template. Variable names cannot contain attribute access (.) or indexing ([]).zk in f-string template. Variable names cannot be all digits as they are interpreted as positional arguments.Ú{Ú}zYInvalid format specifier in f-string template. Nested replacement fields are not allowed.)r9   rq   Ú
ValueErrorÚisdigitrK   Úsorted)r,   r4   Úvarrp   r%   r   r   r   Úvalidate_f_string_template  s     
ÿ
ÿÿrz   )r,   Útemplate_formatr4   r   c              
   C  s´   zt | }W nD tyP } z,d|›dttƒ› d�}t|ƒ|‚W Y d}~n
d}~0 0 |dkrbt| ƒ z|| |ƒ W n> ttfy® } z"d|› d�}t|ƒ|‚W Y d}~n
d}~0 0 dS )a_  Check that template string is valid.

    Args:
        template: The template string.
        template_format: The template format. Should be one of "f-string" or "jinja2".
        input_variables: The input variables.

    Raises:
        ValueError: If the template format is not supported.
        ValueError: If the prompt schema is invalid.
    zInvalid template format z, should be one of rI   Nr*   zMInvalid prompt schema; check for mismatched or missing input parameters from )rm   ÚKeyErrorÚlistrl   rv   rz   Ú
IndexError)r,   r{   r4   Zvalidator_funcÚexcr%   r   r   r   Úcheck_valid_template2  s$    ÿÿ ÿÿr€   )r,   r{   r   c                 C  sT   |dkrt t| ƒƒ}n6|dkr(t| ƒ}n$|dkr:t| ƒ}nd|› �}t|ƒ‚t |ƒS )a3  Get the variables from the template.

    Args:
        template: The template string.
        template_format: The template format. Should be one of "f-string" or "jinja2".

    Returns:
        The variables from the template.

    Raises:
        ValueError: If the template format is not supported.
    r+   r*   r   zUnsupported template format: )rx   r:   rz   rP   rv   )r,   r{   r4   r%   r   r   r   Úget_template_variablesT  s    


r�   c                   @  sb   e Zd ZdZeddœdd„ƒZ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 )ÚStringPromptTemplatezAString prompt that exposes the format method, returning a prompt.r2   )r   c                 C  s   g d¢S )zvGet the namespace of the langchain object.

        Returns:
            ``["langchain", "prompts", "base"]``
        )Z	langchainZpromptsÚbaser   )Úclsr   r   r   Úget_lc_namespaces  s    z%StringPromptTemplate.get_lc_namespacer   r   )r-   r   c                 K  s   t | jf i |¤Žd�S )z³Format the prompt with the inputs.

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

        Returns:
            A formatted string.
        ©Útext)r   Úformat©r   r-   r   r   r   Úformat_prompt|  s    	z"StringPromptTemplate.format_promptc                 Ë  s   t | jf i |¤ŽI dH d�S )z¹Async format the prompt with the inputs.

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

        Returns:
            A formatted string.
        Nr†   )r   Zaformatr‰   r   r   r   Úaformat_prompt‡  s    	z#StringPromptTemplate.aformat_promptFr   r   )Úhtmlr   c                 C  s6   dd„ | j D ƒ}|r&dd„ | ¡ D ƒ}| jf i |¤ŽS )zÅGet a pretty representation of the prompt.

        Args:
            html: Whether to return an HTML-formatted string.

        Returns:
            A pretty representation of the prompt.
        c                 S  s   i | ]}|d |›  d “qS )rt   ru   r   )rT   Z	input_varr   r   r   rk   Ÿ  s   z4StringPromptTemplate.pretty_repr.<locals>.<dictcomp>c                 S  s   i | ]\}}|t |d ƒ“qS )Zyellow)r   ri   r   r   r   rk   £  s   )r4   r\   rˆ   )r   rŒ   Z
dummy_varsr   r   r   Úpretty_repr’  s    ÿÿz StringPromptTemplate.pretty_reprr3   c                 C  s   t | jtƒ d�ƒ dS )z,Print a pretty representation of the prompt.)rŒ   N)Úprintr�   r   )r   r   r   r   Úpretty_print¨  s    z!StringPromptTemplate.pretty_printN)F)
r$   r'   r(   r)   Úclassmethodr…   rŠ   r‹   r�   r�   r   r   r   r   r‚   p  s    þr‚   r   r   )ÚchildÚparentr   c                   sP   t ˆ ƒdkst ˆƒdkrdS t ˆƒt ˆ ƒk r0dS t‡ ‡fdd„tt ˆ ƒƒD ƒƒS )z.Return True if child is subsequence of parent.r   Fc                 3  s   | ]}ˆ | ˆ| kV  qd S rR   r   )rT   Úi©r‘   r’   r   r   rW   ³  ó    z!is_subsequence.<locals>.<genexpr>)ÚlenÚallÚranger”   r   r”   r   rS   ­  s
    rS   )<r)   Ú
__future__r   r;   Úabcr   Úcollections.abcr   r   Ústringr   Útypingr   r   Zpydanticr	   r
   Zlangchain_core.prompt_valuesr   r   Zlangchain_core.prompts.baser   Zlangchain_core.utilsr   r   Zlangchain_core.utils.formattingr   Z$langchain_core.utils.interactive_envr   r+   r   Zjinja2.exceptionsr   Zjinja2.sandboxr   r   r.   r/   ZPromptTemplateFormatr1   r>   r:   rB   rP   Údictr   rQ   rg   r`   rˆ   rl   Ú__annotations__Zvalidate_input_variablesrm   rq   rz   r€   r�   r‚   rS   r   r   r   r   Ú<module>   sT   8
&'ýþ "=