HEX
Server: Apache/2.4.52 (Ubuntu)
System: Linux spn-python 5.15.0-89-generic #99-Ubuntu SMP Mon Oct 30 20:42:41 UTC 2023 x86_64
User: arjun (1000)
PHP: 8.1.2-1ubuntu2.20
Disabled: NONE
Upload Files
File: //home/arjun/.local/lib/python3.10/site-packages/langsmith/__pycache__/run_helpers.cpython-310.pyc
o

���g��
@sjUdZddlmZddlZddlZddlZddlZddlZddlZddl	Z	ddl
Z
ddlZddlmZddl
mZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZmZm Z m!Z!m"Z"m#Z#m$Z$m%Z%m&Z&ddl'm(Z(m)Z)m*Z*m+Z+m,Z,ddl-m.Z/ddl-m0Z0m1Z1m2Z2dd	l3m4Z5dd
l6m7Z7er�ddl8m9Z9ddl:m;Z;e	�<e=�Z>ej?ee0j@d
dd�ZAej?eeBddd�ZCej?eeeBddd�ZDej?eeeBefddd�ZEej?ee#eFedfddd�ZGej?ee/jHddd�ZIeAeCeDeEeGeId�ZJdeKd<d�dd�ZL	d�d�dd �ZMejNddddddd!�d�d1d2��ZOeLZPd�d5d6�ZQddddddddd7�d�dBdC�ZRd�dFdG�ZSGdHdI�dIe!dJdK�ZTe"dLdMdN�ZUe)dO�ZVe&GdPdQ�dQeeeVeUf��ZWe%d�dRdS��ZXe%	Td�ddddddddddJdU�
d�d[dS��ZXd�d^dS�ZXGd_d`�d`�ZYd�dadb�ZZd�dedf�Z[hdg�Z\Gdhdi�die!dJdK�Z]Gdjdk�dke!dJdK�Z^		d�d�drds�Z_d�dwdx�Z`	d�d�d{d|�Za			d�d�dd��Zb			d�d�d�d��Zcd�d�d��Zdd�d�d��Zed�d�d��Zfd�d�d��Zgd�d�d��Zhejid�d��d�d�d���Zjd�d�d��Zkd�d�d��Zld�d�d��Zmd�d�d��Znd�d�d��Zoe"d��ZpGd�d��d�eep�ZqGd�d��d�eqeep�ZrGd�d��d�eqeep�Zsd�d�d��ZtdS)�z1Decorator for creating a run tree from functions.�)�annotationsN)�copy_context)�
TYPE_CHECKING�Any�AsyncGenerator�
AsyncIterator�	Awaitable�Callable�Dict�	Generator�Generic�Iterator�List�Literal�Mapping�Optional�Protocol�Sequence�Set�Tuple�Type�	TypedDict�TypeVar�Union�cast�overload�runtime_checkable)�	Annotated�	ParamSpec�	TypeGuard�get_args�
get_origin��client)�	run_trees�schemas�utils)�_aiter)�_runtime_env)�
TracebackType)�Runnable�_PARENT_RUN_TREE��default�
_PROJECT_NAME�_TAGS�	_METADATA�local�_TRACING_ENABLED�_CLIENT��parent�project_name�tags�metadata�enabledr#z!Dict[str, contextvars.ContextVar]�
_CONTEXT_KEYS�return�Optional[run_trees.RunTree]cCst��S)zGet the current run tree.)r+�get�r>r>�H/home/arjun/.local/lib/python3.10/site-packages/langsmith/run_helpers.py�get_current_run_treeN�r@�context�Optional[contextvars.Context]�Dict[str, Any]csH�durt��t��t��t��t��t��d�S�fdd�t��D�S)z Get the current tracing context.Nr4csi|]
\}}|��|��qSr>�r=��.0�k�v�rBr>r?�
<dictcomp>`sz'get_tracing_context.<locals>.<dictcomp>)	r+r=r.r/r0r2r3r:�itemsrJr>rJr?�get_tracing_contextSs�rM)r6r7r8r5r9r#r6�
Optional[str]r7�Optional[List[str]]r8�Optional[Dict[str, Any]]r5�@Optional[Union[run_trees.RunTree, Mapping, str, Literal[False]]]r9�'Optional[Union[bool, Literal['local']]]r#�Optional[ls_client.Client]�kwargsr�Generator[None, None, None]c	ks��|r
t�d|�d�t�t�}|durtd|p|�d�i�nd}|dur=tt|p*g�t|jp0g�B�}i|j	�|p;i�}|durC|n|�d�}t
||||||d��z
dVWt
|�dSt
|�w)	a�Set the tracing context for a block of code.

    Args:
        project_name: The name of the project to log the run to. Defaults to None.
        tags: The tags to add to the run. Defaults to None.
        metadata: The metadata to add to the run. Defaults to None.
        parent: The parent run to use for the context. Can be a Run/RunTree object,
            request headers (for distributed tracing), or the dotted order string.
            Defaults to None.
        client: The client to use for logging the run to LangSmith. Defaults to None,
        enabled: Whether tracing is enabled. Defaults to None, meaning it will use the
            current context value or environment variables.


    z Unrecognized keyword arguments: �.Fr5�
