
    h                        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rd dlZ ej                   e      Zeeee      ee   ef   ZddZddZ G d d	ed
      Z G d d      Zy)    )annotationsN)Sequence)TYPE_CHECKINGAnyCallableLiteralOptionalUnion)	TypedDictc                   ddl }t        |       dk(  st        |      dk(  r |j                  g       S  |j                  |       }  |j                  |      }| j                  d   |j                  d   k7  r&t	        d| j                   d|j                   d      	 ddl} |j                  | |j                        }  |j                  ||j                        }d|j                  | |d	      z
  }t        |t              r |j                  |g      S  |j                  |      S # t        $ r t        j                  d
       |j                  j                  | d      }|j                  j                  |d      } |j                  dd      5   |j                   | |j"                         |j$                  ||      z  }ddd       n# 1 sw Y   nxY wd |j&                  |       |j(                  |      z  <   |cY S w xY w)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 .)dtypecosine)metriczUnable to import simsimd, defaulting to NumPy implementation. If you want to use simsimd please install with `pip install simsimd`.)axisignore)divideinvalidg        )numpylenarrayshape
ValueErrorsimsimdfloat32cdist
isinstancefloatImportErrorloggerdebuglinalgnormerrstatedotTouterisnanisinf)XYnpsimdZX_normY_norm
similaritys           e/var/www/html/eduruby.in/venv/lib/python3.12/site-packages/langsmith/_internal/_embedding_distance.pycosine_similarityr4      s   
1v{c!fkrxx|AAwwqzQWWQZI!'' S wwiq*
 	
BHHQbjj)BHHQbjj)

1a
11a288QC= rxx{ H	
 **R[[(; 	C133("((66*BBJ	C 	C 	CBE
8288J'("((:*>>?s2   A9D) D) )A,H	2G	H	G	1H	H	c                 R    	 ddl m dfd} | S # t        $ r t        d      w xY w)zGet the OpenAI GPT-3 encoder.r   )ClientzTHe 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]]).c                            }|j                   j                  t        |       d      }|j                  D cg c]  }|j                   c}S c c}w )Nztext-embedding-3-small)inputmodel)
embeddingscreatelistdata	embedding)textsclientresponsedOpenAIClients       r3   encode_textz(_get_openai_encoder.<locals>.encode_textI   sM    $$++u+%= , 
 &.]]3333s   A)r?   zSequence[str]returnzSequence[Sequence[float]])openair6   r    )rD   rC   s    @r3   _get_openai_encoderrG   >   s<    
14   
T
 	

s    &c                  "    e Zd ZU ded<   ded<   y)EmbeddingConfigz0Callable[[list[str]], Sequence[Sequence[float]]]encoderzCLiteral['cosine', 'euclidean', 'manhattan', 'chebyshev', 'hamming']r   N)__name__
__module____qualname____annotations__     r3   rI   rI   S   s    ==OOrP   rI   F)totalc                      e Zd Z	 d
	 ddZ	 	 	 	 	 	 ddZddZedd       Zedd       Zedd       Z	edd       Z
edd	       Zy)EmbeddingDistanceNc                    |xs i }|j                  d      xs d| _        |j                  d      xs
 t               | _        y )Nr   r   rJ   )getdistancerG   rJ   )selfconfigs     r3   __init__zEmbeddingDistance.__init__Y   s;     2

8,8zz),E0C0ErP   c                    	 dd l }| j                  ||g      } |j                  |      }| j	                  |d   |d         j                         S # t        $ r t        d      w xY w)Nr   zWThe EmbeddingDistance class requires NumPy. Please install it with `pip install numpy`.r   )r   r    rJ   r   _compute_distanceitem)rW   
prediction	referencer-   r:   vectors         r3   evaluatezEmbeddingDistance.evaluatea   sv    
	 \\:y"9:
*%%%fQi;@@BB  	' 	s   A A&c                |   | j                   dk(  r| j                  ||      S | j                   dk(  r| j                  ||      S | j                   dk(  r| j                  ||      S | j                   dk(  r| j	                  ||      S | j                   dk(  r| j                  ||      S t        d| j                          )Nr   	euclidean	manhattan	chebyshevhammingzInvalid distance metric: )rV   _cosine_distance_euclidean_distance_manhattan_distance_chebyshev_distance_hamming_distancer   )rW   abs      r3   r[   z#EmbeddingDistance._compute_distanceq   s    ==H$((A..]]k)++Aq11]]k)++Aq11]]k)++Aq11]]i'))!Q//8HIIrP   c                $    dt        | g|g      z
  S )zCompute 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      ?)r4   rk   rl   s     r3   rf   z"EmbeddingDistance._cosine_distance   s     &sQC000rP   c                F    t         j                  j                  | |z
        S )zCompute 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$   rn   s     r3   rg   z%EmbeddingDistance._euclidean_distance   s     yy~~a!e$$rP   c                X    t        j                  t        j                  | |z
              S )zCompute 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absrn   s     r3   rh   z%EmbeddingDistance._manhattan_distance        vvbffQUm$$rP   c                X    t        j                  t        j                  | |z
              S )zCompute 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-   maxrr   rn   s     r3   ri   z%EmbeddingDistance._chebyshev_distance   rs   rP   c                2    t        j                  | |k7        S )zCompute 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-   meanrn   s     r3   rj   z#EmbeddingDistance._hamming_distance   s     wwqAvrP   )N)rX   zOptional[EmbeddingConfig])r]   strr^   rx   rE   r   )rk   
np.ndarrayrl   ry   rE   znp.floating)rk   ry   rl   ry   rE   ry   )rK   rL   rM   rY   r`   r[   staticmethodrf   rg   rh   ri   rj   rO   rP   r3   rS   rS   X   s     -1F)FCC C 
	C J 
1 
1 
% 
% 
% 
% 
% 
% 
 
rP   rS   )r+   Matrixr,   r{   rE   ry   )rE   z4Callable[[Sequence[str]], Sequence[Sequence[float]]])
__future__r   loggingcollections.abcr   typingr   r   r   r   r	   r
   typing_extensionsr   r   r-   	getLoggerrK   r!   r<   r   r{   r4   rG   rI   rS   rO   rP   r3   <module>r      s|    "  $  ( 
		8	$	tDK $s)S0	1"J*Piu P
f frP   