o
    +i                  
   @  s*  d dl mZ d dlZd dlZd dlZd dlZd dlZd dlZd dlZd dl	Z	d dl
Z
d dlZd dlZd dlZd dlZd dlZd dlmZmZ d dlmZ d dlm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' d dl!m(Z( d dl!m(Z) d dl!m*Z+ d dl!m,Z- d dl.m/Z/ d dl0m1Z1 d dl2m3Z3 z
d dl4Z4e4j5j6Z7W n e8y   G dd de6Z7Y nw e
9e:Z;e<dZ=edZ>edZ?dddZ@edddZAeddddddddd dd1dZAdd4dZAdd5d6ZBdd7d8ZCdd;d<ZDdd?d@ZE	dddFdGZFddJdKZGddMdNZHedOeeI dPZJddRdSZKG dTdL dLZLG dUdV dVZMejNeeM  dWddXZOG dYdZ dZe d[d\ZPdd_d`ZQddddeZRddfdgZSeAZTddhdiZUddjdkZVddmdnZW	ddddoddwdxZXejYdydzdd}d~ZZdddZ[dddZ\ej]dddZ^dS )    )annotationsN)	GeneratorSequence)Future)Path)AnyCallableOptionalTypeVarUnioncastoverload)	TypedDict)client)env)run_helpers)	run_trees)schemas)utils)_orjson)
dumps_json)ID_TYPEc                   @  s   e Zd ZdS )SkipExceptionN)__name__
__module____qualname__ r   r   X/var/www/html/psymed-ai/venv/lib/python3.10/site-packages/langsmith/testing/_internal.pyr   1   s    r   z$6ba7b810-9dad-11d1-80b4-00c04fd430c8TUobjr   returnstrc                 C  s   t | }t|  S )z4Hash an object to generate a consistent hash string.)
_stringifyhashlibsha256encode	hexdigest)r    
serializedr   r   r   _object_hash>   s   r)   funcr   c                 C     d S Nr   )r*   r   r   r   testE   s   r-   idoutput_keysr   test_suite_namemetadatarepetitionssplitcached_hostsr/   Optional[uuid.UUID]r0   Optional[Sequence[str]]r   Optional[ls_client.Client]r1   Optional[str]r2   Optional[dict]r3   Optional[int]r4    Optional[Union[str | list[str]]]r5   Callable[[Callable], Callable]c                 C  r+   r,   r   r.   r   r   r   r-   K   s   argskwargsc                    s   | dd}t| dd}|r|stdt| dd| dd| dd| dd|| d	d| d
d| dd|d	|rLtd|   t   rWt	
d d fdd}| rmt| d rm|| d S |S )ai"  Trace a pytest test case in LangSmith.

    This decorator is used to trace a pytest test to LangSmith. It ensures
    that the necessary example data is created and associated with the test function.
    The decorated function will be executed as a test case, and the results will be
    recorded and reported by LangSmith.

    Args:
        - id (Optional[uuid.UUID]): A unique identifier for the test case. If not
            provided, an ID will be generated based on the test function's module
            and name.
        - output_keys (Optional[Sequence[str]]): A list of keys to be considered as
            the output keys for the test case. These keys will be extracted from the
            test function's inputs and stored as the expected outputs.
        - client (Optional[ls_client.Client]): An instance of the LangSmith client
            to be used for communication with the LangSmith service. If not provided,
            a default client will be used.
        - test_suite_name (Optional[str]): The name of the test suite to which the
            test case belongs. If not provided, the test suite name will be determined
            based on the environment or the package name.
        - cached_hosts (Optional[Sequence[str]]): A list of hosts or URL prefixes to
            cache requests to during testing. If not provided, all requests will be
            cached (default behavior). This is useful for caching only specific
            API calls (e.g., ["api.openai.com"] or ["https://api.openai.com"]).

    Returns:
        Callable: The decorated test function.

    Environment:
        - `LANGSMITH_TEST_CACHE`: If set, API calls will be cached to disk to
            save time and costs during testing. Recommended to commit the
            cache files to your repository for faster CI/CD runs.
            Requires the 'langsmith[vcr]' package to be installed.
        - `LANGSMITH_TEST_TRACKING`: Set this variable to the path of a directory
            to enable caching of test results. This is useful for re-running tests
            without re-executing the code. Requires the 'langsmith[vcr]' package.

    Example:
        For basic usage, simply decorate a test function with `@pytest.mark.langsmith`.
        Under the hood this will call the `test` method:

        ```python
        import pytest


        # Equivalently can decorate with `test` directly:
        # from langsmith import test
        # @test
        @pytest.mark.langsmith
        def test_addition():
            assert 3 + 4 == 7
        ```


        Any code that is traced (such as those traced using `@traceable`
        or `wrap_*` functions) will be traced within the test case for
        improved visibility and debugging.

        ```python
        import pytest
        from langsmith import traceable


        @traceable
        def generate_numbers():
            return 3, 4


        @pytest.mark.langsmith
        def test_nested():
            # Traced code will be included in the test case
            a, b = generate_numbers()
            assert a + b == 7
        ```

        LLM calls are expensive! Cache requests by setting
        `LANGSMITH_TEST_CACHE=path/to/cache`. Check in these files to speed up
        CI/CD pipelines, so your results only change when your prompt or requested
        model changes.

        Note that this will require that you install langsmith with the `vcr` extra:

        `pip install -U "langsmith[vcr]"`

        Caching is faster if you install libyaml. See
        https://vcrpy.readthedocs.io/en/latest/installation.html#speed for more details.

        ```python
        # os.environ["LANGSMITH_TEST_CACHE"] = "tests/cassettes"
        import openai
        import pytest
        from langsmith import wrappers

        oai_client = wrappers.wrap_openai(openai.Client())


        @pytest.mark.langsmith
        def test_openai_says_hello():
            # Traced code will be included in the test case
            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!"},
                ],
            )
            assert "hello" in response.choices[0].message.content.lower()
        ```

        You can also specify which hosts to cache by using the `cached_hosts` parameter.
        This is useful when you only want to cache specific API calls:

        ```python
        @pytest.mark.langsmith(cached_hosts=["https://api.openai.com"])
        def test_openai_with_selective_caching():
            # Only OpenAI API calls will be cached, other API calls will not
            # be cached
            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!"},
                ],
            )
            assert "hello" in response.choices[0].message.content.lower()
        ```

        LLMs are stochastic. Naive assertions are flakey. You can use langsmith's
        `expect` to score and make approximate assertions on your results.

        ```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!"},
                ],
            )
            # The embedding_distance call logs the embedding distance to LangSmith
            expect.embedding_distance(
                prediction=response.choices[0].message.content,
                reference="Hello!",
                # The following optional assertion logs a
                # pass/fail score to LangSmith
                # and raises an AssertionError if the assertion fails.
            ).to_be_less_than(1.0)
            # Compute damerau_levenshtein distance
            expect.edit_distance(
                prediction=response.choices[0].message.content,
                reference="Hello!",
                # And then log a pass/fail score to LangSmith
            ).to_be_less_than(1.0)
        ```

        The `@test` decorator works natively with pytest fixtures.
        The values will populate the "inputs" of the corresponding example in LangSmith.

        ```python
        import pytest


        @pytest.fixture
        def some_input():
            return "Some input"


        @pytest.mark.langsmith
        def test_with_fixture(some_input: str):
            assert "input" in some_input
        ```

        You can still use `pytest.parametrize()` as usual to run multiple test cases
        using the same test function.

        ```python
        import pytest


        @pytest.mark.langsmith(output_keys=["expected"])
        @pytest.mark.parametrize(
            "a, b, expected",
            [
                (1, 2, 3),
                (3, 4, 7),
            ],
        )
        def test_addition_with_multiple_inputs(a: int, b: int, expected: int):
            assert a + b == expected
        ```

        By default, each test case will be assigned a consistent, unique identifier
        based on the function name and module. You can also provide a custom identifier
        using the `id` argument:

        ```python
        import pytest
        import uuid

        example_id = uuid.uuid4()


        @pytest.mark.langsmith(id=str(example_id))
        def test_multiplication():
            assert 3 * 4 == 12
        ```

        By default, all test inputs are saved as "inputs" to a dataset.
        You can specify the `output_keys` argument to persist those keys
        within the dataset's "outputs" fields.

        ```python
        import pytest


        @pytest.fixture
        def expected_output():
            return "input"


        @pytest.mark.langsmith(output_keys=["expected_output"])
        def test_with_expected_output(some_input: str, expected_output: str):
            assert expected_output in some_input
        ```


        To run these tests, use the pytest CLI. Or directly run the test functions.

        ```python
        test_output_semantically_close()
        test_addition()
        test_nested()
        test_with_fixture("Some input")
        test_with_expected_output("Some input", "Some")
        test_multiplication()
        test_openai_says_hello()
        test_addition_with_multiple_inputs(1, 2, 3)
        ```
    r5   Ncachea2  cached_hosts parameter requires caching to be enabled. Please set the LANGSMITH_TEST_CACHE environment variable to a cache directory path, or pass a cache parameter to the test decorator. Example: LANGSMITH_TEST_CACHE='tests/cassettes' or @pytest.mark.langsmith(cache='tests/cassettes', cached_hosts=[...])r/   r0   r   r1   r2   r3   r4   )	r/   r0   r   r1   r@   r2   r3   r4   r5   zUnexpected keyword arguments: zLLANGSMITH_TEST_TRACKING is set to 'false'. Skipping LangSmith test tracking.r*   r   r!   c                   sj    ddpdt r!t d dd fdd	}|S t d dd fd
d}|S )Nr3      )request	test_argsr   rB   test_kwargsc                   s\    r|i |I d H S t D ]} }tg|R d| i|d|iI d H  qd S Npytest_requestlangtest_extra)rangecopy
_arun_testrB   rC   rD   irepetition_extradisable_trackingr*   rG   r3   r   r   async_wrapperv  s"   z.test.<locals>.decorator.<locals>.async_wrapperc                   sN    r	|i |S t D ]} }tg|R d| i|d|i qd S rE   )rH   rI   	_run_testrK   rN   r   r   wrapper  s    
z(test.<locals>.decorator.<locals>.wrapper)rC   r   rB   r   rD   r   )getinspectiscoroutinefunction	functoolswraps)r*   rP   rR   rO   rG   )r*   r3   r   	decoratorp  s   
ztest.<locals>.decoratorr   r*   r   r!   r   )popls_utilsget_cache_dir
ValueError_UTExtrawarningswarnkeystest_tracking_is_disabledloggerinfocallable)r>   r?   r5   	cache_dirrY   r   rX   r   r-   Y   s:    v	






,c                 C  s   t jdr"tjdr"| t jd  }tttj	|j
d d }ntt j
d d }t jdr9t jd }ntdp?d}| d| }|S )NPYTEST_XDIST_TESTRUNUIDxdist   LANGSMITH_EXPERIMENTFTestSuiteResult:)osenvironrS   	importlibutil	find_specr"   uuiduuid5NAMESPACE_DNShexuuid4r\   get_tracer_project)r1   id_nameid_prefixnamer   r   r   _get_experiment_name  s   r}   c                 C  sl   t d}|r	|S t d }zt| }|r | d|j W S W t
d ty5   t	d Y t
dw )N
TEST_SUITE	repo_name.z3Could not determine test suite name from file path.z9Please set the LANGSMITH_TEST_SUITE environment variable.)r\   get_env_varls_envget_git_inforT   	getmoduler   BaseExceptionrd   debugr^   )r*   r1   r   modr   r   r   _get_test_suite_name  s   

r   ls_client.Clientls_schemas.Datasetc                 C  sx   | j |dr| j|dS t dpd}d}|r |d| 7 }z| j||ddidW S  tjy;   | j|d Y S w )	N)dataset_name
remote_url z
Test suitez for __ls_runnerpytest)r   descriptionr2   )has_datasetread_datasetr   r   rS   create_datasetr\   LangSmithConflictError)r   r1   repor   r   r   r   _get_test_suite  s   r   
test_suitels_schemas.TracerSessionc                 C  sR   t |j}z| j||jdt ddddW S  tjy(   | j	|d Y S w )NzTest Suite Results.revision_idr   )r   r   )reference_dataset_idr   r2   )project_name)
r}   r|   create_projectr/   r   get_langchain_env_var_metadatarS   r\   r   read_project)r   r   experiment_namer   r   r   _start_experiment  s   
r   
dataset_idinputsdictoutputs	uuid.UUIDc                 C  s*   | t |t |pi f}t|}tt|S )z=Generate example ID based on inputs, outputs, and dataset ID.)r)   r#   rs   rt   UUID5_NAMESPACE)r   r   r   identifier_obj
identifierr   r   r   _get_example_id  s   r   suite_idtuple[uuid.UUID, str]c                 C  s   zt tt| t }W n ty   | j}Y nw | | d| j }t	| dr<t
dd | jD r<|t|7 }ttj||tt |d  fS )Nz::
pytestmarkc                 s  s    | ]}|j d kV  qdS )parametrizeNr|   ).0mr   r   r   	<genexpr>  s    

z)_get_example_id_legacy.<locals>.<genexpr>)r"   r   rT   getfilerelative_tocwdr^   r   r   hasattranyr   r#   rs   rt   ru   len)r*   r   r   	file_pathr   r   r   r   _get_example_id_legacy  s    
"r   _LangSmithTestSuitec                 C  s   t  pi }|   |  }| jj}| jj| ji ||t 	 
dddd |r>|d d ur>| jj||d|d  d |rV|d d urX| jj||d	|d  d d S d S d S )
Nr   r   )dataset_versionr   r   )r2   commitzgit:commit:)r   as_oftagbranchzgit:branch:)r   r   shutdownget_dataset_version_datasetr/   r   update_projectexperiment_idr   rS   update_dataset_tag)r   git_infor   r   r   r   r   
_end_tests  s6   	
r   VT)boundvaluesc                 C  s&   | d u r	t t| S t| }t|S r,   )r   r   	ls_client_dumps_jsonr   loads)r   btsr   r   r   _serde_example_values*  s   


r   c                   @  s   e Zd ZU dZded< e ZdFd
dZe	dd Z
e	dd Ze	dd Ze	dGdHddZe	dd Zdd Z				dIdJd'd(ZdKd+d,Zddddddd-dLd4d5Z		dMdNd:d;ZdOd=d>Zd?d@ Z		dMdPdBdCZdQdDdEZdS )Rr   Nr:   
_instancesr   r8   
experimentr   datasetr   c                 C  s<   |pt  | _|| _|| _|j| _t | _	t
t|  d S r,   )rtget_cached_clientr   _experimentr   modified_at_dataset_versionr\   ContextThreadPoolExecutor	_executoratexitregisterr   )selfr   r   r   r   r   r   __init__5  s   
z_LangSmithTestSuite.__init__c                 C     | j jS r,   )r   r/   r   r   r   r   r/   B     z_LangSmithTestSuite.idc                 C  r   r,   )r   r/   r   r   r   r   r   F  r   z!_LangSmithTestSuite.experiment_idc                 C     | j S r,   )r   r   r   r   r   r   J  s   z_LangSmithTestSuite.experimentr*   r   r1   r9   r!   c                 C  s   |pt  }|pt|}| j& | jsi | _|| jvr.t||}t||}| |||| j|< W d    n1 s8w   Y  | j| S r,   )r   r   r   _lockr   r   r   )clsr   r*   r1   r   r   r   r   r   	from_testN  s   



z_LangSmithTestSuite.from_testc                 C  r   r,   )r   r|   r   r   r   r   r|   `  r   z_LangSmithTestSuite.namec                 C  r   r,   )r   r   r   r   r   r   d  s   z'_LangSmithTestSuite.get_dataset_versionFrun_idr   errorskippedboolpytest_pluginr   pytest_nodeidNonec                 C  sR   |rd }d}n|rd}d}nd}d}|r|r| |d|i | j| j|| d S )Nr   r   failedrA   passedstatus)update_process_statusr   submit_submit_result)r   r   r   r   r   r   scorer   r   r   r   submit_resultg  s   z!_LangSmithTestSuite.submit_resultr   r;   c                 C  s   | j j|d||d d S )Npass)keyr   trace_idr   create_feedback)r   r   r   r   r   r   r   |  s   z"_LangSmithTestSuite._submit_result)r   r   r2   r4   r   r   
example_idr   r   r2   r4   Optional[Union[str, list[str]]]c                C  s  |pi }|r|r||d}dd |  D }||| |r"| n|}t|}t|}z	| jj|d}	W n tjyO   | jj|||| j	||| j
jd}	Y nZw |}
t|
trZ|
g}
|
rb|rb|
|d< |	jpfi d}||	jks|d urx||	jks|d ur||	jkst|	jt| j	ks|
d ur||
kr| jj|	j	||||| j	d | jj|	j	d}	| jd u r|	j| _d S |	jr| jr|	j| jkr|	j| _d S d S d S d S )N)r   reference_outputsc                 S  s   i | ]\}}|d ur||qS r,   r   r   kvr   r   r   
<dictcomp>  s    z4_LangSmithTestSuite.sync_example.<locals>.<dictcomp>)r   )r   r   r   r   r2   r4   
created_atdataset_split)r   r   r   r2   r4   r   )itemsr   rI   r   r   read_exampler\   LangSmithNotFoundErrorcreate_exampler/   r   
start_time
isinstancer"   r2   r[   r   r   r   update_exampler   r   )r   r   r   r   r2   r4   r   r   updateexamplenormalized_splitexisting_dataset_splitr   r   r   sync_example  sh   




