
    gh,                        d Z ddlmZ ddlZddlm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mZmZmZmZ erdd	lmZ  G d
 de          ZdS )zPrompt schema definition.    )annotationsN)Path)TYPE_CHECKINGAnyOptionalUnion)	BaseModelmodel_validator)override)DEFAULT_FORMATTER_MAPPINGPromptTemplateFormatStringPromptTemplatecheck_valid_templateget_template_variablesmustache_schema)RunnableConfigc                  t    e Zd ZU dZeed1d                        Zeed2d                        Zde	d<   	 d	Z
d
e	d<   	 dZde	d<   	  ed          ed3d                        Zed4d5 fd            Zd6dZed7d            Zd8dZe	 	 d9d:d&            Ze	 	 d;d<d,            Zed	dd-d=d0            Z xZS )>PromptTemplatea3  Prompt template for a language model.

    A prompt template consists of a string template. It accepts a set of parameters
    from the user that can be used to generate a prompt for a language model.

    The template can be formatted using either f-strings (default), jinja2,
    or mustache syntax.

    *Security warning*:
        Prefer using `template_format="f-string"` instead of
        `template_format="jinja2"`, or make sure to NEVER accept jinja2 templates
        from untrusted sources as they may lead to arbitrary Python code execution.

        As of LangChain 0.0.329, Jinja2 templates will be rendered using
        Jinja2's SandboxedEnvironment by default. This sand-boxing should
        be treated as a best-effort approach rather than a guarantee of security,
        as it is an opt-out rather than opt-in approach.

        Despite the sand-boxing, we recommend to never use jinja2 templates
        from untrusted sources.

    Example:

        .. code-block:: python

            from langchain_core.prompts import PromptTemplate

            # Instantiation using from_template (recommended)
            prompt = PromptTemplate.from_template("Say {foo}")
            prompt.format(foo="bar")

            # Instantiation using initializer
            prompt = PromptTemplate(template="Say {foo}")
    returndict[str, Any]c                    d| j         iS )Ntemplate_format)r   selfs    Z/var/www/FlaskApp/flask-venv/lib/python3.11/site-packages/langchain_core/prompts/prompt.pylc_attributeszPromptTemplate.lc_attributes=   s     t3
 	
    	list[str]c                
    g dS )N)	langchainpromptsprompt )clss    r   get_lc_namespacezPromptTemplate.get_lc_namespaceD   s     2111r   strtemplatef-stringr   r   Fboolvalidate_templatebefore)modevaluesdictr   c                                        d          S                     dd                               di                                 d          rmd         dk    rd}t          |          d	vrd
}t          |          d	         t          d                   z   }t	          d         d         |           d         r+fdt          d         d                   D             d	<   S )z7Check that template and input variables are consistent.r'   Nr   r(   partial_variablesr*   mustachez'Mustache templates cannot be validated.input_variablesz:Input variables must be provided to validate the template.c                (    g | ]}|d          v|S )r0   r#   ).0varr-   s     r   
<listcomp>z6PromptTemplate.pre_init_validation.<locals>.<listcomp>o   s8     ) ) ) f%8999	  :99r   )get
setdefault
ValueErrorlistr   r   )r$   r-   msg
all_inputss    `  r   pre_init_validationz"PromptTemplate.pre_init_validationS   sB    ::j!!) M 	+Z888-r222::)** 	'(J66? oo% ..R oo% 12T&AT:U5V5VVJ z"F+<$=z   #$ 	) ) ) )1:&/@(A ) ) )F$% r   NconfigRunnableConfig | Nonetype[BaseModel]c                    | j         dk    r!t                                          |          S t          | j                  S )zGet the input schema for the prompt.

        Args:
            config: The runnable configuration.

        Returns:
            The input schema for the prompt.
        r1   )r   superget_input_schemar   r'   )r   r>   	__class__s     r   rC   zPromptTemplate.get_input_schemay   s;     :--77++F333t}---r   otherc                   t          |t                    r| j        dk    rd}t          |          |j        dk    rd}t          |          t	          t          | j                  t          |j                  z            }| j        |j        z   }| j        o|j        }t          | j
                                                  }|j
                                        D ]\  }}||v rd}t          |          |||<    t          |||d|          S t          |t                    rt                              |          }	| |	z   S dt          |           }t          |          )z@Override the + operator to allow for combining prompt templates.r(   z5Adding prompt templates only supported for f-strings.z*Cannot have same variable partialed twice.)r'   r2   r0   r   r*   z Unsupported operand type for +: )
isinstancer   r   r9   r:   setr2   r'   r*   r.   r0   itemsr&   from_templatetypeNotImplementedError)
r   rE   r;   r2   r'   r*   r0   kvr"   s
             r   __add__zPromptTemplate.__add__   s    e^,, 	#z11M oo%$
22M oo%"D())C0E,F,FF O }u~5H $ 6 R5;R $T%;%A%A%C%C D D/5577 ) )1)))FC$S//)'(!!$$!! /"3 *"3    eS!! 	!#11%88F&= >e>>!#&&&r   c                    dS )zReturn the prompt type key.r"   r#   r   s    r   _prompt_typezPromptTemplate._prompt_type   s	     xr   kwargsc                V     | j         di |}t          | j                 | j        fi |S )zFormat the prompt with the inputs.

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

        Returns:
            A formatted string.
        r#   )!_merge_partial_and_user_variablesr   r   r'   )r   rR   s     r   formatzPromptTemplate.format   s=     87AA&AA()=>t}WWPVWWWr   

 examplessuffixr2   example_separatorprefixc                L    |                     |g||          } | d||d|S )a  Take examples in list format with prefix and suffix to create a prompt.

        Intended to be used as a way to dynamically create a prompt from examples.

        Args:
            examples: List of examples to use in the prompt.
            suffix: String to go after the list of examples. Should generally
                set up the user's input.
            input_variables: A list of variable names the final prompt template
                will expect.
            example_separator: The separator to use in between examples. Defaults
                to two new line characters.
            prefix: String that should go before any examples. Generally includes
                examples. Default to an empty string.

        Returns:
            The final prompt generated.
        )r2   r'   r#   )join)r$   rX   rY   r2   rZ   r[   rR   r'   s           r   from_exampleszPromptTemplate.from_examples   sA    8 %))6*EH*Ef*EFFsP?XPPPPPr   template_fileUnion[str, Path]Optional[list[str]]encodingOptional[str]c                    t          |                              |          }|rt          j        dt          d            | j        dd|i|S )a#  Load a prompt from a file.

        Args:
            template_file: The path to the file containing the prompt template.
            input_variables: [DEPRECATED] A list of variable names the final prompt
                template will expect. Defaults to None.
            encoding: The encoding system for opening the template file.
                If not provided, will use the OS default.

        input_variables is ignored as from_file now delegates to from_template().

        Returns:
            The prompt loaded from the file.
        )rb   z,`input_variables' is deprecated and ignored.   )