parent_runNr9r4)�warnings�warn�DeprecationWarningrM�_get_parent_runr=�sorted�setr7r8�_set_tracing_context)	r6r7r8r5r9r#rT�current_contextrWr>r>r?�tracing_contextcs6�
�����
r`�func�'TypeGuard[SupportsLangsmithExtra[P, R]]cCs2t|�pt|tj�ot|j�pt|d�ot|j�S)z,Check if a function is @traceable decorated.�__call__)�_is_traceable_function�
isinstance�	functools�partialra�hasattrrc�rar>r>r?�is_traceable_function�s
��rj��namer8r7r#�	reduce_fnr6�process_inputs�process_outputs�Callable[P, R]rl�Optional[Mapping[str, Any]]rm�$Optional[Callable[[Sequence], dict]]rn� Optional[Callable[[dict], dict]]ro�Optional[Callable[..., dict]]�SupportsLangsmithExtra[P, R]c	
Cs(t|�r|St||||||||d�|�S)z$Ensure that a function is traceable.rk)rj�	traceable)	rarlr8r7r#rmr6rnror>r>r?�ensure_traceable�s
�	�rwr	�boolcCs t�|�pt|d�ot�|j�S)z;Inspect function or wrapped function to see if it is async.�__wrapped__)�inspect�iscoroutinefunctionrhryrir>r>r?�is_async�s
�r|c@s~eZdZUdZded<	ded<	ded<	ded	<	d
ed<	ded<	d
ed<	ded<	ded<	ded<	ded<dS)�LangSmithExtraz<Any additional info to be injected into the run dynamically.rNrl�Optional[ls_client.ID_TYPE]�reference_example_id�Optional[Dict]�	run_extraz0Optional[Union[run_trees.RunTree, str, Mapping]]r5r<�run_treer6rPr8rOr7�run_idrSr#�,Optional[Callable[[run_trees.RunTree], Any]]�on_endN��__name__�
__module__�__qualname__�__doc__�__annotations__r>r>r>r?r}�s0
r}F)�total�RT)�	covariant�Pc@s eZdZdZdd�ddd
�ZdS)�SupportsLangsmithExtraa`Implementations of this Protoc accept an optional langsmith_extra parameter.

    Args:
        *args: Variable length arguments.
        langsmith_extra (Optional[LangSmithExtra): Optional dictionary of
            additional parameters for Langsmith.
        **kwargs: Keyword arguments.

    Returns:
        R: The return type of the callable.
    N��langsmith_extra�args�P.argsr��Optional[LangSmithExtra]rT�P.kwargsr;r�cOsdS)ajCall the instance when it is called as a function.

        Args:
            *args: Variable length argument list.
            langsmith_extra: Optional dictionary containing additional
                parameters specific to Langsmith.
            **kwargs: Arbitrary keyword arguments.

        Returns:
            R: The return value of the method.

        Nr>)�selfr�r�rTr>r>r?rc�szSupportsLangsmithExtra.__call__)r�r�r�r�rTr�r;r�)r�r�r�r�rcr>r>r>r?r��s�r�cC�dS�Nr>rir>r>r?rvsrv�chain)
rlr8r7r#rmr6rnro�_invocation_params_fn�dangerously_allow_filesystem�run_type�ls_client.RUN_TYPE_Tr�r��8Callable[[Callable[P, R]], SupportsLangsmithExtra[P, R]]c
Cr�r�r>)r�rlr8r7r#rmr6rnror�r�r>r>r?rvsr��/Union[Callable, Callable[[Callable], Callable]]cslttj|rt|dt�r|dn|�dd�pd���tvr,t�d��dt�d��d��t	|�d	kr7t�d
�d|vrAt�dt
�|�d
d��t|�dd�|�dd�|�dd�|�dd�|�dd�|�dd��|�dd�|�dd�|�dd�d�
�|�dd�}tj
t|d��|r�t�dt|����d�t
�d ����fdd�}t	|�d	kr�t|d�r�|s�||d�S|S)!aTrace a function with langsmith.

    Args:
        run_type: The type of run (span) to create. Examples: llm, chain, tool, prompt,
            retriever, etc. Defaults to "chain".
        name: The name of the run. Defaults to the function name.
        metadata: The metadata to add to the run. Defaults to None.
        tags: The tags to add to the run. Defaults to None.
        client: The client to use for logging the run to LangSmith. Defaults to
            None, which will use the default client.
        reduce_fn: A function to reduce the output of the function if the function
            returns a generator. Defaults to None, which means the values will be
            logged as a list. Note: if the iterator is never exhausted (e.g.
            the function returns an infinite generator), this will never be
            called, and the run itself will be stuck in a pending state.
        project_name: The name of the project to log the run to. Defaults to None,
            which will use the default project.
        process_inputs: Custom serialization / processing function for inputs.
            Defaults to None.
        process_outputs: Custom serialization / processing function for outputs.
            Defaults to None.
        dangerously_allow_filesystem: Whether to allow filesystem access for attachments.
            Defaults to False.

            Traces that reference local filepaths will be uploaded to LangSmith.
            In general, network-hosted applications should not be using this because
            referenced files are usually on the user's machine, not the host machine.

    Returns:
            Union[Callable, Callable[[Callable], Callable]]: The decorated function.

    Note:
            - Requires that LANGSMITH_TRACING_V2 be set to 'true' in the environment.

    Examples:
        Basic usage:

        .. code-block:: python

            @traceable
            def my_function(x: float, y: float) -> float:
                return x + y


            my_function(5, 6)


            @traceable
            async def my_async_function(query_params: dict) -> dict:
                async with httpx.AsyncClient() as http_client:
                    response = await http_client.get(
                        "https://api.example.com/data",
                        params=query_params,
                    )
                    return response.json()


            asyncio.run(my_async_function({"param": "value"}))

        Streaming data with a generator:

        .. code-block:: python

            @traceable
            def my_generator(n: int) -> Iterable:
                for i in range(n):
                    yield i


            for item in my_generator(5):
                print(item)

        Async streaming data:

        .. code-block:: python

            @traceable
            async def my_async_generator(query_params: dict) -> Iterable:
                async with httpx.AsyncClient() as http_client:
                    response = await http_client.get(
                        "https://api.example.com/data",
                        params=query_params,
                    )
                    for item in response.json():
                        yield item


            async def async_code():
                async for item in my_async_generator({"param": "value"}):
                    print(item)


            asyncio.run(async_code())

        Specifying a run type and name:

        .. code-block:: python

            @traceable(name="CustomName", run_type="tool")
            def another_function(a: float, b: float) -> float:
                return a * b


            another_function(5, 6)

        Logging with custom metadata and tags:

        .. code-block:: python

            @traceable(
                metadata={"version": "1.0", "author": "John Doe"}, tags=["beta", "test"]
            )
            def tagged_function(x):
                return x**2


            tagged_function(5)

        Specifying a custom client and project name:

        .. code-block:: python

            custom_client = Client(api_key="your_api_key")


            @traceable(client=custom_client, project_name="My Special Project")
            def project_specific_function(data):
                return data


            project_specific_function({"data": "to process"})

        Manually passing langsmith_extra:

        .. code-block:: python

            @traceable
            def manual_extra_function(x):
                return x**2


            manual_extra_function(5, langsmith_extra={"metadata": {"version": "1.0"}})
    rr�Nr�zUnrecognized run_type: z. Must be one of: z . Did you mean @traceable(name='z')?�z�The `traceable()` decorator only accepts one positional argument, which should be the run_type. All other arguments should be passed as keyword arguments.�extrazJThe `extra` keyword argument is deprecated. Please use `metadata` instead.rmrlr8r7r#r6rnr�r�F)
