a
    `gp                  	   @  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mZ d dlmZ d dlmZmZmZ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l/m0Z0 d dl1m2Z2 zd dl3Z3e3j4j5Z6W n$ e7yx   G dd de5Z6Y n0 e	8e9Z:edZ;edZ<edddddZ=edddddddddddddZ=d d dd!d"dZ=d#d#d$d%d&Z>dd#dd'd(Z?d)d#d*d+d,d-Z@d)d*d.d/d0d1ZAdd2d3d4d5d6d7ZBd8d9d:d;ZCed<eeD d=ZEd<d<d>d?d@ZFG dAd8 d8ZGG dBdC dCZHejIeeH  dDddEZJG dFdG dGedHdIZKddJd#dKdLdMZLdd d dGd dCdNdOdPZMdd d dGd dQdRdSdTZNdd d dGd dQdRdUdVZOe=ZPdWdQdXdYdZZQdWdQd[d\d]ZRdWdQd^d_d`ZSdqdddadbd#dcddd dQdedfdgZTejUdhdid#djdkdldmZVd d#dndodpZWdS )r    )annotationsN)Future)Path)
AnyCallable	GeneratorOptionalSequenceTuple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   i/var/www/html/cobodadashboardai.evdpl.com/venv/lib/python3.9/site-packages/langsmith/testing/_internal.pyr   2   s   r   TUr   funcreturnc                 C  s   d S Nr   r"   r   r   r   test=   s    r&   idoutput_keysr   test_suite_nameOptional[uuid.UUID]Optional[Sequence[str]]Optional[ls_client.Client]Optional[str]zCallable[[Callable], Callable])r(   r)   r   r*   r#   c                 C  s   d S r$   r   r'   r   r   r   r&   C   s    r   )argskwargsr#   c                    s   t |dd|dd|dd|ddt|ddd|rXtd|   t   rnt	d	 d
d
d fdd}| rt
| d r|| d S |S )a  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.

    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:

        .. code-block:: 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.

        .. code-block:: 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.

        .. code-block:: 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()

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

        .. 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!"},
                    ],
                )
                # 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.

        .. code-block:: 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.

        .. code-block:: 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:

        .. code-block:: 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.

        .. code-block:: 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.

        .. code-block:: 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)
    r(   Nr)   r   r*   cache)r(   r)   r   r*   r1   zUnexpected keyword arguments: zLLANGSMITH_TEST_TRACKING is set to 'false'. Skipping LangSmith test tracking.r   r!   c                   sf   t  r8t d ddddd fdd}|S t d ddddd fdd}|S )N)requestr   )	test_argsr2   test_kwargsc                   sD    r|i |I d H S t g|R d| i|diI d H  d S Npytest_requestlangtest_extra)
_arun_testr2   r3   r4   disable_trackingr"   r7   r   r   async_wrapper?  s    z.test.<locals>.decorator.<locals>.async_wrapperc                   s8    r|i |S t g|R d| i|di d S r5   )	_run_testr9   r:   r   r   wrapperO  s    z(test.<locals>.decorator.<locals>.wrapper)inspectiscoroutinefunction	functoolswraps)r"   r<   r>   r;   r7   r%   r   	decorator<  s    
 "ztest.<locals>.decoratorr   )_UTExtrapopls_utilsZget_cache_dirwarningswarnkeystest_tracking_is_disabledloggerinfocallable)r/   r0   rD   r   rC   r   r&   M   s&     `



!str)r*   r#   c                 C  s   t jdrDtjdrD| t jd  }tttj	|j
d d }ntt j
d d }t jdrrt jd }ntdp~d}| d| }|S )NZPYTEST_XDIST_TESTRUNUIDZxdist   ZLANGSMITH_EXPERIMENTFZTestSuiteResult:)osenvironget	importlibutil	find_specrO   uuiduuid5NAMESPACE_DNShexuuid4rG   Zget_tracer_project)r*   Zid_nameZid_prefixnamer   r   r   _get_experiment_namef  s    r_   c                 C  sl   t d}|r|S t d }z$t| }|r@| d|j W S W n ty^   t	d Y n0 t
dd S )NZ
TEST_SUITE	repo_name.z3Could not determine test suite name from file path.z9Please set the LANGSMITH_TEST_SUITE environment variable.)rG   Zget_env_varls_envget_git_infor?   	getmoduler   BaseExceptionrL   debug
ValueError)r"   r*   r`   modr   r   r   _get_test_suite_namex  s    

