
    6|h{:                        d Z ddlmZ ddlZddlZddlmZmZmZm	Z	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 erdd	lmZ dd
lmZ  G d d      Z e       Z G d d      Z G d d      Z e       ZdgZy)a  Make approximate assertions as "expectations" on test results.

This module is designed to be used within test cases decorated with the
`@pytest.mark.decorator` decorator
It allows you to log scores about a test case and optionally make assertions that log as
"expectation" feedback to LangSmith.

Example usage:
    .. code-block:: python

        import pytest
        from langsmith import expect


        @pytest.mark.langsmith
        def test_output_semantically_close():
            response = oai_client.chat.completions.create(
                model="gpt-3.5-turbo",
                messages=[
                    {"role": "system", "content": "You are a helpful assistant."},
                    {"role": "user", "content": "Say hello!"},
                ],
            )
            response_txt = response.choices[0].message.content
            # Intended usage
            expect.embedding_distance(
                prediction=response_txt,
                reference="Hello!",
            ).to_be_less_than(0.9)

            # Score the test case
            matcher = expect.edit_distance(
                prediction=response_txt,
                reference="Hello!",
            )
            # Apply an assertion and log 'expectation' feedback to LangSmith
            matcher.to_be_less_than(1)

            # You can also directly make assertions on values directly
            expect.value(response_txt).to_contain("Hello!")
            # Or using a custom check
            expect.value(response_txt).against(lambda x: "Hello" in x)

            # You can even use this for basic metric logging within tests

            expect.score(0.8)
            expect.score(0.7, key="similarity").to_be_greater_than(0.7)
    )annotationsN)TYPE_CHECKINGAnyCallableLiteralOptionalUnionoverloadclient)run_helpers)	run_trees)utils)EditDistanceConfig)EmbeddingConfigc                       e Zd ZdZddZddZy)_NULL_SENTRYzA sentinel singleton class used to distinguish omitted keyword arguments
    from those passed in with the value None (which may have different behavior).
    c                     y)NF selfs    P/var/www/html/test/engine/venv/lib/python3.12/site-packages/langsmith/_expect.py__bool__z_NULL_SENTRY.__bool__P   s        c                     y)N	NOT_GIVENr   r   s    r   __repr__z_NULL_SENTRY.__repr__S   s    r   N)returnzLiteral[False])r   str)__name__
__module____qualname____doc__r   r   r   r   r   r   r   K   s    r   r   c                      e Zd ZdZ	 	 d	 	 	 	 	 	 	 	 	 ddZdddZddZddZddZddZ	ddd	Z
dd
ZddZddZddZy)_Matcherz4A class for making assertions on expectation values.Nc                    || _         || _        || _        |xs t        j                  d      | _        t        j                         }|r|j                  | _	        y || _	        y )N   max_workers)
_clientkeyvaluels_utilsContextThreadPoolExecutor	_executorrhget_current_run_treetrace_id_run_id)r   r   r+   r,   r/   run_idrts          r   __init__z_Matcher.__init__]   sR     
"Wh&H&HUV&W$$&&(r{{fr   c                    t        j                         sd| j                  st        j                         | _        | j
                  j                  | j                  j                  | j                  d||       y y )Nexpectation)r4   r+   scorecomment)	r-   test_tracking_is_disabledr*   r5   get_cached_clientr/   submitcreate_feedbackr3   )r   r9   messages      r   _submit_feedbackz_Matcher._submit_feedbackl   s^    113<<!335NN!!,,||! "  4r   c                    	 |sJ |       | j                  dd| j                   d|        y # t        $ r#}| j                  dt        |             |d d }~ww xY w)N   z	Success: .)r?   r   )r@   r+   AssertionErrorrepr)r   	conditionr?   method_namees        r   _assertz_Matcher._assertx   sd    	%g%9!!!y
!K=-Q!R 	!!!T!W-	s   ,/ 	AAAc           	     ~    | j                  | j                  |k  d| j                   d| d| j                   d       y)zAssert that the expectation value is less than the given value.

        Args:
            value: The value to compare against.

        Raises:
            AssertionError: If the expectation value is not less than the given value.
        	Expected z to be less than 
, but got to_be_less_thanNrI   r,   r+   r   r,   s     r   rM   z_Matcher.to_be_less_than   s>     	JJz!25'DJJ<P	
r   c           	     ~    | j                  | j                  |kD  d| j                   d| d| j                   d       y)a  Assert that the expectation value is greater than the given value.

        Args:
            value: The value to compare against.

        Raises:
            AssertionError: If the expectation value is not
            greater than the given value.
        rK   z to be greater than rL   to_be_greater_thanNrN   rO   s     r   rQ   z_Matcher.to_be_greater_than   s>     	JJz!5eWJtzzlS 	
