
    zh|                        d dl mZ d dlZd dlmZmZ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)TYPE_CHECKINGAnyCallableListLiteralOptionalSequence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           a/var/www/html/engine/venv/lib/python3.12/site-packages/langsmith/_internal/_embedding_distance.pycosine_similarityr5      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       r4   encode_textz(_get_openai_encoder.<locals>.encode_textJ   sM    $$++u+%= , 
 &.]]3333s   A)r@   zSequence[str]returnzSequence[Sequence[float]])openair7   r!   )rE   rD   s    @r4   _get_openai_encoderrH   ?   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__     r4   rJ   rJ   T   s    ==OOrQ   rJ   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   rK   )getdistancerH   rK   )selfconfigs     r4   __init__zEmbeddingDistance.__init__Z   s;     2

8,8zz),E0C0ErQ   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!   rK   r   _compute_distanceitem)rX   
prediction	referencer.   r;   vectors         r4   evaluatezEmbeddingDistance.evaluateb   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: )rW   _cosine_distance_euclidean_distance_manhattan_distance_chebyshev_distance_hamming_distancer   )rX   abs      r4   r\   z#EmbeddingDistance._compute_distancer   s    ==H$((A..]]k)++Aq11]]k)++Aq11]]k)++Aq11]]i'))!Q//8HIIrQ   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      ?)r5   rl   rm   s     r4   rg   z"EmbeddingDistance._cosine_distance   s     &sQC000rQ   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%   ro   s     r4   rh   z%EmbeddingDistance._euclidean_distance   s     yy~~a!e$$rQ   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absro   s     r4   ri   z%EmbeddingDistance._manhattan_distance        vvbffQUm$$rQ   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.   maxrs   ro   s     r4   rj   z%EmbeddingDistance._chebyshev_distance   rt   rQ   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.   meanro   s     r4   rk   z#EmbeddingDistance._hamming_distance   s     wwqAvrQ   )N)rY   zOptional[EmbeddingConfig])r^   strr_   ry   rF   r    )rl   
np.ndarrayrm   rz   rF   znp.floating)rl   rz   rm   rz   rF   rz   )rL   rM   rN   rZ   ra   r\   staticmethodrg   rh   ri   rj   rk   rP   rQ   r4   rT   rT   Y   s     -1F)FCC C 
	C J 
1 
1 
% 
% 
% 
% 
% 
% 
 
rQ   rT   )r,   Matrixr-   r|   rF   rz   )rF   z4Callable[[Sequence[str]], Sequence[Sequence[float]]])
__future__r   loggingtypingr   r   r   r   r   r	   r
   r   typing_extensionsr   r   r.   	getLoggerrL   r"   r    r|   r5   rH   rJ   rT   rP   rQ   r4   <module>r      s~    " 	 	 	 ( 
		8	$	tDK $s)S0	1"J*Piu P
f frQ   