�extra_outerrlr8r7r#r6r�rn�invocation_params_fnr�ro)�outputs_processorzHThe following keyword arguments are not recognized and will be ignored: rVrar	c
	s�t���}|j�dd�du�|j�dd�du�t���dd�d�����fd
d��}t���dd�d������fd
d��}t���dd�d����fdd��}t���dd�d������fdd��}t���dd�d������fdd��}t���dd�d������fdd��}t���r�|}nt���r�|}nt��r��r�|}n
|}n�r�|}n|}t	|dd�t�|�}	|	j�d�s�|	j
gdd�|	j��D��tjdtjj
dd��dd�|	j��D��d�}	|	|_|S) Nr��configr�r�rr�r�rTr;c
�s
�tjt��|||d�IdH}zLt��}�r|d|d<�s$|�dd��|i|��}|r:tj||dd�IdH}n td
it|d����
|IdH}Wd�n1sUwYWnt	yw}zt�
tj�||d��IdH|�d}~wwtj�||d	�IdH|S)z"Async version of wrapper function.��container_inputr�r�rTN�new_runr�r�rBrJ��error��outputsr>)�
aitertools�
aio_to_thread�
_setup_run�asyncio_accepts_context�pop�asyncio�create_taskr`rM�
BaseException�shield)r�r�rT�
run_container�accepts_context�fr_coro�function_result�e)�_on_run_endr�ra�func_accepts_config�func_accepts_parent_runr>r?�
async_wrapper�sJ��	�
���
����z3traceable.<locals>.decorator.<locals>.async_wrapperrc	sd�tjt��|||d�IdH}g}zp�r|d|d<�s"|�dd��|i|��}t��}t�|�ra|rAtj||dd�IdH}n t	dit
|d����
|IdH}Wd�n1s\wYt|||dro|djdknd||d	�2z	3dHW}|Vqu6Wn t
y�}zt�tj�||t|��d
��IdH|�d}~wwtj�|t|��d�IdHdS)
Nr�r�r�r�rBrJ�llmF��	generatorr��
is_llm_runr��results�r�r�r�r>)r�r�r�r�r�rz�iscoroutiner�r�r`rM�_process_async_iteratorr�r�r��_get_function_result)	r�r�rTr�r��async_gen_resultr��itemr��r�r�rar�r�rmr>r?�async_generator_wrappersn��
�
������
���
�z=traceable.<locals>.decorator.<locals>.async_generator_wrapperc
s�t��|||d�}t���j�dd�du}z |r|d|d<�s&|�dd�|dj�g|�Ri|��}WntyI}z�||d�|�d}~ww�||d�|S)	�>Create a new run or create_child() if run is passed in kwargs.r�r�Nr�r�rBr�r�)r�rz�	signature�
parametersr=r��runr�)r�r�rTr�r�r�r�)r�r�rar�r>r?�wrapper\s,�� ��z-traceable.<locals>.decorator.<locals>.wrapperc	
?s��t��|||d�}t���j�dd�du}g}d}z6|r#|d|d<�s+|�dd�|dj�g|�Ri|��}t||�dk|d�EdH}|durO|�|�Wnt	yh}z�||t
|��d�|�d}~ww�|t
|��d	�|S)
Nr�r�r�r�rBr��r�r�r�r�)r�rzr�r�r=r�r��_process_iterator�appendr�r�)	r�r�rTr�r�r��function_return�generator_resultr�)r�r�rar�rmr�r>r?�generator_wrapperysL����
����z7traceable.<locals>.decorator.<locals>.generator_wrapperc
s�t��|||d�}z �r|d|d<�s|�dd�|dj�g|�Ri|��}Wnty<}z�||d��d}~wwt|d�rHt||��St|d�rSt||��S�||d	�|S)
Nr�r�r�r�rBr��__iter__�	__aiter__r�)r�r�r��	Exceptionrh�
_TracedStream�_TracedAsyncStream�r�r�rT�trace_container�streamr�r�r>r?�stream_wrapper�s0� ��

