o
    Zh6                     @   s   d Z ddlmZ ddlmZmZmZmZmZ ddl	m
Z
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 dd	lmZ d
efddZG dd deeZG dd deZG dd deeZG dd deeZdS )z:String distance evaluators based on the RapidFuzz library.    )Enum)AnyCallableDictListOptional)AsyncCallbackManagerForChainRunCallbackManagerForChainRun	Callbacks)pre_init)Field)Chain)PairwiseStringEvaluatorStringEvaluator)RUN_KEYreturnc                  C   s(   zddl } W | jS  ty   tdw )z
    Load the RapidFuzz library.

    Raises:
        ImportError: If the rapidfuzz library is not installed.

    Returns:
        Any: The rapidfuzz.distance module.
    r   NzyPlease install the rapidfuzz library to use the FuzzyMatchStringEvaluator.Please install it with `pip install rapidfuzz`.)	rapidfuzzImportErrordistance)r    r   `/var/www/html/lang_env/lib/python3.10/site-packages/langchain/evaluation/string_distance/base.py_load_rapidfuzz   s   

r   c                   @   s(   e Zd ZdZdZdZdZdZdZdZ	dS )	StringDistancea7  Distance metric to use.

    Attributes:
        DAMERAU_LEVENSHTEIN: The Damerau-Levenshtein distance.
        LEVENSHTEIN: The Levenshtein distance.
        JARO: The Jaro distance.
        JARO_WINKLER: The Jaro-Winkler distance.
        HAMMING: The Hamming distance.
        INDEL: The Indel distance.
    Zdamerau_levenshteinZlevenshteinZjaroZjaro_winklerZhammingZindelN)
__name__
__module____qualname____doc__DAMERAU_LEVENSHTEINLEVENSHTEINJAROJARO_WINKLERHAMMINGINDELr   r   r   r   r   '   s    r   c                   @   s   e Zd ZU dZeejdZeed< eddZ	e
ed< 	 edeeef deeef fdd	Zedee fd
dZdeeef deeef fddZeddede
defddZedefddZdededefddZdS )_RapidFuzzChainMixinz<Shared methods for the rapidfuzz string distance evaluators.)defaultr   Tnormalize_scorevaluesr   c                 C   s
   t   |S )z
        Validate that the rapidfuzz library is installed.

        Args:
            values (Dict[str, Any]): The input values.

        Returns:
            Dict[str, Any]: The validated values.
        )r   )clsr&   r   r   r   validate_dependenciesC   s   z*_RapidFuzzChainMixin.validate_dependenciesc                 C   s   dgS )z`
        Get the output keys.

        Returns:
            List[str]: The output keys.
        scorer   selfr   r   r   output_keysQ   s   z _RapidFuzzChainMixin.output_keysresultc                 C   s(   d|d i}t |v r|t   |t < |S )z
        Prepare the output dictionary.

        Args:
            result (Dict[str, Any]): The evaluation results.

        Returns:
            Dict[str, Any]: The prepared output dictionary.
        r)   )r   dict)r+   r-   r   r   r   _prepare_output[   s   
z$_RapidFuzzChainMixin._prepare_outputFc                 C   sx   ddl m} tj|jtj|jtj|jtj	|j
tj|jtj|ji}| |vr0td|  dtt ||  }|r9|jS |jS )a  
        Get the distance metric function based on the distance type.

        Args:
            distance (str): The distance type.

        Returns:
            Callable: The distance metric function.

        Raises:
            ValueError: If the distance metric is invalid.
        r   )r   zInvalid distance metric: z
Must be one of: )r   r   r   r   ZDamerauLevenshteinr   ZLevenshteinr   ZJaror    ZJaroWinklerr!   ZHammingr"   ZIndel
ValueErrorlistZnormalized_distance)r   r%   Zrf_distanceZ
module_mapmoduler   r   r   _get_metricj   s$   z _RapidFuzzChainMixin._get_metricc                 C   s   t j| j| jdS )zy
        Get the distance metric function.

        Returns:
            Callable: The distance metric function.
        )r%   )r#   r3   r   r%   r*   r   r   r   metric   s   z_RapidFuzzChainMixin.metricabc                 C   s   |  ||S )z
        Compute the distance between two strings.

        Args:
            a (str): The first string.
            b (str): The second string.

        Returns:
            float: The distance between the two strings.
        )r4   )r+   r5   r6   r   r   r   compute_metric   s   z#_RapidFuzzChainMixin.compute_metricN)F)r   r   r   r   r   r   r    r   __annotations__r%   boolr   r   strr   r(   propertyr   r,   r/   staticmethodr   r3   r4   floatr7   r   r   r   r   r#   ;   s   
 $"	"r#   c                   @   sl  e Zd ZdZedefddZedefddZedee	 fddZ