stacklevelr'   r#   )r   	read_textwarningswarnDeprecationWarningrJ   )r$   r_   r2   rb   rR   r'   s         r   	from_filezPromptTemplate.from_file   sl    , &&00(0CC 	M>"   
 !s ==(=f===r   )r   r0   r0   Optional[dict[str, Any]]c               f    t          ||          }|pi rfd|D             } | d|||d|S )a$  Load a prompt template from a template.

        *Security warning*:
            Prefer using `template_format="f-string"` instead of
            `template_format="jinja2"`, or make sure to NEVER accept jinja2 templates
            from untrusted sources as they may lead to arbitrary Python code execution.

            As of LangChain 0.0.329, Jinja2 templates will be rendered using
            Jinja2's SandboxedEnvironment by default. This sand-boxing should
            be treated as a best-effort approach rather than a guarantee of security,
            as it is an opt-out rather than opt-in approach.

            Despite the sand-boxing, we recommend never using jinja2 templates
            from untrusted sources.

        Args:
            template: The template to load.
            template_format: The format of the template. Use `jinja2` for jinja2,
                             `mustache` for mustache, and `f-string` for f-strings.
                             Defaults to `f-string`.
            partial_variables: A dictionary of variables that can be used to partially
                               fill in the template. For example, if the template is
                              `"{variable1} {variable2}"`, and `partial_variables` is
                              `{"variable1": "foo"}`, then the final prompt will be
                              `"foo {variable2}"`. Defaults to None.
            kwargs: Any other arguments to pass to the prompt template.

        Returns:
            The prompt template loaded from the template.
        c                    g | ]}|v|	S r#   r#   )r4   r5   _partial_variabless     r   r6   z0PromptTemplate.from_template.<locals>.<listcomp>%  s+       #=O2O2O2O2O2Or   )r2   r'   r   r0   r#   )r   )r$   r'   r   r0   rR   r2   ro   s         @r   rJ   zPromptTemplate.from_template   s    N 1?KK.4" 	   .  O s 
++0	
 

 
 
 	
r   )r   r   )r   r   )r-   r.   r   r   )N)r>   r?   r   r@   )rE   r   r   r   )r   r&   )rR   r   r   r&   )rV   rW   )rX   r   rY   r&   r2   r   rZ   r&   r[   r&   rR   r   r   r   )NN)
r_   r`   r2   ra   rb   rc   rR   r   r   r   )
r'   r&   r   r   r0   rl   rR   r   r   r   )__name__
__module____qualname____doc__propertyr   r   classmethodr%   __annotations__r   r*   r
   r=   rC   rO   rQ   rU   r^   rk   rJ   __classcell__)rD   s   @r   r   r      s        ! !F 
 
 
 X X

 2 2 2 X [2 MMM,6O66666 $####8_(###" " " [ $#"H . . . . . . X.!' !' !' !'F    X
X 
X 
X 
X  "(Q Q Q Q [Q<  04"&	> > > > [>< 
 1;6:4
 4
 4
 4
 4
 [4
 4
 4
 4
 4
r   r   )rs   
__future__r   rh   pathlibr   typingr   r   r   r   pydanticr	   r
   typing_extensionsr   langchain_core.prompts.stringr   r   r   r   r   r   langchain_core.runnables.configr   r   r#   r   r   <module>r      s1     " " " " " "        6 6 6 6 6 6 6 6 6 6 6 6 / / / / / / / / & & & & & &                 ?>>>>>>V
 V
 V
 V
 V
) V
 V
 V
 V
 V
r   