ri   zls_client.Clientls_schemas.Dataset)r   r*   r#   c                 C  s|   | j |dr| j|dS t dp(d}d}|r@|d| 7 }z| j||ddidW S  tjyv   | j|d Y S 0 d S )	N)dataset_name
remote_url z
Test suitez for __ls_runnerpytest)rk   descriptionmetadata)Zhas_datasetZread_datasetrb   rc   rT   Zcreate_datasetrG   LangSmithConflictError)r   r*   reporp   r   r   r   _get_test_suite  s    rt   ls_schemas.TracerSession)r   
test_suiter#   c                 C  sV   t |j}z&| j||jdt ddddW S  tjyP   | j	|d Y S 0 d S )NzTest Suite Results.revision_idro   )rw   rn   )Zreference_dataset_idrp   rq   )project_name)
r_   r^   Zcreate_projectr(   rb   get_langchain_env_var_metadatarT   rG   rr   Zread_project)r   rv   Zexperiment_namer   r   r   _start_experiment  s    
rz   Optional[dict]	uuid.UUIDzTuple[uuid.UUID, str])r"   inputssuite_idr#   c                 C  s   z t tt| t }W n ty8   | j}Y n0 | | d| j }t	| drxt
dd | jD rx|t|7 }ttj||tt |d  fS )Nz::
pytestmarkc                 s  s   | ]}|j d kV  qdS )ZparametrizeNr^   ).0mr   r   r   	<genexpr>  s   z"_get_example_id.<locals>.<genexpr>)rO   r   r?   getfilerelative_tocwdrg   r   r   hasattranyr   
_stringifyrX   rY   rZ   len)r"   r}   r~   	file_path
identifierr   r   r   _get_example_id  s     r   _LangSmithTestSuite)rv   c                 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 |r|d d ur| jj||d	|d  d d S )
Nrw   ro   )dataset_versionrw   rn   )rq   commitzgit:commit:)
dataset_idZas_oftagbranchzgit:branch:)rb   rc   shutdownget_dataset_version_datasetr(   r   Zupdate_projectexperiment_idry   rT   Zupdate_dataset_tag)rv   Zgit_infor   r   r   r   r   
_end_tests  s4    	r   VT)bound)valuesr#   c                 C  s    | d u r| S t | }t|S r$   )	ls_clientZ_dumps_jsonr   loads)r   Zbtsr   r   r   _serde_example_values  s    
r   c                   @  s(  e Zd ZU dZded< e Zdddddd	Ze	d
d Z
e	dd Ze	dd Zed:dddd dddZe	dd Zdd Zd;ddddddddd Zdd!dd"d#d$Zdddddd%dddddd&d'd(Zd<d)d*dddd+d,d-Zd)d.ddd/d0d1Zd2d3 Zd=d4d5d6d7Zdd5d8d9ZdS )>r   Nr{   
_instancesr-   ru   rj   )r   
experimentdatasetc                 C  s<   |p
t  | _|| _|| _|j| _t | _	t
t|  d S r$   )rtget_cached_clientr   _experimentr   modified_at_dataset_versionrG   ZContextThreadPoolExecutor	_executoratexitregisterr   )selfr   r   r   r   r   r   __init__  s    
z_LangSmithTestSuite.__init__c                 C  s   | j jS r$   )r   r(   r   r   r   r   r(     s    z_LangSmithTestSuite.idc                 C  s   | j jS r$   )r   r(   r   r   r   r   r     s    z!_LangSmithTestSuite.experiment_idc                 C  s   | j S r$   )r   r   r   r   r   r      s    z_LangSmithTestSuite.experimentr   r.   )r   r"   r*   r#   c                 C  s   |p
t  }|pt|}| jL | js,i | _|| jvr\t||}t||}| |||| j|< W d    n1 sp0    Y  | j| S r$   )r   r   ri   _lockr   rt   rz   )clsr   r"   r*   rv   r   r   r   r   	from_test  s    