z4traceable.<locals>.decorator.<locals>.stream_wrapperc
�s��tjt��|||d�IdH}z�r|d|d<�s |�dd��|i|��IdH}WntyC}ztj�||d�IdH�d}~wwt|d�rOt||��St|d�rZt||��Stj�||d�IdH|S)	Nr�r�r�r�r�r�r�r�)r�r�r�r�r�rhr�r�r�r�r>r?�async_stream_wrapper�s4��	��

z:traceable.<locals>.decorator.<locals>.async_stream_wrapper�__langsmith_traceable__Tcss"�|]}|jtjjkr|VqdSr���kindrz�	Parameter�VAR_KEYWORD�rG�paramr>r>r?�	<genexpr>�����z/traceable.<locals>.decorator.<locals>.<genexpr>r,css"�|]}|jtjjkr|VqdSr�r�r�r>r>r?r�r�)r�)r�rr�r�rTrr;r)r�rr�r�rTrr;r)rzr�r�r=rf�wraps�isasyncgenfunction�isgeneratorfunctionr|�setattr�replace�valuesr��KEYWORD_ONLY�
__signature__)
ra�func_sigr�r�r�r�r�r��selected_wrapper�sig�r�r�rmr�)rar�r�r?�	decorator�sh
�+�?��.��
 

��
��	���ztraceable.<locals>.decorator)rar	)r�	ls_client�
RUN_TYPE_Tre�strr��_VALID_RUN_TYPESrXrY�lenrZ�_ContainerInputrfrg�_handle_container_endr\�keys�callable)r�rTr�r�r>r�r?rv%sl�
������








�
�
��'c
@s�eZdZdZ	d6dddddddddddd�d7dd �Zd8d#d$�Zd9d,d-�Zd8d.d/�Z			d:d9d0d1�Zd8d2d3�Z				d:d9d4d5�Z
dS);�tracea�
Manage a LangSmith run in context.

    This class can be used as both a synchronous and asynchronous context manager.

    Args:
        name (str): Name of the run.
        run_type (ls_client.RUN_TYPE_T, optional): Type of run (e.g., "chain", "llm", "tool"). Defaults to "chain".
        inputs (Optional[Dict], optional): Initial input data for the run. Defaults to None.
        project_name (Optional[str], optional): Project name to associate the run with. Defaults to None.
        parent (Optional[Union[run_trees.RunTree, str, Mapping]], optional): Parent run. Can be a RunTree, dotted order string, or tracing headers. Defaults to None.
        tags (Optional[List[str]], optional): List of tags for the run. Defaults to None.
        metadata (Optional[Mapping[str, Any]], optional): Additional metadata for the run. Defaults to None.
        client (Optional[ls_client.Client], optional): LangSmith client for custom settings. Defaults to None.
        run_id (Optional[ls_client.ID_TYPE], optional): Preset identifier for the run. Defaults to None.
        reference_example_id (Optional[ls_client.ID_TYPE], optional): Associates run with a dataset example. Only for root runs in evaluation. Defaults to None.
        exceptions_to_handle (Optional[Tuple[Type[BaseException], ...]], optional): Exception types to ignore. Defaults to None.
        extra (Optional[Dict], optional): Extra data to send to LangSmith. Use 'metadata' instead. Defaults to None.

    Examples:
        Synchronous usage:

        .. code-block:: python

            >>> with trace("My Operation", run_type="tool", tags=["important"]) as run:
            ...     result = "foo"  # Perform operation
            ...     run.metadata["some-key"] = "some-value"
            ...     run.end(outputs={"result": result})

        Asynchronous usage:

        .. code-block:: python

            >>> async def main():
            ...     async with trace("Async Operation", run_type="tool", tags=["async"]) as run:
            ...         result = "foo"  # Await async operation
            ...         run.metadata["some-key"] = "some-value"
            ...         # "end" just adds the outputs and sets error to None
            ...         # The actual patching of the run happens when the context exits
            ...         run.end(outputs={"result": result})
            >>> asyncio.run(main())

        Handling specific exceptions:

        .. code-block:: python

            >>> import pytest
            >>> import sys
            >>> with trace("Test", exceptions_to_handle=(pytest.skip.Exception,)):
            ...     if sys.platform == "win32": # Just an example
            ...         pytest.skip("Skipping test for windows")
            ...     result = "foo"  # Perform test operation
    r�N)�inputsr�r6r5r7r8r#r�r�exceptions_to_handle�attachmentsrlr�r�r�rr�r�r6rNr5�COptional[Union[run_trees.RunTree, str, Mapping, Literal['ignore']]]r7rOr8rqr#rSr�r~rr�)Optional[Tuple[Type[BaseException], ...]]r�Optional[schemas.Attachments]rTrcKs�|�dd�|_|rt�dt|����d�t�||_||_||_	|
|_
||_||_||_
|�d�|_||_||_|	|_|
|_||_||_d|_d|_dS)z_Initialize the trace context manager.

        Warns if unsupported kwargs are passed.
        �_end_on_exitTzEThe `trace` context manager no longer supports the following kwargs: rVr�N)r�rrXrYr\r�rZrlr�rrr�r6r5r=r�r7r8r#r�rrr��old_ctx)r�rlr�rr�r6r5r7r8r#r�rrrrTr>r>r?�__init__Ls0
