
    gh(                    h   U d Z ddlmZ ddl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mZ dd	lmZ dd
lmZmZ ddlmZ ddlmZ ed         Zd,dZd-dZd.dZd,dZd.dZ e!e"df         Z#d/dZ$d0d"Z%ej&        eedZ'd#e(d$<   ej)        ed%Z*d#e(d&<   d1d(Z+d2d)Z, G d* d+ee          Z-dS )3zBasePrompt schema definition.    )annotationsN)ABC)	Formatter)AnyCallableLiteral)	BaseModelcreate_model)PromptValueStringPromptValue)BasePromptTemplate)get_colored_textmustache)	formatter)is_interactive_env)f-stringr   jinja2templatestrkwargsr   returnc                   	 ddl m} n$# t          $ r}d}t          |          |d}~ww xY w  |                                |           j        d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.
    r   )SandboxedEnvironmenta  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.N )jinja2.sandboxr   ImportErrorfrom_stringrender)r   r   r   emsgs        Z/var/www/FlaskApp/flask-venv/lib/python3.11/site-packages/langchain_core/prompts/string.pyjinja2_formatterr"      s    ,
&7777777 & & &L 	 #A%&" ?!!--h77>HHHHHs   	 
*%*input_variables	list[str]Nonec                    t          |          }t          |           }||z
  }||z
  }d}|r	|d| dz  }|r|d| z  }|r*t          j        |                                d           dS dS )zValidate 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   r#   input_variables_setvalid_variablesmissing_variablesextra_variableswarning_messages          r!   validate_jinja2r5   A   s     o..9(CCO'*==)O;OO FE1BEEEE A@@@@ =o++--!<<<<<<= =    set[str]c                    	 ddl m}m} n$# t          $ r}d}t          |          |d }~ww xY w |            }|                    |           }|                    |          S )Nr   )Environmentmetazojinja2 not installed, which is needed to use the jinja2_formatter. Please install it with `pip install jinja2`.)r   r9   r:   r   parsefind_undeclared_variables)r   r9   r:   r   r    envasts          r!   r,   r,   Z   s    &,,,,,,,,, & & &; 	 #A%& +--C
))H

C))#...s    
,',c               ,    t          j        | |          S )zFormat a template using mustache.

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

    Returns:
        The formatted string.
    )r   r   )r   r   s     r!   mustache_formatterr@   h   s     ?8V,,,r6   c                    t                      }d}t          j        |           D ]X\  }}|dk    r|dz  }n>|dv r:|dk    r4|dk    r.|                    |                    d          d                    |dv r|dz  }Y|S )zGet the variables from a mustache template.

    Args:
        template: The template string.

    Returns:
        The variables from the template.
    r   end   )variablesectioninverted section	no escape.rE   rF   )r+   r   tokenizeaddsplit)r   varssection_depthtypekeys        r!   mustache_template_varsrQ   u   s     UUDM&x00 
 
	c5==QMMLLLs