0z_LangSmithTestSuite.from_testc                 C  s   | j jS r$   )r   r^   r   r   r   r   r^     s    z_LangSmithTestSuite.namec                 C  s   | j S r$   )r   r   r   r   r   r     s    z'_LangSmithTestSuite.get_dataset_versionFr|   boolr   None)run_iderrorskippedpytest_pluginpytest_nodeidr#   c                 C  sR   |rd }d}n|rd}d}nd}d}|r<|r<| |d|i | j| j|| d S )Nr   r   failed   Zpassedstatus)update_process_statusr   submit_submit_result)r   r   r   r   r   r   scorer   r   r   r   submit_result  s    z!_LangSmithTestSuite.submit_resultzOptional[int])r   r   r#   c                 C  s   | j j|d|d d S )Npass)keyr   r   Zcreate_feedback)r   r   r   r   r   r   r   2  s    z"_LangSmithTestSuite._submit_result)r}   outputsrq   r   r   )
example_idr}   r   rq   r#   c          	      C  sL  |r0|r0||d}dd |  D }||| |r<| n|}t|}t|}z| jj|d}W n2 tjy   | jj|||| j	|| j
jd}Y nx0 |d ur||jks|d ur||jks|d ur||jkst|jt| j	kr| jj|j	|||| j	d | jj|j	d}| jd u r"|j| _n&|jrH| jrH|j| jkrH|j| _d S )N)r}   reference_outputsc                 S  s   i | ]\}}|d ur||qS r$   r   )r   kvr   r   r   
<dictcomp>A      z4_LangSmithTestSuite.sync_example.<locals>.<dictcomp>)r   )r   r}   r   r   rq   Z
created_at)r   r}   r   rq   r   )itemsr   copyr   r   Zread_examplerG   ZLangSmithNotFoundErrorZcreate_exampler(   r   
start_timer}   r   rq   rO   r   Zupdate_exampler   r   )	r   r   r}   r   rq   r   r   updateZexampler   r   r   sync_example5  sb    




z _LangSmithTestSuite.sync_exampler   zUnion[dict, list])r   feedbackr   r   r0   c                 K  sv   t |tr|n|g}|D ]X}|rT|rTd|v r4|d n|d }||d|d |ii | jj| jf||d| qd S )Nr   valuer   r   )r   r   )
isinstancelistr   r   r   _create_feedback)r   r   r   r   r   r0   Zfbvalr   r   r   _submit_feedbacki  s    z$_LangSmithTestSuite._submit_feedbackdict)r   r   r0   r#   c                 K  s   | j j|fi || d S r$   r   )r   r   r   r0   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   r#   c              	   C  s   | j j| j||||||dS )N)run_treer   r   r   r   r   )r   r   _end_runr   r   r   r   r   r   r   r   r   r   end_run  s    	z_LangSmithTestSuite.end_runc                 C  s*   | j ||j|d |j|d |  d S )Nr}   r   )r   )r   r}   endpatchr   r   r   r   r     s    z_LangSmithTestSuite._end_run)N)NFNN)NN)NN)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     sH   



 
    8  	  c                
   @  s   e Zd Zd(ddddddddddd	Zddd
ddddddZddddZdddddZdddddZdddddZd)dddddd Z	dd!d"d#Z
dd!d$d%Zdddd&d'ZdS )*	_TestCaseNr   r|   r   r{   r   )rv   r   r   r   r   r}   r   r#   c                 C  sh   || _ || _|| _|| _|| _d | _|| _|| _|rd|rd||j	j
| |rV| | |rd| | d S r$   )rv   r   r   r   r   _logged_reference_outputsr}   r   Zadd_process_to_test_suiter   r^   
log_inputslog_reference_outputs)r   rv   r   r   r   r   r}   r   r   r   r   r     s     