��
ztrace.__init__r;�run_trees.RunTreec
Csht�|_t�|j�}t��}t��}|jp|j�d�}t|j	|j
|d��}tt|j
p+g|p.g��}i|jp7i�|p;i�ddi�}|jpEi}||d<t|j�}	|durh|rh|j|j|j|j||j||jd�|_n$tj|jt�|j�tj|jdd	�|j||	p~d
|jp�i|||jp�id�
|_|dur�|j��|r�t�|�t�|�t�|j�t �|	�t!�|�|jS)a]Set up the tracing context and create a new run.

        This method initializes the tracing context, merges tags and metadata,
        creates a new run (either as a child of an existing run or as a new root run),
        and sets up the necessary context variables.

        Returns:
            run_trees.RunTree: The newly created run.
        r#)r5r�r#�	ls_methodrr8N)rlr�r�r�rr7rT��accept_nullr-)
rl�idrr�r�r6rr7r#r)"rMr	r&�tracing_is_enabledr/r=r0r#r[r5r�r\r]r7r8r��_get_project_namer6�create_childrlr�r�rrr�r$�RunTreer��_ensure_uuidr�postr+r.r3)
r�r9�
outer_tags�outer_metadata�client_�parent_run_�tags_r8r��
project_name_r>r>r?�_setup~sn
�����


�

��




ztrace._setup�exc_type�Optional[Type[BaseException]]�	exc_value�Optional[BaseException]�	traceback�Optional[TracebackType]�NonecCs�|jdurdS|dur-|jrt||j�rd}nt��}|j�d|�d|��}|jj|d�|jdurKt�|j�}|durD|j	rD|j�
�t|j�dSt�
dt�dS)a�Clean up the tracing context and finalize the run.

        This method handles exceptions, ends the run if necessary,
        patches the run if it's not disabled, and resets the tracing context.

        Args:
            exc_type: The type of the exception that occurred, if any.
            exc_value: The exception instance that occurred, if any.
            traceback: The traceback object associated with the exception, if any.
        N�: �

r�Tz(Tracing context was not set up properly.)r�r�
issubclassr&�_format_excr��endr	rr�patchr^rXrY�RuntimeWarning)r�rrr!�tbr9r>r>r?�	_teardown�s 
�

ztrace._teardowncCs|��S)zyEnter the context manager synchronously.

        Returns:
            run_trees.RunTree: The newly created run.
        )r�r�r>r>r?�	__enter__�sztrace.__enter__cCs|�|||�dS)aExit the context manager synchronously.

        Args:
            exc_type: The type of the exception that occurred, if any.
            exc_value: The exception instance that occurred, if any.
            traceback: The traceback object associated with the exception, if any.
        N)r,)r�rrr!r>r>r?�__exit__�s
ztrace.__exit__c�s.�t�}tj|j|d�IdH}tt|��|S)zzEnter the context manager asynchronously.

        Returns:
            run_trees.RunTree: The newly created run.
        ��__ctxN)rr�r�rr^rM)r��ctx�resultr>r>r?�
__aenter__s
�ztrace.__aenter__c	�s`�t�}|durt�tj|j||||d��IdHntj|j||||d�IdHtt|��dS)aExit the context manager asynchronously.

        Args:
            exc_type: The type of the exception that occurred, if any.
            exc_value: The exception instance that occurred, if any.
            traceback: The traceback object associated with the exception, if any.
        Nr0)rr�r�r�r�r,r^rM)r�rrr!r2r>r>r?�	__aexit__s�
���ztrace.__aexit__�r�)rlr�r�r�rr�r�r�r6rNr5rr7rOr8rqr#rSr�r~rr~rrrrrTr)r;r)rrrr r!r"r;r#�NNN)r�r�r�r�r
rr,r.r/r4r5r>r>r>r?rs88��
2
I
$
�
�rcCs.|r|St��}t��p|r|jndpt��Sr�)r+r=r.�session_namer&�get_tracer_project)r6�prtr>r>r?r)s��r�traceable_fnr*c
s�zddlm�m}ddlm�m�Wnty#}ztd�|�d}~wwt|�sEzt�	|�}Wnt
y:d}Ynwtd|�d|����G���fd	d
�d
|�}||�S)a�Convert a function wrapped by the LangSmith @traceable decorator to a Runnable.

    Args:
        traceable_fn (Callable): The function wrapped by the @traceable decorator.

    Returns:
        Runnable: A Runnable object that maintains a consistent LangSmith
            tracing context.

    Raises:
        ImportError: If langchain module is not installed.
        ValueError: If the provided function is not wrapped by the @traceable decorator.

    Example:
        >>> @traceable
        ... def my_function(input_data):
        ...     # Function implementation
        ...     pass
        >>> runnable = as_runnable(my_function)
    r)�RunnableConfig�RunnableLambda)�Input�Outputzjas_runnable requires langchain-core to be installed. You can install it with `pip install langchain-core`.Nz<source unavailable>zRas_runnable expects a function wrapped by the LangSmith @traceable decorator. Got z
 defined as:
csVeZdZdZ	dd���fd	d
�
Zed���fd
d��Zed���fdd��Z�ZS)z&as_runnable.<locals>.RunnableTraceablez�Converts a @traceable decorated function to a Runnable.

        This helps maintain a consistent LangSmith tracing context.
        Nrar	�afunc�*Optional[Callable[..., Awaitable[Output]]]r;r#c	s�d}|�|�}t|�r!|durtd��tt�g�f|�|��}nt|�r2tt�g�f|�|��}|durAt|jj	�d|����t
��|ttt�gt
�f|��dS)Nz�Func was provided as a coroutine function, but afunc was also provided. If providing both, func should be a regular function to avoid ambiguity.zG expects a function wrapped by the LangSmith @traceable decorator. Got )�_wrap_asyncr|�	TypeErrorrr	rj�
_wrap_sync�
ValueError�	__class__r��superr
rr)r�rar@�wrapped�awrapped)r>r?rFr>r?r
cs.
�
����z/as_runnable.<locals>.RunnableTraceable.__init__�Callable[..., Output]�)Callable[[Input, RunnableConfig], Output]cs$d
�fdd�}tt��g�f|�S)z4Wrap a synchronous function to make it asynchronous.r�dictr�r<r;rcs,tj�tt|��}�di|�dd|ii��S�Nr�r�r>�r$r�from_runnable_configrrL�rr�r�rir>r?�wrap_traceable�szIas_runnable.<locals>.RunnableTraceable._wrap_sync.<locals>.wrap_traceableN�rrLr�r<r;r)rr	)rarQ�r>r?r<rir?rD�sz1as_runnable.<locals>.RunnableTraceable._wrap_sync�>Optional[Callable[[Input, RunnableConfig], Awaitable[Output]]]cs`|durdSt|�std|����ttdt�f|��d�fd
d�}tt��gt�f|�S)
z.Wrap an async function to make it synchronous.NzXRunnableTraceable expects a function wrapped by the LangSmith @traceable decorator. Got .rrLr�r<r;rc�s4�tj�tt|��}�di|�dd|ii��IdHSrMrNrP��afunc_r>r?�awrap_traceable�s� zKas_runnable.<locals>.RunnableTraceable._wrap_async.<locals>.awrap_traceablerR)rjrErr	r)r@rWrSrUr?rB�s���z2as_runnable.<locals>.RunnableTraceable._wrap_asyncr�)rar	r@rAr;r#)rarJr;rK)r@rAr;rT)	r�r�r�r�r
�staticmethodrDrB�
__classcell__r>rS�rFr?�RunnableTraceable]s� r[)�langchain_core.runnablesr<r=�langchain_core.runnables.utilsr>r?�ImportErrorrjrz�	getsourcer�rE)r;r=r��fn_srcr[r>rSr?�as_runnable6s4��������Ira>r��toolr��parser�prompt�	embedding�	retrieverc@sJeZdZUdZded<ded<ded<ded<d	ed
<ded<d
ed<dS)�_TraceableContainer�3Typed response when initializing a run a traceable.r<r�rNr6�
outer_projectrPrrOrr�r�zcontextvars.ContextrBNr�r>r>r>r?rg�s
rgc@sjeZdZUdZded<ded<ded<ded	<d
ed<ded
<ded<ded<ded<ded<ded<dS)r�rhr�r�rNrlrPr8rOr7rSr#�Optional[Callable]rmr6r�r�rsrnr�zOptional[bool]r�Nr�r>r>r>r?r��s
r��	containerr��
Optional[Any]r�r r#c	
Cs�|�d�}|durdSt|t�r|nd|i}d}|r't��}t|��d|��}|j||d�t��dur8|��|�d�}|durht	|�rjz||�WdSt
yg}zt�d|���WYd}~dSd}~wwdSdS)	zEnd the run.r�N�outputr%�r�r�Tr�zFailed to run on_end function: )
r=rerLr&r'�reprr(rr)rr��LOGGER�warning)	rkr�r�r��outputs_�error_�
stacktracer�r�r>r>r?�_container_end�s(

���rur�rLr�cCs(|�dd�}|ri|�|�}|S|}|S)Nr�rE)r�r�r��extra_innerr>r>r?�_collect_extra�s�rwr��Optional[dict]cCs�|�d�}|dkrdSt|tj�r|St|t�r)tjj||�d�t|�d��d�St|t�rAtjj||�d�t|�d��d�}|S|�d�}|rJ|St	�}t
��durstjj||�d�d�}rs|rq|durk|�d�sq|j
|j
krs|S|S)	Nr5�ignorer#r6)r#r6r�r"�	callbacks)r=rer$rrL�from_headersrr��from_dotted_orderr@r(�get_langchain_core_versionrO�dotted_order)r�r�r5�dortr��crt�rtr>r>r?r[�s@

�
�


��r[r�r�c$Cs�|�d�pi}|�d�}|�d�}|�d�}|�d�pd}	|�dd�}
t��}|p+t�}|�d	�p5|�d	�}|�d|�p?t��}
ti|�d|
i�|�d
��}t��}|pg|rY|jndpg|�d�pg|dpgt��}|�d
�}|�d�}|s�t��s�t�	t
jd�td||dd|�d�t
�d�S|p�tt���}t�|�}|p�t�|�}|j}t||�}t��}t��}t
�}i|�d�p�i�|p�i�}|�tj|�|�|p�i�d|d<||d<t|g|�Ri|��\}}|�d�}|�r'zdd�||���D�}|�rt|t��r|�|�Wnt�y&}zt �!d|�d|���WYd}~nd}~ww|�d�} | �rTz| |�}Wnt�yS}zt �!d|�d|���WYd}~nd}~ww|�d��p[g|�p_g}!|�tj|!�|!|�pmg7}!|du�r�|j"||	|t|�|d�||!|||d�}"nt#j$t%�&|�||t|�|d�||	t%j&|dd�|||!|
||
d�}"t��du�r�z|"�'�Wnt�y�}zt �!d |"j(�d|���WYd}~nd}~wwt|"|||||�d�|d�}#|�tj|#d�|�t)j|#d!�|#S)"r�r�r8r7r#r�r�r�Frlr�Nr6rr�z>LangSmith tracing is not enabled, returning original function.r�)r�r6rirrr�rBrvrr�cSsi|]\}}|dur||�qSr�r>rFr>r>r?rKmsz_setup_run.<locals>.<dictcomp>z&Failed to infer invocation params for r$rnzFailed to filter inputs for )rlr��doc)rlr��
serializedrr7r�r�rTr
)rrlr�rr�rr6r�r7r#rr�zFailed to post run r�)*r=r.r}r3r[r8r&r9r�log_once�logging�DEBUGrgrr��uuid�uuid4rzr��_get_function_namer�rwr0r/r�r]�update� _get_inputs_and_attachments_saferLrerLr�rpr�rr$rr�rrrr+)$rar�r�r�rTr�r8r7r#r�r�rirlrr�
project_cv�selected_projectr�id_r��name_�	docstringrvrrrB�	metadata_rrr��invocation_paramsr�rnrr��response_containerr>r>r?r�(s


�
�����
	
��	

��

�
�"��
"��
�����$���	r�r�c
Cs`z|dur	||�}t|||d�WdSty/}zt�dt|����WYd}~dSd}~ww)zHandle the end of run.Nrnz!Unable to process trace outputs: )rur�rprqro)rkr�r�r�r�r>r>r?r��s"��r�cCst|dd�S)Nr�F)�getattrrir>r>r?rd��rdr��inspect.SignaturecOs�|j|i|��}|��t|j�}|�dd�|�dd�|j��D]\}}|jtj	j
kr=||vr=|�||�|�|�q"|S)z:Return a dictionary of inputs from the function signature.r�N�cls)�bind_partial�apply_defaultsrL�	argumentsr�r�rLr�rzr�r�r�)r�r�rT�boundr��
param_namer�r>r>r?�_get_inputs�s

�r�c
Os^zt|g|�Ri|��WSty.}zt�d|�d|���||d�WYd}~Sd}~ww�NzFailed to get inputs for r$)r�rT)r�r�rp�debug)r�r�rTr�r>r>r?�_get_inputs_safe�s��r�r��inspect.ParametercCs2|jtjkpt|j�tkotdd�t|j�D��S)Ncss�|]}|tjkVqdSr�)r%�
Attachment)rG�argr>r>r?r��s�z!_is_attachment.<locals>.<genexpr>)�
annotationr%r�r!r�anyr )r�r>r>r?�_is_attachment�s�r��Set[str]cCsdd�|j��D�S)NcSsh|]
\}}t|�r|�qSr>)r�)rGrlr�r>r>r?�	<setcomp>�s
��z*_attachment_args_helper.<locals>.<setcomp>)r�rL�r�r>r>r?�_attachment_args_helper�s�r�i�)�maxsizecCst|�Sr�)r�r�r>r>r?�_cached_attachment_args�rAr�cCs&zt|�WStyt|�YSwr�)r�rCr�r�r>r>r?�_attachment_args�s

�r�� Tuple[dict, schemas.Attachments]c

Os�z6t|g|�Ri|��}t|�}|r2ii}}|��D]\}}||vr(|||<q|||<q||fWS|ifWStyZ}	zt�d|�d|	���||d�ifWYd}	~	Sd}	~	wwr�)r�r�rLr�rprq)
r�r�rT�inferred�attachment_argsrrrHrIr�r>r>r?r��s 




��r�cCs(|��D]
\}}t|}|�|�qdS)zSet the tracing context.N)rLr:r])rBrHrI�varr>r>r?r^s�r^r��Iterator[T]r�r�r��	List[Any]�Generator[T, None, Any]c
cs��z-	|d�t|�}|r&|dr&|d�dtj�tjj���d|id��|�|�|Vqt	yC}z	|j
WYd}~Sd}~ww)NTrBr��	new_token�token�rl�timerT)r��next�	add_event�datetime�now�timezone�utc�	isoformatr��
StopIteration�value)r�r�r�r�r�r�r>r>r?r�s*����
	���r��AsyncIterator[T]r��AsyncGenerator[T, None]cCs��zZ	|rtjt�|�|dd�IdH}n#tdit|d����t�|�IdH}Wd�n1s3wY|rS|drS|d�dtj�tj	j
���d|id��|�|�|Vqt
yeYdSw)	NTrBrJr�r�r�r�r>)r�r�r��py_anextr`rMr�r�r�r�r�r�r��StopAsyncIteration)r�r�r�r�r�r�r>r>r?r�4s6������
	��r��Tc@sTeZdZdZ	ddd	d