r   c                    | j                  || j                  cxk  xr |k  nc d| j                   d| d| d| j                   d       y)aJ  Assert that the expectation value is between the given min and max values.

        Args:
            min_value: The minimum value (exclusive).
            max_value: The maximum value (exclusive).

        Raises:
            AssertionError: If the expectation value
                is not between the given min and max.
        rK   z to be between z and rL   to_be_betweenNrN   )r   	min_value	max_values      r   rS   z_Matcher.to_be_between   sO     	

.Y.z5 L

|%		
r   c           	         | j                  t        | j                  |      t        ||      k(  d| j                   d| d| j                   d       y)ak  Assert that the expectation value is approximately equal to the given value.

        Args:
            value: The value to compare against.
            precision: The number of decimal places to round to for comparison.

        Raises:
            AssertionError: If the rounded expectation value
                does not equal the rounded given value.
        rK   z to be approximately rL   to_be_approximatelyN)rI   roundr,   r+   )r   r,   	precisions      r   rW   z_Matcher.to_be_approximately   sL     	$**i(E%,CCz!6ugZ

|T!	
r   c           	     ~    | j                  | j                  |k(  d| j                   d| d| j                   d       y)a   Assert that the expectation value equals the given value.

        Args:
            value: The value to compare against.

        Raises:
            AssertionError: If the expectation value does
                not exactly equal the given value.
        rK   z to be equal to rL   to_equalNrN   rO   s     r   r[   z_Matcher.to_equal   s>     	JJ%z!1%
4::,O	
r   c                v    | j                  | j                  du d| j                   d| j                   d       y)zAssert that the expectation value is None.

        Raises:
            AssertionError: If the expectation value is not None.
        NrK   z to be None, but got 
to_be_nonerN   r   s    r   r]   z_Matcher.to_be_none   s8     	JJ$z!6tzzlC	
r   c                d    | j                  || j                  v d| j                   d| dd       y)zAssert that the expectation value contains the given value.

        Args:
            value: The value to check for containment.

        Raises:
            AssertionError: If the expectation value does not contain the given value.
        rK   z to contain z, but it does not
to_containNrN   rO   s     r   r_   z_Matcher.to_contain   s6     	TZZzeW4EF	
r   c                   t        j                  |      }| j                   || j                        d| d| j                   d       y)zAssert the expectation value against a custom function.

        Args:
            func: A custom function that takes the expectation value as input.

        Raises:
            AssertionError: If the custom function returns False.
        z
Assertion z failed for againstN)inspect	signaturerI   r,   r+   )r   funcfunc_signatures      r   ra   z_Matcher.against   sD     !**40(TXXJ?	
r   )NN)
r   Optional[ls_client.Client]r+   r   r,   r   r/   z,Optional[ls_utils.ContextThreadPoolExecutor]r4   Optional[str]N)r9   intr?   rg   r   None)rF   boolr?   r   rG   r   r   rj   )r,   floatr   rj   )rT   rl   rU   rl   r   rj   )   )r,   rl   rY   ri   r   rj   )r   rj   )r,   r   r   rj   )rd   r   r   rj   )r    r!   r"   r#   r6   r@   rI   rM   rQ   rS   rW   r[   r]   r_   ra   r   r   r   r%   r%   Z   sw    > CG $5*5 5 	5
 @5 5


 
$
"
 


 
r   r%   c                      e Zd ZdZddddZdd	 	 	 	 	 	 	 ddZdd	 	 	 	 	 	 	 ddZddZd	ddd
	 	 	 	 	 	 	 	 	 ddZe	dd       Z
e	dd       Z
edf	 	 	 	 	 ddZ
ddZy)_Expectz1A class for setting expectations on test results.Nr   c                   || _         t        j                  d      | _        t	        j
                  | j                  j                  d       y )Nr'   r(   T)wait)r*   r-   r.   executoratexitregistershutdownr   r   s     r   r6   z_Expect.__init__  s3     ::qI..T:r   configc          	     ,   ddl m} |xs i }|j                  d      rdnd} ||      }|j                  ||      }||j                  d}| j                  d	||d
| d|j                   d       t        | j                  d	|| j                        S )a  Compute the embedding distance between the prediction and reference.

        This logs the embedding distance to LangSmith and returns a `_Matcher` instance
        for making assertions on the distance value.

        By default, this uses the OpenAI API for computing embeddings.

        Args:
            prediction: The predicted string to compare.
            reference: The reference string to compare against.
            config: Optional configuration for the embedding distance evaluator.
                Supported options:
                - `encoder`: A custom encoder function to encode the list of input
                     strings to embeddings. Defaults to the OpenAI API.
                - `metric`: The distance metric to use for comparison.
                    Supported values: "cosine", "euclidean", "manhattan",
                    "chebyshev", "hamming".

        Returns:
            A `_Matcher` instance for the embedding distance value.


        Examples:
            >>> expect.embedding_distance(
            ...     prediction="hello",
            ...     reference="hi",
            ... ).to_be_less_than(1.0)
        r   )EmbeddingDistanceencodercustomopenairw   