z _LangSmithTestSuite.sync_exampler   feedbackUnion[dict, list]r?   c                 K  sv   t |tr|n|g}|D ],}|r*|r*d|v r|d n|d }||d|d |ii | jj| jf||d| qd S )Nr   valuer  r   )r   r  )r  listr   r   r   _create_feedback)r   r   r  r   r   r?   fbvalr   r   r   _submit_feedback  s   z$_LangSmithTestSuite._submit_feedbackr   c                 K  s$   | j j|fi ||d|i d S )Nr   r   )r   r   r  r?   r   r   r   r    s   $z$_LangSmithTestSuite._create_feedbackc                 C  s   | j   d S r,   )r   r   r   r   r   r   r     s   z_LangSmithTestSuite.shutdownr   c	           	      C  s    | j j| j||||||||d	S )N)run_treer   r   r   r2   r4   r   r   )r   r   _end_run	r   r  r   r   r   r2   r4   r   r   r   r   r   end_run  s   z_LangSmithTestSuite.end_runc	           	      C  s:   | j ||j|||d ||_|j|d|id |  d S )N)r   r   r4   r2   reference_example_id)r   r2   )r  r   r  endpatchr  r   r   r   r    s   z_LangSmithTestSuite._end_run)r   r8   r   r   r   r   r,   )r   r8   r*   r   r1   r9   r!   r   )NFNN)r   r   r   r9   r   r   r   r   r   r   r!   r   )r   r   r   r;   r!   r   )r   r   r   r:   r   r:   r2   r:   r4   r   r!   r   )NN)
r   r   r  r  r   r   r   r   r?   r   )r   r   r  r   r?   r   r!   r   )r!   r   r!   r   )r   r   r   r   __annotations__	threadingRLockr   r   propertyr/   r   r   classmethodr   r|   r   r   r   r  r  r  r   r  r  r   r   r   r   r   1  sL   
 





	F
