a
    ”˜ëj‰  ã                   @  sÂ   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	m
Z
mZ d dlmZ erXd dlZe e¡Zeeee  ee ef Zddddœd	d
„Zddœdd„ZG dd„ dedd�ZG dd„ dƒZdS )é    )ÚannotationsN)ÚSequence)ÚTYPE_CHECKINGÚAnyÚCallableÚLiteralÚOptionalÚUnion)Ú	TypedDictÚMatrixú
np.ndarray)ÚXÚYÚreturnc                 C  sv  ddl }t| ƒdks t|ƒdkr*| g ¡S | | ¡} | |¡}| jd |jd krltd| j› d|j› d�ƒ‚z`ddl}|j| |jd�} |j||jd�}d|j| |dd	� }t|t	ƒrÂ| |g¡W S | |¡W S  t
�yp   t d
¡ |jj| dd�}|jj|dd�}|jddd��* | | |j¡| ||¡ }W d  ƒ n1 �sF0    Y  d|| |¡| |¡B < | Y S 0 dS )z<Row-wise cosine similarity between two equal-width matrices.r   Né   z;Number of columns in X and Y must be the same. X has shape z and Y has shape Ú.)ZdtypeÚcosine)ÚmetriczƒUnable to import simsimd, defaulting to NumPy implementation. If you want to use simsimd please install with `pip install simsimd`.)ZaxisÚignore)ÚdivideÚinvalidg        )ÚnumpyÚlenÚarrayÚshapeÚ
ValueErrorZsimsimdÚfloat32ZcdistÚ
isinstanceÚfloatÚImportErrorÚloggerÚdebugÚlinalgÚnormZerrstateÚdotÚTÚouterÚisnanÚisinf)r   r   ÚnpZsimdÚZZX_normZY_normZ
similarity© r+   úf/mnt/bigstor/www/usecases/.venv/lib/python3.9/site-packages/langsmith/_internal/_embedding_distance.pyÚcosine_similarity   s:    



ÿÿ
ÿ:r-   z4Callable[[Sequence[str]], Sequence[Sequence[float]]])r   c                    sD   zddl m‰  W n ty*   tdƒ‚Y n0 dddœ‡ fdd„} | S )	zGet the OpenAI GPT-3 encoder.r   )ÚClientzÔTHe default encoder for the EmbeddingDistance class uses the OpenAI API. Please either install the openai library with `pip install openai` or provide a custom encoder function (Callable[[str], Sequence[float]]).zSequence[str]zSequence[Sequence[float]])Útextsr   c                   s*   ˆ ƒ }|j jt| ƒdd�}dd„ |jD ƒS )Nztext-embedding-3-small)ÚinputÚmodelc                 S  s   g | ]
}|j ‘qS r+   )Z	embedding)Ú.0Údr+   r+   r,   Ú
<listcomp>N   ó    z<_get_openai_encoder.<locals>.encode_text.<locals>.<listcomp>)Ú
embeddingsÚcreateÚlistÚdata)r/   ÚclientÚresponse©ZOpenAIClientr+   r,   Úencode_textI   s
    ÿz(_get_openai_encoder.<locals>.encode_text)Zopenair.   r   )r=   r+   r<   r,   Ú_get_openai_encoder>   s    ÿ
r>   c                   @  s   e Zd ZU ded< ded< dS )ÚEmbeddingConfigz0Callable[[list[str]], Sequence[Sequence[float]]]ÚencoderzCLiteral['cosine', 'euclidean', 'manhattan', 'chebyshev', 'hamming']r   N)Ú__name__Ú
__module__Ú__qualname__Ú__annotations__r+   r+   r+   r,   r?   S   s   
r?   F)Útotalc                   @  s®   e Zd Zdddœdd„Zddddœd	d
„Zddddœdd„Zeddddœdd„ƒZeddddœdd„ƒZeddddœdd„ƒZ	eddddœdd„ƒZ
eddddœdd„ƒZdS )ÚEmbeddingDistanceNzOptional[EmbeddingConfig])Úconfigc                 C  s.   |pi }|  d¡pd| _|  d¡p&tƒ | _d S )Nr   r   r@   )ÚgetÚdistancer>   r@   )ÚselfrG   r+   r+   r,   Ú__init__Y   s    zEmbeddingDistance.__init__Ústrr   )Ú
predictionÚ	referencer   c                 C  sX   zdd l }W n ty&   tdƒ‚Y n0 |  ||g¡}| |¡}|  |d |d ¡ ¡ S )Nr   zWThe EmbeddingDistance class requires NumPy. Please install it with `pip install numpy`.r   )r   r   r@   r   Ú_compute_distanceÚitem)rJ   rM   rN   r)   r6   Zvectorr+   r+   r,   Úevaluatea   s    ÿ

zEmbeddingDistance.evaluater   znp.floating)ÚaÚbr   c                 C  s‚   | j dkr|  ||¡S | j dkr,|  ||¡S | j dkrB|  ||¡S | j dkrX|  ||¡S | j dkrn|  ||¡S td| j › �ƒ‚d S )Nr   Z	euclideanZ	manhattanZ	chebyshevZhammingzInvalid distance metric: )rI   Ú_cosine_distanceÚ_euclidean_distanceÚ_manhattan_distanceÚ_chebyshev_distanceÚ_hamming_distancer   )rJ   rR   rS   r+   r+   r,   rO   q   s    




z#EmbeddingDistance._compute_distancec                 C  s   dt | g|gƒ S )zäCompute the cosine distance between two vectors.

        Args:
            a (np.ndarray): The first vector.
            b (np.ndarray): The second vector.

        Returns:
            np.ndarray: The cosine distance.
        g      ð?)r-   ©rR   rS   r+   r+   r,   rT      s    z"EmbeddingDistance._cosine_distancec                 C  s   t j | | ¡S )zëCompute the Euclidean distance between two vectors.

        Args:
            a (np.ndarray): The first vector.
            b (np.ndarray): The second vector.

        Returns:
            np.floating: The Euclidean distance.
        )r)   r"   r#   rY   r+   r+   r,   rU   Œ   s    z%EmbeddingDistance._euclidean_distancec                 C  s   t  t  | | ¡¡S )zëCompute the Manhattan distance between two vectors.

        Args:
            a (np.ndarray): The first vector.
            b (np.ndarray): The second vector.

        Returns:
            np.floating: The Manhattan distance.
        )r)   ÚsumÚabsrY   r+   r+   r,   rV   ™   s    z%EmbeddingDistance._manhattan_distancec                 C  s   t  t  | | ¡¡S )zëCompute the Chebyshev distance between two vectors.

        Args:
            a (np.ndarray): The first vector.
            b (np.ndarray): The second vector.

        Returns:
            np.floating: The Chebyshev distance.
        )r)   Úmaxr[   rY   r+   r+   r,   rW   ¦   s    z%EmbeddingDistance._chebyshev_distancec                 C  s   t  | |k¡S )zçCompute the Hamming distance between two vectors.

        Args:
            a (np.ndarray): The first vector.
            b (np.ndarray): The second vector.

        Returns:
            np.floating: The Hamming distance.
        )r)   ÚmeanrY   r+   r+   r,   rX   ³   s    z#EmbeddingDistance._hamming_distance)N)rA   rB   rC   rK   rQ   rO   ÚstaticmethodrT   rU   rV   rW   rX   r+   r+   r+   r,   rF   X   s    þrF   )Ú
__future__r   ÚloggingÚcollections.abcr   Útypingr   r   r   r   r   r	   Ztyping_extensionsr
   r   r)   Ú	getLoggerrA   r    r8   r   r   r-   r>   r?   rF   r+   r+   r+   r,   Ú<module>   s    	
%