prediction	reference)r{   metricembedding_distanceUsing z
, Metric: r9   source_infor:   r/   )	'langsmith._internal._embedding_distancerz   getevaluatedistancer@   r%   r*   rr   )	r   r   r   rx   rz   encoder_func	evaluatorr9   src_infos	            r   r   z_Expect.embedding_distance  s    F 	N2#)::i#8xh%V4	""jI"N+y7I7IJ '#L>I<N<N;OP	
 LL.
 	
r   c          	     (   ddl m} |xs i }|j                  d      xs d}|j                  dd      } ||      }|j                  ||      }||d	}	| j	                  d
||	d| d| d       t        | j                  d
|| j                        S )a  Compute the string distance between the prediction and reference.

        This logs the string distance (Damerau-Levenshtein) to LangSmith and returns
        a `_Matcher` instance for making assertions on the distance value.

        This depends on the `rapidfuzz` package for string distance computation.

        Args:
            prediction: The predicted string to compare.
            reference: The reference string to compare against.
            config: Optional configuration for the string distance evaluator.
                Supported options:
                - `metric`: The distance metric to use for comparison.
                    Supported values: "damerau_levenshtein", "levenshtein",
                    "jaro", "jaro_winkler", "hamming", "indel".
                - `normalize_score`: Whether to normalize the score between 0 and 1.

        Returns:
            A `_Matcher` instance for the string distance value.

        Examples:
            >>> expect.edit_distance("hello", "helo").to_be_less_than(1)
        r   )EditDistancer   damerau_levenshteinnormalize_scoreTrw   r~   )r   	normalizeedit_distancer   z, Normalize: r   r   )"langsmith._internal._edit_distancer   r   r   r@   r%   r*   rr   )
r   r   r   rx   r   r   r   r   r9   r   s
             r   r   z_Expect.edit_distance=  s    < 	D2H%>)>JJ0$7	 /	""jI"N$9='#F8=D	
 LLmm	
 	
r   c                H    t        | j                  d|| j                        S )a"  Create a `_Matcher` instance for making assertions on the given value.

        Args:
            value: The value to make assertions on.

        Returns:
            A `_Matcher` instance for the given value.

        Examples:
           >>> expect.value(10).to_be_less_than(20)
        r,   r   )r%   r*   rr   rO   s     r   r,   z_Expect.valuer  s     guNNr   r9   )r+   source_run_idr:   c               z    | j                  ||ddi||d       t        | j                  ||| j                        S )a  Log a numeric score to LangSmith.

        Args:
            score: The score value to log.
            key: The key to use for logging the score. Defaults to "score".

        Examples:
            >>> expect.score(0.8)  # doctest: +ELLIPSIS
            <langsmith._expect._Matcher object at ...>

            >>> expect.score(0.8, key="similarity").to_be_greater_than(0.7)
        methodzexpect.score)r9   r   r   r:   r   )r@   r%   r*   rr   )r   r9   r+   r   r:   s        r   r9   z_Expect.score  sF    ( 	 (.9!."		
 c5DMMJJr   c                    y rh   r   rO   s     r   __call__z_Expect.__call__  s    36r   c                   y rh   r   rv   s     r   r   z_Expect.__call__  s    CFr   c               P    t        |      }|t        ur|j                  |      S |S )Nr   )ro   r   r,   )r   r,   r   expecteds       r   r   z_Expect.__call__  s*     &)	!>>%((r   c                (   t        j                         }|r|j                  nd }t        j                         sZ| j
                  st        j                         | _         | j                  j                  | j
                  j                  f||d| y y )N)r4   r+   )r0   r1   r2   r-   r;   r*   r5   r<   rr   r=   r>   )r   r+   resultscurrent_runr4   s        r   r@   z_Expect._submit_feedback  sz    --/)4%%$113<<!335 DMM  ,,5;HO 4r   )r   rf   )r   r   r   r   rx   zOptional[EmbeddingConfig]r   r%   )r   r   r   r   rx   zOptional[EditDistanceConfig]r   r%   )r,   r   r   r%   )
r9   zUnion[float, int, bool]r+   r   r   zOptional[ls_client.ID_TYPE]r:   rg   r   r%   )r   zls_client.Clientr   ro   )r   rf   r,   zOptional[Any]r   zUnion[_Expect, _Matcher])r+   r   r   dict)r    r!   r"   r#   r6   r   r   r,   r9   r
   r   r   r@   r   r   r   ro   ro      s   ;?C ; -14
4
 4

 *4
 
4
v 043
3
 3

 -3
 
3
jO$ 59!%K&K 	K
 3K K 
KB 6 6F F  )-1		 +			
 
"	r   ro   expect) r#   
__future__r   rs   rb   typingr   r   r   r   r   r	   r
   	langsmithr   	ls_clientr   r0   r   r5   r   r-   r   r   r   r   r   r   r%   ro   r   __all__r   r   r   <module>r      sy   /b #     * ' % 'EG	 	 N	b
 b
J{ {| 
*r   