z_TestCase.__init__r   )r}   r   r#   c                C  s    | j j| j||| j| jd d S )N)r}   r   r   r   )rv   r   r   r   r   )r   r}   r   r   r   r   r     s    z_TestCase.sync_example)r0   c                 O  s*   | j j|i i |t| j| jd d S )N)r   r   )rv   r   r   r   r   )r   r/   r0   r   r   r   submit_feedback  s    z_TestCase.submit_feedbackr   r}   r#   c                 C  s$   | j r | jr | j | jd|i d S )Nr}   r   r   r   )r   r}   r   r   r   r     s    
z_TestCase.log_inputsr   r#   c                 C  s$   | j r | jr | j | jd|i d S )Nr   r   )r   r   r   r   r   log_outputs  s    
z_TestCase.log_outputsr   r#   c                 C  s*   || _ | jr&| jr&| j| jd|i d S )Nr   )r   r   r   r   )r   r   r   r   r   r     s
    
z_TestCase.log_reference_outputsFr.   r   )r   r   r#   c                 C  s   | j j| j||| j| jdS )N)r   r   r   r   )rv   r   r   r   r   )r   r   r   r   r   r   submit_test_result  s    z_TestCase.submit_test_resultr   c                 C  s(   | j r$| jr$| j | jdt i d S )Nr   r   r   r   timer   r   r   r   r     s    z_TestCase.start_timec                 C  s(   | j r$| jr$| j | jdt i d S )Nend_timer   r   r   r   r   r     s    z_TestCase.end_timec                 C  s>   |d u st |tsd|i}| jj|| j|| j| j| jd d S )Noutput)r   r   r   )r   r   rv   r   r   r   r   r   )r   r   r   r   r   r   r     s    z_TestCase.end_run)NNNN)NF)r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r     s"       	  r   
_TEST_CASE)defaultc                   @  s6   e Zd ZU ded< ded< ded< ded< ded	< d
S )rE   r-   r   r+   r(   r,   r)   r.   r*   r1   N)r   r   r   r   r   r   r   r   rE     s
   
rE   F)totalzinspect.Signature)r"   sigr#   c                 C  sB   t | dd pd}t | dd pd}|r2d|  }| | | S )Nr   rm   __doc__z - )getattrstrip)r"   r   r^   rp   r   r   r   _get_test_repr  s
    r   )r"   r/   r6   r7   r0   r#   c             	   O  s  |d pt  }|d }t| }tj|g|R i |p<d }d }	|rti }	|sZd}
t|
|D ]}||d |	|< q^t	|| |
d}t| ||j\}}|d p|}|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   r)   zU'output_keys' should only be specified when marked test function has input arguments.r*   r(   Zlangsmith_output_pluginz/compare?selectedSessions=)r   r}   r   r   r   )r   r   r?   	signaturerhZ_get_inputs_saferg   rF   r   r   rT   r   r(   configZpluginmanagerZ
get_pluginnodeZnodeidr   rO   r   urlr   Ztest_suite_urlsr^   r   rX   r\   )r"   r6   r7   r/   r0   r   r)   r   r}   r   msgr   rv   r   Zexample_namer   r   	test_caser   r   r   _create_test_case%  sP    
	r  r   )r"   r3   r6   r7   r4   r#   c          	   	     s  t  gR i ||dt  fdd}|d r`t|d jj d }nd }t }i |d pxi jjj	t
jd}tjf i i |d|iL tj|jjjgd |  W d    n1 s0    Y  W d    n1 s0    Y  d S )	Nr6   r7   c                    sn     tjt ddjjjjjt	fdd} zz i }W n t	y } z6j
t|dd | dt|i |W Y d }~nXd }~0  ty } z,j
t|d | d  |W Y d }~nd }~0 0 | | W   n
  0 W d    n1 s0    Y  z
  W n> tyh } z$td	j d