ede	fd	d
Z	d dee	ef dee dee	ef fddZ	d dee	ef dee dee	ef fddZdddddddde	dee	 dee	 dedeee	  deee	ef  dededefddZdddddddde	dee	 dee	 dedeee	  deee	ef  dededefddZdS )!StringDistanceEvalChainak  Compute string distances between the prediction and the reference.

    Examples
    ----------

    >>> from langchain.evaluation import StringDistanceEvalChain
    >>> evaluator = StringDistanceEvalChain()
    >>> evaluator.evaluate_strings(
            prediction="Mindy is the CTO",
            reference="Mindy is the CEO",
        )

    Using the `load_evaluator` function:

    >>> from langchain.evaluation import load_evaluator
    >>> evaluator = load_evaluator("string_distance")
    >>> evaluator.evaluate_strings(
            prediction="The answer is three",
            reference="three",
        )
    r   c                 C      dS )z8
        This evaluator does not require input.
        Fr   r*   r   r   r   requires_input      z&StringDistanceEvalChain.requires_inputc                 C   r?   )z>
        This evaluator does not require a reference.
        Tr   r*   r   r   r   requires_reference   rA   z*StringDistanceEvalChain.requires_referencec                 C      ddgS )^
        Get the input keys.

        Returns:
            List[str]: The input keys.
        	reference
predictionr   r*   r   r   r   
input_keys      z"StringDistanceEvalChain.input_keysc                 C   s   | j j dS )b
        Get the evaluation name.

        Returns:
            str: The evaluation name.
        	_distancer   valuer*   r   r   r   evaluation_name   s   z'StringDistanceEvalChain.evaluation_nameNinputsrun_managerc                 C      d|  |d |d iS )a^  
        Compute the string distance between the prediction and the reference.

        Args:
            inputs (Dict[str, Any]): The input values.
            run_manager (Optional[CallbackManagerForChainRun]):
                The callback manager.

        Returns:
            Dict[str, Any]: The evaluation results containing the score.
        r)   rE   rF   r7   r+   rN   rO   r   r   r   _call   s   zStringDistanceEvalChain._callc                       d|  |d |d iS )a}  
        Asynchronously compute the string distance between the prediction
            and the reference.

        Args:
            inputs (Dict[str, Any]): The input values.
            run_manager (Optional[AsyncCallbackManagerForChainRun]:
                The callback manager.

        Returns:
            Dict[str, Any]: The evaluation results containing the score.
        r)   rE   rF   rQ   rR   r   r   r   _acall   s   zStringDistanceEvalChain._acallF)rE   input	callbackstagsmetadatainclude_run_inforF   rE   rV   rW   rX   rY   rZ   kwargsc          
      K   s"   | ||d||||d}	|  |	S )a  
        Evaluate the string distance between the prediction and the reference.

        Args:
            prediction (str): The prediction string.
            reference (Optional[str], optional): The reference string.
            input (Optional[str], optional): The input string.
            callbacks (Callbacks, optional): The callbacks to use.
            kwargs: Additional keyword arguments.

        Returns:
            dict: The evaluation results containing the score.
        rF   rE   rN   rW   rX   rY   rZ   r/   