�Zdd
d�Zdd�Zdd�Zdd�Zdd�Z	dddd�Z
dS)�_TracedStreamBasez%Base class for traced stream objects.Nr��$Union[Iterator[T], AsyncIterator[T]]r�rgrmrjcCsD||_||_d|_||_g|_|dr|djdk|_dSd|_dS)NFr�r�)�
__ls_stream__�__ls_trace_container__�__ls_completed__�__ls_reduce_fn__�__ls_accumulated_output__r��__is_llm_run__�r�r�r�rmr>r>r?r
]s���z_TracedStreamBase.__init__rlr�cCst|j|�Sr�)r�r�)r�rlr>r>r?�__getattr__nr�z_TracedStreamBase.__getattr__cCsttt|j�t|j���Sr�)�listr]�dirrFr�r-r>r>r?�__dir__qsz_TracedStreamBase.__dir__cCsd|j�d�S)Nz
Traceable(�))r�r-r>r>r?�__repr__tsz_TracedStreamBase.__repr__cCs
t|j�Sr�)r�r�r-r>r>r?�__str__w�
z_TracedStreamBase.__str__cCsLz	|js|��Wn	tyYnwz|j��WdSty%YdSwr�)r��
_end_tracer�r��__del__r-r>r>r?r�zs���z_TracedStreamBase.__del__r�r cCsJ|jrdSz|jr|�|j�}n|j}t|j||d�Wd|_dSd|_w)NrnT)r�r�r�rur�)r�r��reduced_outputr>r>r?r��s�z_TracedStreamBase._end_tracer�)r�r�r�rgrmrj)rlr��r�r )r�r�r�r�r
r�r�r�r�r�r�r>r>r>r?r�Zs�
r�csJeZdZdZ	dd�fd	d
�
Zdd
d�Zddd�Zdd�Zdd�Z�Z	S)r�z>A wrapper for synchronous stream objects that handles tracing.Nr�r�r�rgrmrjcs6t�j|||d�||_t|j|j|j|jd�|_dS)N�r�r�rmr�)rGr
r�r�r�r�r��__ls__gen__r�rZr>r?r
�s��z_TracedStream.__init__r;r�cCs&zt|j�WSty|���wr�)r�r�r�r�r-r>r>r?�__next__�s�z_TracedStream.__next__c
csF�z|jEdHWnty}z|j|d��d}~ww|��dS�Nr�)r�r�r�)r�r�r>r>r?r��s���z_TracedStream.__iter__cCs
|j��Sr�)r�r.r-r>r>r?r.�r�z_TracedStream.__enter__c	CsJz|j�|||�W|j|r|d�Sdd�S|j|r |d�wdd�wr�)r�r/r��r�r�exc_val�exc_tbr>r>r?r/�s8z_TracedStream.__exit__r�)r�r�r�rgrmrj�r;r�)r;r�)
r�r�r�r�r
r�r�r.r/rYr>r>rZr?r��s�

	r�csVeZdZdZ	dd�fd	d
�
Zddd
d�Zddd�Zddd�Zdd�Zdd�Z	�Z
S)r�z?A wrapper for asynchronous stream objects that handles tracing.Nr�r�r�rgrmrjcs<t�j|||d�||_t|j|j|jt��|jd�|_	dS)Nr�r�)
rGr
r�r�r�r�r�r�r��_TracedAsyncStream__ls_genr�rZr>r?r
�s��z_TracedAsyncStream.__init__r�r c�s6�t�}t�tj|j||d��IdHtt|��dS)Nr0)rr�r�r�r�r�r^rM)r�r�r2r>r>r?�_aend_trace�s�
�z_TracedAsyncStream._aend_tracer;r�c�s<�z
ttt�|j�IdH�WSty|��IdH�wr�)rr�r�r�r�r�r�r-r>r>r?�	__anext__�s��z_TracedAsyncStream.__anext__cCsT�z|j2z	3dHW}|Vq6Wnty |��IdH�w|��IdHdSr�)r�r�r�)r�r�r>r>r?r��s���z_TracedAsyncStream.__aiter__c�s�|j��IdHSr�)r�r4r-r>r>r?r4�s�z_TracedAsyncStream.__aenter__c�s:�z|j�|||�IdHW|��IdHS|��IdHwr�)r�r5r�r�r>r>r?r5�s� z_TracedAsyncStream.__aexit__r�)r�r�r�rgrmrjr�r�)r;r�)r�r�r�r�r
r�r�r�r4r5rYr>r>rZr?r��s�


r�r�c
CsR|r'|dur%z||�WSty$}z
t�|�|WYd}~Sd}~ww|SdSr�)r�rpr�)r�rmr�r>r>r?r��s

���r�)r;r<r�)rBrCr;rD)r6rNr7rOr8rPr5rQr9rRr#rSrTrr;rU)rarr;rb)rarprlrNr8rqr7rOr#rSrmrrr6rNrnrsrortr;ru)rar	r;rx)rarpr;rur6)r�r�rlrNr8rqr7rOr#rSrmrrr6rNrnrsrortr�rsr�rxr;r�)r�rrTrr;r�)r6rNr;rN)r;r	r;r*)NN)rkrgr�rlr�r r;r#)r�rLr�r}r;rL)r�r}r�rxr;r<r7)rar	r�r�r�r�r�rrTrr;rg)
rkrgr�rlr�r r�rtr;r#)rarr;rx)r�r�r�rrTrr;rD)r�r�r;rx)r�r�r;r�)r�r�r�rrTrr;r�)rBrD)
r�r�r�rgr�rxr�r�r;r�)r�r�r�rgr�rxr�rxr�r�r;r�)r�r�rmr	r;r)ur��
__future__rr��
contextlib�contextvarsr�rfrzr�r�rXr�typingrrrrrr	r
rrr
rrrrrrrrrrrrrrr�typing_extensionsrrrr r!�	langsmithr#r�r$r%r&�langsmith._internalr'r��
langsmith.envr(�typesr)r\r*�	getLoggerr�rp�
ContextVarrr+r�r.r/r0rxr2�Clientr3r:r�r@rM�contextmanagerr`�get_run_tree_contextrjrwr|r}r�r�r�rvrrrar�rgr�rurwr[r�r�rdr�r�r�r��	lru_cacher�r�r�r^r�r�r�r�r�r�r�r>r>r>r?�<module>s�l
���

��:
�
"��
t


t�
�7��











#:.7