c                   @  s|   e Zd Z							d-d.ddZd/ddZd0ddZd1ddZd2ddZ		 d3d4d%d&Zd5d'd(Z	d5d)d*Z
d6d+d,ZdS )7	_TestCaseNr   r   r   r   r   r6   r2   r:   r4   r   r   r   r   r   r   r!   r   c
           
      C  s   || _ || _|| _|| _|| _|| _|| _|| _|	| _d | _	d | _
|r=|r?||jj| |r4| | |	rA| |	 d S d S d S d S r,   )r   r   r   r2   r4   r   r   r   r   _logged_reference_outputs_logged_outputsadd_process_to_test_suiter   r|   
log_inputslog_reference_outputs)
r   r   r   r   r2   r4   r   r   r   r   r   r   r   r     s*   
z_TestCase.__init__r?   c                 O  s*   | j j|i i |t| j| jd d S )N)r   r   )r   r  r   r   r   )r   r>   r?   r   r   r   submit_feedback0  s   
z_TestCase.submit_feedbackr   c                 C  s,   | j r| jr| j | jd|i d S d S d S )Nr   )r   r   r   )r   r   r   r   r   r'  <  s
   
z_TestCase.log_inputsr   c                 C  2   || _ | jr| jr| j| jd|i d S d S d S )Nr   )r%  r   r   r   )r   r   r   r   r   log_outputsB     
z_TestCase.log_outputsc                 C  r*  )Nr   )r$  r   r   r   )r   r   r   r   r   r(  I  r,  z_TestCase.log_reference_outputsFr   r9   r   r   c                 C  s   | j j| j||| j| jdS )N)r   r   r   r   )r   r   r   r   r   )r   r   r   r   r   r   submit_test_resultP  s   z_TestCase.submit_test_resultc                 C  0   | j r| jr| j | jdt i d S d S d S )Nr  r   r   r   timer   r   r   r   r  ]  
   z_TestCase.start_timec                 C  r.  )Nend_timer/  r   r   r   r   r2  c  r1  z_TestCase.end_timec              
   C  sf   |d u st |tsd|i}| jptt| jj| jpi |d}| jj|||| j	| j