""HHSYYs^^A&'''222QMKr6   Defstype[BaseModel]c           	     N   i }d}g }t          j        |           D ]\  }}|dk    r|dk    r|r|                                })|dv r@|                    |           |t	          |                    d                    z   }d||<   m|dv r(d||t	          |                    d                    z   <   i }|r^|                                \  }}|}	|dd	         D ]}
|	                    |
i           }	|	                    |d	         |rd
ni            |^t          d|          S )zGet the variables from a mustache template.

    Args:
        template: The template string.

    Returns:
        The variables from the template as a Pydantic model.
    r   rH   rB   rI   F)rD   rG   TNr'   PromptInput)	r   rJ   popappendtuplerL   popitem
setdefault_create_model_recursive)r   fieldsprefixsection_stackrO   rP   defsfieldis_leafcurrentparts              r!   mustache_schemare      sg    F F+-M&x00 : :	c#::5== -&**,,444  (((eCIIcNN333F"F6NN...59F6E#))C..1112D
 =))w#2#J 	3 	3D((r22GG59G&;bb<<<  = #=$777r6   namer`   rO   c                T    t          | fi d |                                D             S )Nc                `    i | ]+\  }}||rt          ||          d fnt          |          d f,S N)r\   rO   .0kvs      r!   
<dictcomp>z+_create_model_recursive.<locals>.<dictcomp>   sR     
 
 
1 N'1--t44Q
 
 
r6   )r
   items)rf   r`   s     r!   r\   r\      sE     
 



 
 
  r6   zdict[str, Callable]DEFAULT_FORMATTER_MAPPING)r   r   DEFAULT_VALIDATOR_MAPPINGtemplate_formatc                   	 t           |         }n=# t          $ r0}d|dt          t                     d}t	          |          |d}~ww xY w	  || |           dS # t          t
          f$ r}d| d}t	          |          |d}~ww xY w)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 rH   NzMInvalid prompt schema; check for mismatched or missing input parameters from )rq   KeyErrorlistrp   
ValueError
IndexError)r   rr   r#   validator_funcexcr    s         r!   check_valid_templaterz      s    '2?C ' ' '3 3 3.//3 3 3 	 oo3&''x11111j! ' ' '($( ( ( 	 oo3&'s,    
A
+AA
A B-BBc                   |dk    rt          |           }n\|dk    r,d t                                          |           D             }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   c                     h | ]\  }}}}|	|S ri   r   )rk   _rm   s      r!   	<setcomp>z)get_template_variables.<locals>.<setcomp>   s(     
 
 
!Q1q}A}}}r6   r   zUnsupported template format: )r,   r   r;   rQ   rv   sorted)r   rr   r#   r    s       r!   get_template_variablesr      s     (""=hGG	J	&	&
 
 ) 1 1( ; ;
 
 
 
J	&	&0::?o??oo/"""r6   c                  N    e Zd ZdZedd            ZddZdd	Z	 dddZddZ	dS )StringPromptTemplatezAString prompt that exposes the format method, returning a prompt.r   r$   c                
    g dS )z*Get the namespace of the langchain object.)	langchainpromptsbaser   )clss    r!   get_lc_namespacez%StringPromptTemplate.get_lc_namespace  s     0///r6   r   r   r   c                8    t           | j        di |          S )zFormat the prompt with the inputs.

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

        Returns:
            A formatted string.
        textr   )r   formatselfr   s     r!   format_promptz"StringPromptTemplate.format_prompt  s'     !kdk&;&;F&;&;<<<<r6   c                H   K   t           | j        di | d{V           S )zAsync format the prompt with the inputs.

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

        Returns:
            A formatted string.
        Nr   r   )r   aformatr   s     r!   aformat_promptz#StringPromptTemplate.aformat_prompt  s=       !LDL,B,B6,B,B&B&B&B&B&B&BCCCCr6   Fhtmlboolr   c                ~    d | j         D             }|rd |                                D             } | j        di |S )zGet a pretty representation of the prompt.

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

        Returns:
            A pretty representation of the prompt.
        c                "    i | ]}|d | z   dz   S ){}r   )rk   	input_vars     r!   rn   z4StringPromptTemplate.pretty_repr.<locals>.<dictcomp>5  s3     
 
 
6?Is	^+c1
 
 
r6   c                6    i | ]\  }}|t          |d           S )yellow)r   rj   s      r!   rn   z4StringPromptTemplate.pretty_repr.<locals>.<dictcomp>9  s6       59Q#Ax00  r6   r   )r#   ro   r   )r   r   
dummy_varss      r!   pretty_reprz StringPromptTemplate.pretty_repr(  sq    
 
CGCW
 
 

  	 =G=M=M=O=O  J t{((Z(((r6   r%   c                d    t          |                     t                                           dS )z,Print a pretty representation of the prompt.)r   N)printr   r   )r   s    r!   pretty_printz!StringPromptTemplate.pretty_print>  s.    d$6$8$899:::::r6   N)r   r$   )r   r   r   r   )F)r   r   r   r   )r   r%   )
__name__
__module____qualname____doc__classmethodr   r   r   r   r   r   r6   r!   r   r   
  s        KK0 0 0 [0	= 	= 	= 	=	D 	D 	D 	D ) ) ) ) ),; ; ; ; ; ;r6   r   )r   r   r   r   r   r   )r   r   r#   r$   r   r%   )r   r   r   r7   )r   r   r   rS   )rf   r   r`   rR   r   rO   )r   r   rr   r   r#   r$   r   r%   )r   r   rr   r   r   r$   ).r   
__future__r   r-   abcr   stringr   typingr   r   r   pydanticr	   r
   langchain_core.prompt_valuesr   r   langchain_core.prompts.baser   langchain_core.utilsr   r   langchain_core.utils.formattingr   $langchain_core.utils.interactive_envr   PromptTemplateFormatr"   r5   r,   r@   rQ   dictr   rR   re   r\   r   rp   __annotations__validate_input_variablesrq   rz   r   r   r   r6   r!   <module>r      sR   # # # " " " " " "              ) ) ) ) ) ) ) ) ) ) , , , , , , , , G G G G G G G G : : : : : : ; ; ; ; ; ; ; ; 5 5 5 5 5 5 C C C C C C?@ )I )I )I )IX= = = =2/ / / /
- 
- 
- 
-   6 CK!8 !8 !8 !8H     "2 2      22 2     ' ' ' '@# # # #:6; 6; 6; 6; 6;-s 6; 6; 6; 6; 6;r6   