|  W Y d }~n
d }~0 0 d S Nr   ZTestF)r^   r   reference_example_idr}   rx   Zexceptions_to_handleZ_end_on_exitT)r   r   Zskipped_reason)r   z%Failed to create feedback for run_id z:
r   r   tracer   r   r   r}   rv   r^   r   r   reprr   re   r   rL   warningr   resulter"   r3   r   r4   r   r   _testh  s:    
4z_run_test.<locals>._testr1   .yamlrq   r   r  Zignore_hostsr  r   setr   rv   r(   r   Zget_tracing_contextr   r^   rO   r   Ztracing_contextrG   Zwith_optional_cacher   Zapi_url	r"   r6   r7   r3   r4   r  
cache_pathZcurrent_contextrq   r   r  r   r=   X  s>    

 
r=   c          	   	     s  t  gR i ||dt  fdd}|d r`t|d jj d }nd }t }i |d pxi jjj	t
jd}tjf i i |d|iR tj|jjjgd | I d H  W d    n1 s0    Y  W d    n1 s0    Y  d S )	Nr  c                    st     tjt ddjjjjjt	fdd} zz i I d H }W n t	y } z6j
t|dd | dt|i |W Y d }~nXd }~0  ty } z,j
t|d | d  |W Y d }~nd }~0 0 | | W   n
  0 W d    n1 s0    Y  z
  W n> tyn } z$td	j d
|  W Y d }~n
d }~0 0 d S r  r  r	  r  r   r   r    s:    
4z_arun_test.<locals>._testr1   r  rq   r  r  r  r  r   r  r   r8     s>    

 
r8   r   r   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:
        .. code-block:: 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').)rG   rK   rL   rM   r   get_current_run_treer   rT   rg   Z
add_inputsr   )r}   r   r   r   r   r   r   r     s    
r   r   c                C  sR   t  rtd dS t }t }|r.|s:d}t||	|  |
|  dS )aJ  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:
        .. code-block:: 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').)rG   rK   rL   rM   r   r  r   rT   rg   add_outputsr   )r   r   r   r   r   r   r   r     s    
r   r   c                C  s<   t  rtd dS t }|s.d}t|||  dS )as  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:
        outputs: Reference outputs to log.

    Example:
        .. code-block:: 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.)rG   rK   rL   rM   r   rT   rg   r   )r   r   r   r   r   r   r   ;  s    r   )r   r   z!Optional[Union[dict, list[dict]]]z!Optional[Union[int, bool, float]]z&Optional[Union[str, int, float, bool]])r   r   r   r   r0   r#   c         	      K  s  t  rtd dS | r6t|||fr6d}t|nD| sL|sLd}t|n.|rzd|i} |durh|| d< |durz|| d< n t }t	 }|r|sd}t||j
d	kr|j	d
r|jd
 }|t| tr| 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:
        .. code-block:: 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   Zsource_run_id)rG   rK   rL   rM   r   rg   r   r  r   rT   Zsession_namerq   r  r   r   r(   Ztrace_idr   r   r   r   )	r   r   r   r   r0   r   r   r   r   r   r   r   log_feedbacke  sB    '



r  ZFeedbackr   z2Generator[Optional[run_trees.RunTree], None, None])r^   r#   c                 c  s   t  rtd dV  dS t }t }|r4|s@d}t||j	j
j|j|jd}tj| |jdd|d}|V  W d   n1 s0    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:
        .. code-block:: 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()
    r  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  r  ignorer  )r^   r}   parentrx   rq   )rG   rK   rL   rM   r   r  r   rT   rg   rv   r   r^   r   r(   r  r   )r^   Z
parent_runr   r   rq   r   r   r   r   trace_feedback  s2    @r  )xr#   c                 C  s4   zt | jdddW S  ty.   t|  Y S 0 d S )Nzutf-8surrogateescape)errors)r   decode	ExceptionrO   )r  r   r   r   r     s    r   )N)X
__future__r   r   
contextlibcontextvarsdatetimerA   rU   r?   loggingrR   r   r   rX   rH   concurrent.futuresr   pathlibr   typingr   r   r   r   r	   r
   r   r   r   r   Ztyping_extensionsr   Z	langsmithr   r   r   rb   r   r   r   r   r   Z
ls_schemasr   rG   Zlangsmith._internalr   Zlangsmith._internal._serder   Zlangsmith.clientr   ro   skipr"  r   ImportError	getLoggerr   rL   r   r    r&   r_   ri   rt   rz   r   r   r   r   r   r   r   
ContextVarr   rE   r   r  r=   r8   unitr   r   r   r  contextmanagerr  r   r   r   r   r   <module>   s   0
	   ?m3DE+,+ Q]