| j| j| jd d S )Noutput)r   r   r   )r   r2   r4   r   r   )r  r   r   r   r"   r   r/   r   r  r$  r2   r4   r   r   )r   r  r   r   r   r   r   r  i  s"   

z_TestCase.end_run)NNNNNNN)r   r   r   r   r   r6   r2   r:   r4   r   r   r   r   r   r   r:   r   r:   r!   r   )r?   r   r   r   r!   r   r   r   r!   r   r   r   r!   r   )NF)r   r9   r   r   r!   r   r  )r   r   r!   r   )r   r   r   r   r)  r'  r+  r(  r-  r  r2  r  r   r   r   r   r#    s&    
!


	

r#  
_TEST_CASE)defaultc                   @  sV   e Zd ZU ded< ded< ded< ded< ded	< d
ed< ded< ded< ded< dS )r_   r8   r   r6   r/   r7   r0   r9   r1   r@   r:   r2   r;   r3   r   r4   r5   N)r   r   r   r  r   r   r   r   r_     s   
 r_   F)totalrF   rG   c                O  sh  |d pt  }|d }|d }|d }t| }	tj|	g|R i |p&d }
d }|rBi }|
s5d}t||D ]
}|
|d ||< q7t	|| |
d}|d }|jjoe|jj
doe|jj
di 
d	}|rnt|d
s{t| |
|j\}}|pz|}|r|jjdnd }|r|jjnd }|rtt|jjd t|j |j|jj< t|t ||||
|||d	}|S )Nr   r0   r2   r4   zU'output_keys' should only be specified when marked test function has input arguments.r1   r/   runtimesdk_versionz0.4.33langsmith_output_pluginz/compare?selectedSessions=)r   r   r2   r4   r   r   r   r   )r   r   rT   	signaturerh_get_inputs_safer^   r[   r   r   rS   r   r2   r\   is_version_greater_or_equalr   r/   configpluginmanager
get_pluginnodenodeidr   r"   urlr   test_suite_urlsr|   r#  rs   rw   )r*   rF   rG   r>   r?   r   r0   r2   r4   r=  r   r   msgr   r   r   dataset_sdk_versionlegacy_example_idexample_namer   r   	test_caser   r   r   _create_test_case  sn   
rM  rC   rD   r   c             	     s,  t  gR i ||dt  fdd}|d r0t|d jj d }nd }t }i |d p<i djjj	i}jj
jg}	|dpQd }
tjd
i i |d|i, tj||	|
d	 |  W d    n1 sww   Y  W d    d S W d    d S 1 sw   Y  d S )NrF   rG   c                    sd     tjt ddjjdd jpi  D jj	t
fdd`} zRz	 i }W n< t
yO } zjt|dd | d	t|i |d }~w tyj } zjt|d
 | d  |d }~ww | | W   n  w W d    n1 sw   Y  z  W d S  ty } ztdj d|  W Y d }~d S d }~ww )Nr   Testc                 S     i | ]
\}}d | |qS ls_example_r   r   r   r   r   r         
z,_run_test.<locals>._test.<locals>.<dictcomp>F)r|   r   r   r2   r   exceptions_to_handle_end_on_exitTr   r   skipped_reasonr   %Failed to create feedback for run_id :
)r  r>  tracegetattrr   r   r2   r  r   r|   r   r-  reprr  r   r2  rd   warningr  resulter*   rC   rL  rD   r   r   _test  sJ   
z_run_test.<locals>._testr@   .yamlr2   r   r5   ignore_hostsallow_hostsr   )rM  r7  setr   r   r/   r>  get_tracing_contextr   r|   r   api_urlrS   tracing_contextr\   with_optional_cache)r*   rF   rG   rC   rD   rc  
cache_pathcurrent_contextr2   rf  rg  r   rb  r   rQ     s@   

'

PrQ   c             	     sD  t  gR i ||dt  fdd}|d r1t|d jj d }nd }t }i |d p=i jjj	t
jd}jjjg}	|d}
|
rY|
nd }tjd
i i |d|i/ tj||	|d	 | I d H  W d    n1 sw   Y  W d    d S W d    d S 1 sw   Y  d S )NrN  c                    sp     tjt ddjjjdd jpi  D j	j
tfddc} zUz i I d H }W n< tyU } zjt|dd | d	t|i |d }~w typ } zjt|d
 | d  |d }~ww | | W   n  w W d    n1 sw   Y  z  W d S  ty } ztdj d|  W Y d }~d S d }~ww )Nr   rO  c                 S  rP  rQ  r   r   r   r   r   r   4  rS  z-_arun_test.<locals>._test.<locals>.<dictcomp>F)r|   r   r  r   r2   r   rT  rU  TrV  rW  rX  rY  rZ  )r  r>  r[  r\  r   r   r   r2   r  r   r|   r   r-  r]  r  r   r2  rd   r^  r_  rb  r   r   rc  -  sN   
z_arun_test.<locals>._testr@   rd  r2   )r   r  r5   re  r   )rM  r7  rh  r   r   r/   r>  ri  r   r|   r"   r   r   rj  rS   rk  r\   rl  )r*   rF   rG   rC   rD   rc  rm  rn  r2   rf  r5   rg  r   rb  r   rJ     sF   

(

PrJ   c                C  sR   t  rtd dS t }t }|r|sd}t||	|  |
|  dS )a  Log run inputs from within a pytest test run.

    !!! warning

        This API is in beta and might change in future versions.

    Should only be used in pytest tests decorated with @pytest.mark.langsmith.

    Args:
        inputs: Inputs to log.

    Example:
        ```python
        from langsmith import testing as t


        @pytest.mark.langsmith
        def test_foo() -> None:
            x = 0
            y = 1
            t.log_inputs({"x": x, "y": y})
            assert foo(x, y) == 2
        ```
    z?LANGSMITH_TEST_TRACKING is set to 'false'. Skipping log_inputs.Nzlog_inputs should only be called within a pytest test decorated with @pytest.mark.langsmith, and with tracing enabled (by setting the LANGSMITH_TRACING environment variable to 'true').)r\   rc   rd   re   r>  get_current_run_treer7  rS   r^   
add_inputsr'  )r   r  rL  rH  r   r   r   r'  s  s   

r'  c                C  sZ   t  rtd dS t }t }|r|sd}t|t	| } |
|  ||  dS )a'  Log run outputs from within a pytest test run.

    !!! warning

        This API is in beta and might change in future versions.

    Should only be used in pytest tests decorated with @pytest.mark.langsmith.

    Args:
        outputs: Outputs to log.

    Example:
        ```python
        from langsmith import testing as t


        @pytest.mark.langsmith
        def test_foo() -> None:
            x = 0
            y = 1
            result = foo(x, y)
            t.log_outputs({"foo": result})
            assert result == 2
        ```
    z@LANGSMITH_TEST_TRACKING is set to 'false'. Skipping log_outputs.Nzlog_outputs should only be called within a pytest test decorated with @pytest.mark.langsmith, and with tracing enabled (by setting the LANGSMITH_TRACING environment variable to 'true').)r\   rc   rd   re   r>  ro  r7  rS   r^   _dumpdadd_outputsr+  )r   r  rL  rH  r   r   r   r+    s   

r+  r   c                C  s<   t  rtd dS t }|sd}t|||  dS )aZ  Log example reference outputs from within a pytest test run.

    !!! warning

        This API is in beta and might change in future versions.

    Should only be used in pytest tests decorated with @pytest.mark.langsmith.

    Args:
        reference_outputs: Reference outputs to log.

    Example:
        ```python
        from langsmith import testing


        @pytest.mark.langsmith
        def test_foo() -> None:
            x = 0
            y = 1
            expected = 2
            testing.log_reference_outputs({"foo": expected})
            assert foo(x, y) == expected
        ```
    zJLANGSMITH_TEST_TRACKING is set to 'false'. Skipping log_reference_outputs.Nzglog_reference_outputs should only be called within a pytest test decorated with @pytest.mark.langsmith.)r\   rc   rd   re   r7  rS   r^   r(  )r   rL  rH  r   r   r   r(    s   r(  )r   r  r  !Optional[Union[dict, list[dict]]]r   r   !Optional[Union[int, bool, float]]r  &Optional[Union[str, int, float, bool]]c         	      K  s  t  rtd dS | rt|||frd}t|| s$|s$d}t||r;d|i} |dur2|| d< |dur:|| d< n	 t }t	 }|rH|sNd}t||j
d	krr|j	d
rr|jd
 }|t| trg| nd| i |j|d< n|j}|j|ttttf | fi | dS )a  Log run feedback from within a pytest test run.

    !!! warning

        This API is in beta and might change in future versions.

    Should only be used in pytest tests decorated with @pytest.mark.langsmith.

    Args:
        key: Feedback name.
        score: Numerical feedback value.
        value: Categorical feedback value
        kwargs: Any other Client.create_feedback args.

    Example:
        ```python
        import pytest
        from langsmith import testing as t


        @pytest.mark.langsmith
        def test_foo() -> None:
            x = 0
            y = 1
            expected = 2
            result = foo(x, y)
            t.log_feedback(key="right_type", score=isinstance(result, int))
            assert result == expected
        ```
    ALANGSMITH_TEST_TRACKING is set to 'false'. Skipping log_feedback.NzGMust specify one of 'feedback' and ('key', 'score', 'value'), not both.zDMust specify at least one of 'feedback' or ('key', 'score', value').r   r   r  zlog_feedback should only be called within a pytest test decorated with @pytest.mark.langsmith, and with tracing enabled (by setting the LANGSMITH_TRACING environment variable to 'true').
evaluatorsreference_run_idr  source_run_id)r\   rc   rd   re   r   r^   r>  ro  r7  rS   session_namer2   rr  r  r   r/   r   r)  r   r   r  )	r  r   r   r  r?   rH  r  rL  r   r   r   r   log_feedback  sB   '

&r{  Feedbackr   r|   2Generator[Optional[run_trees.RunTree], None, None]c                 c  s    t  rtd dV  dS t }|sd}t||jjj	|j
|jd}tj| |jdd|d}|V  W d   dS 1 s@w   Y  dS )a}  Trace the computation of a pytest run feedback as its own run.

    !!! warning

        This API is in beta and might change in future versions.

    Args:
        name: Feedback run name. Defaults to "Feedback".

    Example:
        ```python
        import openai
        import pytest

        from langsmith import testing as t
        from langsmith import wrappers

        oai_client = wrappers.wrap_openai(openai.Client())


        @pytest.mark.langsmith
        def test_openai_says_hello():
            # Traced code will be included in the test case
            text = "Say hello!"
            response = oai_client.chat.completions.create(
                model="gpt-4o-mini",
                messages=[
                    {"role": "system", "content": "You are a helpful assistant."},
                    {"role": "user", "content": text},
                ],
            )
            t.log_inputs({"text": text})
            t.log_outputs({"response": response.choices[0].message.content})
            t.log_reference_outputs({"response": "hello!"})

            # Use this context manager to trace any steps used for generating evaluation
            # feedback separately from the main application logic
            with t.trace_feedback():
                grade = oai_client.chat.completions.create(
                    model="gpt-4o-mini",
                    messages=[
                        {
                            "role": "system",
                            "content": "Return 1 if 'hello' is in the user message and 0 otherwise.",
                        },
                        {
                            "role": "user",
                            "content": response.choices[0].message.content,
                        },
                    ],
                )
                # Make sure to log relevant feedback within the context for the
                # trace to be associated with this feedback.
                t.log_feedback(
                    key="llm_judge", score=float(grade.choices[0].message.content)
                )

            assert "hello" in response.choices[0].message.content.lower()
        ```
    rv  Nztrace_feedback should only be called within a pytest test decorated with @pytest.mark.langsmith, and with tracing enabled (by setting the LANGSMITH_TRACING environment variable to 'true').)r   r  rx  ignorerw  )r|   r   parentr   r2   )r\   rc   rd   re   r7  rS   r^   r   r   r|   r   r   r>  r[  r%  )r|   rL  rH  r2   r  r   r   r   trace_feedback?  s0   @
"r  xc                 C  s0   z
t | jdddW S  ty   t|  Y S w )Nzutf-8surrogateescape)errors)r   decode	Exceptionr"   )r  r   r   r   r#     s
   r#   c                 C  s4   t  }|s| S z|| }|W S  ty   |  Y S w )z)Serialize LangChain Serializable objects.)_get_langchain_dumpdr  )r  dumpdr(   r   r   r   rq    s   rq  Optional[Callable]c                  C  s(   z	ddl m}  | W S  ty   Y d S w )Nr   r  )langchain_core.loadr  ImportErrorr  r   r   r   r    s   r  )r    r   r!   r"   rZ   )r/   r6   r0   r7   r   r8   r1   r9   r2   r:   r3   r;   r4   r<   r5   r7   r!   r=   )r>   r   r?   r   r!   r   )r1   r"   r!   r"   )r*   r   r!   r"   )r   r   r1   r"   r!   r   )r   r   r   r   r!   r   r,   )r   r"   r   r   r   r:   r!   r   )r*   r   r   r:   r   r   r!   r   )r   r   )r   r   r!   r   )r*   r   r>   r   rF   r   rG   r_   r?   r   r!   r#  )r*   r   rC   r   rF   r   rG   r_   rD   r   r!   r   r4  r5  r6  )r  rs  r   r"   r   rt  r  ru  r?   r   r!   r   )r|   r"   r!   r}  )r  r   r!   r"   )r  r   r!   r   )r!   r  )_
__future__r   r   
contextlibcontextvarsdatetimerV   r$   rp   rT   loggingrn   r  r0  rs   r`   collections.abcr   r   concurrent.futuresr   pathlibr   typingr   r   r	   r
   r   r   r   typing_extensionsr   	langsmithr   r   r   r   r   r>  r   r   r   
ls_schemasr   r\   langsmith._internalr   langsmith._internal._serder   langsmith.clientr   r   skipr  r   r  	getLoggerr   rd   UUIDr   r   r   r)   r-   r}   r   r   r   r   r   r   r   r   r   r   r#  
ContextVarr7  r_   rM  rQ   rJ   unitr'  r+  r(  r{  contextmanagerr  r#   rq  	lru_cacher  r   r   r   r   <module>   s    $




  
N





 ^o

B
OS

)
+*O
Z