r+   rF   rE   rV   rW   rX   rY   rZ   r[   r-   r   r   r   _evaluate_strings  s   
z)StringDistanceEvalChain._evaluate_stringsc          
         s,   | j ||d||||dI dH }	| |	S )a  
        Asynchronously evaluate the string distance between the
            prediction and the reference.

        Args:
            prediction (str): The prediction string.
            reference (Optional[str], optional): The reference string.
            input (Optional[str], optional): The input string.
            callbacks (Callbacks, optional): The callbacks to use.
            kwargs: Additional keyword arguments.

        Returns:
            dict: The evaluation results containing the score.
        r\   r]   NZacallr/   r_   r   r   r   _aevaluate_strings(  s   
z*StringDistanceEvalChain._aevaluate_stringsN)r   r   r   r   r;   r9   r@   rB   r   r:   rG   rM   r   r   r   r	   rS   r   rU   r
   r.   r`   rb   r   r   r   r   r>      s    	






	

'
	
r>   c                   @   s(  e Zd ZdZedee fddZedefddZ	dde	ee
f d	ee de	ee
f fd
dZ	dde	ee
f d	ee de	ee
f fddZddddddedededeee  dee	ee
f  dede
defddZddddddedededeee  dee	ee
f  dede
defddZdS )PairwiseStringDistanceEvalChainz6Compute string edit distances between two predictions.r   c                 C   rC   )rD   rF   prediction_br   r*   r   r   r   rG   O  rH   z*PairwiseStringDistanceEvalChain.input_keysc                 C   s   d| j j dS )rI   Z	pairwise_rJ   rK   r*   r   r   r   rM   Y  s   z/PairwiseStringDistanceEvalChain.evaluation_nameNrN   rO   c                 C   rP   )aN  
        Compute the string distance between two predictions.

        Args:
            inputs (Dict[str, Any]): The input values.
            run_manager (CallbackManagerForChainRun , optional):
                The callback manager.

        Returns:
            Dict[str, Any]: The evaluation results containing the score.
        r)   rF   re   rQ   rR   r   r   r   rS   c  s   z%PairwiseStringDistanceEvalChain._callc                    rT   )ab  
        Asynchronously compute the string distance between two predictions.

        Args:
            inputs (Dict[str, Any]): The input values.
            run_manager (AsyncCallbackManagerForChainRun , optional):
                The callback manager.

        Returns:
            Dict[str, Any]: The evaluation results containing the score.
        r)   rF   re   rQ   rR   r   r   r   rU   w  s   z&PairwiseStringDistanceEvalChain._acallF)rW   rX   rY   rZ   rF   re   rW   rX   rY   rZ   r[   c          	      K   s"   | ||d||||d}|  |S )a$  
        Evaluate the string distance between two predictions.

        Args:
            prediction (str): The first prediction string.
            prediction_b (str): The second prediction string.
            callbacks (Callbacks, optional): The callbacks to use.
            tags (List[str], optional): Tags to apply to traces.
            metadata (Dict[str, Any], optional): Metadata to apply to traces.
            kwargs: Additional keyword arguments.

        Returns:
            dict: The evaluation results containing the score.
        rF   re   r]   r^   	r+   rF   re   rW   rX   rY   rZ   r[   r-   r   r   r   _evaluate_string_pairs  s   
z6PairwiseStringDistanceEvalChain._evaluate_string_pairsc          	         s,   | j ||d||||dI dH }| |S )a3  
        Asynchronously evaluate the string distance between two predictions.

        Args:
            prediction (str): The first prediction string.
            prediction_b (str): The second prediction string.
            callbacks (Callbacks, optional): The callbacks to use.
            tags (List[str], optional): Tags to apply to traces.
            metadata (Dict[str, Any], optional): Metadata to apply to traces.
            kwargs: Additional keyword arguments.

        Returns:
            dict: The evaluation results containing the score.
        rf   r]   Nra   rg   r   r   r   _aevaluate_string_pairs  s   
z7PairwiseStringDistanceEvalChain._aevaluate_string_pairsrc   )r   r   r   r   r;   r   r:   rG   rM   r   r   r   r	   rS   r   rU   r
   r9   r.   rh   ri   r   r   r   r   rd   L  s    	






	

'
	
rd   N)r   enumr   typingr   r   r   r   r   Z langchain_core.callbacks.managerr   r	   r
   Zlangchain_core.utilsr   Zpydanticr   Zlangchain.chains.baser   Zlangchain.evaluation.schemar   r   Zlangchain.schemar   r   r:   r   r#   r>   rd   r   r   r   r   <module>   s    l &